answer stringlengths 17 10.2M |
|---|
package com.cloud.storage;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.BackupSnapshotCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
import com.cloud.agent.api.DeleteStoragePoolCommand;
import com.cloud.agent.api.ManageSnapshotCommand;
import com.cloud.agent.api.ModifyStoragePoolAnswer;
import com.cloud.agent.api.ModifyStoragePoolCommand;
import com.cloud.agent.api.storage.CopyVolumeAnswer;
import com.cloud.agent.api.storage.CopyVolumeCommand;
import com.cloud.agent.api.storage.CreateAnswer;
import com.cloud.agent.api.storage.CreateCommand;
import com.cloud.agent.api.storage.DeleteTemplateCommand;
import com.cloud.agent.api.storage.DestroyCommand;
import com.cloud.agent.api.to.VolumeTO;
import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.async.AsyncInstanceCreateStatus;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.consoleproxy.ConsoleProxyManager;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.event.EventState;
import com.cloud.event.EventTypes;
import com.cloud.event.EventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Host.Type;
import com.cloud.host.dao.DetailsDao;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.network.NetworkManager;
import com.cloud.offering.ServiceOffering;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Volume.MirrorState;
import com.cloud.storage.Volume.SourceType;
import com.cloud.storage.Volume.VolumeType;
import com.cloud.storage.allocator.StoragePoolAllocator;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.listener.StoragePoolMonitor;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.storage.snapshot.SnapshotScheduler;
import com.cloud.template.TemplateManager;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.vm.DiskCharacteristics;
import com.cloud.vm.State;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value = { StorageManager.class })
public class StorageManagerImpl implements StorageManager {
private static final Logger s_logger = Logger.getLogger(StorageManagerImpl.class);
protected String _name;
@Inject protected UserVmManager _userVmMgr;
@Inject protected AgentManager _agentMgr;
@Inject protected TemplateManager _tmpltMgr;
@Inject protected AsyncJobManager _asyncMgr;
@Inject protected SnapshotManager _snapshotMgr;
@Inject protected SnapshotScheduler _snapshotScheduler;
@Inject protected AccountManager _accountMgr;
@Inject protected ConfigurationManager _configMgr;
@Inject protected ConsoleProxyManager _consoleProxyMgr;
@Inject protected SecondaryStorageVmManager _secStorageMgr;
@Inject protected NetworkManager _networkMgr;
@Inject protected VolumeDao _volsDao;
@Inject protected HostDao _hostDao;
@Inject protected ConsoleProxyDao _consoleProxyDao;
@Inject protected DetailsDao _detailsDao;
@Inject protected SnapshotDao _snapshotDao;
protected Adapters<StoragePoolAllocator> _storagePoolAllocators;
protected Adapters<StoragePoolDiscoverer> _discoverers;
@Inject protected StoragePoolHostDao _storagePoolHostDao;
@Inject protected AlertManager _alertMgr;
@Inject protected VMTemplateHostDao _vmTemplateHostDao = null;
@Inject protected VMTemplatePoolDao _vmTemplatePoolDao = null;
@Inject protected VMTemplateDao _vmTemplateDao = null;
@Inject protected StoragePoolHostDao _poolHostDao = null;
@Inject protected UserVmDao _userVmDao;
@Inject protected VMInstanceDao _vmInstanceDao;
@Inject protected StoragePoolDao _storagePoolDao = null;
@Inject protected CapacityDao _capacityDao;
@Inject protected DiskOfferingDao _diskOfferingDao;
@Inject protected AccountDao _accountDao;
@Inject protected EventDao _eventDao = null;
@Inject protected DataCenterDao _dcDao = null;
@Inject protected HostPodDao _podDao = null;
@Inject protected VMTemplateDao _templateDao;
@Inject protected VMTemplateHostDao _templateHostDao;
@Inject protected ServiceOfferingDao _offeringDao;
@Inject protected UserDao _userDao;
protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
protected SearchBuilder<StoragePoolVO> PoolsUsedByVmSearch;
ScheduledExecutorService _executor = null;
boolean _storageCleanupEnabled;
int _storageCleanupInterval;
int _storagePoolAcquisitionWaitSeconds = 1800; // 30 minutes
protected int _retry = 2;
protected int _pingInterval = 60; // seconds
protected int _hostRetry;
protected int _overProvisioningFactor = 1;
private int _totalRetries;
private int _pauseInterval;
private final boolean _shouldBeSnapshotCapable = true;
private Hypervisor.Type _hypervisorType;
@Override
public boolean share(VMInstanceVO vm, List<VolumeVO> vols, HostVO host, boolean cancelPreviousShare) {
//this check is done for maintenance mode for primary storage
//if any one of the volume is unusable, we return false
//if we return false, the allocator will try to switch to another PS if available
for(VolumeVO vol: vols)
{
if(vol.getRemoved()!=null)
{
s_logger.warn("Volume id:"+vol.getId()+" is removed, cannot share on this instance");
//not ok to share
return false;
}
}
//ok to share
return true;
}
@DB
public List<VolumeVO> allocate(DiskCharacteristics rootDisk, List<DiskCharacteristics> dataDisks, VMInstanceVO vm, DataCenterVO dc, AccountVO account) {
ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(dataDisks.size() + 1);
VolumeVO dataVol = null;
VolumeVO rootVol = null;
long deviceId = 0;
Transaction txn = Transaction.currentTxn();
txn.start();
rootVol = new VolumeVO(VolumeType.ROOT, rootDisk.getName(), dc.getId(), account.getDomainId(), account.getId(), rootDisk.getDiskOfferingId(), rootDisk.getSize());
if (rootDisk.getTemplateId() != null) {
rootVol.setTemplateId(rootDisk.getTemplateId());
}
rootVol.setInstanceId(vm.getId());
rootVol.setDeviceId(deviceId++);
rootVol = _volsDao.persist(rootVol);
vols.add(rootVol);
for (DiskCharacteristics dataDisk : dataDisks) {
dataVol = new VolumeVO(VolumeType.DATADISK, dataDisk.getName(), dc.getId(), account.getDomainId(), account.getId(), dataDisk.getDiskOfferingId(), dataDisk.getSize());
dataVol.setDeviceId(deviceId++);
dataVol.setInstanceId(vm.getId());
dataVol = _volsDao.persist(dataVol);
vols.add(dataVol);
}
txn.commit();
return vols;
}
@Override
public List<VolumeVO> allocateTemplatedVm(VMInstanceVO vm, VMTemplateVO template, DiskOfferingVO rootOffering, DiskOfferingVO diskOffering, Long size, DataCenterVO dc, AccountVO account) {
assert (template.getFormat() != ImageFormat.ISO) : "You can't create user vm based on ISO with this format";
DiskCharacteristics rootDisk = null;
List<DiskCharacteristics> dataDisks = new ArrayList<DiskCharacteristics>(diskOffering != null ? 1 : 0);
long rootId = _volsDao.getNextInSequence(Long.class, "volume_seq");
rootDisk = new DiskCharacteristics(rootId, VolumeType.ROOT, "ROOT-" + vm.getId() + " rootId", rootOffering.getId(), 0, rootOffering.getTagsArray(), rootOffering.getUseLocalStorage(), rootOffering.isRecreatable(), template.getId());
if (diskOffering != null) {
long dataId = _volsDao.getNextInSequence(Long.class, "volume_seq");
dataDisks.add(new DiskCharacteristics(dataId, VolumeType.DATADISK, "DATA-" + vm.getId() + "-" + dataId, diskOffering.getId(), size != null ? size : diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null));
}
return allocate(rootDisk, dataDisks, vm, dc, account);
}
@Override
public VolumeVO allocateIsoInstalledVm(VMInstanceVO vm, VMTemplateVO template, DiskOfferingVO rootOffering, Long size, DataCenterVO dc, AccountVO account) {
assert (template.getFormat() == ImageFormat.ISO) : "The template has to be ISO";
long rootId = _volsDao.getNextInSequence(Long.class, "volume_seq");
DiskCharacteristics rootDisk = new DiskCharacteristics(rootId, VolumeType.ROOT, "ROOT-" + vm.getId() + "-" + rootId, rootOffering.getId(), size != null ? size : rootOffering.getDiskSizeInBytes(), rootOffering.getTagsArray(), rootOffering.getUseLocalStorage(), rootOffering.isRecreatable(), null);
List<VolumeVO> vols = allocate(rootDisk, null, vm, dc, account);
return vols.get(0);
}
@Override
public VolumeVO allocateSystemVm(VMInstanceVO vm, VMTemplateVO template, DiskOfferingVO rootOffering, DataCenterVO dc) {
List<VolumeVO> vols = allocateTemplatedVm(vm, template, rootOffering, null, null, dc, _accountMgr.getSystemAccount());
return vols.get(0);
}
@Override
public List<VolumeVO> prepare(VMInstanceVO vm, HostVO host) {
List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId());
List<VolumeVO> recreateVols = new ArrayList<VolumeVO>(vols.size());
for (VolumeVO vol : vols) {
if (!vol.isRecreatable()) {
return vols;
}
//if we have a system vm
//get the storage pool
//if pool is in maintenance
//add to recreate vols, and continue
if(vm.getType().equals(VirtualMachine.Type.ConsoleProxy) || vm.getType().equals(VirtualMachine.Type.DomainRouter) || vm.getType().equals(VirtualMachine.Type.SecondaryStorageVm))
{
StoragePoolVO sp = _storagePoolDao.findById(vol.getPoolId());
if(sp.getStatus().equals(Status.PrepareForMaintenance))
{
recreateVols.add(vol);
continue;
}
}
StoragePoolHostVO ph = _storagePoolHostDao.findByPoolHost(vol.getPoolId(), host.getId());
if (ph == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Must recreate " + vol + " since " + vol.getPoolId() + " has is not hooked up with host " + host.getId());
}
recreateVols.add(vol);
}
}
if (recreateVols.size() == 0) {
s_logger.debug("No need to recreate the volumes");
return vols;
}
List<VolumeVO> createds = new ArrayList<VolumeVO>(recreateVols.size());
for (VolumeVO vol : recreateVols) {
VolumeVO create = new VolumeVO(vol.getVolumeType(), vol.getInstanceId(), vol.getTemplateId(), vol.getName(), vol.getDataCenterId(), host.getPodId(), vol.getAccountId(), vol.getDomainId(), vol.isRecreatable());
create.setDiskOfferingId(vol.getDiskOfferingId());
create.setDeviceId(vol.getDeviceId());
create = _volsDao.persist(create);
VMTemplateVO template = _templateDao.findById(create.getTemplateId());
DataCenterVO dc = _dcDao.findById(create.getDataCenterId());
HostPodVO pod = _podDao.findById(host.getPodId());
DiskOfferingVO diskOffering = null;
diskOffering = _diskOfferingDao.findById(vol.getDiskOfferingId());
ServiceOfferingVO offering;
if (vm instanceof UserVmVO) {
offering = _offeringDao.findById(((UserVmVO)vm).getServiceOfferingId());
} else {
offering = _offeringDao.findById(vol.getDiskOfferingId());
}
VolumeVO created = createVolume(create, vm, template, dc, pod, host.getClusterId(), offering, diskOffering, new ArrayList<StoragePoolVO>(),0);
if (created == null) {
break;
}
createds.add(created);
}
for (VolumeVO vol : recreateVols) {
_volsDao.remove(vol.getId());
}
return createds;
}
@Override
public List<Pair<VolumeVO, StoragePoolVO>> isStoredOn(VMInstanceVO vm) {
List<Pair<VolumeVO, StoragePoolVO>> lst = new ArrayList<Pair<VolumeVO, StoragePoolVO>>();
List<VolumeVO> vols = _volsDao.findByInstance(vm.getId());
for (VolumeVO vol : vols) {
StoragePoolVO pool = _storagePoolDao.findById(vol.getPoolId());
lst.add(new Pair<VolumeVO, StoragePoolVO>(vol, pool));
}
return lst;
}
@Override
public boolean isLocalStorageActiveOnHost(HostVO host) {
List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId());
for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) {
StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId());
if (storagePool.getPoolType() == StoragePoolType.LVM) {
SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder();
volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ);
volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL);
SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder();
activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN);
volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId());
SearchCriteria<VolumeVO> volumeSC = volumeSB.create();
volumeSC.setParameters("poolId", storagePool.getId());
volumeSC.setJoinParameters("activeVmSB", "state", new Object[] {State.Creating, State.Starting, State.Running, State.Stopping, State.Migrating});
List<VolumeVO> volumes = _volsDao.search(volumeSC, null);
if (volumes.size() > 0) {
return true;
}
}
}
return false;
}
@Override
public List<VolumeVO> unshare(VMInstanceVO vm, HostVO host) {
final List<VolumeVO> vols = _volsDao.findCreatedByInstance(vm.getId());
if (vols.size() == 0) {
return vols;
}
return unshare(vm, vols, host) ? vols : null;
}
protected StoragePoolVO findStoragePool(DiskCharacteristics dskCh, final DataCenterVO dc, HostPodVO pod, Long clusterId, final ServiceOffering offering, final VMInstanceVO vm, final VMTemplateVO template, final Set<StoragePool> avoid) {
Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration();
while (en.hasMoreElements()) {
final StoragePoolAllocator allocator = en.nextElement();
final StoragePool pool = allocator.allocateToPool(dskCh, offering, dc, pod, clusterId, vm, template, avoid);
if (pool != null) {
return (StoragePoolVO) pool;
}
}
return null;
}
protected Long findHostIdForStoragePool(StoragePoolVO pool) {
List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up);
if (poolHosts.size() == 0) {
return null;
} else {
return poolHosts.get(0).getHostId();
}
}
@Override
public Answer[] sendToPool(StoragePoolVO pool, Command[] cmds, boolean stopOnError) {
List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(pool.getId(), Status.Up);
Collections.shuffle(poolHosts);
for (StoragePoolHostVO poolHost: poolHosts) {
try {
return _agentMgr.send(poolHost.getHostId(), cmds, stopOnError);
} catch (AgentUnavailableException e) {
s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage());
} catch (OperationTimedoutException e) {
s_logger.debug("Moving on because unable to send to " + poolHost.getHostId() + " due to " + e.getMessage());
}
}
if( !poolHosts.isEmpty() ) {
s_logger.warn("Unable to send commands to the pool because we ran out of hosts to send to");
}
return null;
}
@Override
public Answer sendToPool(StoragePoolVO pool, Command cmd) {
Command[] cmds = new Command[]{cmd};
Answer[] answers = sendToPool(pool, cmds, true);
if (answers == null) {
return null;
}
return answers[0];
}
protected DiskCharacteristics createDiskCharacteristics(VolumeVO volume, VMTemplateVO template, DataCenterVO dc, DiskOfferingVO diskOffering) {
if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) {
SearchCriteria<VMTemplateHostVO> sc = HostTemplateStatesSearch.create();
sc.setParameters("id", template.getId());
sc.setParameters("state", com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
sc.setJoinParameters("host", "dcId", dc.getId());
List<VMTemplateHostVO> sss = _vmTemplateHostDao.search(sc, null);
if (sss.size() == 0) {
throw new CloudRuntimeException("Template " + template.getName() + " has not been completely downloaded to zone " + dc.getId());
}
VMTemplateHostVO ss = sss.get(0);
return new DiskCharacteristics(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), ss.getSize(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), Storage.ImageFormat.ISO != template.getFormat() ? template.getId() : null);
} else {
return new DiskCharacteristics(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null);
}
}
@Override
public boolean canVmRestartOnAnotherServer(long vmId) {
List<VolumeVO> vols = _volsDao.findCreatedByInstance(vmId);
for (VolumeVO vol : vols) {
if (!vol.isRecreatable() && !vol.getPoolType().isShared()) {
return false;
}
}
return true;
}
@DB
protected Pair<VolumeVO, String> createVolumeFromSnapshot(long userId, long accountId, String userSpecifiedName, DataCenterVO dc, DiskOfferingVO diskOffering, SnapshotVO snapshot, String templatePath, Long originalVolumeSize, VMTemplateVO template) {
VolumeVO createdVolume = null;
Long volumeId = null;
String volumeFolder = null;
// Create the Volume object and save it so that we can return it to the user
Account account = _accountDao.findById(accountId);
VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.VolumeType.DATADISK);
volume.setPoolId(null);
volume.setDataCenterId(dc.getId());
volume.setPodId(null);
volume.setAccountId(accountId);
volume.setDomainId(account.getDomainId());
volume.setMirrorState(MirrorState.NOT_MIRRORED);
if (diskOffering != null) {
volume.setDiskOfferingId(diskOffering.getId());
}
volume.setSize(originalVolumeSize);
volume.setStorageResourceType(Storage.StorageResourceType.STORAGE_POOL);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setStatus(AsyncInstanceCreateStatus.Creating);
volume.setSourceType(SourceType.Snapshot);
volume.setSourceId(snapshot.getId());
volume = _volsDao.persist(volume);
volumeId = volume.getId();
AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor();
if(asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if(s_logger.isInfoEnabled())
s_logger.info("CreateVolume created a new instance " + volumeId + ", update async job-" + job.getId() + " progress status");
_asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volumeId);
_asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volumeId);
}
final HashSet<StoragePool> poolsToAvoid = new HashSet<StoragePool>();
StoragePoolVO pool = null;
boolean success = false;
Set<Long> podsToAvoid = new HashSet<Long>();
Pair<HostPodVO, Long> pod = null;
String volumeUUID = null;
String details = null;
DiskCharacteristics dskCh = createDiskCharacteristics(volume, template, dc, diskOffering);
// Determine what pod to store the volume in
while ((pod = _agentMgr.findPod(null, null, dc, account.getId(), podsToAvoid)) != null) {
// Determine what storage pool to store the volume in
while ((pool = findStoragePool(dskCh, dc, pod.first(), null, null, null, null, poolsToAvoid)) != null) {
volumeFolder = pool.getPath();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Attempting to create volume from snapshotId: " + snapshot.getId() + " on storage pool " + pool.getName());
}
// Get the newly created VDI from the snapshot.
// This will return a null volumePath if it could not be created
Pair<String, String> volumeDetails = createVDIFromSnapshot(userId, snapshot, pool, templatePath);
volumeUUID = volumeDetails.first();
details = volumeDetails.second();
if (volumeUUID != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Volume with UUID " + volumeUUID + " was created on storage pool " + pool.getName());
}
success = true;
break; // break out of the "find storage pool" loop
}
s_logger.warn("Unable to create volume on pool " + pool.getName() + ", reason: " + details);
}
if (success) {
break; // break out of the "find pod" loop
} else {
podsToAvoid.add(pod.first().getId());
}
}
// Update the volume in the database
Transaction txn = Transaction.currentTxn();
txn.start();
createdVolume = _volsDao.findById(volumeId);
if (success) {
// Increment the number of volumes
_accountMgr.incrementResourceCount(accountId, ResourceType.volume);
createdVolume.setStatus(AsyncInstanceCreateStatus.Created);
createdVolume.setPodId(pod.first().getId());
createdVolume.setPoolId(pool.getId());
createdVolume.setPoolType(pool.getPoolType());
createdVolume.setFolder(volumeFolder);
createdVolume.setPath(volumeUUID);
createdVolume.setDomainId(account.getDomainId());
} else {
createdVolume.setStatus(AsyncInstanceCreateStatus.Corrupted);
createdVolume.setDestroyed(true);
}
_volsDao.update(volumeId, createdVolume);
txn.commit();
return new Pair<VolumeVO, String>(createdVolume, details);
}
@Override
@DB
public VolumeVO createVolumeFromSnapshot(long userId, long accountId, long snapshotId, String volumeName, long startEventId) {
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(accountId);
event.setType(EventTypes.EVENT_VOLUME_CREATE);
event.setState(EventState.Started);
event.setStartId(startEventId);
event.setDescription("Creating volume from snapshot with id: "+snapshotId);
_eventDao.persist(event);
// By default, assume failure.
VolumeVO createdVolume = null;
String details = null;
Long volumeId = null;
SnapshotVO snapshot = _snapshotDao.findById(snapshotId); // Precondition: snapshot is not null and not removed.
Long origVolumeId = snapshot.getVolumeId();
VolumeVO originalVolume = _volsDao.findById(origVolumeId); // NOTE: Original volume could be destroyed and removed.
String templatePath = null;
VMTemplateVO template = null;
if(originalVolume.getVolumeType().equals(Volume.VolumeType.ROOT)){
if(originalVolume.getTemplateId() == null){
details = "Null Template Id for Root Volume Id: " + origVolumeId + ". Cannot create volume from snapshot of root disk.";
s_logger.error(details);
}
else {
Long templateId = originalVolume.getTemplateId();
template = _templateDao.findById(templateId);
if(template == null) {
details = "Unable find template id: " + templateId + " to create volume from root disk";
s_logger.error(details);
}
else if (template.getFormat() != ImageFormat.ISO) {
// For ISOs there is no base template VHD file. The root disk itself is the base template.
// Creating a volume from an ISO Root Disk is the same as creating a volume for a Data Disk.
// Absolute crappy way of getting the template path on secondary storage.
// Why is the secondary storage a host? It's just an NFS mount point. Why do we need to look into the templateHostVO?
HostVO secondaryStorageHost = getSecondaryStorageHost(originalVolume.getDataCenterId());
VMTemplateHostVO templateHostVO = _templateHostDao.findByHostTemplate(secondaryStorageHost.getId(), templateId);
if (templateHostVO == null ||
templateHostVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED ||
(templatePath = templateHostVO.getInstallPath()) == null)
{
details = "Template id: " + templateId + " is not present on secondaryStorageHost Id: " + secondaryStorageHost.getId() + ". Can't create volume from ROOT DISK";
}
}
}
}
if (details == null) {
// everything went well till now
DataCenterVO dc = _dcDao.findById(originalVolume.getDataCenterId());
DiskOfferingVO diskOffering = null;
if (originalVolume.getVolumeType() == VolumeType.DATADISK || originalVolume.getVolumeType() == VolumeType.ROOT) {
Long diskOfferingId = originalVolume.getDiskOfferingId();
if (diskOfferingId != null) {
diskOffering = _diskOfferingDao.findById(diskOfferingId);
}
}
// else if (originalVolume.getVolumeType() == VolumeType.ROOT) {
// // Create a temporary disk offering with the same size as the ROOT DISK
// Long rootDiskSize = originalVolume.getSize();
// Long rootDiskSizeInMB = rootDiskSize/(1024*1024);
// Long sizeInGB = rootDiskSizeInMB/1024;
// String name = "Root Disk Offering";
// String displayText = "Temporary Disk Offering for Snapshot from Root Disk: " + originalVolume.getId() + "[" + sizeInGB + "GB Disk]";
// diskOffering = new DiskOfferingVO(originalVolume.getDomainId(), name, displayText, rootDiskSizeInMB, false, null);
else {
// The code never reaches here.
s_logger.error("Original volume must have been a ROOT DISK or a DATA DISK");
return null;
}
Pair<VolumeVO, String> volumeDetails = createVolumeFromSnapshot(userId, accountId, volumeName, dc, diskOffering, snapshot, templatePath, originalVolume.getSize(), template);
createdVolume = volumeDetails.first();
if (createdVolume != null) {
volumeId = createdVolume.getId();
}
details = volumeDetails.second();
}
Transaction txn = Transaction.currentTxn();
txn.start();
// Create an event
long templateId = -1;
long diskOfferingId = -1;
if(originalVolume.getTemplateId() != null){
templateId = originalVolume.getTemplateId();
}
diskOfferingId = originalVolume.getDiskOfferingId();
long sizeMB = createdVolume.getSize()/(1024*1024);
String poolName = _storagePoolDao.findById(createdVolume.getPoolId()).getName();
String eventParams = "id=" + volumeId +"\ndoId="+diskOfferingId+"\ntId="+templateId+"\ndcId="+originalVolume.getDataCenterId()+"\nsize="+sizeMB;
event = new EventVO();
event.setAccountId(accountId);
event.setUserId(userId);
event.setType(EventTypes.EVENT_VOLUME_CREATE);
event.setParameters(eventParams);
event.setStartId(startEventId);
event.setState(EventState.Completed);
if (createdVolume.getPath() != null) {
event.setDescription("Created volume: "+ createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + poolName + " from snapshot id: " + snapshotId);
event.setLevel(EventVO.LEVEL_INFO);
}
else {
details = "CreateVolume From Snapshot for snapshotId: " + snapshotId + " failed at the backend, reason " + details;
event.setDescription(details);
event.setLevel(EventVO.LEVEL_ERROR);
}
_eventDao.persist(event);
txn.commit();
return createdVolume;
}
protected Pair<String, String> createVDIFromSnapshot(long userId, SnapshotVO snapshot, StoragePoolVO pool, String templatePath) {
String vdiUUID = null;
Long volumeId = snapshot.getVolumeId();
VolumeVO volume = _volsDao.findById(volumeId);
String primaryStoragePoolNameLabel = pool.getUuid(); // pool's uuid is actually the namelabel.
String secondaryStoragePoolUrl = getSecondaryStorageURL(volume.getDataCenterId());
Long dcId = volume.getDataCenterId();
long accountId = volume.getAccountId();
String backedUpSnapshotUuid = snapshot.getBackupSnapshotId();
CreateVolumeFromSnapshotCommand createVolumeFromSnapshotCommand =
new CreateVolumeFromSnapshotCommand(primaryStoragePoolNameLabel,
secondaryStoragePoolUrl,
dcId,
accountId,
volumeId,
backedUpSnapshotUuid,
snapshot.getName(),
templatePath);
String basicErrMsg = "Failed to create volume from " + snapshot.getName() + " for volume: " + volume.getId();
CreateVolumeFromSnapshotAnswer answer = (CreateVolumeFromSnapshotAnswer) sendToHostsOnStoragePool(pool.getId(),
createVolumeFromSnapshotCommand,
basicErrMsg,
_totalRetries,
_pauseInterval,
_shouldBeSnapshotCapable, null);
if (answer != null && answer.getResult()) {
vdiUUID = answer.getVdi();
}
else if (answer != null) {
s_logger.error(basicErrMsg);
}
return new Pair<String, String>(vdiUUID, basicErrMsg);
}
@DB
protected VolumeVO createVolume(VolumeVO volume, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, Long clusterId,
ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) {
StoragePoolVO pool = null;
final HashSet<StoragePool> avoidPools = new HashSet<StoragePool>(avoids);
DiskCharacteristics dskCh = null;
if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) {
dskCh = createDiskCharacteristics(volume, template, dc, offering);
} else {
dskCh = createDiskCharacteristics(volume, template, dc, diskOffering);
}
Transaction txn = Transaction.currentTxn();
VolumeType volType = volume.getVolumeType();
VolumeTO created = null;
int retry = _retry;
while (--retry >= 0) {
created = null;
txn.start();
long podId = pod.getId();
pod = _podDao.lock(podId, true);
if (pod == null) {
txn.rollback();
volume.setStatus(AsyncInstanceCreateStatus.Failed);
volume.setDestroyed(true);
_volsDao.persist(volume);
throw new CloudRuntimeException("Unable to acquire lock on the pod " + podId);
}
pool = findStoragePool(dskCh, dc, pod, clusterId, offering, vm, template, avoidPools);
if (pool == null) {
txn.rollback();
break;
}
avoidPools.add(pool);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to create " + volume + " on " + pool);
}
volume.setPoolId(pool.getId());
_volsDao.persist(volume);
txn.commit();
CreateCommand cmd = null;
VMTemplateStoragePoolVO tmpltStoredOn = null;
if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) {
tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool);
if (tmpltStoredOn == null) {
continue;
}
cmd = new CreateCommand(volume, vm, dskCh, tmpltStoredOn.getLocalDownloadPath(), pool);
} else {
cmd = new CreateCommand(volume, vm, dskCh, pool, size);
}
Answer answer = sendToPool(pool, cmd);
if (answer != null && answer.getResult()) {
created = ((CreateAnswer)answer).getVolume();
break;
}
volume.setPoolId(null);
_volsDao.persist(volume);
s_logger.debug("Retrying the create because it failed on pool " + pool);
}
if (created == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to create a volume for " + volume);
}
volume.setStatus(AsyncInstanceCreateStatus.Failed);
volume.setDestroyed(true);
_volsDao.persist(volume);
return null;
}
volume.setStatus(AsyncInstanceCreateStatus.Created);
volume.setFolder(pool.getPath());
volume.setPath(created.getPath());
volume.setSize(created.getSize());
volume.setPoolType(pool.getPoolType());
volume.setPodId(pod.getId());
_volsDao.persist(volume);
return volume;
}
@Override
public List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering, long size) throws StorageUnavailableException, ExecutionException {
List<StoragePoolVO> avoids = new ArrayList<StoragePoolVO>();
return create(account, vm, template, dc, pod, offering, diskOffering, avoids, size);
}
@DB
protected List<VolumeVO> create(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod,
ServiceOfferingVO offering, DiskOfferingVO diskOffering, List<StoragePoolVO> avoids, long size) {
ArrayList<VolumeVO> vols = new ArrayList<VolumeVO>(2);
VolumeVO dataVol = null;
VolumeVO rootVol = null;
Transaction txn = Transaction.currentTxn();
txn.start();
if (Storage.ImageFormat.ISO == template.getFormat()) {
rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(),(size>0)? size : diskOffering.getDiskSizeInBytes());
rootVol.setDiskOfferingId(diskOffering.getId());
rootVol.setSourceType(SourceType.Template);
rootVol.setSourceId(template.getId());
rootVol.setDeviceId(0l);
rootVol = _volsDao.persist(rootVol);
} else {
rootVol = new VolumeVO(VolumeType.ROOT, vm.getId(), template.getId(), vm.getInstanceName() + "-ROOT", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), offering.isRecreatable());
rootVol.setDiskOfferingId(offering.getId());
rootVol.setTemplateId(template.getId());
rootVol.setSourceId(template.getId());
rootVol.setSourceType(SourceType.Template);
rootVol.setDeviceId(0l);
rootVol = _volsDao.persist(rootVol);
if (diskOffering != null && diskOffering.getDiskSizeInBytes() > 0) {
dataVol = new VolumeVO(VolumeType.DATADISK, vm.getId(), vm.getInstanceName() + "-DATA", dc.getId(), pod.getId(), account.getId(), account.getDomainId(), (size>0)? size : diskOffering.getDiskSizeInBytes());
dataVol.setDiskOfferingId(diskOffering.getId());
dataVol.setSourceType(SourceType.DiskOffering);
dataVol.setSourceId(diskOffering.getId());
dataVol.setDeviceId(1l);
dataVol = _volsDao.persist(dataVol);
}
}
txn.commit();
VolumeVO dataCreated = null;
VolumeVO rootCreated = null;
try {
rootCreated = createVolume(rootVol, vm, template, dc, pod, null, offering, diskOffering, avoids,size);
if (rootCreated == null) {
throw new CloudRuntimeException("Unable to create " + rootVol);
}
vols.add(rootCreated);
if (dataVol != null) {
StoragePoolVO pool = _storagePoolDao.findById(rootCreated.getPoolId());
dataCreated = createVolume(dataVol, vm, null, dc, pod, pool.getClusterId(), offering, diskOffering, avoids,size);
if (dataCreated == null) {
throw new CloudRuntimeException("Unable to create " + dataVol);
}
vols.add(dataCreated);
}
return vols;
} catch (Exception e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(e.getMessage());
}
if (rootCreated != null) {
destroyVolume(rootCreated);
}
throw new CloudRuntimeException("Unable to create volumes for " + vm, e);
}
}
@Override
public long createUserVM(Account account, VMInstanceVO vm, VMTemplateVO template, DataCenterVO dc, HostPodVO pod, ServiceOfferingVO offering, DiskOfferingVO diskOffering,
List<StoragePoolVO> avoids, long size) {
List<VolumeVO> volumes = create(account, vm, template, dc, pod, offering, diskOffering, avoids, size);
if( volumes == null || volumes.size() == 0) {
throw new CloudRuntimeException("Unable to create volume for " + vm.getName());
}
for (VolumeVO v : volumes) {
//when the user vm is created, the volume is attached upon creation
//set the attached datetime
try{
v.setAttached(new Date());
_volsDao.update(v.getId(), v);
}catch(Exception e)
{
s_logger.warn("Error updating the attached value for volume "+v.getId()+":"+e);
}
long volumeId = v.getId();
// Create an event
long sizeMB = v.getSize() / (1024 * 1024);
String diskOfferingIdentifier = (diskOffering != null) ? String.valueOf(diskOffering.getId()) : "-1";
String eventParams = "id=" + volumeId + "\ndoId=" + diskOfferingIdentifier + "\ntId=" + template.getId() + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB;
EventVO event = new EventVO();
event.setAccountId(account.getId());
event.setUserId(1L);
event.setType(EventTypes.EVENT_VOLUME_CREATE);
event.setParameters(eventParams);
event.setDescription("Created volume: " + v.getName() + " with size: " + sizeMB + " MB");
_eventDao.persist(event);
}
return volumes.get(0).getPoolId();
}
public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) {
if (sendToVmResidesOn) {
if (vmId != null) {
VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if (vmInstance != null) {
Long hostId = vmInstance.getHostId();
if (hostId != null && !avoidHosts.contains(vmInstance.getHostId()))
return hostId;
}
}
/*Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host to send the cmd */
}
List<StoragePoolHostVO> poolHosts = _poolHostDao.listByHostStatus(poolVO.getId(), Status.Up);
Collections.shuffle(poolHosts);
if (poolHosts != null && poolHosts.size() > 0) {
for (StoragePoolHostVO sphvo : poolHosts) {
if (!avoidHosts.contains(sphvo.getHostId())) {
return sphvo.getHostId();
}
}
}
return null;
}
@Override
public String chooseStorageIp(VMInstanceVO vm, Host host, Host storage) {
Enumeration<StoragePoolAllocator> en = _storagePoolAllocators.enumeration();
while (en.hasMoreElements()) {
StoragePoolAllocator allocator = en.nextElement();
String ip = allocator.chooseStorageIp(vm, host, storage);
if (ip != null) {
return ip;
}
}
assert false : "Hmm....fell thru the loop";
return null;
}
@Override
public boolean unshare(VMInstanceVO vm, List<VolumeVO> vols, HostVO host) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Asking for volumes of " + vm.toString() + " to be unshared to " + (host != null ? host.toString() : "all"));
}
return true;
}
@Override
public void destroy(VMInstanceVO vm, List<VolumeVO> vols) {
if (s_logger.isDebugEnabled() && vm != null) {
s_logger.debug("Destroying volumes of " + vm.toString());
}
for (VolumeVO vol : vols) {
_volsDao.detachVolume(vol.getId());
_volsDao.destroyVolume(vol.getId());
// First delete the entries in the snapshot_policy and
// snapshot_schedule table for the volume.
// They should not get executed after the volume is destroyed.
_snapshotMgr.deletePoliciesForVolume(vol.getId());
String volumePath = vol.getPath();
Long poolId = vol.getPoolId();
if (poolId != null && volumePath != null && !volumePath.trim().isEmpty()) {
Answer answer = null;
StoragePoolVO pool = _storagePoolDao.findById(poolId);
final DestroyCommand cmd = new DestroyCommand(pool, vol);
boolean removed = false;
List<StoragePoolHostVO> poolhosts = _storagePoolHostDao.listByPoolId(poolId);
for (StoragePoolHostVO poolhost : poolhosts) {
answer = _agentMgr.easySend(poolhost.getHostId(), cmd);
if (answer != null && answer.getResult()) {
removed = true;
break;
}
}
if (removed) {
_volsDao.remove(vol.getId());
} else {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_STORAGE_MISC, vol.getDataCenterId(), vol.getPodId(),
"Storage cleanup required for storage pool: " + pool.getName(), "Volume folder: " + vol.getFolder() + ", Volume Path: " + vol.getPath() + ", Volume id: " +vol.getId()+ ", Volume Name: " +vol.getName()+ ", Storage PoolId: " +vol.getPoolId());
s_logger.warn("destroy volume " + vol.getFolder() + " : " + vol.getPath() + " failed for Volume id : " +vol.getId()+ " Volume Name: " +vol.getName()+ " Storage PoolId : " +vol.getPoolId());
}
} else {
_volsDao.remove(vol.getId());
}
}
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao == null) {
s_logger.error("Unable to get the configuration dao.");
return false;
}
_storagePoolAllocators = locator.getAdapters(StoragePoolAllocator.class);
if (!_storagePoolAllocators.isSet()) {
throw new ConfigurationException("Unable to get any storage pool allocators.");
}
_discoverers = locator.getAdapters(StoragePoolDiscoverer.class);
String overProvisioningFactorStr = (String) params.get("storage.overprovisioning.factor");
if (overProvisioningFactorStr != null) {
_overProvisioningFactor = Integer.parseInt(overProvisioningFactorStr);
}
Map<String, String> configs = configDao.getConfiguration("management-server", params);
_retry = NumbersUtil.parseInt(configs.get(Config.StartRetry.key()), 2);
_pingInterval = NumbersUtil.parseInt(configs.get("ping.interval"), 60);
_hostRetry = NumbersUtil.parseInt(configs.get("host.retry"), 2);
_storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800);
s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds + " seconds");
_totalRetries = NumbersUtil.parseInt(configDao.getValue("total.retries"), 4);
_pauseInterval = 2*NumbersUtil.parseInt(configDao.getValue("ping.interval"), 60);
String hypervisoType = configDao.getValue("hypervisor.type");
if (hypervisoType.equalsIgnoreCase("KVM")) {
_hypervisorType = Hypervisor.Type.KVM;
} else if(hypervisoType.equalsIgnoreCase("vmware")) {
_hypervisorType = Hypervisor.Type.VmWare;
}
_agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _hostDao, _storagePoolDao), true, false, true);
String storageCleanupEnabled = configs.get("storage.cleanup.enabled");
_storageCleanupEnabled = (storageCleanupEnabled == null) ? true : Boolean.parseBoolean(storageCleanupEnabled);
String time = configs.get("storage.cleanup.interval");
_storageCleanupInterval = NumbersUtil.parseInt(time, 86400);
String workers = configs.get("expunge.workers");
int wrks = NumbersUtil.parseInt(workers, 10);
_executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger"));
boolean localStorage = Boolean.parseBoolean(configs.get(Config.UseLocalStorage.key()));
if (localStorage) {
_agentMgr.registerForHostEvents(ComponentLocator.inject(LocalStoragePoolListener.class), true, false, false);
}
PoolsUsedByVmSearch = _storagePoolDao.createSearchBuilder();
SearchBuilder<VolumeVO> volSearch = _volsDao.createSearchBuilder();
PoolsUsedByVmSearch.join("volumes", volSearch, volSearch.entity().getPoolId(), PoolsUsedByVmSearch.entity().getId());
volSearch.and("vm", volSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
volSearch.done();
PoolsUsedByVmSearch.done();
HostTemplateStatesSearch = _vmTemplateHostDao.createSearchBuilder();
HostTemplateStatesSearch.and("id", HostTemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ);
HostTemplateStatesSearch.and("state", HostTemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.EQ);
SearchBuilder<HostVO> HostSearch = _hostDao.createSearchBuilder();
HostSearch.and("dcId", HostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
HostTemplateStatesSearch.join("host", HostSearch, HostSearch.entity().getId(), HostTemplateStatesSearch.entity().getHostId());
HostSearch.done();
HostTemplateStatesSearch.done();
return true;
}
public String getVolumeFolder(String parentDir, long accountId, String diskFolderName) {
StringBuilder diskFolderBuilder = new StringBuilder();
Formatter diskFolderFormatter = new Formatter(diskFolderBuilder);
diskFolderFormatter.format("%s/u%06d/%s", parentDir, accountId, diskFolderName);
return diskFolderBuilder.toString();
}
public String getRandomVolumeName() {
return UUID.randomUUID().toString();
}
@Override
public boolean volumeOnSharedStoragePool(VolumeVO volume) {
Long poolId = volume.getPoolId();
if (poolId == null) {
return false;
} else {
StoragePoolVO pool = _storagePoolDao.findById(poolId);
if (pool == null) {
return false;
} else {
return pool.isShared();
}
}
}
@Override
public boolean volumeInactive(VolumeVO volume) {
Long vmId = volume.getInstanceId();
if (vmId != null) {
UserVm vm = _userVmDao.findById(vmId);
if (vm == null) {
return false;
}
if (!vm.getState().equals(State.Stopped)) {
return false;
}
}
return true;
}
@Override
public String getVmNameOnVolume(VolumeVO volume) {
Long vmId = volume.getInstanceId();
if (vmId != null) {
VMInstanceVO vm = _vmInstanceDao.findById(vmId);
if (vm == null) {
return null;
}
return vm.getInstanceName();
}
return null;
}
@Override
public String getAbsoluteIsoPath(long templateId, long dataCenterId) {
String isoPath = null;
List<HostVO> storageHosts = _hostDao.listBy(Host.Type.SecondaryStorage, dataCenterId);
if (storageHosts != null) {
for (HostVO storageHost : storageHosts) {
VMTemplateHostVO templateHostVO = _vmTemplateHostDao.findByHostTemplate(storageHost.getId(), templateId);
if (templateHostVO != null) {
isoPath = storageHost.getStorageUrl() + "/" + templateHostVO.getInstallPath();
break;
}
}
}
return isoPath;
}
@Override
public String getSecondaryStorageURL(long zoneId) {
// Determine the secondary storage URL
HostVO secondaryStorageHost = _hostDao.findSecondaryStorageHost(zoneId);
if (secondaryStorageHost == null) {
return null;
}
return secondaryStorageHost.getStorageUrl();
}
@Override
public HostVO getSecondaryStorageHost(long zoneId) {
return _hostDao.findSecondaryStorageHost(zoneId);
}
@Override
public String getStoragePoolTags(long poolId) {
return _configMgr.listToCsvTags(_storagePoolDao.searchForStoragePoolDetails(poolId, "true"));
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
if (_storageCleanupEnabled) {
_executor.scheduleWithFixedDelay(new StorageGarbageCollector(), _storageCleanupInterval, _storageCleanupInterval, TimeUnit.SECONDS);
} else {
s_logger.debug("Storage cleanup is not enabled, so the storage cleanup thread is not being scheduled.");
}
return true;
}
@Override
public boolean stop() {
if (_storageCleanupEnabled) {
_executor.shutdown();
}
return true;
}
protected StorageManagerImpl() {
}
@Override
public StoragePoolVO createPool(long zoneId, Long podId, Long clusterId, String poolName, URI uri, String tags, Map<String, String> details) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceAllocationException {
if (tags != null) {
if (details == null) {
details = new HashMap<String, String>();
}
String[] tokens = tags.split(",");
for (String tag : tokens) {
tag = tag.trim();
if (tag.length() == 0) {
continue;
}
details.put(tag, "true");
}
}
Hypervisor.Type hypervisorType = null;
List<HostVO> hosts = null;
if (podId != null) {
hosts = _hostDao.listByHostPod(podId);
} else {
hosts = _hostDao.listByDataCenter(zoneId);
}
for (HostVO h : hosts) {
if (h.getType() == Type.Routing) {
hypervisorType = h.getHypervisorType();
break;
}
}
if (hypervisorType == null) {
if (_hypervisorType == Hypervisor.Type.KVM) {
hypervisorType = Hypervisor.Type.KVM;
} else if(_hypervisorType == Hypervisor.Type.VmWare) {
hypervisorType = Hypervisor.Type.VmWare;
} else {
s_logger.debug("Couldn't find a host to serve in the server pool");
return null;
}
}
String scheme = uri.getScheme();
String storageHost = uri.getHost();
String hostPath = uri.getPath();
int port = uri.getPort();
StoragePoolVO pool = null;
s_logger.debug("createPool Params @ scheme - " +scheme+ " storageHost - " +storageHost+ " hostPath - " +hostPath+ " port - " +port);
if (scheme.equalsIgnoreCase("nfs")) {
if (port == -1) {
port = 2049;
}
pool = new StoragePoolVO(StoragePoolType.NetworkFilesystem, storageHost, port, hostPath);
if (hypervisorType == Hypervisor.Type.XenServer && clusterId == null) {
throw new IllegalArgumentException("NFS need to have clusters specified for XenServers");
}
} else if (scheme.equalsIgnoreCase("file")) {
if (port == -1) {
port = 0;
}
pool = new StoragePoolVO(StoragePoolType.Filesystem, "localhost", 0, hostPath);
} else if (scheme.equalsIgnoreCase("iscsi")) {
String[] tokens = hostPath.split("/");
int lun = NumbersUtil.parseInt(tokens[tokens.length - 1], -1);
if (port == -1) {
port = 3260;
}
if (lun != -1) {
if (hypervisorType == Hypervisor.Type.XenServer && clusterId == null) {
throw new IllegalArgumentException("IscsiLUN need to have clusters specified");
}
hostPath.replaceFirst("/", "");
pool = new StoragePoolVO(StoragePoolType.IscsiLUN, storageHost, port, hostPath);
} else {
Enumeration<StoragePoolDiscoverer> en = _discoverers.enumeration();
while (en.hasMoreElements()) {
Map<StoragePoolVO, Map<String, String>> pools;
try {
pools = en.nextElement().find(zoneId, podId, uri, details);
} catch (DiscoveryException e) {
throw new IllegalArgumentException("Not enough information for discovery " + uri, e);
}
if (pools != null) {
Map.Entry<StoragePoolVO, Map<String, String>> entry = pools.entrySet().iterator().next();
pool = entry.getKey();
details = entry.getValue();
break;
}
}
}
} else if (scheme.equalsIgnoreCase("iso")) {
if (port == -1) {
port = 2049;
}
pool = new StoragePoolVO(StoragePoolType.ISO, storageHost, port, hostPath);
} else {
s_logger.warn("Unable to figure out the scheme for URI: " + uri);
throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri);
}
if (pool == null) {
s_logger.warn("Unable to figure out the scheme for URI: " + uri);
throw new IllegalArgumentException("Unable to figure out the scheme for URI: " + uri);
}
List<StoragePoolVO> pools = _storagePoolDao.listPoolByHostPath(storageHost, hostPath);
if (!pools.isEmpty()) {
Long oldPodId = pools.get(0).getPodId();
throw new ResourceInUseException("Storage pool " + uri + " already in use by another pod (id=" + oldPodId + ")", "StoragePool", uri.toASCIIString());
}
// iterate through all the hosts and ask them to mount the filesystem.
// FIXME Not a very scalable implementation. Need an async listener, or
// perhaps do this on demand, or perhaps mount on a couple of hosts per
// pod
List<HostVO> allHosts = _hostDao.listBy(Host.Type.Routing, clusterId, podId, zoneId);
if (allHosts.isEmpty() && _hypervisorType != Hypervisor.Type.KVM) {
throw new ResourceAllocationException("No host exists to associate a storage pool with");
}
long poolId = _storagePoolDao.getNextInSequence(Long.class, "id");
String uuid = UUID.nameUUIDFromBytes(new String(storageHost + hostPath).getBytes()).toString();
List<StoragePoolVO> spHandles = _storagePoolDao.findIfDuplicatePoolsExistByUUID(uuid);
if(spHandles!=null && spHandles.size()>0)
{
s_logger.debug("Another active pool with the same uuid already exists");
throw new ResourceInUseException("Another active pool with the same uuid already exists");
}
s_logger.debug("In createPool Setting poolId - " +poolId+ " uuid - " +uuid+ " zoneId - " +zoneId+ " podId - " +podId+ " poolName - " +poolName);
pool.setId(poolId);
pool.setUuid(uuid);
pool.setDataCenterId(zoneId);
pool.setPodId(podId);
pool.setName(poolName);
pool.setClusterId(clusterId);
pool.setStatus(Status.Up);
pool = _storagePoolDao.persist(pool, details);
if (_hypervisorType == Hypervisor.Type.KVM && allHosts.isEmpty()) {
return pool;
}
s_logger.debug("In createPool Adding the pool to each of the hosts");
List<HostVO> poolHosts = new ArrayList<HostVO>();
for (HostVO h : allHosts) {
boolean success = addPoolToHost(h.getId(), pool);
if (success) {
poolHosts.add(h);
}
}
if (poolHosts.isEmpty()) {
_storagePoolDao.expunge(pool.getId());
pool = null;
} else {
createCapacityEntry(pool);
}
return pool;
}
@Override
public StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException {
StoragePoolVO pool = _storagePoolDao.findById(poolId);
if (pool == null) {
throw new IllegalArgumentException("Unable to find storage pool with ID: " + poolId);
}
if (tags != null) {
Map<String, String> details = _storagePoolDao.getDetails(poolId);
String[] tagsList = tags.split(",");
for (String tag : tagsList) {
tag = tag.trim();
if (tag.length() > 0 && !details.containsKey(tag)) {
details.put(tag, "true");
}
}
_storagePoolDao.updateDetails(poolId, details);
}
return pool;
}
@Override
@DB
public boolean deletePool(long id) {
boolean deleteFlag = false;
// get the pool to delete
StoragePoolVO sPool = _storagePoolDao.findById(id);
if (sPool == null)
return false;
// for the given pool id, find all records in the storage_pool_host_ref
List<StoragePoolHostVO> hostPoolRecords = _storagePoolHostDao.listByPoolId(id);
// if not records exist, delete the given pool (base case)
if (hostPoolRecords.size() == 0) {
_storagePoolDao.remove(id);
return true;
} else {
// 1. Check if the pool has associated volumes in the volumes table
// 2. If it does, then you cannot delete the pool
Pair<Long, Long> volumeRecords = _volsDao.getCountAndTotalByPool(id);
if (volumeRecords.first() > 0) {
return false; // cannot delete as there are associated vols
}
// 3. Else part, remove the SR associated with the Xenserver
else {
// First get the host_id from storage_pool_host_ref for given
// pool id
StoragePoolVO lock = _storagePoolDao.acquire(sPool.getId());
try {
if (lock == null) {
s_logger.debug("Failed to acquire lock when deleting StoragePool with ID: " + sPool.getId());
return false;
}
for (StoragePoolHostVO host : hostPoolRecords) {
DeleteStoragePoolCommand cmd = new DeleteStoragePoolCommand(sPool);
final Answer answer = _agentMgr.easySend(host.getHostId(), cmd);
if (answer != null) {
if (answer.getResult() == true) {
deleteFlag = true;
break;
}
}
}
} finally {
if (lock != null) {
_storagePoolDao.release(lock.getId());
}
}
if (deleteFlag) {
// now delete the storage_pool_host_ref and storage_pool
// records
for (StoragePoolHostVO host : hostPoolRecords) {
_storagePoolHostDao.deleteStoragePoolHostDetails(host.getHostId(),host.getPoolId());
}
_storagePoolDao.remove(id);
return true;
}
}
}
return false;
}
@Override
public boolean addPoolToHost(long hostId, StoragePoolVO pool) {
s_logger.debug("Adding pool " + pool.getName() + " to host " + hostId);
if (pool.getPoolType() != StoragePoolType.NetworkFilesystem && pool.getPoolType() != StoragePoolType.Filesystem && pool.getPoolType() != StoragePoolType.IscsiLUN && pool.getPoolType() != StoragePoolType.Iscsi) {
return true;
}
ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(true, pool);
final Answer answer = _agentMgr.easySend(hostId, cmd);
if (answer != null) {
if (answer.getResult() == false) {
String msg = "Add host failed due to ModifyStoragePoolCommand failed" + answer.getDetails();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, pool.getDataCenterId(), pool.getPodId(), msg, msg);
s_logger.warn(msg);
return false;
}
if (answer instanceof ModifyStoragePoolAnswer) {
ModifyStoragePoolAnswer mspAnswer = (ModifyStoragePoolAnswer) answer;
StoragePoolHostVO poolHost = _poolHostDao.findByPoolHost(pool.getId(), hostId);
if (poolHost == null) {
poolHost = new StoragePoolHostVO(pool.getId(), hostId, mspAnswer.getPoolInfo().getLocalPath().replaceAll("
_poolHostDao.persist(poolHost);
} else {
poolHost.setLocalPath(mspAnswer.getPoolInfo().getLocalPath().replaceAll("
}
pool.setAvailableBytes(mspAnswer.getPoolInfo().getAvailableBytes());
pool.setCapacityBytes(mspAnswer.getPoolInfo().getCapacityBytes());
_storagePoolDao.update(pool.getId(), pool);
return true;
}
} else {
return false;
}
return false;
}
@Override
public VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId) throws InternalErrorException {
// Find a destination storage pool with the specified criteria
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
DiskCharacteristics dskCh = new DiskCharacteristics(volume.getId(), volume.getVolumeType(), volume.getName(), diskOffering.getId(), diskOffering.getDiskSizeInBytes(), diskOffering.getTagsArray(), diskOffering.getUseLocalStorage(), diskOffering.isRecreatable(), null);
DataCenterVO destPoolDataCenter = _dcDao.findById(destPoolDcId);
HostPodVO destPoolPod = _podDao.findById(destPoolPodId);
StoragePoolVO destPool = findStoragePool(dskCh, destPoolDataCenter, destPoolPod, destPoolClusterId, null, null, null, new HashSet<StoragePool>());
if (destPool == null) {
throw new InternalErrorException("Failed to find a storage pool with enough capacity to move the volume to.");
}
StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId());
String secondaryStorageURL = getSecondaryStorageURL(volume.getDataCenterId());
String secondaryStorageVolumePath = null;
// Find hosts where the source and destination storage pools are visible
Long sourceHostId = findHostIdForStoragePool(srcPool);
Long destHostId = findHostIdForStoragePool(destPool);
if (sourceHostId == null) {
throw new InternalErrorException("Failed to find a host where the source storage pool is visible.");
} else if (destHostId == null) {
throw new InternalErrorException("Failed to find a host where the dest storage pool is visible.");
}
// Copy the volume from the source storage pool to secondary storage
CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true);
CopyVolumeAnswer cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(sourceHostId, cvCmd);
if (cvAnswer == null || !cvAnswer.getResult()) {
throw new InternalErrorException("Failed to copy the volume from the source primary storage pool to secondary storage.");
}
secondaryStorageVolumePath = cvAnswer.getVolumePath();
// Copy the volume from secondary storage to the destination storage
// pool
cvCmd = new CopyVolumeCommand(volume.getId(), secondaryStorageVolumePath, destPool, secondaryStorageURL, false);
cvAnswer = (CopyVolumeAnswer) _agentMgr.easySend(destHostId, cvCmd);
if (cvAnswer == null || !cvAnswer.getResult()) {
throw new InternalErrorException("Failed to copy the volume from secondary storage to the destination primary storage pool.");
}
String destPrimaryStorageVolumePath = cvAnswer.getVolumePath();
String destPrimaryStorageVolumeFolder = cvAnswer.getVolumeFolder();
// Delete the volume on the source storage pool
final DestroyCommand cmd = new DestroyCommand(srcPool, volume);
Answer destroyAnswer = _agentMgr.easySend(sourceHostId, cmd);
if (destroyAnswer == null || !destroyAnswer.getResult()) {
throw new InternalErrorException("Failed to delete the volume from the source primary storage pool.");
}
volume.setPath(destPrimaryStorageVolumePath);
volume.setFolder(destPrimaryStorageVolumeFolder);
volume.setPodId(destPool.getPodId());
volume.setPoolId(destPool.getId());
_volsDao.update(volume.getId(), volume);
return _volsDao.findById(volume.getId());
}
@Override
@DB
public VolumeVO createVolume(long accountId, long userId, String userSpecifiedName, DataCenterVO dc, DiskOfferingVO diskOffering, long startEventId, long size)
{
String volumeName = "";
VolumeVO createdVolume = null;
try
{
// Determine the volume's name
volumeName = getRandomVolumeName();
// Create the Volume object and save it so that we can return it to the user
Account account = _accountDao.findById(accountId);
VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.VolumeType.DATADISK);
volume.setPoolId(null);
volume.setDataCenterId(dc.getId());
volume.setPodId(null);
volume.setAccountId(accountId);
volume.setDomainId(account.getDomainId());
volume.setMirrorState(MirrorState.NOT_MIRRORED);
volume.setDiskOfferingId(diskOffering.getId());
volume.setStorageResourceType(Storage.StorageResourceType.STORAGE_POOL);
volume.setInstanceId(null);
volume.setUpdated(new Date());
volume.setStatus(AsyncInstanceCreateStatus.Creating);
volume.setDomainId(account.getDomainId());
volume.setSourceId(diskOffering.getId());
volume.setSourceType(SourceType.DiskOffering);
volume = _volsDao.persist(volume);
AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor();
if (asyncExecutor != null) {
AsyncJobVO job = asyncExecutor.getJob();
if (s_logger.isInfoEnabled())
s_logger.info("CreateVolume created a new instance " + volume.getId() + ", update async job-" + job.getId() + " progress status");
_asyncMgr.updateAsyncJobAttachment(job.getId(), "volume", volume.getId());
_asyncMgr.updateAsyncJobStatus(job.getId(), BaseCmd.PROGRESS_INSTANCE_CREATED, volume.getId());
}
List<StoragePoolVO> poolsToAvoid = new ArrayList<StoragePoolVO>();
Set<Long> podsToAvoid = new HashSet<Long>();
Pair<HostPodVO, Long> pod = null;
while ((pod = _agentMgr.findPod(null, null, dc, account.getId(), podsToAvoid)) != null) {
if ((createdVolume = createVolume(volume, null, null, dc, pod.first(), null, null, diskOffering, poolsToAvoid, size)) != null) {
break;
} else {
podsToAvoid.add(pod.first().getId());
}
}
// Create an event
EventVO event = new EventVO();
event.setAccountId(accountId);
event.setUserId(userId);
event.setType(EventTypes.EVENT_VOLUME_CREATE);
event.setStartId(startEventId);
Transaction txn = Transaction.currentTxn();
txn.start();
if (createdVolume != null) {
// Increment the number of volumes
_accountMgr.incrementResourceCount(accountId, ResourceType.volume);
// Set event parameters
long sizeMB = createdVolume.getSize() / (1024 * 1024);
StoragePoolVO pool = _storagePoolDao.findById(createdVolume.getPoolId());
String eventParams = "id=" + createdVolume.getId() + "\ndoId=" + diskOffering.getId() + "\ntId=" + -1 + "\ndcId=" + dc.getId() + "\nsize=" + sizeMB;
event.setLevel(EventVO.LEVEL_INFO);
event.setDescription("Created volume: " + createdVolume.getName() + " with size: " + sizeMB + " MB in pool: " + pool.getName());
event.setParameters(eventParams);
_eventDao.persist(event);
} else {
// Mark the existing volume record as corrupted
volume.setStatus(AsyncInstanceCreateStatus.Corrupted);
volume.setDestroyed(true);
_volsDao.update(volume.getId(), volume);
}
txn.commit();
} catch (Exception e) {
s_logger.error("Unhandled exception while saving volume " + volumeName, e);
}
return createdVolume;
}
@Override
@DB
public void destroyVolume(VolumeVO volume) {
Transaction txn = Transaction.currentTxn();
txn.start();
Long volumeId = volume.getId();
_volsDao.destroyVolume(volumeId);
String eventParams = "id=" + volumeId;
EventVO event = new EventVO();
event.setAccountId(volume.getAccountId());
event.setUserId(1L);
event.setType(EventTypes.EVENT_VOLUME_DELETE);
event.setParameters(eventParams);
event.setDescription("Volume " +volume.getName()+ " deleted");
event.setLevel(EventVO.LEVEL_INFO);
_eventDao.persist(event);
// Delete the recurring snapshot policies for this volume.
_snapshotMgr.deletePoliciesForVolume(volumeId);
// Decrement the resource count for volumes
_accountMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume);
txn.commit();
}
@Override
public void createCapacityEntry(StoragePoolVO storagePool) {
SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria();
capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId());
capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId());
capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE);
List<CapacityVO> capacities = _capacityDao.search(capacitySC, null);
if (capacities.size() == 0) {
CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), 0L, storagePool.getCapacityBytes(),
CapacityVO.CAPACITY_TYPE_STORAGE);
_capacityDao.persist(capacity);
} else {
CapacityVO capacity = capacities.get(0);
if (capacity.getTotalCapacity() != storagePool.getCapacityBytes()) {
capacity.setTotalCapacity(storagePool.getCapacityBytes());
_capacityDao.update(capacity.getId(), capacity);
}
}
s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()+ " for CAPACITY_TYPE_STORAGE, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId());
capacitySC = _capacityDao.createSearchCriteria();
capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId());
capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId());
capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED);
capacities = _capacityDao.search(capacitySC, null);
if (capacities.size() == 0) {
int provFactor = 1;
if( storagePool.getPoolType() == StoragePoolType.NetworkFilesystem ) {
provFactor = _overProvisioningFactor;
}
CapacityVO capacity = new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), 0L, storagePool.getCapacityBytes()
* provFactor, CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED);
_capacityDao.persist(capacity);
} else {
CapacityVO capacity = capacities.get(0);
long currCapacity = _overProvisioningFactor * storagePool.getCapacityBytes();
if (capacity.getTotalCapacity() != currCapacity) {
capacity.setTotalCapacity(currCapacity);
_capacityDao.update(capacity.getId(), capacity);
}
}
s_logger.debug("Successfully set Capacity - " +storagePool.getCapacityBytes()* _overProvisioningFactor+ " for CAPACITY_TYPE_STORAGE_ALLOCATED, DataCenterId - " +storagePool.getDataCenterId()+ ", HostOrPoolId - " +storagePool.getId()+ ", PodId " +storagePool.getPodId());
}
@Override
public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg) {
return sendToHostsOnStoragePool(poolId, cmd, basicErrMsg, 1, 0, false, null);
}
@Override
public Answer sendToHostsOnStoragePool(Long poolId, Command cmd, String basicErrMsg, int totalRetries, int pauseBeforeRetry, boolean shouldBeSnapshotCapable,
Long vmId) {
Answer answer = null;
Long hostId = null;
StoragePoolVO storagePool = _storagePoolDao.findById(poolId);
List<Long> hostsToAvoid = new ArrayList<Long>();
int tryCount = 0;
boolean sendToVmHost = sendToVmResidesOn(cmd);
if (chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId) == null) {
// Don't just fail. The host could be reconnecting.
// wait for some time for it to get connected
// Wait for 3*ping.interval, since the code attempts a manual
// reconnect after that timeout.
try {
Thread.sleep(3 * _pingInterval * 1000);
} catch (InterruptedException e) {
s_logger.error("Interrupted while waiting for any host on poolId: " + poolId + " to get connected. " + e.getMessage());
// continue.
}
}
while ((hostId = chooseHostForStoragePool(storagePool, hostsToAvoid, sendToVmHost, vmId)) != null && tryCount++ < totalRetries) {
String errMsg = basicErrMsg + " on host: " + hostId + " try: " + tryCount + ", reason: ";
try {
HostVO hostVO = _hostDao.findById(hostId);
if (shouldBeSnapshotCapable) {
if (hostVO == null ) {
hostsToAvoid.add(hostId);
continue;
}
}
s_logger.debug("Trying to execute Command: " + cmd + " on host: " + hostId + " try: " + tryCount);
// set 120 min timeout for storage related command
answer = _agentMgr.send(hostId, cmd, 120*60*1000);
if (answer != null && answer.getResult()) {
return answer;
} else {
s_logger.warn(errMsg + ((answer != null) ? answer.getDetails() : "null"));
Thread.sleep(pauseBeforeRetry * 1000);
}
} catch (AgentUnavailableException e1) {
s_logger.warn(errMsg + e1.getMessage(), e1);
} catch (OperationTimedoutException e1) {
s_logger.warn(errMsg + e1.getMessage(), e1);
} catch (InterruptedException e) {
s_logger.warn(errMsg + e.getMessage(), e);
}
}
s_logger.error(basicErrMsg + ", no hosts available to execute command: " + cmd);
return answer;
}
protected class StorageGarbageCollector implements Runnable {
public StorageGarbageCollector() {
}
@Override
public void run() {
try {
s_logger.info("Storage Garbage Collection Thread is running.");
GlobalLock scanLock = GlobalLock.getInternLock(this.getClass().getName());
try {
if (scanLock.lock(3)) {
try {
cleanupStorage(true);
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
} catch (Exception e) {
s_logger.error("Caught the following Exception", e);
}
}
}
@Override
public void cleanupStorage(boolean recurring) {
// Cleanup primary storage pools
List<StoragePoolVO> storagePools = _storagePoolDao.listAll();
for (StoragePoolVO pool : storagePools) {
try {
if (recurring && pool.isLocal()) {
continue;
}
List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool);
s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " + pool.getName());
for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) {
if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
s_logger.debug("Storage pool garbage collector is skipping templatePoolVO with ID: " + templatePoolVO.getId() + " because it is not completely downloaded.");
continue;
}
if (!templatePoolVO.getMarkedForGC()) {
templatePoolVO.setMarkedForGC(true);
_vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO);
s_logger.debug("Storage pool garbage collector has marked templatePoolVO with ID: " + templatePoolVO.getId() + " for garbage collection.");
continue;
}
_tmpltMgr.evictTemplateFromStoragePool(templatePoolVO);
}
} catch (Exception e) {
s_logger.warn("Problem cleaning up primary storage pool " + pool, e);
}
}
// Cleanup secondary storage hosts
List<HostVO> secondaryStorageHosts = _hostDao.listSecondaryStorageHosts();
for (HostVO secondaryStorageHost : secondaryStorageHosts) {
try {
long hostId = secondaryStorageHost.getId();
List<VMTemplateHostVO> destroyedTemplateHostVOs = _vmTemplateHostDao.listDestroyed(hostId);
s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateHostVOs.size() + " templates to cleanup on secondary storage host: "
+ secondaryStorageHost.getName());
for (VMTemplateHostVO destroyedTemplateHostVO : destroyedTemplateHostVOs) {
if (!_tmpltMgr.templateIsDeleteable(destroyedTemplateHostVO)) {
s_logger.debug("Not deleting template at: " + destroyedTemplateHostVO.getInstallPath());
continue;
}
String installPath = destroyedTemplateHostVO.getInstallPath();
if (installPath != null) {
Answer answer = _agentMgr.easySend(hostId, new DeleteTemplateCommand(destroyedTemplateHostVO.getInstallPath()));
if (answer == null || !answer.getResult()) {
s_logger.debug("Failed to delete template at: " + destroyedTemplateHostVO.getInstallPath());
} else {
_vmTemplateHostDao.remove(destroyedTemplateHostVO.getId());
s_logger.debug("Deleted template at: " + destroyedTemplateHostVO.getInstallPath());
}
} else {
_vmTemplateHostDao.remove(destroyedTemplateHostVO.getId());
}
}
} catch (Exception e) {
s_logger.warn("problem cleaning up secondary storage " + secondaryStorageHost, e);
}
}
List<VolumeVO> vols = _volsDao.listRemovedButNotDestroyed();
for (VolumeVO vol : vols) {
try {
Long poolId = vol.getPoolId();
Answer answer = null;
StoragePoolVO pool = _storagePoolDao.findById(poolId);
final DestroyCommand cmd = new DestroyCommand(pool, vol);
answer = sendToPool(pool, cmd);
if (answer != null && answer.getResult()) {
s_logger.debug("Destroyed " + vol);
vol.setDestroyed(true);
_volsDao.update(vol.getId(), vol);
}
} catch (Exception e) {
s_logger.warn("Unable to destroy " + vol.getId(), e);
}
}
}
@Override
public List<StoragePoolVO> getStoragePoolsForVm(long vmId) {
SearchCriteria<StoragePoolVO> sc = PoolsUsedByVmSearch.create();
sc.setJoinParameters("volumes", "vm", vmId);
return _storagePoolDao.search(sc, null);
}
@Override
public String getPrimaryStorageNameLabel(VolumeVO volume) {
Long poolId = volume.getPoolId();
// poolId is null only if volume is destroyed, which has been checked before.
assert poolId != null;
StoragePoolVO storagePoolVO = _storagePoolDao.findById(poolId);
assert storagePoolVO != null;
return storagePoolVO.getUuid();
}
@Override
@DB
public boolean preparePrimaryStorageForMaintenance(long primaryStorageId, long userId)
{
long count = 1;
boolean restart = true;
try
{
//1. Get the primary storage record
StoragePoolVO primaryStorage = _storagePoolDao.findById(primaryStorageId);
if(primaryStorage == null)
{
s_logger.warn("The primary storage does not exist");
return false;
}
//check to see if other ps exist
//if they do, then we can migrate over the system vms to them
//if they dont, then just stop all vms on this one
count = _storagePoolDao.countBy(primaryStorage.getPodId(), Status.Up);
if(count == 0)
restart = false;
//2. Get a list of all the volumes within this storage pool
List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId);
//3. Each volume has an instance associated with it, stop the instance if running
for(VolumeVO volume : allVolumes)
{
VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId());
if(vmInstance == null)
continue;
//shut down the running vms
if(vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Stopping) || vmInstance.getState().equals(State.Starting))
{
//if the instance is of type consoleproxy, call the console proxy
if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy))
{
//make sure it is not restarted again, update config to set flag to false
_configMgr.updateConfiguration(userId, "consoleproxy.restart", "false");
//create a dummy event
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_STOP, "stopping console proxy with Id: "+vmInstance.getId());
//call the consoleproxymanager
if(!_consoleProxyMgr.stopProxy(vmInstance.getId(), eventId))
{
s_logger.warn("There was an error stopping the console proxy id: "+vmInstance.getId()+" ,cannot enable storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
else if(restart)
{
//create a dummy event
long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId());
//Restore config val for consoleproxy.restart to true
_configMgr.updateConfiguration(userId, "consoleproxy.restart", "true");
if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId1)==null)
{
s_logger.warn("There was an error starting the console proxy id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
}
//if the instance is of type uservm, call the user vm manager
if(vmInstance.getType().equals(VirtualMachine.Type.User))
{
if(!_userVmMgr.stopVirtualMachine(userId, vmInstance.getId()))
{
s_logger.warn("There was an error stopping the user vm id: "+vmInstance.getId()+" ,cannot enable storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
//if the instance is of type secondary storage vm, call the secondary storage vm manager
if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm))
{
//create a dummy event
long eventId1 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_STOP, "stopping ssvm with Id: "+vmInstance.getId());
if(!_secStorageMgr.stopSecStorageVm(vmInstance.getId(), eventId1))
{
s_logger.warn("There was an error stopping the ssvm id: "+vmInstance.getId()+" ,cannot enable storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
else if(restart)
{
//create a dummy event and restart the ssvm immediately
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId());
if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId)==null)
{
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
}
//if the instance is of type domain router vm, call the network manager
if(vmInstance.getType().equals(VirtualMachine.Type.DomainRouter))
{
//create a dummy event
long eventId2 = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping domain router with Id: "+vmInstance.getId());
if(!_networkMgr.stopRouter(vmInstance.getId(), eventId2))
{
s_logger.warn("There was an error stopping the domain router id: "+vmInstance.getId()+" ,cannot enable primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
else if(restart)
{
//create a dummy event and restart the domr immediately
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting domr with Id: "+vmInstance.getId());
if(_networkMgr.startRouter(vmInstance.getId(), eventId)==null)
{
s_logger.warn("There was an error starting the omr id: "+vmInstance.getId()+" on another storage pool, cannot enable primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
}
}
}
//5. Update the status
primaryStorage.setStatus(Status.Maintenance);
_storagePoolDao.persist(primaryStorage);
} catch (Exception e) {
s_logger.error("Exception in enabling primary storage maintenance:"+e);
}
return true;
}
private Long saveScheduledEvent(Long userId, Long accountId, String type, String description)
{
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(accountId);
event.setType(type);
event.setState(EventState.Scheduled);
event.setDescription("Scheduled async job for "+description);
event = _eventDao.persist(event);
return event.getId();
}
@Override
@DB
public boolean cancelPrimaryStorageForMaintenance(long primaryStorageId,long userId)
{
//1. Get the primary storage record
StoragePoolVO primaryStorage = _storagePoolDao.findById(primaryStorageId);
if(primaryStorage == null)
{
s_logger.warn("The primary storage does not exist");
return false;
}
//2. Get a list of all the volumes within this storage pool
List<VolumeVO> allVolumes = _volsDao.findByPoolId(primaryStorageId);
//3. If the volume is not removed AND not destroyed, start the vm corresponding to it
for(VolumeVO volume: allVolumes)
{
if((!volume.destroyed) && (volume.removed==null))
{
VMInstanceVO vmInstance = _vmInstanceDao.findById(volume.getInstanceId());
if(vmInstance.getState().equals(State.Stopping) || vmInstance.getState().equals(State.Stopped))
{
//if the instance is of type consoleproxy, call the console proxy
if(vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy))
{
//create a dummy event
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_PROXY_START, "starting console proxy with Id: "+vmInstance.getId());
if(_consoleProxyMgr.startProxy(vmInstance.getId(), eventId)==null)
{
s_logger.warn("There was an error starting the console proxy id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
//if the instance is of type ssvm, call the ssvm manager
if(vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm))
{
//create a dummy event
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_SSVM_START, "starting ssvm with Id: "+vmInstance.getId());
if(_secStorageMgr.startSecStorageVm(vmInstance.getId(), eventId)==null)
{
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
//if the instance is of type user vm, call the user vm manager
if(vmInstance.getType().equals(VirtualMachine.Type.User))
{
//create a dummy event
long eventId = saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_VM_START, "starting ssvm with Id: "+vmInstance.getId());
try {
if(_userVmMgr.start(vmInstance.getId(), eventId)==null)
{
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
} catch (StorageUnavailableException e) {
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
s_logger.warn(e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
} catch (InsufficientCapacityException e) {
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
s_logger.warn(e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
} catch (ConcurrentOperationException e) {
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
s_logger.warn(e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
} catch (ExecutionException e) {
s_logger.warn("There was an error starting the ssvm id: "+vmInstance.getId()+" on storage pool, cannot complete primary storage maintenance");
s_logger.warn(e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
}
}
}
}
//Restore config val for consoleproxy.restart to true
try {
_configMgr.updateConfiguration(userId, "consoleproxy.restart", "true");
} catch (InvalidParameterValueException e) {
s_logger.warn("Error changing consoleproxy.restart back to false at end of cancel maintenance:"+e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
} catch (InternalErrorException e) {
s_logger.warn("Error changing consoleproxy.restart back to false at end of cancel maintenance:"+e);
primaryStorage.setStatus(Status.ErrorInMaintenance);
_storagePoolDao.persist(primaryStorage);
return false;
}
//Change the storage state back to up
primaryStorage.setStatus(Status.Up);
_storagePoolDao.persist(primaryStorage);
return true;
}
private boolean sendToVmResidesOn(Command cmd) {
if ((_hypervisorType == Hypervisor.Type.KVM) &&
((cmd instanceof ManageSnapshotCommand) ||
(cmd instanceof BackupSnapshotCommand))) {
return true;
} else {
return false;
}
}
@Override
public <T extends VMInstanceVO> VolumeVO allocate(VolumeType type, DiskOfferingVO offering, String name, Long size, VMTemplateVO template, T vm, AccountVO account) {
VolumeVO vol = new VolumeVO(VolumeType.ROOT, name, vm.getDataCenterId(), account.getDomainId(), account.getId(), offering.getId(), size);
if (vm != null) {
vol.setInstanceId(vm.getId());
}
if (template != null && template.getFormat() != ImageFormat.ISO) {
vol.setTemplateId(template.getId());
}
vol = _volsDao.persist(vol);
return vol;
}
final protected DiskCharacteristics createDiskCharacteristics(VolumeVO volume, DiskOfferingVO offering) {
return new DiskCharacteristics(volume.getId(), volume.getVolumeType(), volume.getName(), offering.getId(), volume.getSize(), offering.getTagsArray(), offering.getUseLocalStorage(), offering.isRecreatable(), volume.getTemplateId());
}
final protected DiskCharacteristics createDiskCharacteristics(VolumeVO volume) {
DiskOfferingVO offering = _diskOfferingDao.findById(volume.getDiskOfferingId());
return createDiskCharacteristics(volume, offering);
}
@Override
public <T extends VMInstanceVO> void create(T vm) {
List<VolumeVO> vols = _volsDao.findByInstance(vm.getId());
assert vols.size() >= 1 : "Come on, what's with the zero volumes for " + vm;
for (VolumeVO vol : vols) {
DiskCharacteristics dskCh = createDiskCharacteristics(vol);
int retry = _retry;
while (--retry >= 0) {
}
}
/*
StoragePoolVO pool = null;
final HashSet<StoragePool> avoidPools = new HashSet<StoragePool>(avoids);
VolumeType volType = volume.getVolumeType();
VolumeTO created = null;
int retry = _retry;
while (--retry >= 0) {
created = null;
txn.start();
long podId = pod.getId();
pod = _podDao.lock(podId, true);
if (pod == null) {
txn.rollback();
volume.setStatus(AsyncInstanceCreateStatus.Failed);
volume.setDestroyed(true);
_volsDao.persist(volume);
throw new CloudRuntimeException("Unable to acquire lock on the pod " + podId);
}
pool = findStoragePool(dskCh, dc, pod, clusterId, offering, vm, template, avoidPools);
if (pool == null) {
txn.rollback();
break;
}
avoidPools.add(pool);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to create " + volume + " on " + pool);
}
volume.setPoolId(pool.getId());
_volsDao.persist(volume);
txn.commit();
CreateCommand cmd = null;
VMTemplateStoragePoolVO tmpltStoredOn = null;
if (volume.getVolumeType() == VolumeType.ROOT && Storage.ImageFormat.ISO != template.getFormat()) {
tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool);
if (tmpltStoredOn == null) {
continue;
}
cmd = new CreateCommand(volume, vm, dskCh, tmpltStoredOn.getLocalDownloadPath(), pool);
} else {
cmd = new CreateCommand(volume, vm, dskCh, pool, size);
}
Answer answer = sendToPool(pool, cmd);
if (answer != null && answer.getResult()) {
created = ((CreateAnswer)answer).getVolume();
break;
}
volume.setPoolId(null);
_volsDao.persist(volume);
s_logger.debug("Retrying the create because it failed on pool " + pool);
}
if (created == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to create a volume for " + volume);
}
volume.setStatus(AsyncInstanceCreateStatus.Failed);
volume.setDestroyed(true);
_volsDao.persist(volume);
return null;
}
volume.setStatus(AsyncInstanceCreateStatus.Created);
volume.setFolder(pool.getPath());
volume.setPath(created.getPath());
volume.setSize(created.getSize());
volume.setPoolType(pool.getPoolType());
volume.setPodId(pod.getId());
_volsDao.persist(volume);
return volume;
*/
}
} |
package io.spine.server;
import com.google.common.annotations.VisibleForTesting;
import io.spine.annotation.Internal;
import io.spine.base.EnvironmentType;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* A mutable value that may differ between {@linkplain EnvironmentType environment types}.
*
* <p>For example:
* <pre>
*
* {@literal EnvSetting<StorageFactory>} storageFactory = new EnvSetting<>();
* storageFactory.use(InMemoryStorageFactory.newInstance(), Production.class);
*
* assertThat(storageFactory.optionalValue(Production.class)).isPresent();
* assertThat(storageFactory.optionalValue(Tests.class)).isEmpty();
*
* </pre>
*
*
* <h1>Fallback</h1>
* <p>{@code EnvSetting} allows fallback value configuration:
* <pre>
*
* // Assuming the environment is `Tests`.
* StorageFactory fallbackStorageFactory = createStorageFactory();
* {@literal EnvSetting<StorageFactory>} setting =
* new EnvSetting<>(Tests.class, () -> fallbackStorageFactory);
*
* // Despite having never configured the `StorageFactory` for `Tests`, we still get the
* // fallback value.
* assertThat(setting.optionalValue()).isPresent();
* assertThat(setting.value()).isSameInstanceAs(fallbackStorageFactory);
* </pre>
*
* <p>Fallback values are calculated once, after it they are {@linkplain #use(Object, Class)
* configured} internally.
*
* <pre>
*
* // This `Supplier` is calculated only once.
* {@literal Supplier<StorageFactory>} fallbackStorage = InMemoryStorageFactory::newInstance;
*
* {@literal EnvSetting<StorageFactory>} setting = new EnvSetting<>(Tests.class, fallbackStorage);
*
* // `Supplier` is calculated and cached.
* StorageFactory storageFactory = setting.value();
*
* // Fallback value is taken from cache.
* StorageFactory theSameFactory = setting.value();
*
* </pre>
*
* <p>{@code EnvSetting} values do not determine the environment themselves: it's up to the
* caller to ask for the appropriate one.
*
* <p>This implementation does <b>not</b> perform any synchronization, thus, if different threads
* {@linkplain #use(Object, Class) configure} and {@linkplain #value(Class) read the value},
* no effort is made to ensure any consistency.
*
* @param <V>
* the type of value
*/
@Internal
public final class EnvSetting<V> {
private final Map<Class<? extends EnvironmentType>, V> environmentValues =
new HashMap<>();
private final Map<Class<? extends EnvironmentType>, Supplier<V>> fallbacks =
new HashMap<>();
/**
* Creates a new instance without any fallback configuration.
*/
public EnvSetting() {
}
/**
* Creates a new instance, configuring the specified function to act as a fallback value.
*
* <p>If a value was not configured for the type {@code type}, and an attempt to access it
* with {@code setting.value(type)} was made, {@code fallback} is calculated, cached and
* returned.
*/
public EnvSetting(Class<? extends EnvironmentType> type, Supplier<V> fallback) {
this.fallbacks.put(type, fallback);
}
/**
* Returns the value for the specified environment type if it was set, an
* empty {@code Optional} otherwise.
*/
Optional<V> optionalValue(Class<? extends EnvironmentType> type) {
Optional<V> result = valueFor(type);
return result;
}
/**
* Runs the specified operations against the value corresponding to the specified environment
* type if it's present, does nothing otherwise.
*
* <p>If you wish to run an operation that doesn't throw, use {@code
* value(type).ifPresent(operation)}.
*
* @param operation
* operation to run
*/
void ifPresentForEnvironment(Class<? extends EnvironmentType> type,
SettingOperation<V> operation) throws Exception {
Optional<V> value = valueFor(type);
if (value.isPresent()) {
operation.accept(value.get());
}
}
/**
* If the value corresponding to the specified environment type is set, just returns it.
*
* <p>If it is not set, runs the specified supplier, configures and returns the supplied value.
*/
V value(Class<? extends EnvironmentType> type) {
checkNotNull(type);
Optional<V> result = valueFor(type);
return result.orElseThrow(
() -> newIllegalStateException("Env setting for environment `%s` is unset.",
type));
}
/**
* Changes the value for all environments types, such that all of them return
* {@code Optional.empty()} when {@linkplain #value(Class) accessing the value}.
*
* <p>Fallback settings, however, remain unchanged.
*/
@VisibleForTesting
void reset() {
environmentValues.clear();
}
/**
* Sets the specified value for the specified environment type.
*
* @param value
* value to assign to one of environments
*/
void use(V value, Class<? extends EnvironmentType> type) {
checkNotNull(value);
checkNotNull(type);
this.environmentValues.put(type, value);
}
private Optional<V> valueFor(Class<? extends EnvironmentType> type) {
checkNotNull(type);
V result = this.environmentValues.get(type);
if (result == null) {
Supplier<V> resultSupplier = this.fallbacks.get(type);
if (resultSupplier == null) {
return Optional.empty();
}
V newValue = resultSupplier.get();
checkNotNull(newValue);
this.use(newValue, type);
return Optional.of(newValue);
}
return Optional.of(result);
}
/**
* Represents an operation over the setting that returns no result and may finish with an error.
*
* @param <V>
* the type of setting to perform the operation over
*/
interface SettingOperation<V> {
/** Performs this operation on the specified value. */
void accept(V value) throws Exception;
}
} |
package texteditor;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class Main {
public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUI();
}
});
}
} |
package org.subethamail.smtp.server;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.common.ThreadModel;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.integration.jmx.IoServiceManager;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.MessageHandlerFactory;
import org.subethamail.smtp.MessageListener;
import org.subethamail.smtp.Version;
/**
* Main SMTPServer class. Construct this object, set the
* hostName, port, and bind address if you wish to override the
* defaults, and call start().
*
* This class starts opens a ServerSocket and creates a new
* instance of the ConnectionHandler class when a new connection
* comes in. The ConnectionHandler then parses the incoming SMTP
* stream and hands off the processing to the CommandHandler which
* will execute the appropriate SMTP command class.
*
* This class also manages a watchdog thread which will timeout
* stale connections.
*
* There are two ways of using this server. The first is to
* construct with a MessageHandlerFactory. This provides the
* lowest-level and most flexible access. The second way is
* to construct with a collection of MessageListeners. This
* is a higher, and sometimes more convenient level of abstraction.
*
* In neither case is the SMTP server (this library) responsible
* for deciding what recipients to accept or what to do with the
* incoming data. That is left to you.
*
* @author Jon Stevens
* @author Ian McFarland <ian@neo.com>
* @author Jeff Schnitzer
*
* This file has been used and differs from the original
* by the use of MINA NIO framework.
*
* @author De Oliveira Edouard <doe_wanted@yahoo.fr>
*/
@SuppressWarnings("serial")
public class SMTPServer
{
private static Logger log = LoggerFactory.getLogger(SMTPServer.class);
public final static String CODEPAGE = "UTF-8";
/**
* default to all interfaces
*/
private InetAddress bindAddress = null;
/**
* default to 25
*/
private int port = 25;
/**
* defaults to a lookup of the local address
*/
private String hostName;
/**
* defaults to 5000
*/
private int backlog = 5000;
private MessageHandlerFactory messageHandlerFactory;
private CommandHandler commandHandler;
private SocketAcceptor acceptor;
private ExecutorService executor;
private SocketAcceptorConfig config;
private IoServiceManager serviceManager;
private ObjectName jmxName;
private ConnectionHandler handler;
private boolean go = false;
/**
* set a hard limit on the maximum number of connections this server will accept
* once we reach this limit, the server will gracefully reject new connections.
* Default is 1000.
*/
private int maxConnections = 1000;
/**
* The timeout for waiting for data on a connection is one minute: 1000 * 60 * 1
*/
private int connectionTimeout = 1000 * 60 * 1;
/**
* The maximal number of recipients that this server accepts per message delivery request.
*/
private int maxRecipients = 1000;
/**
* 4 megs by default. The server will buffer incoming messages to disk
* when they hit this limit in the DATA received.
*/
private final static int DEFAULT_DATA_DEFERRED_SIZE = 1024*1024*4;
private int dataDeferredSize = DEFAULT_DATA_DEFERRED_SIZE;
/**
* The primary constructor.
*/
public SMTPServer(MessageHandlerFactory handlerFactory)
{
this.messageHandlerFactory = handlerFactory;
try
{
this.hostName = InetAddress.getLocalHost().getCanonicalHostName();
}
catch (UnknownHostException e)
{
this.hostName = "localhost";
}
this.commandHandler = new CommandHandler();
initService();
}
/**
* A convenience constructor that splits the smtp data among multiple listeners
* (and multiple recipients).
*/
public SMTPServer(Collection<MessageListener> listeners)
{
this(new MessageListenerAdapter(listeners));
}
/**
* Starts the JMX service with a polling interval default of 1000ms.
*
* @throws InstanceAlreadyExistsException
* @throws MBeanRegistrationException
* @throws NotCompliantMBeanException
*/
public void startJMXService()
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
startJMXService(1000);
}
/**
* Start the JMX service.
*
* @param pollingInterval
* @throws InstanceAlreadyExistsException
* @throws MBeanRegistrationException
* @throws NotCompliantMBeanException
*/
public void startJMXService(int pollingInterval)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
serviceManager.startCollectingStats(pollingInterval);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(serviceManager, jmxName);
}
/**
* Stop the JMX service.
*
* @throws InstanceNotFoundException
* @throws MBeanRegistrationException
*/
public void stopJMXService() throws InstanceNotFoundException, MBeanRegistrationException
{
serviceManager.stopCollectingStats();
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.unregisterMBean(jmxName);
}
/**
* Initializes the runtime service.
*/
private void initService()
{
try
{
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptor =
new SocketAcceptor(Runtime.getRuntime().availableProcessors() + 1, Executors.newCachedThreadPool());
// JMX instrumentation
serviceManager = new IoServiceManager(acceptor);
jmxName = new ObjectName("wizer.mina.server:type=IoServiceManager");
config = new SocketAcceptorConfig();
config.setThreadModel(ThreadModel.MANUAL);
((SocketAcceptorConfig)config).setReuseAddress(true);
DefaultIoFilterChainBuilder chain = config.getFilterChain();
if (log.isTraceEnabled())
chain.addLast("logger", new LoggingFilter());
chain.addLast("codec", new ProtocolCodecFilter(new SMTPCodecFactory(Charset.forName(CODEPAGE))));
executor = Executors.newCachedThreadPool(new ThreadFactory() {
int sequence;
public Thread newThread(Runnable r)
{
sequence += 1;
return new Thread(r, "SubEthaSMTP Thread "+sequence);
}
});
chain.addLast("threadPool", new ExecutorFilter(executor));
handler = new ConnectionHandler(this);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
/**
* Call this method to get things rolling after instantiating the
* SMTPServer.
*/
public synchronized void start()
{
if (go == true)
throw new RuntimeException("SMTPServer is already started.");
InetSocketAddress isa;
if (this.bindAddress == null)
{
isa = new InetSocketAddress(this.port);
}
else
{
isa = new InetSocketAddress(this.bindAddress, this.port);
}
((SocketAcceptorConfig)config).setBacklog(getBacklog());
try
{
acceptor.bind(isa, handler, config);
go = true;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/**
* Shut things down gracefully.
*/
public synchronized void stop()
{
try
{
log.info("SMTP Server socket shut down.");
acceptor.unbindAll();
}
finally
{
go = false;
}
}
/** @return the host name that will be reported to SMTP clients */
public String getHostName()
{
if (this.hostName == null)
return "localhost";
else
return this.hostName;
}
/** The host name that will be reported to SMTP clients */
public void setHostName(String hostName)
{
this.hostName = hostName;
}
/** null means all interfaces */
public InetAddress getBindAddress()
{
return this.bindAddress;
}
/**
* null means all interfaces
*/
public void setBindAddress(InetAddress bindAddress)
{
this.bindAddress = bindAddress;
}
/**
* get the port the server is running on.
*/
public int getPort()
{
return this.port;
}
/**
* set the port the server is running on.
* @param port
*/
public void setPort(int port)
{
this.port = port;
}
/**
* Is the server running after start() has been called?
*/
public synchronized boolean isRunning()
{
return this.go;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*
* @return the backlog
*/
public int getBacklog()
{
return this.backlog;
}
/**
* The backlog is the Socket backlog.
*
* The backlog argument must be a positive value greater than 0.
* If the value passed if equal or less than 0, then the default value will be assumed.
*/
public void setBacklog(int backlog)
{
this.backlog = backlog;
}
/**
* The name of the server software.
*/
public String getName()
{
return "SubEthaSMTP";
}
/**
* The name + version of the server software.
*/
public String getNameVersion()
{
return getName() + " " + Version.getSpecification();
}
/**
* All smtp data is eventually routed through the handlers.
*/
public MessageHandlerFactory getMessageHandlerFactory()
{
return this.messageHandlerFactory;
}
/**
* The CommandHandler manages handling the SMTP commands
* such as QUIT, MAIL, RCPT, DATA, etc.
*
* @return An instance of CommandHandler
*/
public CommandHandler getCommandHandler()
{
return this.commandHandler;
}
/**
* Number of connections in the handler.
*/
public int getNumberOfConnections()
{
return handler.getNumberOfConnections();
}
/**
* Are we over the maximum amount of connections ?
*/
public boolean hasTooManyConnections()
{
return (this.maxConnections > -1 &&
getNumberOfConnections() >= this.maxConnections);
}
/**
* What is the maximum amount of connections?
*/
public int getMaxConnections()
{
return this.maxConnections;
}
/**
* Set's the maximum number of connections this server instance will
* accept. If set to -1 then limit is ignored.
*
* @param maxConnections
*/
public void setMaxConnections(int maxConnections)
{
this.maxConnections = maxConnections;
}
/**
* What is the connection timeout?
*/
public int getConnectionTimeout()
{
return this.connectionTimeout;
}
/**
* Set the connection timeout.
*/
public void setConnectionTimeout(int connectionTimeout)
{
this.connectionTimeout = connectionTimeout;
}
/**
* What is the maximum number of recipients for a single message ?
*/
public int getMaxRecipients()
{
return this.maxRecipients;
}
/**
* Set the maximum number of recipients for a single message.
* If set to -1 then limit is ignored.
*/
public void setMaxRecipients(int maxRecipients)
{
this.maxRecipients = maxRecipients;
}
/**
* Get the maximum size in bytes of a single message before it is
* dumped to a temporary file.
*/
public int getDataDeferredSize()
{
return dataDeferredSize;
}
/**
* Set the maximum size in bytes of a single message before it is
* dumped to a temporary file. Argument must be a positive power
* of two in order to follow the expanding algorithm of
* {@link org.apache.mina.common.ByteBuffer} to prevent unnecessary
* memory consumption.
*/
public void setDataDeferredSize(int dataDeferredSize)
{
if (isPowerOfTwo(dataDeferredSize))
this.dataDeferredSize = dataDeferredSize;
else
throw new IllegalArgumentException(
"Argument dataDeferredSize must be a positive power of two");
}
/**
* Demonstration : if x is a power of 2, it can't share any bit with x-1. So
* x & (x-1) should be equal to 0. To get rid of negative values, we check
* that x is higher than 1 (0 and 1 being of course unacceptable values
* for a buffer length).
*
* @param x the number to test
* @return true if x is a power of two
*/
protected boolean isPowerOfTwo(int x)
{
return (x > 1) && (x & (x-1)) == 0;
}
} |
//package org.RDKit;
import org.junit.*;
import static org.junit.Assert.*;
import org.RDKit.*;
public class WrapperTests {
private ROMol mol1;
@Before public void setUp() {
String smiles="c1ccccc1";
mol1 = RDKFuncs.MolFromSmiles(smiles);
}
@Test public void testBasics() {
assertTrue(mol1.getNumAtoms()==6);
assertTrue(mol1.getNumBonds()==6);
}
@Test public void testAtoms() {
assertTrue(mol1.getAtomWithIdx(0).getAtomicNum()==6);
assertFalse(mol1.hasAtomBookmark(1));
mol1.setAtomBookmark(mol1.getAtomWithIdx(0),1);
assertTrue(mol1.hasAtomBookmark(1));
}
@Test public void testBonds() {
assertTrue(mol1.getBondWithIdx(0).getBondType()==Bond.BondType.AROMATIC);
}
@Test public void testSmilesWrite() {
String smi=RDKFuncs.MolToSmiles(mol1);
assertEquals(smi,"c1ccccc1",smi);
}
@Test public void testReactionBasics() {
ChemicalReaction rxn;
rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]");
assertTrue(rxn.getNumReactantTemplates()==2);
assertTrue(rxn.getNumProductTemplates()==1);
ROMol r1,r2;
r1=RDKFuncs.MolFromSmiles("CC(=O)O");
r2=RDKFuncs.MolFromSmiles("ClCN");
assertTrue(r1.getNumAtoms()==4);
assertTrue(r2.getNumAtoms()==3);
ROMol_Vect rs= new ROMol_Vect(2);
rs.set(0,r1);
rs.set(1,r2);
ROMol_Vect_Vect ps;
ps=rxn.runReactants(rs);
assertFalse(ps.isEmpty());
assertTrue(ps.size()==1);
assertFalse(ps.get(0).isEmpty());
assertTrue(ps.get(0).size()==1);
assertTrue(r1.getNumAtoms()==4);
assertTrue(r2.getNumAtoms()==3);
assertTrue(ps.get(0).get(0).getNumAtoms()==6);
}
@Test public void testSubstruct1() {
ROMol p;
Match_Vect mv;
p = RDKFuncs.MolFromSmarts("c");
assertTrue(mol1.hasSubstructMatch(p));
mv=mol1.getSubstructMatch(p);
assertTrue(mv.size()==1);
assertTrue(mv.get(0).getFirst()==0);
assertTrue(mv.get(0).getSecond()==0);
}
@Test public void testSubstruct2() {
ROMol p;
Match_Vect mv;
p = RDKFuncs.MolFromSmarts("C");
assertFalse(mol1.hasSubstructMatch(p));
mv=mol1.getSubstructMatch(p);
assertTrue(mv.size()==0);
}
@Test public void testSubstruct3() {
ROMol p;
Match_Vect mv;
ROMol m2;
m2 = RDKFuncs.MolFromSmiles("NC(=O)CC");
p = RDKFuncs.MolFromSmarts("CN");
mv=m2.getSubstructMatch(p);
assertTrue(mv.size()==2);
assertTrue(mv.get(0).getFirst()==0);
assertTrue(mv.get(0).getSecond()==1);
assertTrue(mv.get(1).getFirst()==1);
assertTrue(mv.get(1).getSecond()==0);
}
@Test public void testSubstruct4() {
ROMol p;
Match_Vect_Vect mvv;
ROMol m2;
m2 = RDKFuncs.MolFromSmiles("NC(=O)CC");
p = RDKFuncs.MolFromSmarts("CN");
mvv=m2.getSubstructMatches(p);
assertTrue(mvv.size()==1);
assertTrue(mvv.get(0).size()==2);
assertTrue(mvv.get(0).get(0).getFirst()==0);
assertTrue(mvv.get(0).get(0).getSecond()==1);
assertTrue(mvv.get(0).get(1).getFirst()==1);
assertTrue(mvv.get(0).get(1).getSecond()==0);
}
@Test public void testSubstruct5() {
ROMol p;
Match_Vect_Vect mvv;
ROMol m2;
m2 = RDKFuncs.MolFromSmiles("NC(=O)NCC");
p = RDKFuncs.MolFromSmarts("[$(C=O)]N");
mvv=m2.getSubstructMatches(p);
assertTrue(mvv.size()==2);
assertTrue(mvv.get(0).size()==2);
assertTrue(mvv.get(0).get(0).getFirst()==0);
assertTrue(mvv.get(0).get(0).getSecond()==1);
assertTrue(mvv.get(0).get(1).getFirst()==1);
assertTrue(mvv.get(0).get(1).getSecond()==0);
assertTrue(mvv.get(1).size()==2);
assertTrue(mvv.get(1).get(0).getFirst()==0);
assertTrue(mvv.get(1).get(0).getSecond()==1);
assertTrue(mvv.get(1).get(1).getFirst()==1);
assertTrue(mvv.get(1).get(1).getSecond()==3);
}
@Test public void testFingerprints1() {
ROMol m1,m2;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
ExplicitBitVect fp1,fp2;
fp1=RDKFuncs.RDKFingerprintMol(m1);
fp2=RDKFuncs.RDKFingerprintMol(m1);
assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)==1.0);
fp2=RDKFuncs.RDKFingerprintMol(m2);
assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)<1.0);
assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)>0.0);
}
@Test public void testFingerprints2() {
ROMol m1,m2;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
SparseIntVectu32 fp1,fp2;
fp1=RDKFuncs.getMorganFingerprint(m1,2);
fp2=RDKFuncs.getMorganFingerprint(m1,2);
assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)==1.0);
fp2=RDKFuncs.getMorganFingerprint(m2,2);
assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)<1.0);
assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)>0.0);
UInt_Pair_Vect v1=fp1.getNonzero();
assertTrue(v1.size()>0);
UInt_Pair_Vect v2=fp2.getNonzero();
assertTrue(v2.size()>0);
assertTrue(v2.size()>v1.size());
}
@Test public void testFingerprints3() {
ROMol m1,m2;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
SparseIntVecti32 fp1,fp2;
fp1=RDKFuncs.getAtomPairFingerprint(m1,2,6);
fp2=RDKFuncs.getAtomPairFingerprint(m1,2,6);
assertTrue(RDKFuncs.DiceSimilaritySIVi32(fp1,fp2)==1.0);
fp2=RDKFuncs.getAtomPairFingerprint(m2,2,6);
assertEquals(RDKFuncs.DiceSimilaritySIVi32(fp1,fp2),0.66667,.0001);
}
@Test public void testFingerprints4() {
ROMol m1,m2;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
SparseIntVecti64 fp1,fp2;
fp1=RDKFuncs.getTopologicalTorsionFingerprint(m1);
fp2=RDKFuncs.getTopologicalTorsionFingerprint(m1);
assertTrue(RDKFuncs.DiceSimilaritySIVi64(fp1,fp2)==1.0);
fp2=RDKFuncs.getTopologicalTorsionFingerprint(m2);
assertEquals(RDKFuncs.DiceSimilaritySIVi64(fp1,fp2),0.3333,.0001);
}
@Test public void testErrorHandling() {
ROMol m1;
m1 = RDKFuncs.MolFromSmiles("C1CC");
assertTrue(m1==null);
m1 = RDKFuncs.MolFromSmiles("c1cc1");
assertTrue(m1==null);
System.err.println("ok!");
ChemicalReaction rxn=RDKFuncs.ReactionFromSmarts("OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]");
assertTrue(rxn==null);
}
@Test public void testPickling() {
Int_Vect pkl=RDKFuncs.MolToBinary(mol1);
ROMol m1 = RDKFuncs.MolFromBinary(pkl);
assertTrue(m1.getNumAtoms()==6);
assertTrue(m1.getNumBonds()==6);
}
@Test public void testReactionPickling() {
ChemicalReaction rxn;
rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]");
assertTrue(rxn.getNumReactantTemplates()==2);
assertTrue(rxn.getNumProductTemplates()==1);
Int_Vect pkl=RDKFuncs.RxnToBinary(rxn);
ChemicalReaction rxn2=RDKFuncs.RxnFromBinary(pkl);
assertTrue(rxn2.getNumReactantTemplates()==2);
assertTrue(rxn2.getNumProductTemplates()==1);
}
@Test public void testReactionToSmarts() {
ChemicalReaction rxn;
rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]");
assertTrue(rxn.getNumReactantTemplates()==2);
assertTrue(rxn.getNumProductTemplates()==1);
String sma=RDKFuncs.ReactionToSmarts(rxn);
ChemicalReaction rxn2;
rxn2=RDKFuncs.ReactionFromSmarts(sma);
assertTrue(rxn2.getNumReactantTemplates()==2);
assertTrue(rxn2.getNumProductTemplates()==1);
}
@Test public void testSupplier() {
SDMolSupplier suppl=new SDMolSupplier("./test_data/NCI_aids_few.sdf");
int i=0;
while(! suppl.atEnd()){
ROMol m1 = suppl.next();
if(m1==null) continue;
assertTrue(m1.hasProp("NSC"));
assertFalse(m1.hasProp("monkey"));
if(i==0){
assertEquals(m1.getProp("_Name"),"128");
assertEquals(m1.getProp("CAS_RN"),"5395-10-8");
}
String smi1=RDKFuncs.MolToSmiles(m1);
String txt=suppl.getItemText(i);
i++;
ROMol m2 = RDKFuncs.MolFromMolBlock(txt);
assertFalse(m2==null);
String smi2=RDKFuncs.MolToSmiles(m2);
assertEquals(smi1,smi2);
}
}
@Test public void testDescriptors1() {
ROMol m1,m2,m3;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
m3 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1CC(=O)O");
long tmp;
tmp=RDKFuncs.calcNumHBA(m1);
assertEquals(tmp,0);
tmp=RDKFuncs.calcNumHBA(m2);
assertEquals(tmp,1);
tmp=RDKFuncs.calcNumHBA(m3);
assertEquals(tmp,1);
tmp=RDKFuncs.calcNumHBD(m1);
assertEquals(tmp,0);
tmp=RDKFuncs.calcNumHBD(m2);
assertEquals(tmp,0);
tmp=RDKFuncs.calcNumHBD(m3);
assertEquals(tmp,1);
tmp=RDKFuncs.calcLipinskiHBA(m1);
assertEquals(tmp,0);
tmp=RDKFuncs.calcLipinskiHBA(m2);
assertEquals(tmp,1);
tmp=RDKFuncs.calcLipinskiHBA(m3);
assertEquals(tmp,2);
tmp=RDKFuncs.calcLipinskiHBD(m1);
assertEquals(tmp,0);
tmp=RDKFuncs.calcLipinskiHBD(m2);
assertEquals(tmp,0);
tmp=RDKFuncs.calcLipinskiHBD(m3);
assertEquals(tmp,1);
}
@Test public void testDescriptors2() {
ROMol m1,m2;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
double tmp;
tmp=RDKFuncs.calcMolLogP(m1);
assertEquals(tmp,1.687,0.001);
tmp=RDKFuncs.calcMolLogP(m2);
assertEquals(tmp,1.082,0.001);
tmp=RDKFuncs.calcMolMR(m1);
assertEquals(tmp,26.442,0.001);
tmp=RDKFuncs.calcMolMR(m2);
assertEquals(tmp,24.237,0.001);
}
@Test public void testDescriptors3() {
ROMol m1,m2,m3;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1");
m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1");
m3 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1CC(=O)O");
double tmp;
tmp=RDKFuncs.calcTPSA(m1);
assertEquals(tmp,0,0.01);
tmp=RDKFuncs.calcTPSA(m2);
assertEquals(tmp,12.89,0.01);
tmp=RDKFuncs.calcTPSA(m3);
assertEquals(tmp,37.30,0.01);
}
/*@Test*/ public void testMemory2() {
ChemicalReaction rxn;
rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]");
assertTrue(rxn.getNumReactantTemplates()==2);
assertTrue(rxn.getNumProductTemplates()==1);
ROMol r1,r2;
r1=RDKFuncs.MolFromSmiles("CC(=O)O");
r2=RDKFuncs.MolFromSmiles("ClCN");
assertTrue(r1.getNumAtoms()==4);
assertTrue(r2.getNumAtoms()==3);
for(int i=0;i<1000000;i++){
ROMol_Vect rs= new ROMol_Vect(2);
rs.set(0,r1);
rs.set(1,r2);
ROMol_Vect_Vect ps;
ps=rxn.runReactants(rs);
if((i%1000)==0){
System.err.println("done: "+i);
}
ps.delete();
}
}
/*@Test*/ public void testMemory3() {
ROMol m1;
m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1C2CCC(C(=O)OCCC)CC2");
for(int i=0;i<1000000;i++){
/*SparseIntVecti64 fp1;
fp1=RDKFuncs.getTopologicalTorsionFingerprint(m1);*/
SparseIntVectu32 fp1;
fp1=RDKFuncs.getMorganFingerprint(m1,2);
if((i%1000)==0){
System.err.println("done: "+i);
}
fp1.delete();
}
}
static {
try {
System.loadLibrary("RDKFuncs");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. Make sure that libRDKFuncs.so is somewhere in your LD_LIBRARY_PATH.\n" + e);
System.exit(1);
}
}
public static void main(String args[]) {
org.junit.runner.JUnitCore.main("WrapperTests");
}
} |
package theschoolproject;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.UIManager;
public class SchoolProjectForm extends javax.swing.JFrame {
//Global Variables
Properties properties = new Properties();
public SchoolProjectForm() {
initComponents();
try {
properties.load(new FileInputStream("src/resources/settings.properties"));
} catch (IOException e) {
e.printStackTrace();
}
this.setSize(855, 700);
this.setResizable(false);
this.setTitle(properties.getProperty("Game_Name"));
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSpinner1 = new javax.swing.JSpinner();
gamePanel1 = new theschoolproject.GamePanel();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
exitMenuItem = new javax.swing.JMenuItem();
jMenu1 = new javax.swing.JMenu();
documentationBtn = new javax.swing.JMenuItem();
aboutbtn = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(910, 710));
setResizable(false);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
getContentPane().setLayout(null);
javax.swing.GroupLayout gamePanel1Layout = new javax.swing.GroupLayout(gamePanel1);
gamePanel1.setLayout(gamePanel1Layout);
gamePanel1Layout.setHorizontalGroup(
gamePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 850, Short.MAX_VALUE)
);
gamePanel1Layout.setVerticalGroup(
gamePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 650, Short.MAX_VALUE)
);
getContentPane().add(gamePanel1);
gamePanel1.setBounds(0, 0, 850, 650);
fileMenu.setMnemonic('f');
fileMenu.setText("File");
exitMenuItem.setMnemonic('x');
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
jMenu1.setText("Help");
documentationBtn.setText("Documentation");
documentationBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
documentationBtnActionPerformed(evt);
}
});
jMenu1.add(documentationBtn);
aboutbtn.setText("About");
aboutbtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutbtnActionPerformed(evt);
}
});
jMenu1.add(aboutbtn);
menuBar.add(jMenu1);
setJMenuBar(menuBar);
pack();
}// </editor-fold>//GEN-END:initComponents
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
}//GEN-LAST:event_formComponentResized
private void aboutbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutbtnActionPerformed
AboutForm af = new AboutForm();
af.show(true);
}//GEN-LAST:event_aboutbtnActionPerformed
private void documentationBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_documentationBtnActionPerformed
UsefulSnippets.openWebpage("https://github.com/xNovax/The_School_Project/wiki");
}//GEN-LAST:event_documentationBtnActionPerformed
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SchoolProjectForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SchoolProjectForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SchoolProjectForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SchoolProjectForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SchoolProjectForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutbtn;
private javax.swing.JMenuItem documentationBtn;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenu fileMenu;
private theschoolproject.GamePanel gamePanel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
} |
package group5.trackerexpress;
import java.io.IOException;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
* Displays the list of claims made by the current user.
*
* @author Peter Crinklaw, Randy Hu, Parash Rahman, Jesse Emery, Sean Baergen, Rishi Barnwal
* @version Part 4
*/
public class MyClaimsFragment extends Fragment implements TView {
/** The ListView of claims */
private ListView lv_claim_list;
/** The button to Add Claim */
private Button b_add_claim;
/** The textview that shows if the internet is disconnected **/
private TextView tv_has_internet;
/** The menu items to hide in the options menu for clicked claims. */
private static final int[] submittedOrApprovedHiddenItems = {R.id.op_edit_claim, R.id.op_submit_claim, R.id.op_delete_claim, R.id.op_add_expense};
/** Empty fragment constructor. */
public MyClaimsFragment() {
}
/** onCreateView
** @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
**/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_claims,
container, false);
// Fragment's views
lv_claim_list = (ListView) rootView.findViewById(R.id.lv_my_claims);
lv_claim_list.setItemsCanFocus(true);
b_add_claim = (Button) rootView.findViewById(R.id.b_add_claim);
tv_has_internet = (TextView) rootView.findViewById(R.id.tv_internet_status);
Controller.updateClaimsFromInternet(getActivity());
update(null);
Controller.getClaimList(getActivity()).addView(this);
NetworkStateReceiver.addView(this);
b_add_claim.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent( getActivity(), EditClaimActivity.class );
intent.putExtra("isNewClaim", true);
startActivity(intent);
}
});
lv_claim_list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> a, View v,
final int position, long arg3) {
// TODO Auto-generated method stub
final Claim clickedOnClaim = (Claim) lv_claim_list.getAdapter().getItem(position);
PopupMenu popup = new PopupMenu(getActivity(), v);
popup.getMenuInflater().inflate(R.menu.my_claims_popup, popup.getMenu());
onPrepareOptionsMenu(popup, clickedOnClaim);
// Popup menu item click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent;
switch(item.getItemId()){
case R.id.op_delete_claim:
Controller.getClaimList(getActivity()).deleteClaim(getActivity(), clickedOnClaim.getUuid());
break;
case R.id.op_edit_tags:
case R.id.op_edit_claim:
intent = new Intent( getActivity(), EditClaimActivity.class );
intent.putExtra( "isNewClaim", false );
intent.putExtra("claimUUID", clickedOnClaim.getUuid());
startActivity(intent);
break;
case R.id.op_view_claim:
intent = new Intent( getActivity(), ClaimInfoActivity.class );
intent.putExtra( "claimUUID", clickedOnClaim.getUuid() );
intent.putExtra( "fromMyClaims", true);
startActivity(intent);
break;
case R.id.op_submit_claim:
if ( clickedOnClaim.isIncomplete() ){
Toast.makeText(getActivity(), "Can't submit, claim is incomplete.", Toast.LENGTH_SHORT). show();
} else {
//FIXME: Handle connectivity error
AlertDialog.Builder incBuilder = new AlertDialog.Builder(getActivity());
incBuilder.setMessage("Warning");
incBuilder.setMessage("You are submitting a claim with incomplete expenses. Do you wish to continue?");
incBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int old_status = clickedOnClaim.getStatus();
try {
clickedOnClaim.setStatus(getActivity(), Claim.SUBMITTED);
new ElasticSearchEngine().submitClaim(getActivity(), clickedOnClaim);
} catch (IOException e) {
clickedOnClaim.setStatus(getActivity(), old_status);
throw new RuntimeException();
}
Toast.makeText(getActivity(), "Submitting", Toast.LENGTH_LONG).show();
}
});
incBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
incBuilder.show();
}
break;
case R.id.op_add_expense:
Expense exp = new Expense();
clickedOnClaim.getExpenseList().addExpense(getActivity(), exp);
intent = new Intent( getActivity(), EditExpenseActivity.class );
intent.putExtra("claimUUID", clickedOnClaim.getUuid());
intent.putExtra("expenseUUID", exp.getUuid());
startActivity(intent);
default: break;
}
return true;
}
});
popup.show();
}
});
return rootView;
}
/**
* Prepares option menu for when a claim is selected.
*
* @param popup the Popup Menu in question
* @param c the Claim in question
*/
public void onPrepareOptionsMenu( PopupMenu popup, Claim c ){
switch(c.getStatus()){
case Claim.APPROVED:
case Claim.SUBMITTED:
for( int id : submittedOrApprovedHiddenItems ){
popup.getMenu().findItem(id).setVisible(false);
}
popup.getMenu().findItem(R.id.op_edit_tags).setVisible(true);
break;
default:
popup.getMenu().findItem(R.id.op_edit_tags).setVisible(false);
break;
}
}
/**
* Update method updates the listview
*
* @param model for when a model calls it
**/
@Override
public void update(TModel model) {
// TODO Auto-generated method stub
MainClaimListAdapter adapter;
Claim[] listOfClaims = ClaimList.getFilteredClaims(getActivity());
adapter= new MainClaimListAdapter(getActivity(), listOfClaims);
lv_claim_list.setAdapter(adapter);
// Update internet status
if ( Controller.isInternetConnected(getActivity()) ){
tv_has_internet.setVisibility(View.GONE);
} else {
tv_has_internet.setVisibility(View.VISIBLE);
}
}
} |
package com.braintreepayments.api;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import org.json.JSONException;
import org.json.JSONObject;
public class VenmoClient {
static final String VENMO_PACKAGE_NAME = "com.venmo";
static final String APP_SWITCH_ACTIVITY = "controller.SetupMerchantActivity";
static final String META_KEY = "_meta";
static final String EXTRA_MERCHANT_ID = "com.braintreepayments.api.MERCHANT_ID";
static final String EXTRA_ACCESS_TOKEN = "com.braintreepayments.api.ACCESS_TOKEN";
static final String EXTRA_ENVIRONMENT = "com.braintreepayments.api.ENVIRONMENT";
static final String EXTRA_BRAINTREE_DATA = "com.braintreepayments.api.EXTRA_BRAINTREE_DATA";
static final String EXTRA_PAYMENT_METHOD_NONCE = "com.braintreepayments.api.EXTRA_PAYMENT_METHOD_NONCE";
static final String EXTRA_USERNAME = "com.braintreepayments.api.EXTRA_USER_NAME";
static final String EXTRA_RESOURCE_ID = "com.braintreepayments.api.EXTRA_RESOURCE_ID";
private final BraintreeClient braintreeClient;
private final TokenizationClient tokenizationClient;
private final VenmoSharedPrefsWriter sharedPrefsWriter;
private final DeviceInspector deviceInspector;
public VenmoClient(BraintreeClient braintreeClient) {
this(braintreeClient, new TokenizationClient(braintreeClient), new VenmoSharedPrefsWriter(), new DeviceInspector());
}
@VisibleForTesting
VenmoClient(BraintreeClient braintreeClient, TokenizationClient tokenizationClient, VenmoSharedPrefsWriter sharedPrefsWriter, DeviceInspector deviceInspector) {
this.braintreeClient = braintreeClient;
this.tokenizationClient = tokenizationClient;
this.sharedPrefsWriter = sharedPrefsWriter;
this.deviceInspector = deviceInspector;
}
/**
* Launches an Android Intent pointing to the Venmo app on the Google Play Store
*
* @param activity used to open the Venmo's Google Play Store
*/
public void showVenmoInGooglePlayStore(FragmentActivity activity) {
braintreeClient.sendAnalyticsEvent("android.pay-with-venmo.app-store.invoked");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
"https://play.google.com/store/apps/details?id=" + VENMO_PACKAGE_NAME));
activity.startActivity(intent);
}
/**
* Start the Pay With Venmo flow. This will app switch to the Venmo app.
* <p>
* If the Venmo app is not available, {@link AppSwitchNotAvailableException} will be sent to {@link VenmoTokenizeAccountCallback#onResult(Exception)}
*
* @param activity Android FragmentActivity
* @param request {@link VenmoRequest}
* @param callback {@link VenmoTokenizeAccountCallback}
*/
public void tokenizeVenmoAccount(final FragmentActivity activity, final VenmoRequest request, final VenmoTokenizeAccountCallback callback) {
braintreeClient.sendAnalyticsEvent("pay-with-venmo.selected");
braintreeClient.getConfiguration(new ConfigurationCallback() {
@Override
public void onResult(@Nullable final Configuration configuration, @Nullable Exception error) {
if (configuration == null) {
callback.onResult(error);
braintreeClient.sendAnalyticsEvent("pay-with-venmo.app-switch.failed");
return;
}
String exceptionMessage = null;
if (!configuration.isVenmoEnabled()) {
exceptionMessage = "Venmo is not enabled";
} else if (!deviceInspector.isVenmoAppSwitchAvailable(activity)) {
exceptionMessage = "Venmo is not installed";
}
if (exceptionMessage != null) {
callback.onResult(new AppSwitchNotAvailableException(exceptionMessage));
braintreeClient.sendAnalyticsEvent("pay-with-venmo.app-switch.failed");
return;
}
if (request.getPaymentMethodUsage() == VenmoPaymentMethodUsage.UNSPECIFIED) {
callback.onResult(new BraintreeException("Payment method usage must be set."));
}
String venmoProfileId = request.getProfileId();
if (TextUtils.isEmpty(venmoProfileId)) {
venmoProfileId = configuration.getVenmoMerchantId();
}
JSONObject params = new JSONObject();
try {
params.put("query", "mutation CreateVenmoPaymentContext($input: CreateVenmoPaymentContextInput!) { createVenmoPaymentContext(input: $input) { venmoPaymentContext { id } } }");
JSONObject input = new JSONObject();
input.put("paymentMethodUsage", request.getPaymentMethodUsage());
input.put("merchantProfileId", venmoProfileId);
input.put("customerClient", "MOBILE_APP");
input.put("intent", "CONTINUE");
JSONObject variables = new JSONObject();
variables.put("input", input);
params.put("variables", variables);
} catch (JSONException e) {
e.printStackTrace();
}
final String finalVenmoProfileId = venmoProfileId;
braintreeClient.sendGraphQLPOST(params.toString(), new HttpResponseCallback() {
@Override
public void success(String responseBody) {
String paymentContextId = parsePaymentContextId(responseBody);
startVenmoActivityForResult(activity, request, configuration, finalVenmoProfileId, paymentContextId);
}
@Override
public void failure(Exception exception) {
startVenmoActivityForResult(activity, request, configuration, finalVenmoProfileId, null);
}
});
}
});
}
private void startVenmoActivityForResult(FragmentActivity activity, VenmoRequest request, Configuration configuration, String venmoProfileId, @Nullable String paymentContextId) {
sharedPrefsWriter.persistVenmoVaultOption(activity, request.getShouldVault() && braintreeClient.getAuthorization() instanceof ClientToken);
sharedPrefsWriter.persistVenmoPaymentContextId(activity, paymentContextId);
Intent launchIntent = getLaunchIntent(configuration, venmoProfileId, paymentContextId);
activity.startActivityForResult(launchIntent, BraintreeRequestCodes.VENMO);
braintreeClient.sendAnalyticsEvent("pay-with-venmo.app-switch.started");
}
private static String parsePaymentContextId(String createPaymentContextResponse) {
String paymentContextId = null;
try {
JSONObject data = new JSONObject(createPaymentContextResponse).getJSONObject("data");
JSONObject createVenmoPaymentContext = data.getJSONObject("createVenmoPaymentContext");
JSONObject venmoPaymentContext = createVenmoPaymentContext.getJSONObject("venmoPaymentContext");
paymentContextId = venmoPaymentContext.getString("id");
} catch (JSONException ignored) { /* do nothing */ }
return paymentContextId;
}
/**
* @param context Android Context
* @param resultCode a code associated with the Activity result
* @param data Android Intent
* @param callback {@link VenmoOnActivityResultCallback}
*/
public void onActivityResult(final Context context, int resultCode, Intent data, final VenmoOnActivityResultCallback callback) {
if (resultCode == AppCompatActivity.RESULT_OK) {
String paymentContextId = sharedPrefsWriter.getVenmoPaymentContextId(context);
if (paymentContextId != null) {
JSONObject params = new JSONObject();
try {
params.put("query", "query PaymentContext($id: ID!) { node(id: $id) { ... on VenmoPaymentContext { paymentMethodId userName } } }");
JSONObject variables = new JSONObject();
variables.put("id", paymentContextId);
params.put("variables", variables);
braintreeClient.sendGraphQLPOST(params.toString(), new HttpResponseCallback() {
@Override
public void success(String responseBody) {
try {
JSONObject data = new JSONObject(responseBody).getJSONObject("data");
VenmoAccountNonce nonce = VenmoAccountNonce.fromJSON(data.getJSONObject("node"));
callback.onResult(nonce, null);
} catch (JSONException exception) {
callback.onResult(null, exception);
}
}
@Override
public void failure(Exception exception) {
callback.onResult(null, exception);
}
});
} catch (JSONException exception) {
callback.onResult(null, exception);
}
} else {
braintreeClient.sendAnalyticsEvent("pay-with-venmo.app-switch.success");
String nonce = data.getStringExtra(EXTRA_PAYMENT_METHOD_NONCE);
boolean shouldVault = sharedPrefsWriter.getVenmoVaultOption(context);
boolean isClientToken = braintreeClient.getAuthorization() instanceof ClientToken;
if (shouldVault && isClientToken) {
VenmoAccount venmoAccount = new VenmoAccount();
venmoAccount.setNonce(nonce);
tokenizationClient.tokenize(venmoAccount, new TokenizeCallback() {
@Override
public void onResult(JSONObject tokenizationResponse, Exception exception) {
if (tokenizationResponse != null) {
try {
VenmoAccountNonce venmoAccountNonce = VenmoAccountNonce.fromJSON(tokenizationResponse);
callback.onResult(venmoAccountNonce, null);
braintreeClient.sendAnalyticsEvent("pay-with-venmo.vault.success");
} catch (JSONException e) {
callback.onResult(null, e);
}
} else {
callback.onResult(null, exception);
braintreeClient.sendAnalyticsEvent("pay-with-venmo.vault.failed");
}
}
});
} else {
String venmoUsername = data.getStringExtra(EXTRA_USERNAME);
VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce(nonce, venmoUsername, false);
callback.onResult(venmoAccountNonce, null);
}
}
} else if (resultCode == AppCompatActivity.RESULT_CANCELED) {
braintreeClient.sendAnalyticsEvent("pay-with-venmo.app-switch.canceled");
callback.onResult(null, new UserCanceledException("User canceled Venmo."));
}
}
private static Intent getVenmoIntent() {
return new Intent().setComponent(new ComponentName(VENMO_PACKAGE_NAME, VENMO_PACKAGE_NAME + "." + APP_SWITCH_ACTIVITY));
}
private Intent getLaunchIntent(Configuration configuration, String profileId, String paymentContextId) {
Intent venmoIntent = getVenmoIntent()
.putExtra(EXTRA_MERCHANT_ID, profileId)
.putExtra(EXTRA_ACCESS_TOKEN, configuration.getVenmoAccessToken())
.putExtra(EXTRA_ENVIRONMENT, configuration.getVenmoEnvironment());
if (paymentContextId != null) {
venmoIntent.putExtra(EXTRA_RESOURCE_ID, paymentContextId);
}
try {
JSONObject braintreeData = new JSONObject();
JSONObject meta = new MetadataBuilder()
.sessionId(braintreeClient.getSessionId())
.integration(braintreeClient.getIntegrationType())
.version()
.build();
braintreeData.put(META_KEY, meta);
venmoIntent.putExtra(EXTRA_BRAINTREE_DATA, braintreeData.toString());
} catch (JSONException ignored) {
}
return venmoIntent;
}
/**
* Check if Venmo app switch is available.
*
* @param context Application Context
* @return true if the Venmo app is installed, false otherwise
*/
public boolean isVenmoAppSwitchAvailable(Context context) {
return deviceInspector.isVenmoAppSwitchAvailable(context);
}
} |
package inc.flide.vim8.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.Switch;
import com.afollestad.materialdialogs.MaterialDialog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import inc.flide.vim8.BuildConfig;
import inc.flide.vim8.R;
import inc.flide.vim8.structures.Constants;
public class LauncherActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private boolean isKeyboardEnabled;
private Button red_button;
private Button green_button;
private Button yellow_button;
private Button blue_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.white));
toolbar.setTitleTextColor(getResources().getColor(R.color.black));
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Button switchToEmojiKeyboardButton = findViewById(R.id.emoji);
switchToEmojiKeyboardButton.setOnClickListener(v -> askUserPreferredEmoticonKeyboard());
Button resizeButton = findViewById(R.id.resize_button);
resizeButton.setOnClickListener(v -> allowUserToResizeCircle());
Button setCenterButton = findViewById(R.id.setcenter_button);
setCenterButton.setOnClickListener(v -> allowUserToSetCentreForCircle());
Button leftButtonClick = findViewById(R.id.left_button);
leftButtonClick.setOnClickListener(v -> switchSidebarPosition(getString(R.string.mainKeyboard_sidebar_position_preference_left_value)));
Button rightButtonClick = findViewById(R.id.right_button);
rightButtonClick.setOnClickListener(v -> switchSidebarPosition(getString(R.string.mainKeyboard_sidebar_position_preference_right_value)));
Switch touch_trail_switch = findViewById(R.id.touch_trail);
SharedPreferences sp = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
touch_trail_switch.setChecked(sp.getBoolean(getString(R.string.user_preferred_typing_trail_visibility),true));
touch_trail_switch.setOnCheckedChangeListener((buttonView, isChecked) -> touchTrailPreferenceChangeListner(isChecked));
red_button = (Button) findViewById(R.id.red_button);
red_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(getString(R.string.color_selection),"Red");
sharedPreferencesEditor.apply();
}
});
green_button = (Button) findViewById(R.id.green_button);
green_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(getString(R.string.color_selection),"Green");
sharedPreferencesEditor.apply();
}
});
yellow_button = (Button) findViewById(R.id.yellow_button);
yellow_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(getString(R.string.color_selection),"Yellow");
sharedPreferencesEditor.apply();
}
});
blue_button = (Button) findViewById(R.id.blue_button);
blue_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(getString(R.string.color_selection),"Blue");
sharedPreferencesEditor.apply();
}
});
}
private void touchTrailPreferenceChangeListner(boolean isChecked) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putBoolean(getString(R.string.user_preferred_typing_trail_visibility),isChecked);
sharedPreferencesEditor.apply();
}
private void switchSidebarPosition(String userPreferredPositionForSidebar) {
if (userPreferredPositionForSidebar.equals(getString(R.string.mainKeyboard_sidebar_position_preference_left_value)) ||
userPreferredPositionForSidebar.equals(getString(R.string.mainKeyboard_sidebar_position_preference_right_value))) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(
getString(R.string.mainKeyboard_sidebar_position_preference_key),
userPreferredPositionForSidebar);
sharedPreferencesEditor.apply();
}
}
private void allowUserToResizeCircle(){
Intent intent = new Intent(this, ResizeActivity.class);
startActivity(intent);
}
private void allowUserToSetCentreForCircle(){
Intent intent = new Intent(this,SetCenterActivity.class);
startActivity(intent);
}
private void askUserPreferredEmoticonKeyboard(){
InputMethodManager imeManager = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
List<InputMethodInfo> inputMethods = imeManager.getEnabledInputMethodList();
Map<String,String> inputMethodsNameAndId = new HashMap<>();
for(InputMethodInfo inputMethodInfo : inputMethods){
if(inputMethodInfo.getId().compareTo(Constants.SELF_KEYBOARD_ID) != 0) {
inputMethodsNameAndId.put(inputMethodInfo.loadLabel(getPackageManager()).toString(),inputMethodInfo.getId());
}
}
ArrayList<String> keyboardIds = new ArrayList<>(inputMethodsNameAndId.values());
SharedPreferences sp = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
String selectedKeyboardId = sp.getString(getString(R.string.bp_selected_emoticon_keyboard),"");
int selectedKeyboardIndex = -1;
if (!selectedKeyboardId.isEmpty()) {
selectedKeyboardIndex = keyboardIds.indexOf(selectedKeyboardId);
if (selectedKeyboardIndex == -1) {
// seems like we have a stale selection, it should be removed.
sp.edit().remove(getString(R.string.bp_selected_emoticon_keyboard)).apply();
}
}
new MaterialDialog.Builder(this)
.title(R.string.select_preferred_emoticon_keyboard_dialog_title)
.items(inputMethodsNameAndId.keySet())
.itemsCallbackSingleChoice(selectedKeyboardIndex, (dialog, itemView, which, text) -> {
if(which != -1) {
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.basic_preference_file_name), Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString(getString(R.string.bp_selected_emoticon_keyboard),keyboardIds.get(which));
sharedPreferencesEditor.apply();
}
return true;
})
.positiveText(R.string.generic_okay_text)
.show();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, R.string.app_name);
String shareMessage= "\nCheck out this awesome keyboard application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "Share "+ R.string.app_name));
break;
case R.id.help:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:flideravi@gmail.com?subject=" + "Feedback");
intent.setData(data);
startActivity(intent);
break;
case R.id.about :
AlertDialog.Builder about = new AlertDialog.Builder(this);
about.setTitle("About "+ getString(R.string.app_name));
about.setMessage("More than just a clone for now defunct 8Pen Application\n\n" +
"Designed and Developed by Flide\n" + getString(R.string.version_name));
about.setCancelable(true);
about.show();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onStart() {
super.onStart();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
List<InputMethodInfo> enabledInputMethodList = inputMethodManager.getEnabledInputMethodList();
isKeyboardEnabled = false;
for(InputMethodInfo inputMethodInfo: enabledInputMethodList) {
if(inputMethodInfo.getId().compareTo(Constants.SELF_KEYBOARD_ID) == 0) {
isKeyboardEnabled = true;
}
}
}
@Override
protected void onResume() {
super.onResume();
// Ask user to enable the IME if it is not enabled yet
if(!isKeyboardEnabled) {
enableInputMethodDialog();
}
// Ask user to activate the IME while he is using the settings application
else if(!Constants.SELF_KEYBOARD_ID.equals(Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD))) {
activateInputMethodDialog();
}
}
private void enableInputMethodDialog() {
final MaterialDialog enableInputMethodNotificationDialog = new MaterialDialog.Builder(this)
.title(R.string.enable_ime_dialog_title)
.content(R.string.enable_ime_dialog_content)
.neutralText(R.string.enable_ime_dialog_neutral_button_text)
.cancelable(false)
.canceledOnTouchOutside(false)
.build();
enableInputMethodNotificationDialog.getBuilder()
.onNeutral((dialog, which) -> {
startActivityForResult(new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS), 0);
enableInputMethodNotificationDialog.dismiss();
});
enableInputMethodNotificationDialog.show();
}
private void activateInputMethodDialog() {
final MaterialDialog activateInputMethodNotificationDialog = new MaterialDialog.Builder(this)
.title(R.string.activate_ime_dialog_title)
.content(R.string.activate_ime_dialog_content)
.positiveText(R.string.activate_ime_dialog_positive_button_text)
.negativeText(R.string.activate_ime_dialog_negative_button_text)
.cancelable(false)
.canceledOnTouchOutside(false)
.build();
activateInputMethodNotificationDialog.getBuilder()
.onPositive((dialog, which) -> {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showInputMethodPicker();
activateInputMethodNotificationDialog.dismiss();
});
activateInputMethodNotificationDialog.show();
}
} |
package br.net.mirante.singular.util.wicket.bootstrap.layout;
import java.nio.charset.Charset;
import java.util.Optional;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.IMarkupFragment;
import org.apache.wicket.markup.Markup;
import org.apache.wicket.markup.MarkupParser;
import org.apache.wicket.markup.MarkupResourceStream;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.panel.IMarkupSourcingStrategy;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.html.panel.PanelMarkupSourcingStrategy;
import org.apache.wicket.util.resource.StringResourceStream;
import br.net.mirante.singular.commons.base.SingularUtil;
import br.net.mirante.singular.commons.lambda.IFunction;
import br.net.mirante.singular.commons.lambda.ISupplier;
@SuppressWarnings("serial")
public class TemplatePanel extends Panel {
private IFunction<TemplatePanel, String> templateFunction;
public TemplatePanel(String id, ISupplier<String> templateSupplier) {
this(id, p -> templateSupplier.get());
}
public TemplatePanel(String id, String template) {
this(id, p -> template);
}
public TemplatePanel(String id, IFunction<TemplatePanel, String> templateFunction) {
this(id);
this.templateFunction = templateFunction;
}
public TemplatePanel(String id) {
super(id);
}
protected void onBeforeComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
}
protected void onAfterComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
}
public IFunction<TemplatePanel, String> getTemplateFunction() {
return templateFunction;
}
@Override
protected IMarkupSourcingStrategy newMarkupSourcingStrategy() {
return new PanelMarkupSourcingStrategy(false) {
@Override
public IMarkupFragment getMarkup(MarkupContainer parent, Component child) {
// corrige o problema de encoding
StringResourceStream stringResourceStream = new StringResourceStream("<wicket:panel>" + getTemplateFunction().apply(TemplatePanel.this) + "</wicket:panel>", "text/html");
stringResourceStream.setCharset(Charset.forName(Optional.ofNullable(Application.get().getMarkupSettings().getDefaultMarkupEncoding()).orElse("UTF-8")));
MarkupParser markupParser = new MarkupParser(new MarkupResourceStream(stringResourceStream));
markupParser.setWicketNamespace(MarkupParser.WICKET);
Markup markup;
try {
markup = markupParser.parse();
} catch (Exception e) {
throw SingularUtil.propagate(e);
}
// If child == null, than return the markup fragment starting
// with <wicket:panel>
if (child == null)
{
return markup;
}
// Copiado da superclasse. buscando markup do child
IMarkupFragment associatedMarkup = markup.find(child.getId());
if (associatedMarkup != null) {
return associatedMarkup;
}
associatedMarkup = searchMarkupInTransparentResolvers(parent, parent.getMarkup(), child);
if (associatedMarkup != null) {
return associatedMarkup;
}
return findMarkupInAssociatedFileHeader(parent, child);
}
@Override
public void onComponentTagBody(Component component, MarkupStream markupStream, ComponentTag openTag) {
TemplatePanel.this.onBeforeComponentTagBody(markupStream, openTag);
super.onComponentTagBody(component, markupStream, openTag);
TemplatePanel.this.onAfterComponentTagBody(markupStream, openTag);
}
};
}
} |
package com.orientechnologies.lucene.functions;
import com.orientechnologies.lucene.test.BaseLuceneTest;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.InputStream;
import static org.assertj.core.api.Assertions.assertThat;
public class OLuceneSearchMoreLikeThisFunctionTest extends BaseLuceneTest {
@Before
public void setUp() throws Exception {
InputStream stream = ClassLoader.getSystemResourceAsStream("testLuceneIndex.sql");
db.execute("sql", getScriptFromStream(stream));
}
@Test
public void shouldSearchMoreLikeThisWithRid() throws Exception {
db.command("create index Song.title on Song (title) FULLTEXT ENGINE LUCENE ");
OResultSet resultSet = db
.query("SELECT from Song where SEARCH_More([#25:2, #25:3],{'minTermFreq':1, 'minDocFreq':1} ) = true");
assertThat(resultSet).hasSize(48);
resultSet.close();
}
@Test
public void shouldSearchMoreLikeThisWithRidOnMultiFieldsIndex() throws Exception {
db.command("create index Song.multi on Song (title,author) FULLTEXT ENGINE LUCENE ");
OResultSet resultSet = db
.query("SELECT from Song where SEARCH_More([#25:2, #25:3] , {'minTermFreq':1, 'minDocFreq':1} ) = true");
assertThat(resultSet).hasSize(84);
resultSet.close();
}
@Test
public void shouldSearchOnFieldAndMoreLikeThisWithRidOnMultiFieldsIndex() throws Exception {
db.command("create index Song.multi on Song (title) FULLTEXT ENGINE LUCENE ");
OResultSet resultSet = db
.query(
"SELECT from Song where author ='Hunter' AND SEARCH_More([#25:2, #25:3,#25:4,#25:5],{'minTermFreq':1, 'minDocFreq':1} ) = true");
assertThat(resultSet).hasSize(8);
resultSet.close();
// resultSet = db
// .query("SELECT from Song where SEARCH_More([#25:2], {'minTermFreq':1, 'minDocFreq':1} ) = true OR author ='Hunter' ");
// System.out.println(resultSet.getExecutionPlan().get().prettyPrint(1, 1));
// assertThat(resultSet).hasSize(84);
// resultSet.close();
}
@Test
public void shouldSearchMoreLikeThisWithRidOnMultiFieldsIndexWithMetadata() throws Exception {
db.command("create index Song.multi on Song (title,author) FULLTEXT ENGINE LUCENE ");
OResultSet resultSet = db
.query(
"SELECT from Song where SEARCH_More( [#25:2, #25:3] , {'fields': [ 'title' ], 'minTermFreq':1, 'minDocFreq':1}) = true");
System.out.println(resultSet.getExecutionPlan().get().prettyPrint(1, 1));
assertThat(resultSet).hasSize(84);
resultSet.close();
}
@Test
@Ignore
public void shouldSearchMoreLikeThisWithInnerQuery() throws Exception {
db.command("create index Song.multi on Song (title,author) FULLTEXT ENGINE LUCENE ");
// db.query("SELECT @RID FROM Song WHERE author = 'Hunter' ").stream().forEach(e-> System.out.println("e = " + e.toElement().toJSON()));
//for Luigi: execution plan doesn't bind $a correctly
OResultSet resultSet = db
.query("SELECT from Song let $a=(SELECT @rid FROM Song WHERE author = 'Hunter') where SEARCH_More( $a ) = true");
assertThat(resultSet).hasSize(2);
resultSet.close();
}
} |
package com.x.cms.assemble.control.jaxrs.comment;
import javax.servlet.http.HttpServletRequest;
import com.google.gson.JsonElement;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.cms.assemble.control.Business;
import com.x.cms.core.entity.Document;
import com.x.cms.core.entity.DocumentCommentInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.yarn.webapp.hamlet2.Hamlet;
public class ActionSave extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionSave.class);
protected ActionResult<Wo> execute(HttpServletRequest request, EffectivePerson effectivePerson, JsonElement jsonElement ) throws Exception {
ActionResult<Wo> result = new ActionResult<>();
DocumentCommentInfo documentCommentInfo = null;
Document document = null;
Wi wi = null;
Boolean check = true;
try {
wi = this.convertToWrapIn( jsonElement, Wi.class );
documentCommentInfo = Wi.copier.copy(wi);
documentCommentInfo.setId( wi.getId());;
documentCommentInfo.setCreatorName( effectivePerson.getDistinguishedName() );
Business business = new Business(null);
if(StringUtils.isNoneBlank(wi.getCommentUser()) && business.isManager(effectivePerson)){
String person = business.organization().person().get(wi.getCommentUser());
if(StringUtils.isNoneBlank(person)){
documentCommentInfo.setCreatorName( person );
}
}
documentCommentInfo.setAuditorName( "" );
documentCommentInfo.setCommentAuditStatus( "" );
} catch (Exception e) {
check = false;
Exception exception = new ExceptionCommentPersist(e, "JSONJSON:" + jsonElement.toString());
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
if( check ) {
try {
document = documentInfoServiceAdv.get( documentCommentInfo.getDocumentId() );
if (document == null) {
check = false;
Exception exception = new ExceptionDocumentNotExists( documentCommentInfo.getDocumentId() );
result.error(exception);
}else {
documentCommentInfo.setAppId( document.getAppId() );
documentCommentInfo.setAppName( document.getAppName() );
documentCommentInfo.setCategoryId( document.getCategoryId() );
documentCommentInfo.setCategoryName( document.getCategoryName() );
}
} catch (Exception e) {
check = false;
Exception exception = new ExceptionCommentPersist(e, "ID:" + wi.getDocumentId() );
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
if (check) {
try {
documentCommentInfo = documentCommentInfoPersistService.save( documentCommentInfo, wi.getContent(), effectivePerson );
CacheManager.notify( Document.class );
CacheManager.notify( DocumentCommentInfo.class );
Wo wo = new Wo();
wo.setId( documentCommentInfo.getId() );
result.setData( wo );
} catch (Exception e) {
check = false;
Exception exception = new ExceptionCommentPersist(e, "");
result.error(exception);
logger.error(e, effectivePerson, request, null);
}
}
return result;
}
public static class Wi {
@FieldDescribe("ID")
private String id = "";
@FieldDescribe("ID")
private String documentId = "";
@FieldDescribe("")
private String title = "";
@FieldDescribe("ID")
private String parentId = "";
@FieldDescribe("")
private String content = "";
@FieldDescribe("")
private Boolean isPrivate = false;
@FieldDescribe("()")
private String commentUser = "";
public static final WrapCopier<Wi, DocumentCommentInfo> copier = WrapCopierFactory.wi( Wi.class, DocumentCommentInfo.class, null, null );
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDocumentId() {
return documentId;
}
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Boolean getIsPrivate() {
return isPrivate;
}
public void setIsPrivate(Boolean isPrivate) {
this.isPrivate = isPrivate;
}
public String getCommentUser() {
return commentUser;
}
public void setCommentUser(String commentUser) {
this.commentUser = commentUser;
}
}
public static class Wo extends WoId {
}
} |
package it.unibz.krdb.obda.owlapi3.directmapping;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import it.unibz.krdb.obda.model.Atom;
import it.unibz.krdb.obda.model.CQIE;
import it.unibz.krdb.obda.model.Function;
import it.unibz.krdb.obda.model.NewLiteral;
import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.Variable;
import it.unibz.krdb.obda.model.impl.OBDAVocabulary;
import it.unibz.krdb.obda.utils.TypeMapper;
import it.unibz.krdb.sql.DBMetadata;
import it.unibz.krdb.sql.DataDefinition;
import it.unibz.krdb.sql.Reference;
import it.unibz.krdb.sql.TableDefinition;
import it.unibz.krdb.sql.api.Attribute;
public class DirectMappingAxiom {
protected DBMetadata obda_md;
protected DataDefinition table;
protected String SQLString;
protected String baseuri;
public DirectMappingAxiom(){
}
public DirectMappingAxiom(String baseuri, DataDefinition dd, DBMetadata obda_md){
this.table = dd;
this.SQLString = new String();
this.obda_md = obda_md;
if (baseuri!=null)
this.baseuri = baseuri;
else
this.baseuri = new String("http://example.org/");
}
public DirectMappingAxiom(DirectMappingAxiom dmab){
this.table = dmab.table;
this.SQLString = new String(dmab.getSQL());
this.baseuri = new String(dmab.getbaseuri());
}
public String getSQL(){
String SQLStringTemple=new String("SELECT * FROM %s");
SQLString=String.format(SQLStringTemple, "\""+this.table.getName()+"\"");
return new String(SQLString);
}
public Map<String, CQIE> getRefAxioms(OBDADataFactory dfac) {
HashMap<String, CQIE> refAxioms = new HashMap<String, CQIE>();
Map<String, List<Attribute>> fks = ((TableDefinition) table).getForeignKeys();
if (fks.size() > 0) {
Set<String> keys = fks.keySet();
for (String key : keys) {
refAxioms.put(getRefSQL(key), getRefCQ(key, dfac));
}
}
return refAxioms;
}
private String getRefSQL(String key) {
Map<String, List<Attribute>> fks = ((TableDefinition) table)
.getForeignKeys();
List<Attribute> pks = ((TableDefinition) table).getPrimaryKeys();
String SQLStringTempl = new String("SELECT %s FROM %s WHERE %s");
String table = new String("\"" + this.table.getName() + "\"");
String Table = table;
String Column = "";
String Condition = "";
for (Attribute pk : pks)
Column += Table + ".\"" + pk.getName() + "\", ";
// refferring object
List<Attribute> attr = fks.get(key);
for (int i = 0; i < attr.size(); i++) {
Condition += table + ".\"" + attr.get(i).getName() + "\" = ";
// get referenced object
Reference ref = attr.get(i).getReference();
String tableRef = ref.getTableReference();
if (i == 0)
Table += ", \"" + tableRef + "\"";
String columnRef = ref.getColumnReference();
Column += "\"" + tableRef + "\".\"" + columnRef + "\"";
Condition += "\"" + tableRef + "\".\"" + columnRef + "\"";
if (i < attr.size() - 1) {
Column += ", ";
Condition += " AND ";
}
}
return (String.format(SQLStringTempl, Column, Table, Condition));
}
public CQIE getCQ(OBDADataFactory df){
NewLiteral sub = generateSubject(df, (TableDefinition)table, false);
List<Function> atoms = new ArrayList<Function>();
//Class Atom
atoms.add(df.getAtom(df.getClassPredicate(generateClassURI(table.getName())), sub));
//DataType Atoms
TypeMapper typeMapper = TypeMapper.getInstance();
for(int i=0;i<table.countAttribute();i++){
Attribute att = table.getAttribute(i+1);
Predicate type = typeMapper.getPredicate(att.getType());
Function obj = df.getFunctionalTerm(type, df.getVariable(att.getName()));
atoms.add(df.getAtom(df.getDataPropertyPredicate(generateDPURI(table.getName(), att.getName())), sub, obj));
}
//To construct the head, there is no static field about this predicate
List<NewLiteral> headTerms = new ArrayList<NewLiteral>();
for(int i=0;i<table.countAttribute();i++){
headTerms.add(df.getVariable(table.getAttributeName(i+1)));
}
Predicate headPredicate = df.getPredicate("http://obda.inf.unibz.it/quest/vocabulary#q", headTerms.size());
Function head = df.getAtom(headPredicate, headTerms);
return df.getCQIE(head, atoms);
}
private CQIE getRefCQ(String fk, OBDADataFactory df) {
NewLiteral sub = generateSubject(df, (TableDefinition) table, true);
Function atom = null;
// Object Atoms
// Foreign key reference
for (int i = 0; i < table.countAttribute(); i++) {
if (table.getAttribute(i + 1).isForeignKey()){
// if (table.getAttribute(i + 1).hasName(fk)) {
Attribute att = table.getAttribute(i + 1);
Reference ref = att.getReference();
if (ref.getReferenceName().equals(fk)){
String pkTableReference = ref.getTableReference();
TableDefinition tdRef = (TableDefinition) obda_md
.getDefinition(pkTableReference);
NewLiteral obj = generateSubject(df, tdRef, true);
atom = (df.getAtom(
df.getObjectPropertyPredicate(generateOPURI(
table.getName(), table.getAttributes())),
sub, obj));
// construct the head
List<NewLiteral> headTerms = new ArrayList<NewLiteral>();
headTerms.addAll(atom.getReferencedVariables());
Predicate headPredicate = df.getPredicate(
"http://obda.inf.unibz.it/quest/vocabulary
headTerms.size());
Function head = df.getAtom(headPredicate, headTerms);
return df.getCQIE(head, atom);
}
}
}
return null;
}
//Generate an URI for class predicate from a string(name of table)
private String generateClassURI(String table){
return new String(baseuri+table);
}
/*
* Generate an URI for datatype property from a string(name of column)
* The style should be "baseuri/tablename#columnname" as required in Direct Mapping Definition
*/
private String generateDPURI(String table, String column){
return new String(baseuri+percentEncode(table)+"#"+percentEncode(column));
}
//Generate an URI for object property from a string(name of column)
private String generateOPURI(String table, ArrayList<Attribute> columns){
String column = "";
for(Attribute a : columns)
if (a.isForeignKey())
column+= a.getName()+"_";
column = column.substring(0, column.length()-1);
return new String(baseuri+percentEncode(table)+"#ref-"+column);
}
/*
* Generate the subject term of the table
*
*
* TODO replace URI predicate to BNode predicate for tables without PKs
* in the following method after 'else'
*/
private NewLiteral generateSubject(OBDADataFactory df, TableDefinition td, boolean ref){
String tableName = "";
// if (ref)
// tableName = percentEncode(td.getName())+".";
if(td.getPrimaryKeys().size()>0){
Predicate uritemple = df.getUriTemplatePredicate(td.getPrimaryKeys().size()+1);
List<NewLiteral> terms = new ArrayList<NewLiteral>();
terms.add(df.getValueConstant(subjectTemple(td,td.getPrimaryKeys().size())));
for(int i=0;i<td.getPrimaryKeys().size();i++){
terms.add(df.getVariable(tableName + td.getPrimaryKeys().get(i).getName()));
}
return df.getFunctionalTerm(uritemple, terms);
}
else{
List<NewLiteral> vars = new ArrayList<NewLiteral>();
for(int i=0;i<td.countAttribute();i++){
vars.add(df.getVariable(tableName + td.getAttributeName(i+1)));
}
Predicate bNode = df.getBNodeTemplatePredicate(1);
return df.getFunctionalTerm(bNode, vars);
}
}
private String subjectTemple(TableDefinition td, int numPK){
/*
* It is hard to generate a uniform temple since the number of PK differs
* For example, the subject uri temple with one pk should be like:
* baseuri+tablename/PKcolumnname={}('col={}...)
* For table with more than one pk columns, there will be a ";" between column names
*/
String temp = new String(baseuri);
temp+=percentEncode(td.getName());
temp+="/";
for(int i=0;i<numPK;i++){
temp+=percentEncode("{"+td.getPrimaryKeys().get(i).getName())+"};";
}
//remove the last "." which is not neccesary
temp=temp.substring(0, temp.length()-1);
//temp="\""+temp+"\"";
return temp;
}
public String getbaseuri(){
return baseuri;
}
public void setbaseuri(String uri){
if (uri!=null)
baseuri=new String(uri);
}
/*
* percent encoding for a String
*/
private String percentEncode(String pe){
pe = pe.replace("
pe = pe.replace(".", "%2E");
pe = pe.replace("-", "%2D");
pe = pe.replace("/", "%2F");
pe = pe.replace(" ", "%20");
pe = pe.replace("!", "%21");
pe = pe.replace("$", "%24");
pe = pe.replace("&", "%26");
pe = pe.replace("'", "%27");
pe = pe.replace("(", "%28");
pe = pe.replace(")", "%29");
pe = pe.replace("*", "%2A");
pe = pe.replace("+", "%2B");
pe = pe.replace(",", "%2C");
pe = pe.replace(":", "%3A");
pe = pe.replace(";", "%3B");
pe = pe.replace("=", "%3D");
pe = pe.replace("?", "%3F");
pe = pe.replace("@", "%40");
pe = pe.replace("[", "%5B");
pe = pe.replace("]", "%5D");
return new String(pe);
}
} |
package org.eclipse.mylyn.tasks.ui.editors;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPreferenceConstants;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskOutlineNode;
import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskSelection;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.core.TaskList;
import org.eclipse.mylyn.tasks.ui.DatePicker;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.VerifyKeyListener;
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.VerifyEvent;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.Section;
/**
* An editor used to view a locally created bug that does not yet exist on a server.
*
* @author Rob Elves (modifications)
* @since 2.0
*/
public abstract class AbstractNewRepositoryTaskEditor extends AbstractRepositoryTaskEditor {
private static final int DESCRIPTION_WIDTH = 79 * 7; // 500;
private static final int DESCRIPTION_HEIGHT = 10 * 14;
private static final int DEFAULT_FIELD_WIDTH = 150;
private static final int DEFAULT_ESTIMATED_TIME = 1;
private static final String LABEL_SUMBIT = "Submit";
private static final String ERROR_CREATING_BUG_REPORT = "Error creating bug report";
protected DatePicker scheduledForDate;
protected Spinner estimatedTime;
@Deprecated
protected String newSummary = "";
protected Button addToCategory;
protected CCombo categoryChooser;
/**
* @author Raphael Ackermann (bug 195514)
*/
protected class TabVerifyKeyListener implements VerifyKeyListener {
public void verifyKey(VerifyEvent event) {
// if there is a tab key, do not "execute" it and instead select the Attributes section
if (event.keyCode == SWT.TAB) {
event.doit = false;
focusAttributes();
}
}
}
public AbstractNewRepositoryTaskEditor(FormEditor editor) {
super(editor);
}
@Override
public void init(IEditorSite site, IEditorInput input) {
if (!(input instanceof NewTaskEditorInput)) {
return;
}
initTaskEditor(site, (RepositoryTaskEditorInput) input);
setTaskOutlineModel(RepositoryTaskOutlineNode.parseBugReport(taskData, false));
newSummary = taskData.getSummary();
}
@Override
protected void createDescriptionLayout(Composite composite) {
FormToolkit toolkit = this.getManagedForm().getToolkit();
Section section = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR);
section.setText(getSectionLabel(SECTION_NAME.DESCRIPTION_SECTION));
section.setExpanded(true);
section.setLayout(new GridLayout());
section.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite descriptionComposite = toolkit.createComposite(section);
GridLayout descriptionLayout = new GridLayout();
descriptionComposite.setLayout(descriptionLayout);
GridData descriptionData = new GridData(GridData.FILL_BOTH);
descriptionData.grabExcessVerticalSpace = true;
descriptionComposite.setLayoutData(descriptionData);
section.setClient(descriptionComposite);
descriptionTextViewer = addTextEditor(repository, descriptionComposite, taskData.getDescription(), true,
SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
descriptionTextViewer.setEditable(true);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.widthHint = DESCRIPTION_WIDTH;
gd.minimumHeight = DESCRIPTION_HEIGHT;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
descriptionTextViewer.getControl().setLayoutData(gd);
descriptionTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
addDuplicateDetection(descriptionComposite);
toolkit.paintBordersFor(descriptionComposite);
}
/**
* @author Raphael Ackermann (modifications) (bug 195514)
* @param composite
*/
@Override
protected void createSummaryLayout(Composite composite) {
addSummaryText(composite);
if (summaryTextViewer != null) {
summaryTextViewer.prependVerifyKeyListener(new TabVerifyKeyListener());
// TODO: Eliminate this and newSummary field when api can be changed
summaryTextViewer.getTextWidget().addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String sel = summaryText.getText();
if (!(newSummary.equals(sel))) {
newSummary = sel;
}
}
});
}
}
@Override
protected void createAttachmentLayout(Composite comp) {
// currently can't attach while creating new bug
}
@Override
protected void createCommentLayout(Composite comp) {
// ignore
}
@Override
protected void createNewCommentLayout(Composite comp) {
createPlanningLayout(comp);
}
protected void createPlanningLayout(Composite comp) {
Section section = createSection(comp, "Personal Planning");
section.setLayout(new GridLayout());
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
section.setExpanded(true);
Composite sectionClient = getManagedForm().getToolkit().createComposite(section);
section.setClient(sectionClient);
GridLayout layout = new GridLayout();
layout.numColumns = 7;
layout.makeColumnsEqualWidth = false;
sectionClient.setLayout(layout);
GridData clientDataLayout = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
sectionClient.setLayoutData(clientDataLayout);
// Reminder
getManagedForm().getToolkit().createLabel(sectionClient, "Scheduled for:");
// label.setForeground(toolkit.getColors().getColor(FormColors.TITLE));
scheduledForDate = new DatePicker(sectionClient, SWT.FLAT, DatePicker.LABEL_CHOOSE);
scheduledForDate.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
scheduledForDate.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
Calendar newTaskSchedule = Calendar.getInstance();
int scheduledEndHour = TasksUiPlugin.getDefault().getPreferenceStore().getInt(
TasksUiPreferenceConstants.PLANNING_ENDHOUR);
// If past scheduledEndHour set for following day
if (newTaskSchedule.get(Calendar.HOUR_OF_DAY) >= scheduledEndHour) {
TaskActivityUtil.snapForwardNumDays(newTaskSchedule, 1);
} else {
TaskActivityUtil.snapEndOfWorkDay(newTaskSchedule);
}
scheduledForDate.setDate(newTaskSchedule);
// Button removeReminder = getManagedForm().getToolkit().createButton(sectionClient, "Clear",
// SWT.PUSH | SWT.CENTER);
// removeReminder.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// scheduledForDate.setDate(null);
ImageHyperlink clearReminder = getManagedForm().getToolkit().createImageHyperlink(sectionClient, SWT.NONE);
clearReminder.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE));
clearReminder.setToolTipText("Clear");
clearReminder.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
scheduledForDate.setDate(null);
}
});
// 1 Blank column after Reminder clear button
Label dummy = getManagedForm().getToolkit().createLabel(sectionClient, "");
GridData dummyLabelDataLayout = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
dummyLabelDataLayout.horizontalSpan = 1;
dummyLabelDataLayout.widthHint = 30;
dummy.setLayoutData(dummyLabelDataLayout);
// Estimated time
getManagedForm().getToolkit().createLabel(sectionClient, "Estimated hours:");
// label.setForeground(toolkit.getColors().getColor(FormColors.TITLE));
// estimatedTime = new Spinner(sectionClient, SWT.FLAT);
estimatedTime = new Spinner(sectionClient, SWT.FLAT);
estimatedTime.setDigits(0);
estimatedTime.setMaximum(100);
estimatedTime.setMinimum(0);
estimatedTime.setIncrement(1);
estimatedTime.setSelection(DEFAULT_ESTIMATED_TIME);
estimatedTime.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
GridData estimatedDataLayout = new GridData();
estimatedDataLayout.widthHint = 30;
estimatedTime.setLayoutData(estimatedDataLayout);
// getManagedForm().getToolkit().createLabel(sectionClient, "hours ");
// label.setForeground(toolkit.getColors().getColor(FormColors.TITLE));
ImageHyperlink clearEstimated = getManagedForm().getToolkit().createImageHyperlink(sectionClient, SWT.NONE);
clearEstimated.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE));
clearEstimated.setToolTipText("Clear");
clearEstimated.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
estimatedTime.setSelection(0);
}
});
getManagedForm().getToolkit().paintBordersFor(sectionClient);
}
@Override
protected void addRadioButtons(Composite buttonComposite) {
// Since NewBugModels have no special submitting actions,
// no radio buttons are required.
}
@Override
protected void createCustomAttributeLayout(Composite composite) {
// ignore
}
@Override
protected void saveTaskOffline(IProgressMonitor progressMonitor) {
taskData.setSummary(newSummary);
taskData.setDescription(descriptionTextViewer.getTextWidget().getText());
updateEditorTitle();
}
/**
* A listener for selection of the summary textbox.
*/
protected class DescriptionListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(
new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(),
taskData.getRepositoryKind(), "New Description", false, taskData.getSummary()))));
}
}
@Override
protected void validateInput() {
// ignore
}
@Override
public boolean isDirty() {
return true;
}
/**
* @author Raphael Ackermann (bug 198526)
*/
@Override
public void setFocus() {
if (summaryText != null) {
summaryText.setFocus();
}
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
/**
* Creates the button layout. This displays options and buttons at the bottom of the editor to allow actions to be
* performed on the bug.
*/
@Override
protected void createActionsLayout(Composite formComposite) {
Section section = getManagedForm().getToolkit().createSection(formComposite, ExpandableComposite.TITLE_BAR);
section.setText(getSectionLabel(SECTION_NAME.ACTIONS_SECTION));
section.setExpanded(true);
section.setLayout(new GridLayout());
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, true).applyTo(section);
Composite buttonComposite = getManagedForm().getToolkit().createComposite(section);
buttonComposite.setLayout(new GridLayout(4, false));
buttonComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
section.setClient(buttonComposite);
addToCategory = getManagedForm().getToolkit().createButton(buttonComposite, "Add to Category", SWT.CHECK);
categoryChooser = new CCombo(buttonComposite, SWT.FLAT | SWT.READ_ONLY);
categoryChooser.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
categoryChooser.setLayoutData(GridDataFactory.swtDefaults().hint(150, SWT.DEFAULT).create());
getManagedForm().getToolkit().adapt(categoryChooser, true, true);
categoryChooser.setFont(TEXT_FONT);
TaskList taskList = TasksUiPlugin.getTaskListManager().getTaskList();
List<AbstractTaskCategory> categories = taskList.getUserCategories();
Collections.sort(categories, new Comparator<AbstractTaskContainer>() {
public int compare(AbstractTaskContainer c1, AbstractTaskContainer c2) {
if (c1.equals(TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory())) {
return -1;
} else if (c2.equals(TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory())) {
return 1;
} else {
return c1.getSummary().compareToIgnoreCase(c2.getSummary());
}
}
});
for (AbstractTaskContainer category : categories) {
categoryChooser.add(category.getSummary());
}
categoryChooser.select(0);
categoryChooser.setEnabled(false);
categoryChooser.setData(categories);
addToCategory.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
categoryChooser.setEnabled(addToCategory.getSelection());
}
});
GridDataFactory.fillDefaults().hint(DEFAULT_FIELD_WIDTH, SWT.DEFAULT).span(3, SWT.DEFAULT).applyTo(
categoryChooser);
addActionButtons(buttonComposite);
getManagedForm().getToolkit().paintBordersFor(buttonComposite);
}
/**
* Returns the {@link AbstractTaskContainer category} the new task belongs to
*
* @return {@link AbstractTaskContainer category} where the new task must be added to, or null if it must not be
* added to the task list
*/
@Override
@SuppressWarnings("unchecked")
protected AbstractTaskCategory getCategory() {
int index = categoryChooser.getSelectionIndex();
if (addToCategory.getSelection() && index != -1) {
if (index == 0) {
return TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory();
}
return ((List<AbstractTaskCategory>) categoryChooser.getData()).get(index - 1);
}
return null;
}
@Override
protected void addActionButtons(Composite buttonComposite) {
FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay());
submitButton = toolkit.createButton(buttonComposite, LABEL_SUMBIT, SWT.NONE);
GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
submitButtonData.widthHint = 100;
submitButton.setImage(TasksUiImages.getImage(TasksUiImages.REPOSITORY_SUBMIT));
submitButton.setLayoutData(submitButtonData);
submitButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
submitToRepository();
}
});
submitButton.setToolTipText("Submit to " + this.repository.getUrl());
}
protected boolean prepareSubmit() {
submitButton.setEnabled(false);
showBusy(true);
if (summaryText != null && summaryText.getText().trim().equals("")) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(AbstractNewRepositoryTaskEditor.this.getSite().getShell(),
ERROR_CREATING_BUG_REPORT, "A summary must be provided with new bug reports.");
summaryText.setFocus();
submitButton.setEnabled(true);
showBusy(false);
}
});
return false;
}
if (descriptionTextViewer != null && descriptionTextViewer.getTextWidget().getText().trim().equals("")) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(AbstractNewRepositoryTaskEditor.this.getSite().getShell(),
ERROR_CREATING_BUG_REPORT, "A summary must be provided with new reports.");
descriptionTextViewer.getTextWidget().setFocus();
submitButton.setEnabled(true);
showBusy(false);
}
});
return false;
}
return true;
}
@Override
protected void createPeopleLayout(Composite composite) {
// ignore, new editor doesn't have people section
}
@Override
public AbstractTask updateSubmittedTask(String id, IProgressMonitor monitor) throws CoreException {
final AbstractTask newTask = super.updateSubmittedTask(id, monitor);
if (newTask != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
Calendar selectedDate = scheduledForDate.getDate();
if (selectedDate != null) {
// NewLocalTaskAction.scheduleNewTask(newTask);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(newTask, selectedDate.getTime());
}
newTask.setEstimatedTimeHours(estimatedTime.getSelection());
Object selectedObject = null;
if (TaskListView.getFromActivePerspective() != null)
selectedObject = ((IStructuredSelection) TaskListView.getFromActivePerspective()
.getViewer()
.getSelection()).getFirstElement();
if (selectedObject instanceof TaskCategory) {
TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(newTask,
((TaskCategory) selectedObject));
}
}
});
}
return newTask;
}
@Override
public void doSave(IProgressMonitor monitor) {
new MessageDialog(null, "Operation not supported", null,
"Save of un-submitted new tasks is not currently supported.\nPlease submit all new tasks.",
MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0).open();
monitor.setCanceled(true);
return;
}
public static String getStackTraceFromDescription(String description) {
String stackTrace = null;
if (description == null) {
return null;
}
String punct = "!\"
String lineRegex = " *at\\s+[\\w" + punct + "]+ ?\\(.*\\) *\n?";
Pattern tracePattern = Pattern.compile(lineRegex);
Matcher match = tracePattern.matcher(description);
if (match.find()) {
// record the index of the first stack trace line
int start = match.start();
int lastEnd = match.end();
// find the last stack trace line
while (match.find()) {
lastEnd = match.end();
}
// make sure there's still room to find the exception
if (start <= 0) {
return null;
}
// count back to the line before the stack trace to find the
// exception
int stackStart = 0;
int index = start - 1;
while (index > 1 && description.charAt(index) == ' ') {
index
}
// locate the exception line index
stackStart = description.substring(0, index - 1).lastIndexOf("\n");
stackStart = (stackStart == -1) ? 0 : stackStart + 1;
stackTrace = description.substring(stackStart, lastEnd);
}
return stackTrace;
}
@Override
public boolean searchForDuplicates() {
// called so that the description text is set on taskData before we
// search for duplicates
this.saveTaskOffline(new NullProgressMonitor());
return super.searchForDuplicates();
}
} |
/*
* Gameboi
*/
package gameboi;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
*
* @author tomis007
*/
public class GameBoi {
/**
* @param argv the command line arguments
*/
public static void main(String[] argv) {
Path rom_path = Paths.get(argv[0]);
GBMem memory = new GBMem(rom_path);
CPU z80 = new CPU(memory);
GPU gpu = new GPU(memory);
int count = 0;
while (true) {
int cycles;
// count++;
cycles = z80.ExecuteOpcode();
gpu.updateGraphics(cycles);
// System.out.println(count);
}
// System.out.println(count);
// System.exit(1);
}
} |
package com.linkedin.pinot.controller.helix.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.helix.AccessOption;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyPathConfig;
import org.apache.helix.PropertyType;
import org.apache.helix.ZNRecord;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.store.zk.ZkHelixPropertyStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkedin.pinot.common.metadata.resource.RealtimeDataResourceMetadata;
import com.linkedin.pinot.common.segment.SegmentMetadata;
import com.linkedin.pinot.common.utils.BrokerRequestUtils;
import com.linkedin.pinot.common.utils.CommonConstants;
import com.linkedin.pinot.common.utils.CommonConstants.Helix.ResourceType;
import com.linkedin.pinot.controller.api.pojos.BrokerDataResource;
import com.linkedin.pinot.controller.api.pojos.BrokerTagResource;
import com.linkedin.pinot.controller.api.pojos.DataResource;
import com.linkedin.pinot.controller.api.pojos.Instance;
import com.linkedin.pinot.controller.helix.core.PinotResourceManagerResponse.STATUS;
import com.linkedin.pinot.controller.helix.core.utils.PinotHelixUtils;
import com.linkedin.pinot.controller.helix.starter.HelixConfig;
import com.linkedin.pinot.core.segment.creator.impl.V1Constants;
import com.linkedin.pinot.core.segment.index.SegmentMetadataImpl;
/**
* @author Dhaval Patel<dpatel@linkedin.com
* Sep 30, 2014
*/
public class PinotHelixResourceManager {
private static Logger LOGGER = LoggerFactory.getLogger(PinotHelixResourceManager.class);
private String _zkBaseUrl;
private String _helixClusterName;
private HelixManager _helixZkManager;
private HelixAdmin _helixAdmin;
private String _helixZkURL;
private String _instanceId;
private ZkHelixPropertyStore<ZNRecord> _propertyStore;
private String _localDiskDir;
private SegmentDeletionManager _segmentDeletionManager = null;
private long _externalViewReflectTimeOut = 10000; // 10 seconds
@SuppressWarnings("unused")
private PinotHelixResourceManager() {
}
public PinotHelixResourceManager(String zkURL, String helixClusterName, String controllerInstanceId,
String localDiskDir) {
_zkBaseUrl = zkURL;
_helixClusterName = helixClusterName;
_instanceId = controllerInstanceId;
_localDiskDir = localDiskDir;
}
public synchronized void start() throws Exception {
_helixZkURL = HelixConfig.getAbsoluteZkPathForHelix(_zkBaseUrl);
_helixZkManager = HelixSetupUtils.setup(_helixClusterName, _helixZkURL, _instanceId);
_helixAdmin = _helixZkManager.getClusterManagmentTool();
ZkBaseDataAccessor<ZNRecord> baseAccessor =
(ZkBaseDataAccessor<ZNRecord>) _helixZkManager.getHelixDataAccessor().getBaseDataAccessor();
String propertyStorePath = PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _helixClusterName);
_propertyStore =
new ZkHelixPropertyStore<ZNRecord>(baseAccessor, propertyStorePath, Arrays.asList(propertyStorePath));
_segmentDeletionManager = new SegmentDeletionManager(_localDiskDir, _helixAdmin, _helixClusterName, _propertyStore);
}
public synchronized void stop() {
_segmentDeletionManager.stop();
_helixZkManager.disconnect();
}
public String getBrokerInstanceFor(String resourceName) {
final DataResource ds = getDataResource(resourceName);
final List<String> instanceIds = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName, ds.getBrokerTagName());
if (instanceIds == null || instanceIds.size() == 0) {
return null;
}
Collections.shuffle(instanceIds);
return instanceIds.get(0);
}
public DataResource getDataResource(String resourceName) {
final Map<String, String> configs = HelixHelper.getResourceConfigsFor(_helixClusterName, resourceName, _helixAdmin);
return DataResource.fromResourceConfigMap(configs);
}
public List<String> getAllResourceNames() {
return _helixAdmin.getResourcesInCluster(_helixClusterName);
}
/**
* Returns all resources that are actual Pinot resources, not broker resource.
*/
public List<String> getAllPinotResourceNames() {
List<String> resourceNames = getAllResourceNames();
// Filter resource names that are known to be non Pinot resources (ie. brokerResource)
ArrayList<String> pinotResourceNames = new ArrayList<String>();
for (String resourceName : resourceNames) {
if (CommonConstants.Helix.NON_PINOT_RESOURCE_RESOURCE_NAMES.contains(resourceName)) {
continue;
}
pinotResourceNames.add(resourceName);
}
return pinotResourceNames;
}
public synchronized PinotResourceManagerResponse handleCreateNewDataResource(DataResource resource) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
ResourceType resourceType = null;
try {
resourceType = resource.getResourceType();
} catch (Exception e) {
res.errorMessage = "ResourceType has to be REALTIME/OFFLINE/HYBRID : " + e.getMessage();
res.status = STATUS.failure;
LOGGER.error(e.toString());
throw new RuntimeException("ResourceType has to be REALTIME/OFFLINE/HYBRID.", e);
}
try {
switch (resourceType) {
case OFFLINE:
createNewOfflineDataResource(resource);
handleBrokerResource(resource);
break;
case REALTIME:
createNewRealtimeDataResource(resource);
handleBrokerResource(resource);
break;
case HYBRID:
// TODO(xiafu) : createNewHybridDataResource
break;
default:
break;
}
} catch (final Exception e) {
res.errorMessage = e.getMessage();
res.status = STATUS.failure;
LOGGER.error("Caught exception while creating cluster with config " + resource.toString(), e);
revertDataResource(resource);
throw new RuntimeException("Error creating cluster, have successfull rolled back", e);
}
res.status = STATUS.success;
return res;
}
private void createNewRealtimeDataResource(DataResource resource) {
RealtimeDataResourceMetadata realtimeDataResource = getRealtimeDataResourceMetadata(resource);
final List<String> unTaggedInstanceList = getOnlineUnTaggedServerInstanceList();
final String realtimeResourceName =
BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName());
final int numInstanceToUse = resource.getNumberOfDataInstances();
LOGGER.info("Trying to allocate " + numInstanceToUse + " instances.");
LOGGER.info("Current untagged boxes: " + unTaggedInstanceList.size());
if (unTaggedInstanceList.size() < numInstanceToUse) {
throw new UnsupportedOperationException("Cannot allocate enough hardware resource.");
}
for (int i = 0; i < numInstanceToUse; ++i) {
LOGGER.info("tag instance : " + unTaggedInstanceList.get(i).toString() + " to " + realtimeResourceName);
_helixAdmin.removeInstanceTag(_helixClusterName, unTaggedInstanceList.get(i),
CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
_helixAdmin.addInstanceTag(_helixClusterName, unTaggedInstanceList.get(i), realtimeResourceName);
}
// now lets build an ideal state
LOGGER.info("building empty ideal state for resource : " + realtimeResourceName);
final IdealState idealState =
PinotResourceIdealStateBuilder.buildInitialRealtimeIdealStateFor(realtimeResourceName,
resource.getNumberOfCopies(), resource.getNumberOfDataInstances(), realtimeDataResource, _helixAdmin,
_helixClusterName);
LOGGER.info("adding resource via the admin");
_helixAdmin.addResource(_helixClusterName, realtimeResourceName, idealState);
LOGGER.info("successfully added the resource : " + realtimeResourceName + " to the cluster");
// lets add resource configs
HelixHelper.updateResourceConfigsFor(resource.toResourceConfigMap(), realtimeResourceName, _helixClusterName,
_helixAdmin);
}
private RealtimeDataResourceMetadata getRealtimeDataResourceMetadata(DataResource resource) {
RealtimeDataResourceMetadata realtimeDataResourceMetadata = new RealtimeDataResourceMetadata();
// TODO: Adding all required fields here:
return realtimeDataResourceMetadata;
}
public void createNewOfflineDataResource(DataResource resource) {
final List<String> unTaggedInstanceList = getOnlineUnTaggedServerInstanceList();
final String offlineResourceName = BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName());
final int numInstanceToUse = resource.getNumberOfDataInstances();
LOGGER.info("Trying to allocate " + numInstanceToUse + " instances.");
LOGGER.info("Current untagged boxes: " + unTaggedInstanceList.size());
if (unTaggedInstanceList.size() < numInstanceToUse) {
throw new UnsupportedOperationException("Cannot allocate enough hardware resource.");
}
for (int i = 0; i < numInstanceToUse; ++i) {
LOGGER.info("tag instance : " + unTaggedInstanceList.get(i).toString() + " to " + offlineResourceName);
_helixAdmin.removeInstanceTag(_helixClusterName, unTaggedInstanceList.get(i),
CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
_helixAdmin.addInstanceTag(_helixClusterName, unTaggedInstanceList.get(i), offlineResourceName);
}
// now lets build an ideal state
LOGGER.info("building empty ideal state for resource : " + offlineResourceName);
final IdealState idealState =
PinotResourceIdealStateBuilder.buildEmptyIdealStateFor(offlineResourceName, resource.getNumberOfCopies(),
_helixAdmin, _helixClusterName);
LOGGER.info("adding resource via the admin");
_helixAdmin.addResource(_helixClusterName, offlineResourceName, idealState);
LOGGER.info("successfully added the resource : " + offlineResourceName + " to the cluster");
// lets add resource configs
HelixHelper.updateResourceConfigsFor(resource.toResourceConfigMap(), offlineResourceName, _helixClusterName,
_helixAdmin);
}
private List<String> getOnlineUnTaggedServerInstanceList() {
final List<String> instanceList =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
final List<String> liveInstances = HelixHelper.getLiveInstances(_helixClusterName, _helixZkManager);
instanceList.retainAll(liveInstances);
return instanceList;
}
private List<String> getOnlineUnTaggedBrokerInstanceList() {
final List<String> instanceList =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
final List<String> liveInstances = HelixHelper.getLiveInstances(_helixClusterName, _helixZkManager);
instanceList.retainAll(liveInstances);
return instanceList;
}
private void handleBrokerResource(DataResource resource) {
final BrokerTagResource brokerTagResource =
new BrokerTagResource(resource.getNumberOfBrokerInstances(), resource.getBrokerTagName());
BrokerDataResource brokerDataResource;
ResourceType resourceType = resource.getResourceType();
switch (resourceType) {
case OFFLINE:
brokerDataResource =
new BrokerDataResource(BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName()),
brokerTagResource);
createBrokerDataResource(brokerDataResource, brokerTagResource);
break;
case REALTIME:
brokerDataResource =
new BrokerDataResource(BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName()),
brokerTagResource);
createBrokerDataResource(brokerDataResource, brokerTagResource);
break;
case HYBRID:
brokerDataResource =
new BrokerDataResource(BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName()),
brokerTagResource);
createBrokerDataResource(brokerDataResource, brokerTagResource);
brokerDataResource =
new BrokerDataResource(BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName()),
brokerTagResource);
createBrokerDataResource(brokerDataResource, brokerTagResource);
break;
default:
break;
}
}
private void createBrokerDataResource(BrokerDataResource brokerDataResource, BrokerTagResource brokerTagResource) {
PinotResourceManagerResponse createBrokerResourceResp = null;
if (!HelixHelper.getBrokerTagList(_helixAdmin, _helixClusterName).contains(brokerTagResource.getTag())) {
createBrokerResourceResp = createBrokerResourceTag(brokerTagResource);
} else if (HelixHelper.getBrokerTag(_helixAdmin, _helixClusterName, brokerTagResource.getTag())
.getNumBrokerInstances() < brokerTagResource.getNumBrokerInstances()) {
createBrokerResourceResp = updateBrokerResourceTag(brokerTagResource);
}
if ((createBrokerResourceResp == null) || createBrokerResourceResp.isSuccessfull()) {
createBrokerResourceResp = createBrokerDataResource(brokerDataResource);
if (!createBrokerResourceResp.isSuccessfull()) {
throw new UnsupportedOperationException("Failed to update broker resource : "
+ createBrokerResourceResp.errorMessage);
}
} else {
throw new UnsupportedOperationException("Failed to create broker resource : "
+ createBrokerResourceResp.errorMessage);
}
}
private void revertDataResource(DataResource resource) {
ResourceType resourceType = resource.getResourceType();
switch (resourceType) {
case OFFLINE:
revertDataResourceFor(BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName()));
break;
case REALTIME:
revertDataResourceFor(BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName()));
break;
case HYBRID:
revertDataResourceFor(BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName()));
revertDataResourceFor(BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName()));
break;
default:
break;
}
}
private void revertDataResourceFor(String resourceName) {
final List<String> taggedInstanceList = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName, resourceName);
for (final String instance : taggedInstanceList) {
LOGGER.info("untag instance : " + instance.toString());
_helixAdmin.removeInstanceTag(_helixClusterName, instance, resourceName);
_helixAdmin.addInstanceTag(_helixClusterName, instance, CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
}
_helixAdmin.dropResource(_helixClusterName, resourceName);
}
public synchronized PinotResourceManagerResponse handleUpdateDataResource(DataResource resource) {
try {
ResourceType resourceType = resource.getResourceType();
String resourceName;
switch (resourceType) {
case OFFLINE:
resourceName = BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName());
return handleUpdateDataResourceFor(resourceName, resource);
case REALTIME:
resourceName = BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName());
return handleUpdateDataResourceFor(resourceName, resource);
case HYBRID:
resourceName = BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName());
PinotResourceManagerResponse res = handleUpdateDataResourceFor(resourceName, resource);
if (res.isSuccessfull()) {
resourceName = BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName());
return handleUpdateDataResourceFor(resourceName, resource);
} else {
return res;
}
default:
throw new RuntimeException("Unsupported operation for ResourceType: " + resourceType);
}
} catch (Exception e) {
PinotResourceManagerResponse res = new PinotResourceManagerResponse();
res.errorMessage = "ResourceType has to be REALTIME/OFFLINE/HYBRID : " + e.getMessage();
res.status = STATUS.failure;
LOGGER.error(e.toString());
return res;
}
}
public synchronized PinotResourceManagerResponse handleUpdateDataResourceFor(String resourceName,
DataResource resource) {
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
if (!_helixAdmin.getResourcesInCluster(_helixClusterName).contains(resourceName)) {
resp.status = STATUS.failure;
resp.errorMessage = String.format("Resource (%s) does not exist", resourceName);
return resp;
}
// Hardware assignment
final List<String> unTaggedInstanceList =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
final List<String> alreadyTaggedInstanceList =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, resourceName);
if (alreadyTaggedInstanceList.size() > resource.getNumberOfDataInstances()) {
resp.status = STATUS.failure;
resp.errorMessage =
String.format(
"Reducing cluster size is not supported for now, current number instances for resource (%s) is "
+ alreadyTaggedInstanceList.size(), resourceName);
return resp;
}
final int numInstanceToUse = resource.getNumberOfDataInstances() - alreadyTaggedInstanceList.size();
LOGGER.info("Already used boxes: " + alreadyTaggedInstanceList.size() + " instances.");
LOGGER.info("Trying to allocate " + numInstanceToUse + " instances.");
LOGGER.info("Current untagged boxes: " + unTaggedInstanceList.size());
if (unTaggedInstanceList.size() < numInstanceToUse) {
throw new UnsupportedOperationException("Cannot allocate enough hardware resource.");
}
for (int i = 0; i < numInstanceToUse; ++i) {
LOGGER.info("tag instance : " + unTaggedInstanceList.get(i).toString() + " to " + resourceName);
_helixAdmin.removeInstanceTag(_helixClusterName, unTaggedInstanceList.get(i),
CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
_helixAdmin.addInstanceTag(_helixClusterName, unTaggedInstanceList.get(i), resourceName);
}
// now lets build an ideal state
LOGGER.info("recompute ideal state for resource : " + resourceName);
final IdealState idealState =
PinotResourceIdealStateBuilder.updateExpandedDataResourceIdealStateFor(resourceName,
resource.getNumberOfCopies(), _helixAdmin, _helixClusterName);
LOGGER.info("update resource via the admin");
_helixAdmin.setResourceIdealState(_helixClusterName, resourceName, idealState);
LOGGER.info("successfully update the resource : " + resourceName + " to the cluster");
HelixHelper.updateResourceConfigsFor(resource.toResourceConfigMap(), resourceName, _helixClusterName, _helixAdmin);
resp.status = STATUS.success;
return resp;
}
public synchronized PinotResourceManagerResponse handleAddTableToDataResource(DataResource resource) {
String resourceName = null;
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
switch (resource.getResourceType()) {
case OFFLINE:
resourceName = BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName());
break;
case REALTIME:
resourceName = BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName());
break;
case HYBRID:
// TODO(xiafu) : adding hybrid logic.
break;
default:
resp.status = STATUS.failure;
resp.errorMessage = String.format("ResourceType is not valid : (%s)!", resource.getResourceType());
return resp;
}
final Set<String> tableNames = getAllTableNamesForResource(resourceName);
if (tableNames.contains(resource.getTableName())) {
resp.status = STATUS.failure;
resp.errorMessage =
String.format("Table name (%s) is already existed in resource (%s)", resource.getTableName(),
resource.getResourceName());
return resp;
}
tableNames.add(resource.getTableName());
final Map<String, String> tableConfig = new HashMap<String, String>();
tableConfig.put("tableName", StringUtils.join(tableNames, ","));
HelixHelper.updateResourceConfigsFor(tableConfig, resourceName, _helixClusterName, _helixAdmin);
resp.status = STATUS.success;
resp.errorMessage =
String.format("Adding table name (%s) to resource (%s)", resource.getTableName(), resource.getResourceName());
return resp;
}
public synchronized PinotResourceManagerResponse handleRemoveTableFromDataResource(DataResource resource) {
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
final Set<String> tableNames = getAllTableNamesForResource(resource.getResourceName());
if (!tableNames.contains(resource.getTableName())) {
resp.status = STATUS.failure;
resp.errorMessage =
String.format("Table name (%s) is not existed in resource (%s)", resource.getTableName(),
resource.getResourceName());
return resp;
}
tableNames.remove(resource.getTableName());
final Map<String, String> tableConfig = new HashMap<String, String>();
tableConfig.put("tableName", StringUtils.join(tableNames, ","));
HelixHelper.updateResourceConfigsFor(tableConfig, resource.getResourceName(), _helixClusterName, _helixAdmin);
deleteSegmentsInTable(resource.getResourceName(), resource.getTableName());
resp.status = STATUS.success;
resp.errorMessage =
String.format("Removing table name (%s) from resource (%s)", resource.getTableName(),
resource.getResourceName());
return resp;
}
private void deleteSegmentsInTable(String resourceName, String tableName) {
for (String segmentId : getAllSegmentsForTable(resourceName, tableName)) {
deleteSegment(resourceName, segmentId);
}
}
public synchronized PinotResourceManagerResponse handleUpdateDataResourceConfig(DataResource resource) {
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
HelixHelper.updateResourceConfigsFor(resource.toResourceConfigMap(), resource.getResourceName(), _helixClusterName,
_helixAdmin);
resp.status = STATUS.success;
resp.errorMessage = String.format("Resource (%s) properties have been updated", resource.getResourceName());
return resp;
}
public synchronized PinotResourceManagerResponse handleUpdateBrokerResource(DataResource resource) {
String resourceName = null;
switch (resource.getResourceType()) {
case OFFLINE:
resourceName = BrokerRequestUtils.getOfflineResourceNameForResource(resource.getResourceName());
break;
case REALTIME:
resourceName = BrokerRequestUtils.getRealtimeResourceNameForResource(resource.getResourceName());
break;
case HYBRID:
// TODO(xiafu):
break;
default:
break;
}
final String currentResourceBrokerTag =
HelixHelper.getResourceConfigsFor(_helixClusterName, resourceName, _helixAdmin).get(
CommonConstants.Helix.DataSource.BROKER_TAG_NAME);
;
if (!currentResourceBrokerTag.equals(resource.getBrokerTagName())) {
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
resp.status = STATUS.failure;
resp.errorMessage =
"Current broker tag for resource : " + resource + " is " + currentResourceBrokerTag
+ ", not match updated request broker tag : " + resource.getBrokerTagName();
return resp;
}
final BrokerTagResource brokerTagResource =
new BrokerTagResource(resource.getNumberOfBrokerInstances(), resource.getBrokerTagName());
final PinotResourceManagerResponse updateBrokerResourceTagResp = updateBrokerResourceTag(brokerTagResource);
if (updateBrokerResourceTagResp.isSuccessfull()) {
HelixHelper
.updateResourceConfigsFor(resource.toResourceConfigMap(), resourceName, _helixClusterName, _helixAdmin);
return createBrokerDataResource(new BrokerDataResource(resourceName, brokerTagResource));
} else {
return updateBrokerResourceTagResp;
}
}
public synchronized PinotResourceManagerResponse deleteResource(String resourceTag) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
// Remove broker tags
final String brokerResourceTag = "broker_" + resourceTag;
final List<String> taggedBrokerInstanceList =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, brokerResourceTag);
for (final String instance : taggedBrokerInstanceList) {
LOGGER.info("untagging broker instance : " + instance.toString());
_helixAdmin.removeInstanceTag(_helixClusterName, instance, brokerResourceTag);
_helixAdmin.addInstanceTag(_helixClusterName, instance, CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
}
// Update brokerResource idealStates
HelixHelper.deleteResourceFromBrokerResource(_helixAdmin, _helixClusterName, resourceTag);
HelixHelper.deleteBrokerDataResourceConfig(_helixAdmin, _helixClusterName, resourceTag);
// Delete data resource
if (!_helixAdmin.getResourcesInCluster(_helixClusterName).contains(resourceTag)) {
res.status = STATUS.failure;
res.errorMessage = String.format("Resource (%s) does not exist", resourceTag);
return res;
}
final List<String> taggedInstanceList = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName, resourceTag);
for (final String instance : taggedInstanceList) {
LOGGER.info("untagging instance : " + instance.toString());
_helixAdmin.removeInstanceTag(_helixClusterName, instance, resourceTag);
_helixAdmin.addInstanceTag(_helixClusterName, instance, CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE);
}
// remove from property store
_propertyStore.remove("/" + resourceTag, 0);
// dropping resource
_helixAdmin.dropResource(_helixClusterName, resourceTag);
res.status = STATUS.success;
return res;
}
public synchronized void restartResource(String resourceTag) {
final Set<String> allInstances =
HelixHelper.getAllInstancesForResource(HelixHelper.getResourceIdealState(_helixZkManager, resourceTag));
HelixHelper.toggleInstancesWithInstanceNameSet(allInstances, _helixClusterName, _helixAdmin, false);
HelixHelper.toggleInstancesWithInstanceNameSet(allInstances, _helixClusterName, _helixAdmin, true);
}
/*
* fetch list of segments assigned to a give resource from ideal state
*/
public Set<String> getAllSegmentsForResource(String resource) {
final IdealState state = HelixHelper.getResourceIdealState(_helixZkManager, resource);
return state.getPartitionSet();
}
public List<String> getAllSegmentsForTable(String resourceName, String tableName) {
List<ZNRecord> records =
_propertyStore.getChildren(PinotHelixUtils.constructPropertyStorePathForResource(resourceName), null,
AccessOption.PERSISTENT);
List<String> segmentsInTable = new ArrayList<String>();
for (ZNRecord record : records) {
if (record.getSimpleField(V1Constants.MetadataKeys.Segment.TABLE_NAME).equals(tableName)) {
segmentsInTable.add(record.getId());
}
}
return segmentsInTable;
}
/**
*
* @param resource
* @param segmentId
* @return
*/
public Map<String, String> getMetadataFor(String resource, String segmentId) {
final ZNRecord record =
_propertyStore.get(PinotHelixUtils.constructPropertyStorePathForSegment(resource, segmentId), null,
AccessOption.PERSISTENT);
return record.getSimpleFields();
}
/**
* For adding a new segment.
* Helix will compute the instance to assign this segment.
* Then update its ideal state.
*
* @param segmentMetadata
*/
public synchronized PinotResourceManagerResponse addSegment(SegmentMetadata segmentMetadata, String downloadUrl) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
try {
if (!matchResourceAndTableName(segmentMetadata)) {
res.status = STATUS.failure;
res.errorMessage =
"Reject segment: resource name and table name are not registered." + " Resource name: "
+ segmentMetadata.getResourceName() + ", Table name: " + segmentMetadata.getTableName() + "\n";
return res;
}
if (ifSegmentExisted(segmentMetadata)) {
if (ifRefreshAnExistedSegment(segmentMetadata)) {
final ZNRecord record =
_propertyStore.get(PinotHelixUtils.constructPropertyStorePathForSegment(
segmentMetadata.getResourceName(), segmentMetadata.getName()), null, AccessOption.PERSISTENT);
// new ZNRecord(segmentMetadata.getName());
Map<String, String> segmentMetadataMap = segmentMetadata.toMap();
for (String key : segmentMetadataMap.keySet()) {
record.setSimpleField(key, segmentMetadataMap.get(key));
}
record.setSimpleField(V1Constants.SEGMENT_DOWNLOAD_URL, downloadUrl);
record.setSimpleField(V1Constants.SEGMENT_REFRESH_TIME, String.valueOf(System.currentTimeMillis()));
_propertyStore.set(PinotHelixUtils.constructPropertyStorePathForSegment(segmentMetadata), record,
AccessOption.PERSISTENT);
LOGGER.info("Refresh segment : " + segmentMetadata.getName() + " to Property store");
if (updateExistedSegment(segmentMetadata)) {
res.status = STATUS.success;
}
}
} else {
final ZNRecord record = new ZNRecord(segmentMetadata.getName());
record.setSimpleFields(segmentMetadata.toMap());
record.setSimpleField(V1Constants.SEGMENT_DOWNLOAD_URL, downloadUrl);
record.setSimpleField(V1Constants.SEGMENT_PUSH_TIME, String.valueOf(System.currentTimeMillis()));
_propertyStore.create(PinotHelixUtils.constructPropertyStorePathForSegment(segmentMetadata), record,
AccessOption.PERSISTENT);
LOGGER.info("Added segment : " + segmentMetadata.getName() + " to Property store");
final IdealState idealState =
PinotResourceIdealStateBuilder
.addNewSegmentToIdealStateFor(segmentMetadata, _helixAdmin, _helixClusterName);
_helixAdmin.setResourceIdealState(_helixClusterName, segmentMetadata.getResourceName(), idealState);
res.status = STATUS.success;
}
} catch (final Exception e) {
res.status = STATUS.failure;
res.errorMessage = e.getMessage();
LOGGER.error("Caught exception while adding segment", e);
}
return res;
}
private boolean updateExistedSegment(SegmentMetadata segmentMetadata) {
final String resourceName = segmentMetadata.getResourceName();
final String segmentName = segmentMetadata.getName();
final IdealState currentIdealState = _helixAdmin.getResourceIdealState(_helixClusterName, resourceName);
final Set<String> currentInstanceSet = currentIdealState.getInstanceSet(segmentName);
for (final String instance : currentInstanceSet) {
currentIdealState.setPartitionState(segmentName, instance, "OFFLINE");
}
_helixAdmin.setResourceIdealState(_helixClusterName, resourceName, currentIdealState);
// wait until reflect in ExternalView
LOGGER.info("Wait until segment - " + segmentName + " to be OFFLINE in ExternalView");
if (!ifExternalViewChangeReflectedForState(resourceName, segmentName, "OFFLINE", _externalViewReflectTimeOut)) {
throw new RuntimeException("Cannot get OFFLINE state to be reflected on ExternalView changed for segment: "
+ segmentName);
}
for (final String instance : currentInstanceSet) {
currentIdealState.setPartitionState(segmentName, instance, "ONLINE");
}
_helixAdmin.setResourceIdealState(_helixClusterName, resourceName, currentIdealState);
// wait until reflect in ExternalView
LOGGER.info("Wait until segment - " + segmentName + " to be ONLINE in ExternalView");
if (!ifExternalViewChangeReflectedForState(resourceName, segmentName, "ONLINE", _externalViewReflectTimeOut)) {
throw new RuntimeException("Cannot get ONLINE state to be reflected on ExternalView changed for segment: "
+ segmentName);
}
LOGGER.info("Refresh is done for segment - " + segmentName);
return true;
}
private boolean ifExternalViewChangeReflectedForState(String resourceName, String segmentName, String targerStates,
long timeOutInMills) {
long timeOutTimeStamp = System.currentTimeMillis() + timeOutInMills;
boolean isSucess = true;
while (System.currentTimeMillis() < timeOutTimeStamp) {
// Will try to read data every 2 seconds.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
isSucess = true;
ExternalView externalView = _helixAdmin.getResourceExternalView(_helixClusterName, resourceName);
Map<String, String> segmentStatsMap = externalView.getStateMap(segmentName);
for (String instance : segmentStatsMap.keySet()) {
if (!segmentStatsMap.get(instance).equalsIgnoreCase(targerStates)) {
isSucess = false;
}
}
if (isSucess) {
break;
}
}
return isSucess;
}
private boolean ifSegmentExisted(SegmentMetadata segmentMetadata) {
if (segmentMetadata == null) {
return false;
}
return _propertyStore.exists(PinotHelixUtils.constructPropertyStorePathForSegment(segmentMetadata),
AccessOption.PERSISTENT);
}
private boolean ifRefreshAnExistedSegment(SegmentMetadata segmentMetadata) {
final ZNRecord record =
_propertyStore.get(PinotHelixUtils.constructPropertyStorePathForSegment(segmentMetadata), null,
AccessOption.PERSISTENT);
if (record == null) {
return false;
}
final SegmentMetadata existedSegmentMetadata = new SegmentMetadataImpl(record);
if (segmentMetadata.getIndexCreationTime() <= existedSegmentMetadata.getIndexCreationTime()) {
return false;
}
if (segmentMetadata.getCrc().equals(existedSegmentMetadata.getCrc())) {
return false;
}
return true;
}
private boolean matchResourceAndTableName(SegmentMetadata segmentMetadata) {
if (segmentMetadata == null || segmentMetadata.getResourceName() == null || segmentMetadata.getTableName() == null) {
LOGGER.error("SegmentMetadata or resource name or table name is null");
return false;
}
if (!getAllResourceNames().contains(segmentMetadata.getResourceName())) {
LOGGER.error("Resource is not registered");
return false;
}
if (!getAllTableNamesForResource(segmentMetadata.getResourceName()).contains(segmentMetadata.getTableName())) {
LOGGER.error("Table " + segmentMetadata.getTableName() + " is not registered for resource: "
+ segmentMetadata.getResourceName());
return false;
}
return true;
}
private Set<String> getAllTableNamesForResource(String resourceName) {
final Set<String> tableNameSet = new HashSet<String>();
tableNameSet.addAll(Arrays.asList(HelixHelper.getResourceConfigsFor(_helixClusterName, resourceName, _helixAdmin)
.get("tableName").trim().split(",")));
LOGGER.info("Current holding tables for resource: " + resourceName + " is "
+ Arrays.toString(tableNameSet.toArray(new String[0])));
return tableNameSet;
}
public synchronized PinotResourceManagerResponse addInstance(Instance instance) {
final PinotResourceManagerResponse resp = new PinotResourceManagerResponse();
final List<String> instances = HelixHelper.getAllInstances(_helixAdmin, _helixClusterName);
if (instances.contains(instance.toInstanceId())) {
resp.status = STATUS.failure;
resp.errorMessage = "instance already exist";
return resp;
} else {
_helixAdmin.addInstance(_helixClusterName, instance.toInstanceConfig());
resp.status = STATUS.success;
resp.errorMessage = "";
return resp;
}
}
/**
* TODO(xiafu) : Due to the issue of helix, if remove the segment from idealState directly, the node won't get transaction,
* so we first disable the segment, then remove it from idealState, then enable the segment. This will trigger transactions.
* After the helix patch, we can refine the logic here by directly drop the segment from idealState.
*
* @param resourceName
* @param segmentId
* @return
*/
public synchronized PinotResourceManagerResponse deleteSegment(final String resourceName, final String segmentId) {
LOGGER.info("Trying to delete segment : " + segmentId);
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
try {
IdealState idealState = _helixAdmin.getResourceIdealState(_helixClusterName, resourceName);
idealState =
PinotResourceIdealStateBuilder.dropSegmentFromIdealStateFor(resourceName, segmentId, _helixAdmin,
_helixClusterName);
_helixAdmin.setResourceIdealState(_helixClusterName, resourceName, idealState);
idealState =
PinotResourceIdealStateBuilder.removeSegmentFromIdealStateFor(resourceName, segmentId, _helixAdmin,
_helixClusterName);
_helixAdmin.setResourceIdealState(_helixClusterName, resourceName, idealState);
_segmentDeletionManager.deleteSegment(resourceName, segmentId);
res.status = STATUS.success;
} catch (final Exception e) {
res.status = STATUS.failure;
res.errorMessage = e.getMessage();
}
return res;
}
/**
* Assign untagged broker instances to a given tag.
* Broker tag is required to have prefix : "broker_".
*
* @param brokerTagResource
* @return
*/
public synchronized PinotResourceManagerResponse createBrokerResourceTag(BrokerTagResource brokerTagResource) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
if (!brokerTagResource.getTag().startsWith(CommonConstants.Helix.PREFIX_OF_BROKER_RESOURCE_TAG)) {
res.status = STATUS.failure;
res.errorMessage =
"Broker tag is required to have prefix : " + CommonConstants.Helix.PREFIX_OF_BROKER_RESOURCE_TAG;
LOGGER.error(res.errorMessage);
return res;
}
// @xiafu : should this be contains or equals to
if (HelixHelper.getBrokerTagList(_helixAdmin, _helixClusterName).contains(brokerTagResource.getTag())) {
return updateBrokerResourceTag(brokerTagResource);
}
final List<String> untaggedBrokerInstances = getOnlineUnTaggedBrokerInstanceList();
if (untaggedBrokerInstances.size() < brokerTagResource.getNumBrokerInstances()) {
res.status = STATUS.failure;
res.errorMessage =
"Failed to create tag : " + brokerTagResource.getTag() + ", Current number of untagged broker instances : "
+ untaggedBrokerInstances.size() + ", required : " + brokerTagResource.getNumBrokerInstances();
LOGGER.error(res.errorMessage);
return res;
}
for (int i = 0; i < brokerTagResource.getNumBrokerInstances(); ++i) {
_helixAdmin.removeInstanceTag(_helixClusterName, untaggedBrokerInstances.get(i),
CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
_helixAdmin.addInstanceTag(_helixClusterName, untaggedBrokerInstances.get(i), brokerTagResource.getTag());
}
HelixHelper.updateBrokerTag(_helixAdmin, _helixClusterName, brokerTagResource);
res.status = STATUS.success;
return res;
}
/**
* This will take care of update a brokerResource tag.
* Adding a new untagged broker instance.
*
* @param brokerTagResource
* @return
*/
private synchronized PinotResourceManagerResponse updateBrokerResourceTag(BrokerTagResource brokerTagResource) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
final BrokerTagResource currentBrokerTag =
HelixHelper.getBrokerTag(_helixAdmin, _helixClusterName, brokerTagResource.getTag());
if (currentBrokerTag.getNumBrokerInstances() < brokerTagResource.getNumBrokerInstances()) {
// Add more broker instances to this tag
final int numBrokerInstancesToTag =
brokerTagResource.getNumBrokerInstances() - currentBrokerTag.getNumBrokerInstances();
final List<String> untaggedBrokerInstances =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
if (untaggedBrokerInstances.size() < numBrokerInstancesToTag) {
res.status = STATUS.failure;
res.errorMessage =
"Failed to allocate broker instances to Tag : " + brokerTagResource.getTag()
+ ", Current number of untagged broker instances : " + untaggedBrokerInstances.size()
+ ", current number of tagged instances : " + currentBrokerTag.getNumBrokerInstances()
+ ", updated number of tagged instances : " + brokerTagResource.getNumBrokerInstances();
LOGGER.error(res.errorMessage);
return res;
}
for (int i = 0; i < numBrokerInstancesToTag; ++i) {
_helixAdmin.removeInstanceTag(_helixClusterName, untaggedBrokerInstances.get(i),
CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
_helixAdmin.addInstanceTag(_helixClusterName, untaggedBrokerInstances.get(i), brokerTagResource.getTag());
}
} else {
// Remove broker instances from this tag
// TODO(xiafu) : There is rebalancing work and dataResource config changes around the removing.
final int numBrokerInstancesToRemove =
currentBrokerTag.getNumBrokerInstances() - brokerTagResource.getNumBrokerInstances();
final List<String> taggedBrokerInstances =
_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, brokerTagResource.getTag());
unTagBrokerInstance(taggedBrokerInstances.subList(0, numBrokerInstancesToRemove), brokerTagResource.getTag());
}
HelixHelper.updateBrokerTag(_helixAdmin, _helixClusterName, brokerTagResource);
res.status = STATUS.success;
return res;
}
public synchronized PinotResourceManagerResponse deleteBrokerResourceTag(String brokerTag) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
if (!HelixHelper.getBrokerTagList(_helixAdmin, _helixClusterName).contains(brokerTag)) {
res.status = STATUS.failure;
res.errorMessage = "Broker resource tag is not existed!";
return res;
}
// Remove broker instances from this tag
final List<String> taggedBrokerInstances = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName, brokerTag);
unTagBrokerInstance(taggedBrokerInstances, brokerTag);
HelixHelper.deleteBrokerTagFromResourceConfig(_helixAdmin, _helixClusterName, brokerTag);
res.status = STATUS.success;
return res;
}
private void unTagBrokerInstance(List<String> brokerInstancesToUntag, String brokerTag) {
final IdealState brokerIdealState = HelixHelper.getBrokerIdealStates(_helixAdmin, _helixClusterName);
final List<String> dataResourceList = new ArrayList(brokerIdealState.getPartitionSet());
for (final String dataResource : dataResourceList) {
final Set<String> instances = brokerIdealState.getInstanceSet(dataResource);
brokerIdealState.getPartitionSet().remove(dataResource);
for (final String instance : instances) {
if (!brokerInstancesToUntag.contains(instance)) {
brokerIdealState.setPartitionState(dataResource, instance, "ONLINE");
}
}
}
_helixAdmin.setResourceIdealState(_helixClusterName, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE,
brokerIdealState);
for (final String brokerInstanceToUntag : brokerInstancesToUntag) {
_helixAdmin.removeInstanceTag(_helixClusterName, brokerInstanceToUntag, brokerTag);
_helixAdmin.addInstanceTag(_helixClusterName, brokerInstanceToUntag,
CommonConstants.Helix.UNTAGGED_BROKER_INSTANCE);
}
}
public synchronized PinotResourceManagerResponse createBrokerDataResource(BrokerDataResource brokerDataResource) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
try {
LOGGER.info("Trying to update BrokerDataResource with config: \n" + brokerDataResource.toString());
if (_helixAdmin.getInstancesInClusterWithTag(_helixClusterName, brokerDataResource.getTag()).isEmpty()) {
res.status = STATUS.failure;
res.errorMessage = "broker resource tag : " + brokerDataResource.getTag() + " is not existed!";
LOGGER.error(res.toString());
return res;
}
LOGGER.info("Trying to update BrokerDataResource Config!");
HelixHelper.updateBrokerDataResource(_helixAdmin, _helixClusterName, brokerDataResource);
LOGGER.info("Trying to update BrokerDataResource IdealState!");
final IdealState idealState =
PinotResourceIdealStateBuilder.addBrokerResourceToIdealStateFor(brokerDataResource, _helixAdmin,
_helixClusterName);
if (idealState != null) {
_helixAdmin
.setResourceIdealState(_helixClusterName, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE, idealState);
}
res.status = STATUS.success;
} catch (final Exception e) {
res.status = STATUS.failure;
res.errorMessage = e.getMessage();
LOGGER.error(res.toString());
}
return res;
}
public synchronized PinotResourceManagerResponse deleteBrokerDataResource(String brokerDataResourceName) {
final PinotResourceManagerResponse res = new PinotResourceManagerResponse();
try {
IdealState idealState =
_helixAdmin.getResourceIdealState(_helixClusterName, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE);
final Set<String> instanceNames = idealState.getInstanceSet(CommonConstants.Helix.BROKER_RESOURCE_INSTANCE);
for (final String instanceName : instanceNames) {
_helixAdmin.enablePartition(false, _helixClusterName, instanceName,
CommonConstants.Helix.BROKER_RESOURCE_INSTANCE, Arrays.asList(brokerDataResourceName));
}
idealState =
PinotResourceIdealStateBuilder.removeBrokerResourceFromIdealStateFor(brokerDataResourceName, _helixAdmin,
_helixClusterName);
_helixAdmin.setResourceIdealState(_helixClusterName, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE, idealState);
for (final String instanceName : instanceNames) {
_helixAdmin.enablePartition(true, _helixClusterName, instanceName,
CommonConstants.Helix.BROKER_RESOURCE_INSTANCE, Arrays.asList(brokerDataResourceName));
}
HelixHelper.deleteBrokerDataResourceConfig(_helixAdmin, _helixClusterName, brokerDataResourceName);
res.status = STATUS.success;
} catch (final Exception e) {
res.status = STATUS.failure;
res.errorMessage = e.getMessage();
}
return res;
}
public void startInstances(List<String> instances) {
HelixHelper.toggleInstancesWithPinotInstanceList(instances, _helixClusterName, _helixAdmin, false);
HelixHelper.toggleInstancesWithPinotInstanceList(instances, _helixClusterName, _helixAdmin, true);
}
@Override
public String toString() {
return "yay! i am alive and kicking, clusterName is : " + _helixClusterName + " zk url is : " + _zkBaseUrl;
}
public ZkHelixPropertyStore<ZNRecord> getPropertyStore() {
return _propertyStore;
}
public HelixAdmin getHelixAdmin() {
return _helixAdmin;
}
public String getHelixClusterName() {
return _helixClusterName;
}
public boolean isLeader() {
return _helixZkManager.isLeader();
}
public HelixManager getHelixZkManager() {
return _helixZkManager;
}
} |
package gr.sperfect.djuqbox.webapp.client;
import java.util.List;
import org.fusesource.restygwt.client.Defaults;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import gr.sperfect.djuqbox.webapp.shared.FieldVerifier;
import gr.sperfect.djuqbox.webapp.shared.data.Room;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class DJuQBox implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network " + "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting
* service.
*/
private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// set RestyGWT roor url
Defaults.setServiceRoot(GWT.getHostPageBaseURL() + "rest/");
final Button sendButton = new Button("Send test3");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
// test Resty
testResty();
sendNameToServer();
}
private void testResty() {
RestApiService api = GWT.create(RestApiService.class);
api.getAll(new MethodCallback<List<Room>>() {
@Override
public void onSuccess(Method method, List<Room> response) {
// all ok
Window.alert("OK");
}
@Override
public void onFailure(Method method, Throwable exception) {
// error
Window.alert("error: " + exception.getMessage());
}
});
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
/**
* Send the name from the nameField to the server and wait for a
* response.
*/
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
errorLabel.setText("Please enter at least four characters");
return;
}
// Then, we send the input to the server.
sendButton.setEnabled(false);
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
greetingService.greetServer(textToServer, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox.setText("Remote Procedure Call - Failure");
serverResponseLabel.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Remote Procedure Call");
serverResponseLabel.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
} |
package com.python.pydev.analysis;
import java.util.List;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.python.pydev.core.docutils.ImportHandle;
import org.python.pydev.core.docutils.ImportHandle.ImportHandleInfo;
import org.python.pydev.core.docutils.ImportNotRecognizedException;
import org.python.pydev.core.docutils.PyImportsHandling;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.core.docutils.PySelection.LineStartingScope;
import org.python.pydev.core.log.Log;
import org.python.pydev.editor.PyEdit;
import org.python.pydev.editor.actions.PyAction;
import org.python.pydev.editor.autoedit.DefaultIndentPrefs;
import org.python.pydev.editor.codecompletion.AbstractPyCompletionProposalExtension2;
import org.python.pydev.editor.codefolding.PySourceViewer;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.plugin.preferences.PydevPrefs;
import org.python.pydev.ui.importsconf.ImportsPreferencesPage;
/**
* This is the proposal that should be used to do a completion that can have a related import.
*
* @author Fabio
*/
public class CtxInsensitiveImportComplProposal extends AbstractPyCompletionProposalExtension2 implements ICompletionProposalExtension{
/**
* If empty, act as a regular completion
*/
public String realImportRep;
/**
* This is the indentation string that should be used
*/
public String indentString;
/**
* Determines if the import was added or if only the completion was applied.
*/
private int importLen = 0;
/**
* Offset forced to be returned (only valid if >= 0)
*/
private int newForcedOffset = -1;
/**
* Indicates if the completion was applied with a trigger char that should be considered
* (meaning that the resulting position should be summed with 1)
*/
private boolean appliedWithTrigger = false;
/**
* If the import should be added locally or globally.
*/
private boolean addLocalImport = false;
public CtxInsensitiveImportComplProposal(String replacementString, int replacementOffset, int replacementLength,
int cursorPosition, Image image, String displayString, IContextInformation contextInformation,
String additionalProposalInfo, int priority,
String realImportRep) {
super(replacementString, replacementOffset, replacementLength, cursorPosition, image, displayString,
contextInformation, additionalProposalInfo, priority, ON_APPLY_DEFAULT, "");
this.realImportRep = realImportRep;
}
public void setAddLocalImport(boolean b) {
this.addLocalImport = b;
}
/**
* This is the apply that should actually be called!
*/
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
IDocument document = viewer.getDocument();
if(viewer instanceof PySourceViewer){
PySourceViewer pySourceViewer = (PySourceViewer) viewer;
PyEdit pyEdit = pySourceViewer.getEdit();
this.indentString = pyEdit.getIndentPrefs().getIndentationString();
}else{
//happens on compare editor
this.indentString = new DefaultIndentPrefs().getIndentationString();
}
//If the completion is applied with shift pressed, do a local import. Note that the user is only actually
//able to do that if the popup menu is focused (i.e.: request completion and do a tab to focus it, instead
//of having the focus on the editor and just pressing up/down).
if((stateMask & SWT.SHIFT) != 0){
this.setAddLocalImport(true);
}
apply(document, trigger, stateMask, offset);
}
/**
* Note: This apply is not directly called (it's called through
* {@link CtxInsensitiveImportComplProposal#apply(ITextViewer, char, int, int)})
*
* This is the point where the completion is written. It has to be written and if some import is also available
* it should be inserted at this point.
*
* We have to be careful to only add an import if that's really needed (e.g.: there's no other import that
* equals the import that should be added).
*
* Also, we have to check if this import should actually be grouped with another import that already exists.
* (and it could be a multi-line import)
*/
public void apply(IDocument document, char trigger, int stateMask, int offset) {
if(this.indentString == null){
throw new RuntimeException("Indent string not set (not called with a PyEdit as viewer?)");
}
if(!triggerCharAppliesCurrentCompletion(trigger, document, offset)){
newForcedOffset = offset+1; //+1 because that's the len of the trigger
return;
}
try {
PySelection selection = new PySelection(document);
int lineToAddImport=-1;
ImportHandleInfo groupInto=null;
ImportHandleInfo realImportHandleInfo = null;
boolean groupImports = ImportsPreferencesPage.getGroupImports();
LineStartingScope previousLineThatStartsScope = null;
PySelection ps = null;
if(this.addLocalImport){
ps = new PySelection(document, offset);
int startLineIndex = ps.getStartLineIndex();
if(startLineIndex == 0){
this.addLocalImport = false;
}else{
previousLineThatStartsScope = ps.getPreviousLineThatStartsScope(startLineIndex-1);
if(previousLineThatStartsScope == null){
//note that if we have no previous scope, it means we're actually on the global scope, so,
//proceed as usual...
this.addLocalImport = false;
}
}
}
if (realImportRep.length() > 0 && !this.addLocalImport){
//when importing from __future__ import with_statement, we actually want to add a 'with' token, not
//with_statement token.
boolean isWithStatement = realImportRep.equals("from __future__ import with_statement");
if(isWithStatement){
this.fReplacementString = "with";
}
if(groupImports){
try {
realImportHandleInfo = new ImportHandleInfo(realImportRep);
PyImportsHandling importsHandling = new PyImportsHandling(document);
for(ImportHandle handle:importsHandling){
if(handle.contains(realImportHandleInfo)){
lineToAddImport = -2; //signal that there's no need to find a line available to add the import
break;
}else if(groupInto == null && realImportHandleInfo.getFromImportStr() != null){
List<ImportHandleInfo> handleImportInfo = handle.getImportInfo();
for (ImportHandleInfo importHandleInfo : handleImportInfo) {
if(realImportHandleInfo.getFromImportStr().equals(importHandleInfo.getFromImportStr())){
List<String> commentsForImports = importHandleInfo.getCommentsForImports();
if(commentsForImports.size() > 0 && commentsForImports.get(commentsForImports.size()-1).length() == 0){
groupInto = importHandleInfo;
break;
}
}
}
}
}
} catch (ImportNotRecognizedException e1) {
Log.log(e1);//that should not happen at this point
}
}
if(lineToAddImport == -1){
boolean isFutureImport = PySelection.isFutureImportLine(this.realImportRep);
lineToAddImport = selection.getLineAvailableForImport(isFutureImport);
}
}else{
lineToAddImport = -1;
}
String delimiter = PyAction.getDelimiter(document);
appliedWithTrigger = trigger == '.' || trigger == '(';
String appendForTrigger = "";
if(appliedWithTrigger){
if(trigger == '('){
appendForTrigger = "()";
} else if(trigger == '.'){
appendForTrigger = ".";
}
}
//if the trigger is ')', just let it apply regularly -- so, ')' will only be added if it's already in the completion.
//first do the completion
if(fReplacementString.length() > 0){
int dif = offset - fReplacementOffset;
document.replace(offset-dif, dif+this.fLen, fReplacementString+appendForTrigger);
}
if(this.addLocalImport){
//All the code below is because we don't want to work with a generated AST (as it may not be there),
//so, we go to the previous scope, find out the valid indent inside it and then got backwards
//from the position we're in now to find the closer location to where we're now where we're
//actually able to add the import.
try {
int iLineStartingScope;
if(previousLineThatStartsScope != null){
iLineStartingScope = previousLineThatStartsScope.iLineStartingScope;
//Go to a non-empty line from the line we have and the line we're currently in.
int iLine = iLineStartingScope+1;
String line = ps.getLine(iLine);
int startLineIndex = ps.getStartLineIndex();
while(iLine < startLineIndex && (line.startsWith("#") || line.trim().length() == 0)){
iLine++;
line = ps.getLine(iLine);
}
if(iLine >= startLineIndex){
//Sanity check!
iLine = startLineIndex;
line = ps.getLine(iLine);
}
int firstCharPos = PySelection.getFirstCharPosition(line);
//Ok, all good so far, now, this would add the line to the beginning of
//the element (after the if statement, def, etc.), let's try to put
//it closer to where we're now (but still in a valid position).
int j = startLineIndex;
while(j >= 0){
String line2 = ps.getLine(j);
if(PySelection.getFirstCharPosition(line2) == firstCharPos){
iLine = j;
break;
}
if(j == iLineStartingScope){
break;
}
j
}
String indent = line.substring(0, firstCharPos);
String strToAdd = indent+realImportRep+delimiter;
ps.addLine(strToAdd, iLine-1); //Will add it just after the line passed as a parameter.
importLen = strToAdd.length();
return;
}
} catch (Exception e) {
Log.log(e); //Something went wrong, add it as global (i.e.: BUG)
}
}
if(groupInto != null && realImportHandleInfo != null){
//let's try to group it
int maxCols = 80;
if(PydevPlugin.getDefault() != null){
IPreferenceStore chainedPrefStore = PydevPrefs.getChainedPrefStore();
maxCols = chainedPrefStore.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN);
}
int endLine = groupInto.getEndLine();
IRegion lineInformation = document.getLineInformation(endLine);
String strToAdd = ", "+realImportHandleInfo.getImportedStr().get(0);
String line = PySelection.getLine(document, endLine);
if(line.length() + strToAdd.length() > maxCols){
if(line.indexOf('
//no comments: just add it in the next line
int len = line.length();
if(line.trim().endsWith(")")){
len = line.indexOf(")");
strToAdd = ","+delimiter+indentString+realImportHandleInfo.getImportedStr().get(0);
}else{
strToAdd = ",\\"+delimiter+indentString+realImportHandleInfo.getImportedStr().get(0);
}
int end = lineInformation.getOffset()+len;
importLen = strToAdd.length();
document.replace(end, 0, strToAdd);
return;
}
}else{
//regular addition (it won't pass the number of columns expected).
line = PySelection.getLineWithoutCommentsOrLiterals(line);
int len = line.length();
if(line.trim().endsWith(")")){
len = line.indexOf(")");
}
int end = lineInformation.getOffset()+len;
importLen = strToAdd.length();
document.replace(end, 0, strToAdd);
return;
}
}
//if we got here, it hasn't been added in a grouped way, so, let's add it in a new import
if(lineToAddImport >=0 && lineToAddImport <= document.getNumberOfLines()){
IRegion lineInformation = document.getLineInformation(lineToAddImport);
String strToAdd = realImportRep+delimiter;
importLen = strToAdd.length();
document.replace(lineInformation.getOffset(), 0, strToAdd);
return;
}
} catch (BadLocationException x) {
Log.log(x);
}
}
@Override
public Point getSelection(IDocument document) {
if(newForcedOffset >= 0){
return new Point(newForcedOffset, 0);
}
int pos = fReplacementOffset+fReplacementString.length()+importLen;
if(appliedWithTrigger){
pos += 1;
}
return new Point(pos, 0 );
}
public String getInternalDisplayStringRepresentation() {
return fReplacementString;
}
/**
* If another proposal with the same name exists, this method will be called to determine if
* both completions should coexist or if one of them should be removed.
*/
@Override
public int getOverrideBehavior(ICompletionProposal curr) {
if(curr instanceof CtxInsensitiveImportComplProposal){
if(curr.getDisplayString().equals(getDisplayString())){
return BEHAVIOR_IS_OVERRIDEN;
}else{
return BEHAVIOR_COEXISTS;
}
}else{
return BEHAVIOR_IS_OVERRIDEN;
}
}
} |
package org.jkiss.dbeaver.ui.editors.sql.syntax;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.contentassist.*;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.navigator.DBNNode;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.*;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.dbeaver.runtime.properties.PropertyCollector;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.TextUtils;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.dbeaver.ui.editors.sql.SQLPreferenceConstants;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLContext;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplateCompletionProposal;
import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesRegistry;
import org.jkiss.utils.CommonUtils;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The SQL content assist processor. This content assist processor proposes text
* completions and computes context information for a SQL content type.
*/
public class SQLCompletionProcessor implements IContentAssistProcessor
{
private static final Log log = Log.getLog(SQLCompletionProcessor.class);
private enum QueryType {
TABLE,
COLUMN
}
private SQLEditorBase editor;
private IContextInformationValidator validator = new Validator();
private int documentOffset;
private String activeQuery = null;
private SQLWordPartDetector wordDetector;
private static boolean lookupTemplates = false;
public SQLCompletionProcessor(SQLEditorBase editor)
{
this.editor = editor;
}
public static boolean isLookupTemplates() {
return lookupTemplates;
}
public static void setLookupTemplates(boolean lookupTemplates) {
SQLCompletionProcessor.lookupTemplates = lookupTemplates;
}
@Override
public ICompletionProposal[] computeCompletionProposals(
ITextViewer viewer,
int documentOffset)
{
this.documentOffset = documentOffset;
this.activeQuery = null;
this.wordDetector = new SQLWordPartDetector(viewer.getDocument(), editor.getSyntaxManager(), documentOffset);
final String wordPart = wordDetector.getWordPart();
if (lookupTemplates) {
return makeTemplateProposals(viewer, documentOffset, wordPart);
}
final List<SQLCompletionProposal> proposals = new ArrayList<>();
QueryType queryType = null;
{
final String prevKeyWord = wordDetector.getPrevKeyWord();
if (!CommonUtils.isEmpty(prevKeyWord)) {
if (editor.getSyntaxManager().getDialect().isEntityQueryWord(prevKeyWord)) {
// TODO: its an ugly hack. Need a better way
if (SQLConstants.KEYWORD_INTO.equals(prevKeyWord) &&
!CommonUtils.isEmpty(wordDetector.getPrevWords()) &&
("(".equals(wordDetector.getPrevDelimiter()) || ",".equals(wordDetector.getPrevDelimiter())))
{
queryType = QueryType.COLUMN;
} else {
queryType = QueryType.TABLE;
}
} else if (editor.getSyntaxManager().getDialect().isAttributeQueryWord(prevKeyWord)) {
queryType = QueryType.COLUMN;
}
}
}
if (queryType != null && wordPart != null) {
if (editor.getDataSource() != null) {
ProposalSearchJob searchJob = new ProposalSearchJob(proposals, wordPart, queryType);
searchJob.schedule();
// Wait until job finished
Display display = Display.getCurrent();
while (!searchJob.finished) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.update();
}
}
if (proposals.isEmpty() || !CommonUtils.isEmpty(wordPart)) {
// Keyword assist
List<String> matchedKeywords = editor.getSyntaxManager().getDialect().getMatchedKeywords(wordPart);
for (String keyWord : matchedKeywords) {
DBPKeywordType keywordType = editor.getSyntaxManager().getDialect().getKeywordType(keyWord);
if (keywordType != null) {
proposals.add(
createCompletionProposal(
keyWord,
keyWord,
keyWord + " (" + keywordType.name() + ")",
null,
false,
null)
);
}
}
}
// Remove duplications
for (int i = 0; i < proposals.size(); i++) {
SQLCompletionProposal proposal = proposals.get(i);
for (int j = i + 1; j < proposals.size(); ) {
SQLCompletionProposal proposal2 = proposals.get(j);
if (proposal.getDisplayString().equals(proposal2.getDisplayString())) {
proposals.remove(j);
} else {
j++;
}
}
}
DBSObject selectedObject = DBUtils.getSelectedObject(editor.getDataSource(), true);
boolean hideDups = getPreferences().getBoolean(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS) && selectedObject != null;
if (hideDups) {
for (int i = 0; i < proposals.size(); i++) {
SQLCompletionProposal proposal = proposals.get(i);
for (int j = 0; j < proposals.size(); ) {
SQLCompletionProposal proposal2 = proposals.get(j);
if (i != j && proposal.hasStructObject() && proposal2.hasStructObject() &&
CommonUtils.equalObjects(proposal.getObject().getName(), proposal2.getObject().getName()) &&
proposal.getObjectContainer() == selectedObject) {
proposals.remove(j);
} else {
j++;
}
}
}
}
if (hideDups) {
// Remove duplicates from non-active schema
if (selectedObject instanceof DBSObjectContainer) {
//List<ICompletionProposal>
}
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
@NotNull
private ICompletionProposal[] makeTemplateProposals(ITextViewer viewer, int documentOffset, String wordPart) {
wordPart = wordPart.toLowerCase();
final List<SQLTemplateCompletionProposal> templateProposals = new ArrayList<>();
// Templates
for (Template template : editor.getTemplatesPage().getTemplateStore().getTemplates()) {
if (template.getName().toLowerCase().startsWith(wordPart)) {
templateProposals.add(new SQLTemplateCompletionProposal(
template,
new SQLContext(
SQLTemplatesRegistry.getInstance().getTemplateContextRegistry().getContextType(template.getContextTypeId()),
viewer.getDocument(),
new Position(wordDetector.getStartOffset(), wordDetector.getLength()),
editor),
new Region(documentOffset, 0),
null));
}
}
Collections.sort(templateProposals, new Comparator<SQLTemplateCompletionProposal>() {
@Override
public int compare(SQLTemplateCompletionProposal o1, SQLTemplateCompletionProposal o2) {
return o1.getDisplayString().compareTo(o2.getDisplayString());
}
});
return templateProposals.toArray(new ICompletionProposal[templateProposals.size()]);
}
private void makeStructureProposals(
final DBRProgressMonitor monitor,
final List<SQLCompletionProposal> proposals,
final String wordPart,
final QueryType queryType)
{
DBPDataSource dataSource = editor.getDataSource();
if (dataSource == null) {
return;
}
if (queryType != null) {
// Try to determine which object is queried (if wordPart is not empty)
// or get list of root database objects
if (wordPart.length() == 0) {
// Get root objects
DBPObject rootObject = null;
if (queryType == QueryType.COLUMN && dataSource instanceof DBSObjectContainer) {
// Try to detect current table
rootObject = getTableFromAlias(monitor, (DBSObjectContainer)dataSource, null);
} else if (dataSource instanceof DBSObjectContainer) {
// Try to get from active object
DBSObject selectedObject = DBUtils.getActiveInstanceObject(dataSource);
if (selectedObject != null) {
makeProposalsFromChildren(monitor, selectedObject, null, proposals);
rootObject = DBUtils.getPublicObject(selectedObject.getParentObject());
} else {
rootObject = dataSource;
}
}
if (rootObject != null) {
makeProposalsFromChildren(monitor, rootObject, null, proposals);
}
} else {
DBSObject rootObject = null;
if (queryType == QueryType.COLUMN && dataSource instanceof DBSObjectContainer) {
// Part of column name
// Try to get from active object
DBSObjectContainer sc = (DBSObjectContainer) dataSource;
DBSObject selectedObject = DBUtils.getActiveInstanceObject(dataSource);
if (selectedObject instanceof DBSObjectContainer) {
sc = (DBSObjectContainer)selectedObject;
}
int divPos = wordPart.indexOf(editor.getSyntaxManager().getStructSeparator());
String tableAlias = divPos == -1 ? null : wordPart.substring(0, divPos);
rootObject = getTableFromAlias(monitor, sc, tableAlias);
}
if (rootObject != null) {
makeProposalsFromChildren(monitor, rootObject, wordPart, proposals);
} else {
// Get root object or objects from active database (if any)
makeStructureProposals(monitor, dataSource, proposals);
}
}
} else {
// Get list of sub-objects (filtered by wordPart)
makeStructureProposals(monitor, dataSource, proposals);
}
}
private void makeStructureProposals(
DBRProgressMonitor monitor,
DBPDataSource dataSource,
List<SQLCompletionProposal> proposals)
{
final DBSObjectContainer rootContainer = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
if (rootContainer == null) {
return;
}
DBSObjectContainer selectedContainer = null;
{
DBSObject selectedObject = DBUtils.getSelectedObject(dataSource, false);
if (selectedObject != null) {
selectedContainer = DBUtils.getAdapter(DBSObjectContainer.class, selectedObject);
}
}
DBSObjectContainer sc = rootContainer;
DBSObject childObject = sc;
List<String> tokens = wordDetector.splitWordPart();
String lastToken = null;
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
if (i == tokens.size() - 1 && !wordDetector.getWordPart().endsWith(".")) {
lastToken = token;
break;
}
if (sc == null) {
break;
}
// Get next structure container
try {
token = DBUtils.getUnQuotedIdentifier(dataSource, token);
String objectName = DBObjectNameCaseTransformer.transformName(dataSource, token);
childObject = sc.getChild(monitor, objectName);
if (childObject == null && i == 0 && selectedContainer != null) {
// Probably it is from selected object, let's try it
childObject = selectedContainer.getChild(monitor, objectName);
if (childObject != null) {
sc = selectedContainer;
}
}
if (childObject == null) {
if (i == 0) {
// Assume it's a table alias ?
childObject = this.getTableFromAlias(monitor, sc, token);
if (childObject == null) {
DBSStructureAssistant structureAssistant = DBUtils.getAdapter(DBSStructureAssistant.class, sc);
if (structureAssistant != null) {
Collection<DBSObjectReference> references = structureAssistant.findObjectsByMask(
monitor,
null,
structureAssistant.getAutoCompleteObjectTypes(),
wordDetector.removeQuotes(token),
wordDetector.isQuoted(token),
false,
2);
if (!references.isEmpty()) {
childObject = references.iterator().next().resolveObject(monitor);
}
}
}
} else {
// Path element not found. Damn - can't do anything.
return;
}
}
if (childObject instanceof DBSObjectContainer) {
sc = (DBSObjectContainer) childObject;
} else {
sc = null;
}
} catch (DBException e) {
log.error(e);
return;
}
}
if (childObject == null) {
return;
}
if (lastToken == null) {
// Get all children objects as proposals
makeProposalsFromChildren(monitor, childObject, null, proposals);
} else {
// Get matched children
makeProposalsFromChildren(monitor, childObject, lastToken, proposals);
if (proposals.isEmpty() || tokens.size() == 1) {
if (selectedContainer != null && selectedContainer != childObject) {
// Try in active object
makeProposalsFromChildren(monitor, selectedContainer, lastToken, proposals);
}
if (proposals.isEmpty()) {
// At last - try to find child tables by pattern
DBSStructureAssistant structureAssistant = null;
for (DBSObject object = childObject; object != null; object = object.getParentObject()) {
structureAssistant = DBUtils.getAdapter(DBSStructureAssistant.class, object);
if (structureAssistant != null) {
break;
}
}
if (structureAssistant != null) {
makeProposalsFromAssistant(monitor, structureAssistant, sc, lastToken, proposals);
}
}
}
}
}
@Nullable
private DBSObject getTableFromAlias(DBRProgressMonitor monitor, DBSObjectContainer sc, @Nullable String token)
{
final DBPDataSource dataSource = editor.getDataSource();
if (!(dataSource instanceof SQLDataSource)) {
return null;
}
if (activeQuery == null) {
final SQLQuery queryAtPos = editor.extractQueryAtPos(documentOffset);
if (queryAtPos != null) {
activeQuery = queryAtPos.getQuery() + " ";
}
}
final List<String> nameList = new ArrayList<>();
if (token == null) {
token = "";
}
SQLDialect sqlDialect = ((SQLDataSource) dataSource).getSQLDialect();
String quoteString = sqlDialect.getIdentifierQuoteString();
{
String quote = quoteString == null ? SQLConstants.STR_QUOTE_DOUBLE :
SQLConstants.STR_QUOTE_DOUBLE.equals(quoteString) ?
quoteString :
Pattern.quote(quoteString);
String catalogSeparator = sqlDialect.getCatalogSeparator();
while (token.endsWith(catalogSeparator)) token = token.substring(0, token.length() -1);
String tableNamePattern = "([\\w_$" + quote + Pattern.quote(catalogSeparator) + "]+)";
String structNamePattern;
if (CommonUtils.isEmpty(token)) {
structNamePattern = "(?:from|update|join|into)\\s*" + tableNamePattern;
} else {
structNamePattern = tableNamePattern +
"(?:\\s*\\.\\s*" + tableNamePattern + ")?" +
"\\s+(?:(?:AS)\\s)?" + token + "[\\s,]+";
}
Pattern aliasPattern;
try {
aliasPattern = Pattern.compile(structNamePattern, Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException e) {
// Bad pattern - seems to be a bad token
return null;
}
String testQuery = SQLUtils.stripComments(editor.getSyntaxManager().getDialect(), activeQuery);
Matcher matcher = aliasPattern.matcher(testQuery);
if (!matcher.find()) {
return null;
}
int groupCount = matcher.groupCount();
for (int i = 1; i <= groupCount; i++) {
String group = matcher.group(i);
if (!CommonUtils.isEmpty(group)) {
String[] allNames = group.split(Pattern.quote(catalogSeparator));
for (String name : allNames) {
nameList.add(name);
}
}
}
}
if (nameList.isEmpty()) {
return null;
}
// Fix names (convert case or remove quotes)
for (int i = 0; i < nameList.size(); i++) {
String name = nameList.get(i);
if (quoteString != null && name.startsWith(quoteString) && name.endsWith(quoteString)) {
name = name.substring(1, name.length() - 1);
} else {
name = DBObjectNameCaseTransformer.transformName(sc.getDataSource(), name);
}
nameList.set(i, name);
}
try {
DBSObject childObject = null;
while (childObject == null) {
childObject = DBUtils.findNestedObject(monitor, sc, nameList);
if (childObject == null) {
DBSObjectContainer parentSc = DBUtils.getParentAdapter(DBSObjectContainer.class, sc);
if (parentSc == null) {
break;
}
sc = parentSc;
}
}
if (childObject == null && nameList.size() <= 1) {
// No such object found - may be it's start of table name
DBSStructureAssistant structureAssistant = DBUtils.getAdapter(DBSStructureAssistant.class, sc);
if (structureAssistant != null) {
String objectNameMask = nameList.get(0);
Collection<DBSObjectReference> tables = structureAssistant.findObjectsByMask(
monitor,
sc,
structureAssistant.getAutoCompleteObjectTypes(),
wordDetector.removeQuotes(objectNameMask),
wordDetector.isQuoted(objectNameMask),
false,
2);
if (!tables.isEmpty()) {
return tables.iterator().next().resolveObject(monitor);
}
}
return null;
} else {
return childObject;
}
} catch (DBException e) {
log.error(e);
return null;
}
}
private void makeProposalsFromChildren(
DBRProgressMonitor monitor,
DBPObject parent,
@Nullable String startPart,
List<SQLCompletionProposal> proposals)
{
if (startPart != null) {
startPart = wordDetector.removeQuotes(startPart).toUpperCase();
int divPos = startPart.lastIndexOf(editor.getSyntaxManager().getStructSeparator());
if (divPos != -1) {
startPart = startPart.substring(divPos + 1);
}
}
try {
Collection<? extends DBSObject> children = null;
if (parent instanceof DBSObjectContainer) {
children = ((DBSObjectContainer)parent).getChildren(monitor);
} else if (parent instanceof DBSEntity) {
children = ((DBSEntity)parent).getAttributes(monitor);
}
if (children != null && !children.isEmpty()) {
List<DBSObject> matchedObjects = new ArrayList<>();
final Map<String, Integer> scoredMatches = new HashMap<>();
for (DBSObject child : children) {
if (DBUtils.isHiddenObject(child)) {
// Skip hidden
continue;
}
int score = CommonUtils.isEmpty(startPart) ? 1 : TextUtils.fuzzyScore(child.getName(), startPart);
if (score > 0) {
matchedObjects.add(child);
scoredMatches.put(child.getName(), score);
}
}
if (!matchedObjects.isEmpty()) {
if (startPart != null) {
Collections.sort(matchedObjects, new Comparator<DBSObject>() {
@Override
public int compare(DBSObject o1, DBSObject o2) {
int score1 = scoredMatches.get(o1.getName());
int score2 = scoredMatches.get(o2.getName());
if (score1 == score2) {
if (o1 instanceof DBSAttributeBase) {
return ((DBSAttributeBase) o1).getOrdinalPosition() - ((DBSAttributeBase) o2).getOrdinalPosition();
}
return o1.getName().compareTo(o2.getName());
}
return score2 - score1;
}
});
}
for (DBSObject child : matchedObjects) {
proposals.add(makeProposalsFromObject(monitor, child));
}
}
}
} catch (DBException e) {
log.error(e);
}
}
private void makeProposalsFromAssistant(
DBRProgressMonitor monitor,
DBSStructureAssistant assistant,
@Nullable DBSObjectContainer rootSC,
String objectName,
List<SQLCompletionProposal> proposals)
{
try {
Collection<DBSObjectReference> references = assistant.findObjectsByMask(
monitor,
rootSC,
assistant.getAutoCompleteObjectTypes(),
wordDetector.removeQuotes(objectName) + "%",
wordDetector.isQuoted(objectName),
false,
100);
for (DBSObjectReference reference : references) {
proposals.add(makeProposalsFromObject(monitor, reference, reference.getObjectType().getImage()));
}
} catch (DBException e) {
log.error(e);
}
}
private SQLCompletionProposal makeProposalsFromObject(DBRProgressMonitor monitor, DBSObject object)
{
DBNNode node = DBeaverCore.getInstance().getNavigatorModel().getNodeByObject(monitor, object, false);
return makeProposalsFromObject(monitor, object, node == null ? null : node.getNodeIconDefault());
}
private SQLCompletionProposal makeProposalsFromObject(DBRProgressMonitor monitor, DBPNamedObject object, @Nullable DBPImage objectIcon)
{
String objectName = DBUtils.getObjectFullName(object);
boolean isSingleObject = true;
String replaceString = null;
DBPDataSource dataSource = editor.getDataSource();
if (dataSource != null) {
// If we replace short name with referenced object
// and current active schema (catalog) is not this object's container then
// replace with full qualified name
if (!getPreferences().getBoolean(SQLPreferenceConstants.PROPOSAL_SHORT_NAME) && object instanceof DBSObjectReference) {
if (wordDetector.getFullWord().indexOf(editor.getSyntaxManager().getStructSeparator()) == -1) {
DBSObjectReference structObject = (DBSObjectReference) object;
if (structObject.getContainer() != null) {
DBSObject selectedObject = DBUtils.getActiveInstanceObject(dataSource);
if (selectedObject != structObject.getContainer()) {
replaceString = DBUtils.getFullQualifiedName(
dataSource,
structObject.getContainer(),
object);
isSingleObject = false;
}
}
}
}
if (replaceString == null) {
replaceString = DBUtils.getQuotedIdentifier(dataSource, object.getName());
}
} else {
replaceString = DBUtils.getObjectShortName(object);
}
return createCompletionProposal(
replaceString,
objectName,
null,
objectIcon,
isSingleObject,
object);
}
public static String makeObjectDescription(DBRProgressMonitor monitor, DBPNamedObject object, boolean html) {
StringBuilder info = new StringBuilder();
PropertyCollector collector = new PropertyCollector(object, false);
collector.collectProperties();
for (DBPPropertyDescriptor descriptor : collector.getPropertyDescriptors2()) {
if (descriptor.isRemote()) {
// Skip lazy properties
continue;
}
Object propValue = collector.getPropertyValue(monitor, descriptor.getId());
if (propValue == null) {
continue;
}
String propString;
if (propValue instanceof DBPNamedObject) {
propString = ((DBPNamedObject) propValue).getName();
} else {
propString = DBUtils.getDefaultValueDisplayString(propValue, DBDDisplayFormat.UI);
}
if (html) {
info.append("<b>").append(descriptor.getDisplayName()).append(": </b>");
info.append(propString);
info.append("<br>");
} else {
info.append(descriptor.getDisplayName()).append(": ").append(propString).append("\n");
}
}
return info.toString();
}
private DBPPreferenceStore getPreferences() {
DBPPreferenceStore store = null;
DBPDataSource dataSource = editor.getDataSource();
if (dataSource != null) {
store = dataSource.getContainer().getPreferenceStore();
}
if (store == null) {
store = DBeaverCore.getGlobalPreferenceStore();
}
return store;
}
/*
* Turns the vector into an Array of ICompletionProposal objects
*/
protected SQLCompletionProposal createCompletionProposal(
String replaceString,
String displayString,
String description,
@Nullable DBPImage image,
boolean isObject,
@Nullable DBPNamedObject object)
{
DBPPreferenceStore store = getPreferences();
DBPDataSource dataSource = editor.getDataSource();
if (dataSource != null) {
if (isObject) {
// Escape replace string if required
replaceString = DBUtils.getQuotedIdentifier(dataSource, replaceString);
}
}
// If we have quoted string then ignore pref settings
boolean quotedString = wordDetector.isQuoted(replaceString);
final int proposalCase = quotedString ?
SQLPreferenceConstants.PROPOSAL_CASE_DEFAULT :
store.getInt(SQLPreferenceConstants.PROPOSAL_INSERT_CASE);
switch (proposalCase) {
case SQLPreferenceConstants.PROPOSAL_CASE_UPPER:
replaceString = replaceString.toUpperCase();
break;
case SQLPreferenceConstants.PROPOSAL_CASE_LOWER:
replaceString = replaceString.toLowerCase();
break;
default:
DBPIdentifierCase convertCase = quotedString && dataSource instanceof SQLDataSource ?
((SQLDataSource) dataSource).getSQLDialect().storesQuotedCase() : DBPIdentifierCase.MIXED;
replaceString = convertCase.transform(replaceString);
break;
}
Image img = image == null ? null : DBeaverIcons.getImage(image);
return new SQLCompletionProposal(
editor.getSyntaxManager(),
displayString,
replaceString, // replacementString
wordDetector, // wordDetector
replaceString.length(), //cursorPosition the position of the cursor following the insert
// relative to replacementOffset
img, //image to display
new ContextInformation(img, displayString, displayString), //the context information associated with this proposal
description,
object);
}
/**
* This method is incomplete in that it does not implement logic to produce
* some context help relevant to SQL. It just hard codes two strings to
* demonstrate the action
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(ITextViewer,
* int)
*/
@Nullable
@Override
public IContextInformation[] computeContextInformation(
ITextViewer viewer, int documentOffset)
{
SQLQuery statementInfo = editor.extractQueryAtPos(documentOffset);
if (statementInfo == null || CommonUtils.isEmpty(statementInfo.getQuery())) {
return null;
}
IContextInformation[] result = new IContextInformation[1];
result[0] = new ContextInformation(statementInfo.getQuery(), statementInfo.getQuery());
return result;
}
@Override
public char[] getCompletionProposalAutoActivationCharacters()
{
return new char[] {'.'};
}
@Nullable
@Override
public char[] getContextInformationAutoActivationCharacters()
{
return null;
}
@Nullable
@Override
public String getErrorMessage()
{
return null;
}
@Override
public IContextInformationValidator getContextInformationValidator()
{
return validator;
}
/**
* Simple content assist tip closer. The tip is valid in a range of 5
* characters around its popup location.
*/
protected static class Validator implements IContextInformationValidator, IContextInformationPresenter
{
protected int fInstallOffset;
@Override
public boolean isContextInformationValid(int offset)
{
return Math.abs(fInstallOffset - offset) < 5;
}
@Override
public void install(IContextInformation info,
ITextViewer viewer, int offset)
{
fInstallOffset = offset;
}
@Override
public boolean updatePresentation(int documentPosition,
TextPresentation presentation)
{
return false;
}
}
private class ProposalSearchJob extends AbstractJob {
private List<SQLCompletionProposal> proposals;
private String wordPart;
private QueryType qt;
private transient boolean finished = false;
public ProposalSearchJob(List<SQLCompletionProposal> proposals, String wordPart, QueryType qt) {
super("Search proposals...");
setUser(true);
this.proposals = proposals;
this.wordPart = wordPart;
this.qt = qt;
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
monitor.beginTask("Seeking for completion proposals", 1);
try {
monitor.subTask("Make structure proposals");
makeStructureProposals(monitor, proposals, wordPart, qt);
} finally {
monitor.done();
}
applyFilters();
return Status.OK_STATUS;
} catch (Throwable e) {
log.error(e);
return Status.CANCEL_STATUS;
} finally {
finished = true;
}
}
private void applyFilters() {
DBPDataSource dataSource = editor.getDataSource();
if (dataSource == null) {
return;
}
DBPDataSourceContainer dsContainer = dataSource.getContainer();
Map<DBSObject, Map<Class, List<SQLCompletionProposal>>> containerMap = new HashMap<>();
for (SQLCompletionProposal proposal : proposals) {
DBSObject container = proposal.getObjectContainer();
DBPNamedObject object = proposal.getObject();
Map<Class, List<SQLCompletionProposal>> typeMap = containerMap.get(container);
if (typeMap == null) {
typeMap = new HashMap<>();
containerMap.put(container, typeMap);
}
Class objectType = object instanceof DBSObjectReference ? ((DBSObjectReference) object).getObjectClass() : object.getClass();
List<SQLCompletionProposal> list = typeMap.get(objectType);
if (list == null) {
list = new ArrayList<>();
typeMap.put(objectType, list);
}
list.add(proposal);
}
for (Map.Entry<DBSObject, Map<Class, List<SQLCompletionProposal>>> entry : containerMap.entrySet()) {
for (Map.Entry<Class, List<SQLCompletionProposal>> typeEntry : entry.getValue().entrySet()) {
DBSObjectFilter filter = dsContainer.getObjectFilter(typeEntry.getKey(), entry.getKey(), true);
if (filter != null && filter.isEnabled()) {
for (SQLCompletionProposal proposal : typeEntry.getValue()) {
if (!filter.matches(proposal.getObject().getName())) {
proposals.remove(proposal);
}
}
}
}
}
}
}
} |
package org.jkiss.dbeaver.model.impl.jdbc.cache;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Struct cache with ability to load/search single object by name.
*/
public abstract class JDBCStructLookupCache<OWNER extends DBSObject, OBJECT extends DBSObject, CHILD extends DBSObject>
extends JDBCStructCache<OWNER, OBJECT, CHILD>
implements JDBCObjectLookup<OWNER, OBJECT>
{
private final Set<String> missingNames = new HashSet<>();
public JDBCStructLookupCache(Object objectNameColumn) {
super(objectNameColumn);
}
@Override
public OBJECT getObject(@NotNull DBRProgressMonitor monitor, @NotNull OWNER owner, @NotNull String name)
throws DBException
{
OBJECT cachedObject = getCachedObject(name);
if (cachedObject != null) {
return cachedObject;
}
if (isFullyCached() || missingNames.contains(name)) {
return null;
}
// Now cache just one object
OBJECT object = reloadObject(monitor, owner, null, name);
if (object != null) {
cacheObject(object);
} else {
// Not found!
missingNames.add(name);
}
return object;
}
public OBJECT refreshObject(@NotNull DBRProgressMonitor monitor, @NotNull OWNER owner, @NotNull OBJECT oldObject)
throws DBException
{
String objectName = oldObject.getName();
if (!isFullyCached()) {
this.loadObjects(monitor, owner);
} else {
OBJECT newObject = this.reloadObject(monitor, owner, oldObject, null);
if (isChildrenCached(oldObject)) {
clearChildrenCache(oldObject);
}
removeObject(oldObject, false);
if (newObject != null) {
cacheObject(newObject);
}
return newObject;
}
return getCachedObject(objectName);
}
protected OBJECT reloadObject(@NotNull DBRProgressMonitor monitor, @NotNull OWNER owner, @Nullable OBJECT object, @Nullable String objectName)
throws DBException
{
DBPDataSource dataSource = owner.getDataSource();
if (dataSource == null) {
throw new DBException("Not connected to database");
}
try (JDBCSession session = DBUtils.openMetaSession(monitor, dataSource, "Reload object '" + object + "' from " + owner.getName())) {
try (JDBCStatement dbStat = prepareLookupStatement(session, owner, object, objectName)) {
dbStat.setFetchSize(1);
dbStat.executeStatement();
JDBCResultSet dbResult = dbStat.getResultSet();
if (dbResult != null) {
try {
if (dbResult.next()) {
return fetchObject(session, owner, dbResult);
}
} finally {
dbResult.close();
}
}
return null;
}
} catch (SQLException ex) {
throw new DBException("Error loading object metadata from database", ex, dataSource);
}
}
@Override
protected JDBCStatement prepareObjectsStatement(@NotNull JDBCSession session, @NotNull OWNER owner)
throws SQLException
{
return prepareLookupStatement(session, owner, null, null);
}
@Override
public void setCache(List<OBJECT> objects) {
super.setCache(objects);
this.missingNames.clear();
}
@Override
public void clearCache() {
super.clearCache();
this.missingNames.clear();
}
} |
package org.opencps.accountmgt.portlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import org.opencps.accountmgt.InvalidCityCodeException;
import org.opencps.accountmgt.InvalidDistricCodeException;
import org.opencps.accountmgt.InvalidWardCodeException;
import org.opencps.accountmgt.OutOfLengthBusinessEnNameException;
import org.opencps.accountmgt.OutOfLengthBusinessNameException;
import org.opencps.accountmgt.OutOfLengthBusinessRepresentativeNameException;
import org.opencps.accountmgt.OutOfLengthBusinessRepresentativeRoleException;
import org.opencps.accountmgt.OutOfLengthBusinessShortNameException;
import org.opencps.accountmgt.OutOfLengthCitizenAddressException;
import org.opencps.accountmgt.OutOfLengthCitizenNameException;
import org.opencps.accountmgt.model.Business;
import org.opencps.accountmgt.model.Citizen;
import org.opencps.accountmgt.search.BusinessDisplayTerms;
import org.opencps.accountmgt.search.CitizenDisplayTerms;
import org.opencps.accountmgt.service.BusinessLocalServiceUtil;
import org.opencps.accountmgt.service.CitizenLocalServiceUtil;
import org.opencps.datamgt.model.DictItem;
import org.opencps.datamgt.service.DictItemLocalServiceUtil;
import org.opencps.usermgt.search.EmployeeDisplayTerm;
import org.opencps.util.AccountUtil;
import org.opencps.util.MessageKeys;
import org.opencps.util.PortletPropsValues;
import org.opencps.util.WebKeys;
import com.liferay.portal.UserPasswordException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* @author trungnt
*/
public class AccountProfilePortlet extends MVCPortlet {
@Override
public void render(
RenderRequest renderRequest, RenderResponse renderResponse)
throws PortletException, IOException {
ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
String accountType = StringPool.BLANK;
if (themeDisplay.isSignedIn()) {
List<UserGroup> userGroups = new ArrayList<UserGroup>();
try {
User user = themeDisplay.getUser();
userGroups = user.getUserGroups();
if (!userGroups.isEmpty()) {
for (UserGroup userGroup : userGroups) {
if (userGroup.getName().equals(
PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN) ||
userGroup.getName().equals(
PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) {
accountType = userGroup.getName();
break;
}
}
}
renderRequest.setAttribute(WebKeys.ACCOUNT_TYPE, accountType);
if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN)) {
Citizen citizen =
CitizenLocalServiceUtil.getCitizen(user.getUserId());
renderRequest.setAttribute(WebKeys.CITIZEN_ENTRY, citizen);
}
else if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) {
Business business =
BusinessLocalServiceUtil.getBusiness(user.getUserId());
renderRequest.setAttribute(WebKeys.BUSINESS_ENTRY, business);
}
renderRequest.setAttribute(
WebKeys.ACCOUNTMGT_VIEW_PROFILE, true);
}
catch (Exception e) {
_log.error(e);
}
}
super.render(renderRequest, renderResponse);
}
public void updateCitizenProfile(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException {
long citizenId =
ParamUtil.getLong(actionRequest, CitizenDisplayTerms.CITIZEN_ID);
long cityId =
ParamUtil.getLong(
actionRequest, CitizenDisplayTerms.CITIZEN_CITY_ID);
long districtId =
ParamUtil.getLong(
actionRequest, CitizenDisplayTerms.CITIZEN_DISTRICT_ID);
long wardId =
ParamUtil.getLong(
actionRequest, CitizenDisplayTerms.CITIZEN_WARD_ID);
String address =
ParamUtil.getString(
actionRequest, CitizenDisplayTerms.CITIZEN_ADDRESS);
String telNo =
ParamUtil.getString(actionRequest, EmployeeDisplayTerm.TEL_NO);
String curPass =
ParamUtil.getString(
actionRequest, CitizenDisplayTerms.CURRENT_PASSWORD);
String newPass =
ParamUtil.getString(actionRequest, CitizenDisplayTerms.NEW_PASSWORD);
String rePass =
ParamUtil.getString(actionRequest, CitizenDisplayTerms.RE_PASSWORD);
String backURL = ParamUtil.getString(actionRequest, "backURL");
DictItem city = null;
DictItem district = null;
DictItem ward = null;
boolean isChangePassword = false;
if (Validator.isNotNull(curPass) && Validator.isNotNull(newPass) &&
Validator.isNotNull(rePass)) {
isChangePassword = true;
}
boolean updated = false;
try {
AccountRegPortlet.validateCitizen(
citizenId, StringPool.BLANK, StringPool.BLANK, address,
StringPool.BLANK, telNo, 1, StringPool.BLANK, cityId,
districtId, wardId, StringPool.BLANK);
ServiceContext serviceContext =
ServiceContextFactory.getInstance(actionRequest);
city = DictItemLocalServiceUtil.getDictItem(cityId);
district = DictItemLocalServiceUtil.getDictItem(districtId);
ward = DictItemLocalServiceUtil.getDictItem(wardId);
if (citizenId > 0) {
CitizenLocalServiceUtil.updateCitizen(
citizenId, address, city.getItemCode(),
district.getItemCode(), ward.getItemCode(),
city.getItemName(serviceContext.getLocale(), true),
district.getItemName(serviceContext.getLocale(), true),
ward.getItemName(serviceContext.getLocale(), true), telNo,
isChangePassword, newPass, rePass,
serviceContext.getScopeGroupId(), serviceContext);
HttpServletRequest request =
PortalUtil.getHttpServletRequest(actionRequest);
AccountUtil.destroy(request);
updated = true;
}
}
catch (Exception e) {
_log.error(e);
if (e instanceof UserPasswordException) {
SessionErrors.add(actionRequest, UserPasswordException.class);
}
else if (e instanceof OutOfLengthCitizenAddressException) {
SessionErrors.add(
actionRequest, OutOfLengthCitizenAddressException.class);
}
else if (e instanceof OutOfLengthCitizenNameException) {
SessionErrors.add(
actionRequest, OutOfLengthCitizenNameException.class);
}
else if (e instanceof InvalidCityCodeException) {
SessionErrors.add(actionRequest, InvalidCityCodeException.class);
}
else if (e instanceof InvalidDistricCodeException) {
SessionErrors.add(
actionRequest, InvalidDistricCodeException.class);
}
else if (e instanceof InvalidWardCodeException) {
SessionErrors.add(actionRequest, InvalidWardCodeException.class);
}
else {
SessionErrors.add(
actionRequest,
MessageKeys.DATAMGT_SYSTEM_EXCEPTION_OCCURRED);
}
}
finally {
if (updated) {
if (Validator.isNotNull(backURL)) {
actionResponse.sendRedirect(backURL);
}
}
else {
actionResponse.setRenderParameter(
"mvcPath",
"/html/portlets/accountmgt/profile/edit_profile.jsp");
}
}
}
public void updateBusinessProfile(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException {
long businessId =
ParamUtil.getLong(
actionRequest, BusinessDisplayTerms.BUSINESS_BUSINESSID);
long cityId =
ParamUtil.getLong(
actionRequest, BusinessDisplayTerms.BUSINESS_CITY_ID);
long districtId =
ParamUtil.getLong(
actionRequest, BusinessDisplayTerms.BUSINESS_DISTRICT_ID);
long wardId =
ParamUtil.getLong(
actionRequest, BusinessDisplayTerms.BUSINESS_WARD_ID);
long type =
ParamUtil.getLong(
actionRequest, BusinessDisplayTerms.BUSINESS_BUSINESSTYPE);
String backURL = ParamUtil.getString(actionRequest, "backURL");
String name =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_NAME);
String enName =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_ENNAME);
String idNumber =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_IDNUMBER);
String shortName =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_SHORTNAME);
String address =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_ADDRESS);
String telNo =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_TELNO);
String representativeName =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_REPRESENTATIVENAME);
String representativeRole =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.BUSINESS_REPRESENTATIVEROLE);
// String[] domain =
// ParamUtil.getParameterValues(
// actionRequest, BusinessDisplayTerms.BUSINESS_DOMAIN);
String[] listBussinessDomains =
ParamUtil.getParameterValues(actionRequest, "listBussinessDomains");
String curPass =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.CURRENT_PASSWORD);
String newPass =
ParamUtil.getString(
actionRequest, BusinessDisplayTerms.NEW_PASSWORD);
String rePass =
ParamUtil.getString(actionRequest, BusinessDisplayTerms.RE_PASSWORD);
boolean isChangePassword = false;
if (Validator.isNotNull(curPass) && Validator.isNotNull(newPass) &&
Validator.isNotNull(rePass)) {
isChangePassword = true;
}
boolean updated = false;
DictItem city = null;
DictItem district = null;
DictItem ward = null;
DictItem busType = null;
try {
AccountRegPortlet.validateBusiness(
businessId, StringPool.BLANK, StringPool.BLANK, enName,
shortName, address, representativeName, representativeRole,
cityId, districtId, wardId, 1, StringPool.BLANK);
city = DictItemLocalServiceUtil.getDictItem(cityId);
district = DictItemLocalServiceUtil.getDictItem(districtId);
ward = DictItemLocalServiceUtil.getDictItem(wardId);
busType = DictItemLocalServiceUtil.getDictItem(type);
ServiceContext serviceContext =
ServiceContextFactory.getInstance(actionRequest);
if (businessId > 0) {
district.getItemName(serviceContext.getLocale(), true);
BusinessLocalServiceUtil.updateBusiness(
businessId, name, enName, shortName, busType.getItemCode(),
idNumber, address, city.getItemCode(),
district.getItemCode(), ward.getItemCode(),
city.getItemName(serviceContext.getLocale(), true),
district.getItemName(serviceContext.getLocale(), true),
ward.getItemName(serviceContext.getLocale(), true), telNo,
representativeName, representativeRole,
listBussinessDomains, isChangePassword, curPass, rePass,
serviceContext.getScopeGroupId(), serviceContext);
HttpServletRequest request =
PortalUtil.getHttpServletRequest(actionRequest);
AccountUtil.destroy(request);
updated = true;
}
}
catch (Exception e) {
_log.error(e);
if (e instanceof UserPasswordException) {
SessionErrors.add(actionRequest, UserPasswordException.class);
}
else if (e instanceof OutOfLengthBusinessNameException) {
SessionErrors.add(
actionRequest, OutOfLengthBusinessNameException.class);
}
else if (e instanceof OutOfLengthBusinessEnNameException) {
SessionErrors.add(
actionRequest, OutOfLengthBusinessEnNameException.class);
}
else if (e instanceof OutOfLengthBusinessShortNameException) {
SessionErrors.add(
actionRequest, OutOfLengthBusinessShortNameException.class);
}
else if (e instanceof OutOfLengthBusinessRepresentativeNameException) {
SessionErrors.add(
actionRequest,
OutOfLengthBusinessRepresentativeNameException.class);
}
else if (e instanceof OutOfLengthBusinessRepresentativeRoleException) {
SessionErrors.add(
actionRequest,
OutOfLengthBusinessRepresentativeRoleException.class);
}
else if (e instanceof InvalidCityCodeException) {
SessionErrors.add(actionRequest, InvalidCityCodeException.class);
}
else if (e instanceof InvalidDistricCodeException) {
SessionErrors.add(
actionRequest, InvalidDistricCodeException.class);
}
else if (e instanceof InvalidWardCodeException) {
SessionErrors.add(actionRequest, InvalidWardCodeException.class);
}
else {
SessionErrors.add(
actionRequest,
MessageKeys.DATAMGT_SYSTEM_EXCEPTION_OCCURRED);
}
}
finally {
if (updated) {
if (Validator.isNotNull(backURL)) {
actionResponse.sendRedirect(backURL);
}
}
else {
actionResponse.setRenderParameter(
"mvcPath",
"/html/portlets/accountmgt/profile/edit_profile.jsp");
}
}
}
private Log _log =
LogFactoryUtil.getLog(AccountProfilePortlet.class.getName());
} |
package org.batfish.datamodel.answers;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.batfish.datamodel.BgpAdvertisement;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.PrefixSpace;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(Include.NON_NULL)
public class BgpAdvertisementsAnswerElement implements AnswerElement {
private static final String ALL_REQUESTED_ADVERTISEMENTS_VAR = "allRequestedAdvertisements";
private static final String RECEIVED_EBGP_ADVERTISEMENTS_VAR = "receivedEbgpAdvertisements";
private static final String RECEIVED_IBGP_ADVERTISEMENTS_VAR = "receivedIbgpAdvertisements";
private static final String SENT_EBGP_ADVERTISEMENTS_VAR = "sentEbgpAdvertisements";
private static final String SENT_IBGP_ADVERTISEMENTS_VAR = "sentIbgpAdvertisements";
private final Set<BgpAdvertisement> _allRequestedAdvertisements;
private final Map<String, Set<BgpAdvertisement>> _receivedEbgpAdvertisements;
private final Map<String, Set<BgpAdvertisement>> _receivedIbgpAdvertisements;
private final Map<String, Set<BgpAdvertisement>> _sentEbgpAdvertisements;
private final Map<String, Set<BgpAdvertisement>> _sentIbgpAdvertisements;
public BgpAdvertisementsAnswerElement(
Map<String, Configuration> configurations, Pattern nodeRegex,
boolean ebgp, boolean ibgp, PrefixSpace prefixSpace, boolean received,
boolean sent) {
_allRequestedAdvertisements = new TreeSet<BgpAdvertisement>();
_receivedEbgpAdvertisements = (received && ebgp) ? new TreeMap<String, Set<BgpAdvertisement>>()
: null;
_sentEbgpAdvertisements = (sent && ebgp) ? new TreeMap<String, Set<BgpAdvertisement>>()
: null;
_receivedIbgpAdvertisements = (received && ibgp) ? new TreeMap<String, Set<BgpAdvertisement>>()
: null;
_sentIbgpAdvertisements = (sent && ibgp) ? new TreeMap<String, Set<BgpAdvertisement>>()
: null;
for (Entry<String, Configuration> e : configurations.entrySet()) {
String hostname = e.getKey();
Matcher nodeMatcher = nodeRegex.matcher(hostname);
if (!nodeMatcher.matches()) {
continue;
}
Configuration configuration = e.getValue();
if (received) {
if (ebgp) {
Set<BgpAdvertisement> advertisements = configuration
.getReceivedEbgpAdvertisements();
fill(_receivedEbgpAdvertisements, hostname, advertisements,
prefixSpace);
}
if (ibgp) {
Set<BgpAdvertisement> advertisements = configuration
.getReceivedIbgpAdvertisements();
fill(_receivedIbgpAdvertisements, hostname, advertisements,
prefixSpace);
}
}
if (sent) {
if (ebgp) {
Set<BgpAdvertisement> advertisements = configuration
.getSentEbgpAdvertisements();
fill(_sentEbgpAdvertisements, hostname, advertisements,
prefixSpace);
}
if (ibgp) {
Set<BgpAdvertisement> advertisements = configuration
.getSentIbgpAdvertisements();
fill(_sentIbgpAdvertisements, hostname, advertisements,
prefixSpace);
}
}
}
}
@JsonCreator
public BgpAdvertisementsAnswerElement(
@JsonProperty(ALL_REQUESTED_ADVERTISEMENTS_VAR) Set<BgpAdvertisement> allRequested,
@JsonProperty(RECEIVED_EBGP_ADVERTISEMENTS_VAR) Map<String, Set<BgpAdvertisement>> receivedEbgp,
@JsonProperty(RECEIVED_IBGP_ADVERTISEMENTS_VAR) Map<String, Set<BgpAdvertisement>> receivedIbgp,
@JsonProperty(SENT_EBGP_ADVERTISEMENTS_VAR) Map<String, Set<BgpAdvertisement>> sentEbgp,
@JsonProperty(SENT_IBGP_ADVERTISEMENTS_VAR) Map<String, Set<BgpAdvertisement>> sentIbgp) {
_allRequestedAdvertisements = allRequested;
_receivedEbgpAdvertisements = receivedEbgp;
_receivedIbgpAdvertisements = receivedIbgp;
_sentEbgpAdvertisements = sentEbgp;
_sentIbgpAdvertisements = sentIbgp;
}
private void fill(Map<String, Set<BgpAdvertisement>> map, String hostname,
Set<BgpAdvertisement> advertisements, PrefixSpace prefixSpace) {
Set<BgpAdvertisement> placedAdvertisements = new TreeSet<BgpAdvertisement>();
map.put(hostname, placedAdvertisements);
for (BgpAdvertisement advertisement : advertisements) {
if (prefixSpace.isEmpty()
|| prefixSpace.containsPrefix(advertisement.getNetwork())) {
placedAdvertisements.add(advertisement);
_allRequestedAdvertisements.add(advertisement);
}
}
}
@JsonProperty(ALL_REQUESTED_ADVERTISEMENTS_VAR)
public Set<BgpAdvertisement> getAllRequestedAdvertisements() {
return _allRequestedAdvertisements;
}
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty(RECEIVED_EBGP_ADVERTISEMENTS_VAR)
public Map<String, Set<BgpAdvertisement>> getReceivedEbgpAdvertisements() {
return _receivedEbgpAdvertisements;
}
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty(RECEIVED_IBGP_ADVERTISEMENTS_VAR)
public Map<String, Set<BgpAdvertisement>> getReceivedIbgpAdvertisements() {
return _receivedIbgpAdvertisements;
}
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty(SENT_EBGP_ADVERTISEMENTS_VAR)
public Map<String, Set<BgpAdvertisement>> getSentEbgpAdvertisements() {
return _sentEbgpAdvertisements;
}
@JsonIdentityReference(alwaysAsId = true)
@JsonProperty(SENT_IBGP_ADVERTISEMENTS_VAR)
public Map<String, Set<BgpAdvertisement>> getSentIbgpAdvertisements() {
return _sentIbgpAdvertisements;
}
} |
package org.rabix.backend.local.tes.service.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.NotImplementedException;
import org.apache.mina.util.ConcurrentHashSet;
import org.rabix.backend.local.tes.client.TESHTTPClientException;
import org.rabix.backend.local.tes.client.TESHttpClient;
import org.rabix.backend.local.tes.model.TESDockerExecutor;
import org.rabix.backend.local.tes.model.TESJob;
import org.rabix.backend.local.tes.model.TESJobId;
import org.rabix.backend.local.tes.model.TESResources;
import org.rabix.backend.local.tes.model.TESState;
import org.rabix.backend.local.tes.model.TESTask;
import org.rabix.backend.local.tes.model.TESTaskParameter;
import org.rabix.backend.local.tes.model.TESVolume;
import org.rabix.backend.local.tes.service.TESServiceException;
import org.rabix.backend.local.tes.service.TESStorageService;
import org.rabix.backend.local.tes.service.TESStorageService.LocalFileStorage;
import org.rabix.backend.local.tes.service.TESStorageService.SharedFileStorage;
import org.rabix.bindings.BindingException;
import org.rabix.bindings.Bindings;
import org.rabix.bindings.BindingsFactory;
import org.rabix.bindings.CommandLine;
import org.rabix.bindings.helper.FileValueHelper;
import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.bindings.model.FileValue;
import org.rabix.bindings.model.FileValue.FileType;
import org.rabix.bindings.model.Job;
import org.rabix.bindings.model.Job.JobStatus;
import org.rabix.bindings.model.requirement.DockerContainerRequirement;
import org.rabix.bindings.model.requirement.Requirement;
import org.rabix.bindings.transformer.FileTransformer;
import org.rabix.common.helper.JSONHelper;
import org.rabix.common.logging.VerboseLogger;
import org.rabix.executor.engine.EngineStub;
import org.rabix.executor.engine.EngineStubLocal;
import org.rabix.executor.service.ExecutorService;
import org.rabix.executor.status.ExecutorStatusCallback;
import org.rabix.executor.status.ExecutorStatusCallbackException;
import org.rabix.transport.backend.Backend;
import org.rabix.transport.backend.impl.BackendLocal;
import org.rabix.transport.mechanism.TransportPluginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
public class TESExecutorServiceImpl implements ExecutorService {
private final static Logger logger = LoggerFactory.getLogger(TESExecutorServiceImpl.class);
public final static String BUNNY_COMMAND_LINE_DOCKER_IMAGE = "rabix/tes-command-line:v2";
public final static String WORKING_DIR = "working_dir";
public final static String STANDARD_OUT_LOG = "standard_out.log";
public final static String STANDARD_ERROR_LOG = "standard_error.log";
public final static String DEFAULT_PROJECT = "default";
private static final String DEFAULT_COMMAND_LINE_TOOL_ERR_LOG = "job.err.log";
private TESHttpClient tesHttpClient;
private TESStorageService storageService;
private final Set<Future<?>> taskFutures = new ConcurrentHashSet<>();
private final Map<String, Job> taskJobs = new HashMap<>();
private final ScheduledExecutorService scheduledTaskChecker = Executors.newScheduledThreadPool(1);
private final java.util.concurrent.ExecutorService taskPoolExecutor = Executors.newFixedThreadPool(10);
private EngineStub<?, ?, ?> engineStub;
private final Configuration configuration;
private final ExecutorStatusCallback statusCallback;
@Inject
public TESExecutorServiceImpl(final TESHttpClient tesHttpClient, final TESStorageService storageService, final ExecutorStatusCallback statusCallback, final Configuration configuration) {
this.tesHttpClient = tesHttpClient;
this.storageService = storageService;
this.configuration = configuration;
this.statusCallback = statusCallback;
this.scheduledTaskChecker.scheduleAtFixedRate(new Runnable() {
@Override
@SuppressWarnings("unchecked")
public void run() {
for (Iterator<Future<?>> iterator = taskFutures.iterator(); iterator.hasNext();){
Future<TESJob> tesJobFuture = (Future<TESJob>) iterator.next();
if (tesJobFuture.isDone()) {
try {
TESJob tesJob = tesJobFuture.get();
if (tesJob.getState().equals(TESState.Complete)) {
success(tesJob);
} else {
fail(tesJob);
}
taskJobs.remove(tesJob.getTask().getTaskId());
iterator.remove();
} catch (InterruptedException | ExecutionException e) {
logger.error("Failed to retrieve TESJob", e);
handleException(e);
}
}
}
}
/**
* Basic exception handling
*/
private void handleException(Exception e) {
Throwable cause = e.getCause();
if (cause != null) {
if (cause.getClass().equals(TESServiceException.class)) {
Throwable subcause = cause.getCause();
if (subcause != null) {
if (subcause.getClass().equals(TESHTTPClientException.class)) {
VerboseLogger.log("Failed to communicate with TES service");
System.exit(-10);
}
}
}
}
}
}, 0, 1, TimeUnit.SECONDS);
}
@SuppressWarnings("unchecked")
private void success(TESJob tesJob) {
Job job = taskJobs.get(tesJob.getTask().getTaskId());
job = Job.cloneWithStatus(job, JobStatus.COMPLETED);
Map<String, Object> result = (Map<String, Object>) FileValue.deserialize(JSONHelper.readMap(tesJob.getLogs().get(tesJob.getLogs().size()-1).getStdout())); // TODO change log fetching
final Job finalJob = job;
try {
result = (Map<String, Object>) FileValueHelper.updateFileValues(result, new FileTransformer() {
@Override
public FileValue transform(FileValue fileValue) throws BindingException {
String location = fileValue.getLocation();
if (location.startsWith(TESStorageService.DOCKER_PATH_PREFIX)) {
location = finalJob.getId() + "/" + location.substring(TESStorageService.DOCKER_PATH_PREFIX.length() + 1);
}
fileValue.setPath(location);
fileValue.setLocation(location);
return fileValue;
}
});
} catch (BindingException e) {
logger.error("Failed to process output files", e);
throw new RuntimeException("Failed to process output files", e);
}
job = Job.cloneWithOutputs(job, result);
job = Job.cloneWithMessage(job, "Success!");
try {
job = statusCallback.onJobCompleted(job);
} catch (ExecutorStatusCallbackException e1) {
logger.warn("Failed to execute statusCallback: {}", e1);
}
engineStub.send(job);
}
private void fail(TESJob tesJob) {
Job job = taskJobs.get(tesJob.getTask().getTaskId());
job = Job.cloneWithStatus(job, JobStatus.FAILED);
try {
job = statusCallback.onJobFailed(job);
} catch (ExecutorStatusCallbackException e) {
logger.warn("Failed to execute statusCallback: {}", e);
}
}
@Override
public void initialize(Backend backend) {
try {
switch (backend.getType()) {
case LOCAL:
engineStub = new EngineStubLocal((BackendLocal) backend, this, configuration);
break;
default:
throw new TransportPluginException("Backend " + backend.getType() + " is not supported.");
}
engineStub.start();
} catch (TransportPluginException e) {
logger.error("Failed to initialize Executor", e);
throw new RuntimeException("Failed to initialize Executor", e);
}
}
@Override
public void start(Job job, String contextId) {
taskFutures.add(taskPoolExecutor.submit(new TaskRunCallable(job)));
taskJobs.put(job.getId(), job);
}
@SuppressWarnings("unchecked")
private <T extends Requirement> T getRequirement(List<Requirement> requirements, Class<T> clazz) {
for (Requirement requirement : requirements) {
if (requirement.getClass().equals(clazz)) {
return (T) requirement;
}
}
return null;
}
private File createJobDir(SharedFileStorage sharedFileStorage, Job job) {
File jobDir = new File(sharedFileStorage.getBaseDir(), job.getId());
if (!jobDir.exists()) {
jobDir.mkdirs();
}
return jobDir;
}
private File createWorkingDir(SharedFileStorage sharedFileStorage, Job job) {
File workingDir = new File(sharedFileStorage.getBaseDir(), getWorkingDirRelativePath(job));
if (!workingDir.exists()) {
workingDir.mkdirs();
}
return workingDir;
}
private String getWorkingDirRelativePath(Job job) {
return job.getId() + "/" + WORKING_DIR;
}
public class TaskRunCallable implements Callable<TESJob> {
private Job job;
public TaskRunCallable(Job job) {
this.job = job;
}
@Override
public TESJob call() throws Exception {
try {
final SharedFileStorage sharedFileStorage = storageService.getStorageInfo();
LocalFileStorage localFileStorage = new LocalFileStorage(configuration.getString("backend.execution.directory"));
job = storageService.stageInputFiles(job, localFileStorage, sharedFileStorage);
List<TESTaskParameter> inputs = new ArrayList<>();
inputs.add(new TESTaskParameter("mount", null, "", TESStorageService.DOCKER_PATH_PREFIX, FileType.Directory.name(), true));
job = FileValueHelper.mapInputFilePaths(job, new FilePathMapper() {
@Override
public String map(String path, Map<String, Object> config) throws FileMappingException {
return path.replace(sharedFileStorage.getBaseDir(), TESStorageService.DOCKER_PATH_PREFIX);
}
});
Bindings bindings = BindingsFactory.create(job);
createWorkingDir(sharedFileStorage, job);
File jobDir = createJobDir(sharedFileStorage, job);
String workingDirRelativePath = getWorkingDirRelativePath(job);
inputs.add(new TESTaskParameter("working_dir", null, workingDirRelativePath, TESStorageService.DOCKER_PATH_PREFIX + "/working_dir", FileType.Directory.name(), false));
File jobFile = new File(jobDir, "job.json");
FileUtils.writeStringToFile(jobFile, JSONHelper.writeObject(job));
inputs.add(new TESTaskParameter("job.json", null, job.getId() + "/job.json", TESStorageService.DOCKER_PATH_PREFIX + "/job.json", FileType.File.name(), true));
List<TESTaskParameter> outputs = new ArrayList<>();
outputs.add(new TESTaskParameter("working_dir", null, workingDirRelativePath, TESStorageService.DOCKER_PATH_PREFIX + "/working_dir", FileType.Directory.name(), false));
if (!bindings.canExecute(job)) {
outputs.add(new TESTaskParameter("command.sh", null, job.getId() + "/command.sh", TESStorageService.DOCKER_PATH_PREFIX + "/command.sh", FileType.File.name(), false));
outputs.add(new TESTaskParameter("environment.sh", null, job.getId() + "/environment.sh", TESStorageService.DOCKER_PATH_PREFIX + "/environment.sh", FileType.File.name(), false));
}
List<String> firstCommandLineParts = new ArrayList<>();
firstCommandLineParts.add("/usr/share/rabix-tes-command-line/rabix");
firstCommandLineParts.add("-j");
firstCommandLineParts.add(TESStorageService.DOCKER_PATH_PREFIX + "/job.json");
firstCommandLineParts.add("-w");
firstCommandLineParts.add(TESStorageService.DOCKER_PATH_PREFIX + "/working_dir");
firstCommandLineParts.add("-m");
firstCommandLineParts.add("initialize");
List<TESDockerExecutor> dockerExecutors = new ArrayList<>();
String standardOutLog = TESStorageService.DOCKER_PATH_PREFIX + "/" + STANDARD_OUT_LOG;
String standardErrorLog = TESStorageService.DOCKER_PATH_PREFIX + "/" + STANDARD_ERROR_LOG;
dockerExecutors.add(new TESDockerExecutor(BUNNY_COMMAND_LINE_DOCKER_IMAGE, firstCommandLineParts, TESStorageService.DOCKER_PATH_PREFIX + "/working_dir", null, standardOutLog, standardErrorLog));
List<Requirement> combinedRequirements = new ArrayList<>();
combinedRequirements.addAll(bindings.getHints(job));
combinedRequirements.addAll(bindings.getRequirements(job));
DockerContainerRequirement dockerContainerRequirement = getRequirement(combinedRequirements, DockerContainerRequirement.class);
String imageId = null;
if (dockerContainerRequirement == null) {
imageId = "frolvlad/alpine-python2";
} else {
imageId = dockerContainerRequirement.getDockerPull();
}
if (!bindings.canExecute(job)) {
List<String> secondCommandLineParts = new ArrayList<>();
secondCommandLineParts.add("/bin/sh");
secondCommandLineParts.add("../command.sh");
CommandLine commandLine = bindings.buildCommandLineObject(job, new File(TESStorageService.DOCKER_PATH_PREFIX + "/working_dir"), new FilePathMapper() {
@Override
public String map(String path, Map<String, Object> config) throws FileMappingException {
return path;
}
});
String commandLineToolStdout = commandLine.getStandardOut();
if (commandLineToolStdout != null && !commandLineToolStdout.startsWith("/")) {
commandLineToolStdout = TESStorageService.DOCKER_PATH_PREFIX + "/working_dir/" + commandLineToolStdout;
}
String commandLineToolErrLog = commandLine.getStandardError();
String commandLineStandardErrLog = TESStorageService.DOCKER_PATH_PREFIX + "/working_dir/" + (commandLineToolErrLog != null ? commandLineToolErrLog : DEFAULT_COMMAND_LINE_TOOL_ERR_LOG);
dockerExecutors.add(new TESDockerExecutor(imageId, secondCommandLineParts, TESStorageService.DOCKER_PATH_PREFIX + "/working_dir", null, commandLineToolStdout, commandLineStandardErrLog));
}
List<String> thirdCommandLineParts = new ArrayList<>();
thirdCommandLineParts.add("/usr/share/rabix-tes-command-line/rabix");
thirdCommandLineParts.add("-j");
thirdCommandLineParts.add(TESStorageService.DOCKER_PATH_PREFIX + "/job.json");
thirdCommandLineParts.add("-w");
thirdCommandLineParts.add(TESStorageService.DOCKER_PATH_PREFIX + "/working_dir");
thirdCommandLineParts.add("-m");
thirdCommandLineParts.add("finalize");
dockerExecutors.add(new TESDockerExecutor(BUNNY_COMMAND_LINE_DOCKER_IMAGE, thirdCommandLineParts, TESStorageService.DOCKER_PATH_PREFIX + "/working_dir", null, standardOutLog, standardErrorLog));
List<TESVolume> volumes = new ArrayList<>();
volumes.add(new TESVolume("vol_work", 1, null, TESStorageService.DOCKER_PATH_PREFIX));
TESResources resources = new TESResources(null, false, null, volumes, null);
TESTask task = new TESTask(job.getName(), DEFAULT_PROJECT, null, inputs, outputs, resources, job.getId(), dockerExecutors);
TESJobId tesJobId = tesHttpClient.runTask(task);
taskJobs.put(tesJobId.getValue(), job);
TESJob tesJob = null;
do {
Thread.sleep(500L);
tesJob = tesHttpClient.getJob(tesJobId);
if (tesJob == null) {
throw new TESServiceException("TESJob is not created. JobId = " + job.getId());
}
} while(!isFinished(tesJob));
return tesJob;
} catch (IOException e) {
logger.error("Failed to write files to SharedFileStorage", e);
throw new TESServiceException("Failed to write files to SharedFileStorage", e);
} catch (TESHTTPClientException e) {
logger.error("Failed to submit Job to TES", e);
throw new TESServiceException("Failed to submit Job to TES", e);
} catch (BindingException e) {
logger.error("Failed to use Bindings", e);
throw new TESServiceException("Failed to use Bindings", e);
}
}
private boolean isFinished(TESJob tesJob) {
return tesJob.getState().equals(TESState.Canceled) ||
tesJob.getState().equals(TESState.Complete) ||
tesJob.getState().equals(TESState.Error) ||
tesJob.getState().equals(TESState.SystemError);
}
}
@Override
public void stop(List<String> ids, String contextId) {
throw new NotImplementedException("This method is not implemented");
}
@Override
public void free(String rootId, Map<String, Object> config) {
throw new NotImplementedException("This method is not implemented");
}
@Override
public void shutdown(Boolean stopEverything) {
throw new NotImplementedException("This method is not implemented");
}
@Override
public boolean isRunning(String id, String contextId) {
throw new NotImplementedException("This method is not implemented");
}
@Override
public Map<String, Object> getResult(String id, String contextId) {
throw new NotImplementedException("This method is not implemented");
}
@Override
public boolean isStopped() {
throw new NotImplementedException("This method is not implemented");
}
@Override
public JobStatus findStatus(String id, String contextId) {
throw new NotImplementedException("This method is not implemented");
}
} |
package org.jboss.gwt.elemento.sample.templated.client;
import elemental.dom.Element;
import elemental.events.KeyboardEvent;
import elemental.html.ButtonElement;
import elemental.html.InputElement;
import org.jboss.gwt.elemento.core.DataElement;
import org.jboss.gwt.elemento.core.Elements;
import org.jboss.gwt.elemento.core.EventHandler;
import org.jboss.gwt.elemento.core.IsElement;
import org.jboss.gwt.elemento.core.Templated;
import org.jboss.gwt.elemento.sample.common.TodoItem;
import org.jboss.gwt.elemento.sample.common.TodoItemRepository;
import org.jboss.gwt.elemento.sample.common.TodoMessages;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static elemental.events.KeyboardEvent.KeyCode.ENTER;
import static org.jboss.gwt.elemento.core.EventType.*;
import static org.jboss.gwt.elemento.sample.templated.client.Filter.ACTIVE;
import static org.jboss.gwt.elemento.sample.templated.client.Filter.COMPLETED;
@Templated("Todo.html#todos")
abstract class ApplicationElement implements IsElement {
static ApplicationElement create(TodoItemRepository repository, TodoMessages messages) {
return new Templated_ApplicationElement(repository, messages);
}
abstract TodoItemRepository repository();
abstract TodoMessages messages();
Filter filter;
@DataElement InputElement newTodo;
@DataElement Element main;
@DataElement InputElement toggleAll;
@DataElement Element list;
@DataElement Element footer;
@DataElement Element count;
@DataElement("all") Element filterAll;
@DataElement("active") Element filterActive;
@DataElement("completed") Element filterCompleted;
@DataElement ButtonElement clearCompleted;
@PostConstruct
void init() {
Elements.removeChildrenFrom(list);
for (TodoItem item : repository().items()) {
list.appendChild(TodoItemElement.create(this, item, repository()).asElement());
}
update();
}
@EventHandler(element = "newTodo", on = keydown)
void newTodo(KeyboardEvent event) {
if (event.getKeyCode() == ENTER) {
String text = newTodo.getValue().trim();
if (text.length() != 0) {
TodoItem item = repository().add(text);
list.appendChild(TodoItemElement.create(this, item, repository()).asElement());
newTodo.setValue("");
update();
}
}
}
@EventHandler(element = "toggleAll", on = change)
void toggleAll() {
boolean checked = toggleAll.isChecked();
for (Element li : Elements.children(list)) {
if (checked) {
li.getClassList().add("completed");
} else {
li.getClassList().remove("completed");
}
InputElement checkbox = (InputElement) li.getFirstElementChild().getFirstElementChild();
checkbox.setChecked(checked);
}
repository().completeAll(checked);
update();
}
@EventHandler(element = "clearCompleted", on = click)
void clearCompleted() {
Set<String> ids = new HashSet<>();
for (Iterator<Element> iterator = Elements.iterator(list); iterator.hasNext(); ) {
Element li = iterator.next();
if (li.getClassList().contains("completed")) {
String id = String.valueOf(li.getDataset().at("item"));
if (id != null) {
ids.add(id);
}
iterator.remove();
}
}
repository().removeAll(ids);
update();
}
void filter(String token) {
filter = Filter.parseToken(token);
switch (filter) {
case ALL:
filterAll.getClassList().add("selected");
filterActive.getClassList().remove("selected");
filterCompleted.getClassList().remove("selected");
break;
case ACTIVE:
filterAll.getClassList().remove("selected");
filterActive.getClassList().add("selected");
filterCompleted.getClassList().remove("selected");
break;
case COMPLETED:
filterAll.getClassList().remove("selected");
filterActive.getClassList().remove("selected");
filterCompleted.getClassList().add("selected");
break;
}
update();
}
void update() {
int activeCount = 0;
int completedCount = 0;
int size = list.getChildElementCount();
Elements.setVisible(main, size > 0);
Elements.setVisible(footer, size > 0);
for (Element li : Elements.children(list)) {
if (li.getClassList().contains("completed")) {
completedCount++;
Elements.setVisible(li, filter != ACTIVE);
} else {
Elements.setVisible(li, filter != COMPLETED);
activeCount++;
}
}
toggleAll.setChecked(size == completedCount);
Elements.innerHtml(count, messages().items(activeCount));
Elements.setVisible(clearCompleted, completedCount != 0);
}
} |
package org.ow2.proactive_grid_cloud_portal.scheduler.client.view;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.Job;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.ColumnsFactory;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.GridColumns;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs.JobsColumnsFactory;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.tasks.TasksColumnsFactory;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.Layout;
import com.smartgwt.client.widgets.viewer.DetailFormatter;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.client.widgets.viewer.DetailViewerField;
import com.smartgwt.client.widgets.viewer.DetailViewerRecord;
public class InfoView<T> {
/** label when no job is selected */
protected Label label = null;
/** widget shown when a job is selected */
protected DetailViewer details = null;
/** currently displayed job */
protected T displayedItem = null;
protected ColumnsFactory<T> factory;
protected String emptyMessage;
public InfoView(ColumnsFactory<T> factory, String emptyMessage) {
this.factory = factory;
this.emptyMessage = emptyMessage;
}
/**
* @return the Widget to display, ready to be added in a container
*/
public Layout build() {
this.label = new Label(this.emptyMessage);
this.label.setWidth100();
this.label.setAlign(Alignment.CENTER);
this.details = new DetailViewer();
this.details.setWidth100();
this.details.setHeight100();
this.details.setCanSelectText(true);
this.details.hide();
GridColumns[] lines = this.factory.getColumns();
DetailViewerField[] fields = new DetailViewerField[lines.length];
for (int i = 0; i < lines.length; i++) {
fields[i] = new DetailViewerField(lines[i].getName(), lines[i].getTitle());
if (lines[i] == TasksColumnsFactory.EXEC_DURATION_ATTR || lines[i] == JobsColumnsFactory.DURATION_ATTR) {
fields[i].setDetailFormatter(new DetailFormatter() {
@Override
public String format(Object duration, Record record, DetailViewerField detailViewerField) {
if (duration != null) {
return Job.formatDuration(duration.toString());
} else {
return "";
}
}
});
}
}
this.details.setFields(fields);
return getLayout();
}
public void hideDetails() {
this.details.hide();
hideExtraMembers();
this.label.show();
this.displayedItem = null;
}
public void displayItem() {
DetailViewerRecord[] records = new DetailViewerRecord[1];
records[0] = new DetailViewerRecord();
this.factory.buildRecord(this.displayedItem, records[0]);
this.details.setData(records);
displayExtraMembers(this.displayedItem);
this.label.hide();
this.details.show();
}
protected Layout getLayout() {
/* widget that will be returned as the root layout */
Layout root = new Layout();
root.setWidth100();
root.setHeight100();
root.addMember(label);
root.addMember(details);
return root;
}
/**
* Display specific members of the view. This method is meant to be overridden by inheriting classes
* @param object
*/
protected void displayExtraMembers(T object) {
}
/**
* Hide specific members of the view. This method is meant to be overridden by inheriting classes
* @param object
*/
protected void hideExtraMembers() {
}
} |
package org.ow2.proactive.scheduler.task;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.ow2.proactive.scheduler.task.TaskAssertions.assertTaskResultOk;
import java.io.File;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.objectweb.proactive.core.node.NodeImpl;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.VMInformation;
import org.ow2.proactive.authentication.crypto.CredData;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.scheduler.common.SchedulerConstants;
import org.ow2.proactive.scheduler.common.job.JobVariable;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.flow.FlowActionType;
import org.ow2.proactive.scheduler.common.task.flow.FlowScript;
import org.ow2.proactive.scheduler.common.task.util.SerializationUtil;
import org.ow2.proactive.scheduler.job.JobIdImpl;
import org.ow2.proactive.scheduler.task.containers.ScriptExecutableContainer;
import org.ow2.proactive.scheduler.task.context.NodeDataSpacesURIs;
import org.ow2.proactive.scheduler.task.context.NodeInfo;
import org.ow2.proactive.scheduler.task.context.TaskContext;
import org.ow2.proactive.scheduler.task.executors.InProcessTaskExecutor;
import org.ow2.proactive.scheduler.task.utils.Decrypter;
import org.ow2.proactive.scripting.SimpleScript;
import org.ow2.proactive.scripting.TaskScript;
import org.ow2.proactive.utils.ClasspathUtils;
import org.ow2.proactive.utils.NodeSet;
import org.ow2.tests.ProActiveTestClean;
import com.google.common.collect.ImmutableMap;
public class InProcessTaskExecutorTest extends ProActiveTestClean {
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Test
public void simpleScriptTask() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("println('pre')", "groovy"));
initializer.setPostScript(new SimpleScript("println('post')", "groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("println('hello'); java.lang.Thread.sleep(5); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(String.format("pre%nhello%npost%n"), taskOutput.output());
assertEquals("hello", result.value());
assertTrue("Task duration should be at least 5", result.getTaskDuration() >= 5);
}
@Test
public void storePreScriptAbsolute() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("println('pre')", "groovy"));
initializer.setPostScript(new SimpleScript("println('post')", "groovy"));
Map<String, String> genericInfo = new HashMap<>();
File file = File.createTempFile("test", ".py");
genericInfo.put("PRE_SCRIPT_AS_FILE", file.getAbsolutePath());
file.delete();
initializer.setGenericInformation(genericInfo);
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("println('hello'); java.lang.Thread.sleep(5); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
//Make sure that the execution of the pre-script is skipped
assertEquals(String.format("hello%npost%n"), taskOutput.output());
assertEquals("hello", result.value());
//Make sure that the pre-script is stored in a file
assertTrue(file.exists());
String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
assertEquals("println('pre')", content);
file.delete();
}
@Test
public void storePreScriptRelative() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("println('pre')", "groovy"));
initializer.setPostScript(new SimpleScript("println('post')", "groovy"));
Map<String, String> genericInfo = new HashMap<>();
genericInfo.put("PRE_SCRIPT_AS_FILE", "test.py");
initializer.setGenericInformation(genericInfo);
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
Path p = Files.createTempDirectory("");
TaskContext taskContext = new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("println('hello'); java.lang.Thread.sleep(5); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs(p.toString(), "", "", "", "", ""),
"",
new NodeInfo("", "", ""));
TaskResultImpl result = new InProcessTaskExecutor().execute(taskContext,
taskOutput.outputStream,
taskOutput.error);
//Make sure that the execution of the pre-script is skipped
assertEquals(String.format("hello%npost%n"), taskOutput.output());
assertEquals("hello", result.value());
//Make sure that the pre-script is stored in a file
String uri = taskContext.getNodeDataSpaceURIs().getScratchURI();
File file = new File(uri, "test.py");
assertTrue(file.exists());
String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
assertEquals("println('pre')", content);
file.delete();
Files.delete(p);
}
@Test
public void storePreScriptWithoutExtension() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("println('pre')", "groovy"));
initializer.setPostScript(new SimpleScript("println('post')", "groovy"));
Map<String, String> genericInfo = new HashMap<>();
File file = File.createTempFile("test", "");
genericInfo.put("PRE_SCRIPT_AS_FILE", file.getAbsolutePath());
file.delete();
initializer.setGenericInformation(genericInfo);
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("println('hello'); java.lang.Thread.sleep(5); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
//Make sure that the execution of the pre-script is skipped
assertEquals(String.format("hello%npost%n"), taskOutput.output());
assertEquals("hello", result.value());
//Make sure that the pre-script is stored in a file
file = new File(file.getAbsolutePath() + ".groovy");
assertTrue(file.exists());
String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
assertEquals("println('pre')", content);
file.delete();
}
@Test
public void testPaUserVariableAvailabilityFromScriptEngine() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
String jobOwner = "JohnDoe";
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setJobOwner(jobOwner);
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print variables.get('PA_USER')",
"python"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(jobOwner, taskOutput.output().trim());
}
@Test
public void failingScript() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("dsfsdfsdf",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertTrue(result.hadException());
assertFalse(taskOutput.error().isEmpty());
}
@Test
public void contextVariables() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setReplicationIndex(42);
String printEnvVariables = "print(variables.get('PA_JOB_NAME') + '@' + " +
"variables.get('PA_JOB_ID') + '@' + variables.get('PA_TASK_NAME') " +
"+ '@' + variables.get('PA_TASK_ID') +'\\n')";
initializer.setPreScript(new SimpleScript(printEnvVariables, "groovy"));
initializer.setPostScript(new SimpleScript(printEnvVariables, "groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript(printEnvVariables,
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
String[] lines = taskOutput.output().split("\\n");
assertEquals("job@1000@task@42", lines[0]);
assertEquals("job@1000@task@42", lines[1]);
assertEquals("job@1000@task@42", lines[2]);
}
@Test
public void contextVariables_index() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setReplicationIndex(7);
initializer.setIterationIndex(6);
String script = "result = variables.get('PA_TASK_ITERATION') * variables.get('PA_TASK_REPLICATION')";
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript(script,
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(42, result.value());
}
@Test
public void resultMetadata() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
Map<String, String> metadata = ImmutableMap.of("pre", "pre", "post", "post", "task", "task");
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript(SchedulerConstants.RESULT_METADATA_VARIABLE + ".put('pre','pre')",
"groovy"));
initializer.setPostScript(new SimpleScript(SchedulerConstants.RESULT_METADATA_VARIABLE + ".put('post','post')",
"groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript(SchedulerConstants.RESULT_METADATA_VARIABLE +
".put('task','task')",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(metadata, result.getMetadata());
}
@Test
public void variablesPropagation() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("print(variables.get('var')); variables.put('var', 'pre')",
"groovy"));
initializer.setPostScript(new SimpleScript("print(variables.get('var')); variables.put('var', 'post')",
"groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
initializer.setJobVariables(Collections.singletonMap("var", new JobVariable("var", "value")));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print(variables.get('var')); variables.put('var', 'task')",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("valuepretask", taskOutput.output());
assertEquals("post", SerializationUtil.deserializeVariableMap(result.getPropagatedVariables()).get("var"));
}
@Test
public void variablesPropagation_fromParentTask() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
Map<String, Serializable> variablesFromParent = new HashMap<>();
variablesFromParent.put("var", "parent");
variablesFromParent.put(SchedulerVars.PA_TASK_ID.toString(), "1234");
TaskResult[] previousTasksResults = { new TaskResultImpl(null,
null,
null,
null,
null,
SerializationUtil.serializeVariableMap(variablesFromParent),
false) };
new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print(variables.get('var'));print(variables.get('PA_TASK_ID'))",
"groovy"))),
initializer,
previousTasksResults,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("parent42", taskOutput.output());
}
@Test
public void result_from_parent_task() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
TaskResult[] previousTasksResults = { new TaskResultImpl(null, "aresult", null, 0) };
new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print(results[0]);",
"groovy"))),
initializer,
previousTasksResults,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("aresult", taskOutput.output());
}
@Test
public void failingScriptTask() throws Exception {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("return 10/0",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("", taskOutput.output());
assertNotEquals("", taskOutput.error());
assertNotNull(result.getException());
}
@Test
public void failingPrescript() throws Exception {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPreScript(new SimpleScript("return 10/0", "groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print('hello'); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("", taskOutput.output());
assertNotEquals("", taskOutput.error());
assertNotNull(result.getException());
}
@Test
public void failingPostscript() throws Exception {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setPostScript(new SimpleScript("return 10/0", "groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print('hello'); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("hello", taskOutput.output());
assertNotEquals("", taskOutput.error());
assertNotNull(result.getException());
}
@Test
public void taskWithFlowScript() throws Exception {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setControlFlowScript(FlowScript.createReplicateFlowScript("print('flow'); runs=5", "groovy"));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print('hello'); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(FlowActionType.REPLICATE, result.getAction().getType());
assertEquals("helloflow", taskOutput.output());
}
@Test
public void failingFlowScript() throws Exception {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setControlFlowScript(FlowScript.createReplicateFlowScript(""));
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
TaskResultImpl result = new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print('hello'); result='hello'",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("",
"",
"",
"",
"",
""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("hello", taskOutput.output());
assertNotEquals("", taskOutput.error());
assertNotNull(result.getException());
}
@Test
public void scriptArguments() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
String printEnvVariables = "print(args[0])";
initializer.setPreScript(new SimpleScript(printEnvVariables, "groovy", new Serializable[] { "Hello" }));
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals("Hello", taskOutput.output());
}
@Test
public void scriptArgumentsReplacements() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
String printArgs = "println(args[0] + args[1]);";
initializer.setPreScript(new SimpleScript(printArgs,
"groovy",
new Serializable[] { "$credentials_PASSWORD", "$PA_JOB_ID" }));
initializer.setPostScript(new SimpleScript(printArgs,
"groovy",
new Serializable[] { "$credentials_PASSWORD", "$PA_JOB_ID" }));
initializer.setTaskId(TaskIdImpl.createTaskId(new JobIdImpl(1000, "job"), "task", 42L));
Decrypter decrypter = createCredentials("somebody_that_does_not_exists");
TaskContext taskContext = new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript(printArgs,
"groovy",
new Serializable[] { "$credentials_PASSWORD",
"${PA_JOB_ID}" }))),
initializer,
null,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", ""),
decrypter);
new InProcessTaskExecutor().execute(taskContext, taskOutput.outputStream, taskOutput.error);
assertEquals(String.format("p4ssw0rd1000%np4ssw0rd1000%np4ssw0rd1000%n"), taskOutput.output()); // pre, task and post
}
@Test
public void schedulerHomeIsInVariables() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
new InProcessTaskExecutor().execute(new TaskContext(new ScriptExecutableContainer(new TaskScript(new SimpleScript("print(variables.get('PA_SCHEDULER_HOME'))",
"groovy"))),
initializer,
null,
new NodeDataSpacesURIs("", "", "", "", "", ""),
"",
new NodeInfo("", "", "")),
taskOutput.outputStream,
taskOutput.error);
assertEquals(ClasspathUtils.findSchedulerHome(), taskOutput.output());
}
@Test
public void nodesFileIsCreated() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
ScriptExecutableContainer printNodesFileTask = new ScriptExecutableContainer(new TaskScript(new SimpleScript("print new File(variables.get('PA_NODESFILE')).text",
"groovy")));
printNodesFileTask.setNodes(mockedNodeSet());
TaskContext context = new TaskContext(printNodesFileTask,
initializer,
null,
new NodeDataSpacesURIs(tmpFolder.newFolder().getAbsolutePath(),
"",
"",
"",
"",
""),
"",
new NodeInfo("thisHost", "", ""));
TaskResultImpl taskResult = new InProcessTaskExecutor().execute(context,
taskOutput.outputStream,
taskOutput.error);
assertTaskResultOk(taskResult);
assertEquals(String.format("thisHost%ndummyhost%n"), taskOutput.output());
}
@Test
public void multiNodesURLsAreBounded() throws Throwable {
TestTaskOutput taskOutput = new TestTaskOutput();
TaskLauncherInitializer initializer = new TaskLauncherInitializer();
initializer.setTaskId(TaskIdImpl.createTaskId(JobIdImpl.makeJobId("1000"), "job", 1000L));
ScriptExecutableContainer printNodesFileTask = new ScriptExecutableContainer(new TaskScript(new SimpleScript("println nodesurl.size()",
"groovy")));
printNodesFileTask.setNodes(mockedNodeSet());
TaskContext context = new TaskContext(printNodesFileTask,
initializer,
null,
new NodeDataSpacesURIs(tmpFolder.newFolder().getAbsolutePath(),
"",
"",
"",
"",
""),
"",
new NodeInfo("thisHost", "", ""));
TaskResultImpl taskResult = new InProcessTaskExecutor().execute(context,
taskOutput.outputStream,
taskOutput.error);
assertTaskResultOk(taskResult);
assertEquals(String.format("1%n"), taskOutput.output());
}
private NodeSet mockedNodeSet() {
NodeSet nodes = new NodeSet();
ProActiveRuntime proActiveRuntime = mock(ProActiveRuntime.class);
VMInformation vmInformation = mock(VMInformation.class);
when(vmInformation.getHostName()).thenReturn("dummyhost");
when(proActiveRuntime.getVMInformation()).thenReturn(vmInformation);
nodes.add(new NodeImpl(proActiveRuntime, "dummyhost"));
return nodes;
}
private Decrypter createCredentials(String username) throws NoSuchAlgorithmException, KeyException {
CredData credData = new CredData(username, "pwd");
credData.addThirdPartyCredential("PASSWORD", "p4ssw0rd");
KeyPairGenerator keyGen;
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
Decrypter decrypter = new Decrypter(keyPair.getPrivate());
Credentials credentials = Credentials.createCredentials(credData, keyPair.getPublic());
decrypter.setCredentials(credentials);
return decrypter;
}
} |
package de.fosd.jdime;
import java.util.HashMap;
import de.fosd.jdime.common.LangElem;
import de.fosd.jdime.stats.ASTStats;
import de.fosd.jdime.stats.StatsElement;
import org.gnu.glpk.GLPK;
/**
* Contains static methods testing the functionality of various aspects of the program.
*
* @author Olaf Lessenich
*/
public final class InternalTests {
private static String delimiter = "====================================================";
/**
* Utility class constructor.
*/
private InternalTests() {
}
/**
* Runs all internal tests.
*/
public static void run() {
runEnvironmentTest();
runASTStatsTests();
}
/**
* Checks whether the environment for the program is correctly configured. Particularly this verifies that
* the native libraries are working.
*/
public static void runEnvironmentTest() {
try {
System.out.println("GLPK " + GLPK.glp_version() + " is working.");
System.out.println(InternalTests.class.getCanonicalName() + " : OK");
} catch (Throwable t) {
System.out.println(t);
System.out.println(InternalTests.class.getCanonicalName() + " : FAILED");
throw t;
}
}
public static void runASTStatsTests() {
ASTStats[] stats = new ASTStats[2];
for (int i = 0; i < stats.length; i++) {
HashMap<String, StatsElement> diffstats = new HashMap<>();
StatsElement all = new StatsElement();
for (LangElem level : LangElem.values()) {
if (level.equals(LangElem.NODE)) {
continue;
}
StatsElement s = new StatsElement();
s.setAdded((int) (5 * Math.random()));
s.setMatches((int) (5 * Math.random()));
s.setDeleted((int) (5 * Math.random()));
s.setElements(s.getAdded() + s.getDeleted() + s.getMatches());
s.setConflicting((int) (s.getElements() * Math.random()));
s.setChanges(s.getAdded() + s.getDeleted() + s.getConflicting());
all.addStatsElement(s);
diffstats.put(level.toString(), s);
}
diffstats.put(LangElem.NODE.toString(), all);
stats[i] = new ASTStats(all.getElements(), (int) (5 * Math.random()), (int) (5 * Math.random()), diffstats,
all.getChanges() != 0);
}
ASTStats sum = ASTStats.add(stats[0], stats[1]);
System.out.println(delimiter);
System.out.println("Left:");
System.out.println(stats[0]);
System.out.println(delimiter);
System.out.println("Right:");
System.out.println(stats[1]);
System.out.println(delimiter);
System.out.println("Sum:");
System.out.println(sum);
}
} |
package org.opendaylight.ovsdb.southbound;
import static org.opendaylight.ovsdb.lib.operations.Operations.op;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.ovsdb.lib.OvsdbClient;
import org.opendaylight.ovsdb.lib.OvsdbConnection;
import org.opendaylight.ovsdb.lib.OvsdbConnectionListener;
import org.opendaylight.ovsdb.lib.operations.Operation;
import org.opendaylight.ovsdb.lib.operations.OperationResult;
import org.opendaylight.ovsdb.lib.operations.Select;
import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
import org.opendaylight.ovsdb.southbound.transactions.md.OvsdbNodeRemoveCommand;
import org.opendaylight.ovsdb.southbound.transactions.md.TransactionCommand;
import org.opendaylight.ovsdb.southbound.transactions.md.TransactionInvoker;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
public class OvsdbConnectionManager implements OvsdbConnectionListener, AutoCloseable {
private Map<ConnectionInfo, OvsdbConnectionInstance> clients =
new ConcurrentHashMap<>();
private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionManager.class);
private static final String ENTITY_TYPE = "ovsdb";
private DataBroker db;
private TransactionInvoker txInvoker;
private Map<ConnectionInfo,InstanceIdentifier<Node>> instanceIdentifiers =
new ConcurrentHashMap<>();
private Map<Entity, OvsdbConnectionInstance> entityConnectionMap =
new ConcurrentHashMap<>();
private EntityOwnershipService entityOwnershipService;
private OvsdbDeviceEntityOwnershipListener ovsdbDeviceEntityOwnershipListener;
private OvsdbConnection ovsdbConnection;
public OvsdbConnectionManager(DataBroker db,TransactionInvoker txInvoker,
EntityOwnershipService entityOwnershipService,
OvsdbConnection ovsdbConnection) {
this.db = db;
this.txInvoker = txInvoker;
this.entityOwnershipService = entityOwnershipService;
this.ovsdbDeviceEntityOwnershipListener = new OvsdbDeviceEntityOwnershipListener(this, entityOwnershipService);
this.ovsdbConnection = ovsdbConnection;
}
@Override
public void connected(@Nonnull final OvsdbClient externalClient) {
LOG.info("Library connected {} from {}:{} to {}:{}",
externalClient.getConnectionInfo().getType(),
externalClient.getConnectionInfo().getRemoteAddress(),
externalClient.getConnectionInfo().getRemotePort(),
externalClient.getConnectionInfo().getLocalAddress(),
externalClient.getConnectionInfo().getLocalPort());
OvsdbConnectionInstance client = connectedButCallBacksNotRegistered(externalClient);
// Register Cluster Ownership for ConnectionInfo
registerEntityForOwnership(client);
}
public OvsdbConnectionInstance connectedButCallBacksNotRegistered(final OvsdbClient externalClient) {
LOG.info("OVSDB Connection from {}:{}",externalClient.getConnectionInfo().getRemoteAddress(),
externalClient.getConnectionInfo().getRemotePort());
ConnectionInfo key = SouthboundMapper.createConnectionInfo(externalClient);
OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
// Check if existing ovsdbConnectionInstance for the OvsdbClient present.
// In such cases, we will see if the ovsdbConnectionInstance has same externalClient.
if (ovsdbConnectionInstance != null) {
if (ovsdbConnectionInstance.hasOvsdbClient(externalClient)) {
LOG.warn("OVSDB Connection Instance {} already exists for client {}", key, externalClient);
return ovsdbConnectionInstance;
}
LOG.warn("OVSDB Connection Instance {} being replaced with client {}", key, externalClient);
// Unregister Cluster Ownership for ConnectionInfo
// Because the ovsdbConnectionInstance is about to be completely replaced!
unregisterEntityForOwnership(ovsdbConnectionInstance);
ovsdbConnectionInstance.disconnect();
removeConnectionInstance(key);
}
ovsdbConnectionInstance = new OvsdbConnectionInstance(key, externalClient, txInvoker,
getInstanceIdentifier(key));
ovsdbConnectionInstance.createTransactInvokers();
return ovsdbConnectionInstance;
}
@Override
public void disconnected(OvsdbClient client) {
LOG.info("Library disconnected {} from {}:{} to {}:{}. Cleaning up the operational data store",
client.getConnectionInfo().getType(),
client.getConnectionInfo().getRemoteAddress(),
client.getConnectionInfo().getRemotePort(),
client.getConnectionInfo().getLocalAddress(),
client.getConnectionInfo().getLocalPort());
ConnectionInfo key = SouthboundMapper.createConnectionInfo(client);
OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(key);
if (ovsdbConnectionInstance != null) {
// Unregister Entity ownership as soon as possible ,so this instance should
// not be used as a candidate in Entity election (given that this instance is
// about to disconnect as well), if current owner get disconnected from
// OVSDB device.
unregisterEntityForOwnership(ovsdbConnectionInstance);
txInvoker.invoke(new OvsdbNodeRemoveCommand(ovsdbConnectionInstance, null, null));
removeConnectionInstance(key);
} else {
LOG.warn("disconnected : Connection instance not found for OVSDB Node {} ", key);
}
LOG.trace("OvsdbConnectionManager: exit disconnected client: {}", client);
}
public OvsdbClient connect(InstanceIdentifier<Node> iid,
OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
LOG.info("Connecting to {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
// TODO handle case where we already have a connection
// TODO use transaction chains to handle ordering issues between disconnected
// TODO and connected when writing to the operational store
InetAddress ip = SouthboundMapper.createInetAddress(ovsdbNode.getConnectionInfo().getRemoteIp());
OvsdbClient client = ovsdbConnection.connect(ip,
ovsdbNode.getConnectionInfo().getRemotePort().getValue());
// For connections from the controller to the ovs instance, the library doesn't call
// this method for us
if (client != null) {
putInstanceIdentifier(ovsdbNode.getConnectionInfo(), iid.firstIdentifierOf(Node.class));
OvsdbConnectionInstance ovsdbConnectionInstance = connectedButCallBacksNotRegistered(client);
ovsdbConnectionInstance.setOvsdbNodeAugmentation(ovsdbNode);
// Register Cluster Ownership for ConnectionInfo
registerEntityForOwnership(ovsdbConnectionInstance);
} else {
LOG.warn("Failed to connect to OVSDB Node {}", ovsdbNode.getConnectionInfo());
}
return client;
}
public void disconnect(OvsdbNodeAugmentation ovsdbNode) throws UnknownHostException {
LOG.info("Disconnecting from {}", SouthboundUtil.connectionInfoToString(ovsdbNode.getConnectionInfo()));
OvsdbConnectionInstance client = getConnectionInstance(ovsdbNode.getConnectionInfo());
if (client != null) {
// Unregister Cluster Onwership for ConnectionInfo
unregisterEntityForOwnership(client);
client.disconnect();
removeInstanceIdentifier(ovsdbNode.getConnectionInfo());
} else {
LOG.debug("disconnect : connection instance not found for {}",ovsdbNode.getConnectionInfo());
}
}
/* public void init(ConnectionInfo key) {
OvsdbConnectionInstance client = getConnectionInstance(key);
// TODO (FF): make sure that this cluster instance is the 'entity owner' fo the given OvsdbConnectionInstance ?
if (client != null) {
* Note: registerCallbacks() is idemPotent... so if you call it repeatedly all is safe,
* it only registersCallbacks on the *first* call.
client.registerCallbacks();
}
}
*/
@Override
public void close() throws Exception {
if (ovsdbDeviceEntityOwnershipListener != null) {
ovsdbDeviceEntityOwnershipListener.close();
}
for (OvsdbClient client: clients.values()) {
client.disconnect();
}
}
private void putConnectionInstance(ConnectionInfo key,OvsdbConnectionInstance instance) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
clients.put(connectionInfo, instance);
}
private void removeConnectionInstance(ConnectionInfo key) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
clients.remove(connectionInfo);
}
private void putInstanceIdentifier(ConnectionInfo key,InstanceIdentifier<Node> iid) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
instanceIdentifiers.put(connectionInfo, iid);
}
private void removeInstanceIdentifier(ConnectionInfo key) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
instanceIdentifiers.remove(connectionInfo);
}
public OvsdbConnectionInstance getConnectionInstance(ConnectionInfo key) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
return clients.get(connectionInfo);
}
public InstanceIdentifier<Node> getInstanceIdentifier(ConnectionInfo key) {
ConnectionInfo connectionInfo = SouthboundMapper.suppressLocalIpPort(key);
return instanceIdentifiers.get(connectionInfo);
}
public OvsdbConnectionInstance getConnectionInstance(OvsdbBridgeAttributes mn) {
Optional<OvsdbNodeAugmentation> optional = SouthboundUtil.getManagingNode(db, mn);
if (optional.isPresent()) {
return getConnectionInstance(optional.get().getConnectionInfo());
} else {
return null;
}
}
public OvsdbConnectionInstance getConnectionInstance(Node node) {
Preconditions.checkNotNull(node);
OvsdbNodeAugmentation ovsdbNode = node.getAugmentation(OvsdbNodeAugmentation.class);
OvsdbBridgeAugmentation ovsdbManagedNode = node.getAugmentation(OvsdbBridgeAugmentation.class);
if (ovsdbNode != null) {
return getConnectionInstance(ovsdbNode.getConnectionInfo());
} else if (ovsdbManagedNode != null) {
return getConnectionInstance(ovsdbManagedNode);
} else {
LOG.warn("This is not a node that gives any hint how to find its OVSDB Manager: {}",node);
return null;
}
}
public OvsdbConnectionInstance getConnectionInstance(InstanceIdentifier<Node> nodePath) {
try {
ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
CheckedFuture<Optional<Node>, ReadFailedException> nodeFuture = transaction.read(
LogicalDatastoreType.OPERATIONAL, nodePath);
transaction.close();
Optional<Node> optional = nodeFuture.get();
if (optional != null && optional.isPresent() && optional.get() != null) {
return this.getConnectionInstance(optional.get());
} else {
LOG.warn("Found non-topological node {} on path {}",optional);
return null;
}
} catch (Exception e) {
LOG.warn("Failed to get Ovsdb Node {}",nodePath, e);
return null;
}
}
public OvsdbClient getClient(ConnectionInfo connectionInfo) {
return getConnectionInstance(connectionInfo);
}
public OvsdbClient getClient(OvsdbBridgeAttributes mn) {
return getConnectionInstance(mn);
}
public OvsdbClient getClient(Node node) {
return getConnectionInstance(node);
}
public Boolean getHasDeviceOwnership(ConnectionInfo connectionInfo) {
OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstance(connectionInfo);
if (ovsdbConnectionInstance == null) {
return Boolean.FALSE;
}
return ovsdbConnectionInstance.getHasDeviceOwnership();
}
private void handleOwnershipChanged(EntityOwnershipChange ownershipChange) {
OvsdbConnectionInstance ovsdbConnectionInstance = getConnectionInstanceFromEntity(ownershipChange.getEntity());
LOG.debug("handleOwnershipChanged: {} event received for device {}",
ownershipChange, ovsdbConnectionInstance != null ? ovsdbConnectionInstance.getConnectionInfo()
: "that's currently NOT registered by *this* southbound plugin instance");
if (ovsdbConnectionInstance == null) {
if (ownershipChange.isOwner()) {
LOG.warn("handleOwnershipChanged: *this* instance is elected as an owner of the device {} but it "
+ "is NOT registered for ownership", ownershipChange.getEntity());
} else {
// EntityOwnershipService sends notification to all the nodes, irrespective of whether
// that instance registered for the device ownership or not. It is to make sure that
// If all the controller instance that was connected to the device are down, so the
// running instance can clear up the operational data store even though it was not
// connected to the device.
LOG.debug("handleOwnershipChanged: No connection instance found for {}", ownershipChange.getEntity());
}
// If entity has no owner, clean up the operational data store (it's possible because owner controller
// might went down abruptly and didn't get a chance to clean up the operational data store.
if (!ownershipChange.hasOwner()) {
LOG.info("{} has no owner, cleaning up the operational data store", ownershipChange.getEntity());
cleanEntityOperationalData(ownershipChange.getEntity());
}
return;
}
//Connection detail need to be cached, irrespective of ownership result.
putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
if (ownershipChange.isOwner() == ovsdbConnectionInstance.getHasDeviceOwnership()) {
LOG.info("handleOwnershipChanged: no change in ownership for {}. Ownership status is : {}",
ovsdbConnectionInstance.getConnectionInfo(), ovsdbConnectionInstance.getHasDeviceOwnership()
? SouthboundConstants.OWNERSHIPSTATES.OWNER.getState()
: SouthboundConstants.OWNERSHIPSTATES.NONOWNER.getState());
return;
}
ovsdbConnectionInstance.setHasDeviceOwnership(ownershipChange.isOwner());
// You were not an owner, but now you are
if (ownershipChange.isOwner()) {
LOG.info("handleOwnershipChanged: *this* southbound plugin instance is an OWNER of the device {}",
ovsdbConnectionInstance.getConnectionInfo());
/* Switch initiated connection won't have iid, till it gets OpenVSwitch
* table update but update callback is always registered after ownership
* is granted. So we are explicitly fetch the row here to get the iid.
*/
OpenVSwitch openvswitchRow = getOpenVswitchTableEntry(ovsdbConnectionInstance);
iid = SouthboundMapper.getInstanceIdentifier(openvswitchRow);
LOG.info("InstanceIdentifier {} generated for device "
+ "connection {}",iid,ovsdbConnectionInstance.getConnectionInfo());
ovsdbConnectionInstance.setInstanceIdentifier(iid);
}
YangInstanceIdentifier entityId = SouthboundUtil.getInstanceIdentifierCodec().getYangInstanceIdentifier(iid);
Entity deviceEntity = new Entity(ENTITY_TYPE, entityId);
LOG.debug("Entity {} created for device connection {}",
deviceEntity, ovsdbConnectionInstance.getConnectionInfo());
return deviceEntity;
}
private OvsdbConnectionInstance getConnectionInstanceFromEntity(Entity entity) {
return entityConnectionMap.get(entity);
}
private void registerEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
Entity candidateEntity = getEntityFromConnectionInstance(ovsdbConnectionInstance);
entityConnectionMap.put(candidateEntity, ovsdbConnectionInstance);
ovsdbConnectionInstance.setConnectedEntity(candidateEntity);
try {
EntityOwnershipCandidateRegistration registration =
entityOwnershipService.registerCandidate(candidateEntity);
ovsdbConnectionInstance.setDeviceOwnershipCandidateRegistration(registration);
LOG.info("OVSDB entity {} is registered for ownership.", candidateEntity);
//If entity already has owner, it won't get notification from EntityOwnershipService
//so cache the connection instances.
Optional<EntityOwnershipState> ownershipStateOpt =
entityOwnershipService.getOwnershipState(candidateEntity);
if (ownershipStateOpt.isPresent()) {
EntityOwnershipState ownershipState = ownershipStateOpt.get();
if (ownershipState.hasOwner() && !ownershipState.isOwner()) {
LOG.info("OVSDB entity {} is already owned by other southbound plugin "
+ "instance, so *this* instance is NOT an OWNER of the device",
ovsdbConnectionInstance.getConnectionInfo());
putConnectionInstance(ovsdbConnectionInstance.getMDConnectionInfo(),ovsdbConnectionInstance);
}
}
} catch (CandidateAlreadyRegisteredException e) {
LOG.warn("OVSDB entity {} was already registered for ownership", candidateEntity, e);
}
}
private void unregisterEntityForOwnership(OvsdbConnectionInstance ovsdbConnectionInstance) {
ovsdbConnectionInstance.closeDeviceOwnershipCandidateRegistration();
entityConnectionMap.remove(ovsdbConnectionInstance.getConnectedEntity());
}
private class OvsdbDeviceEntityOwnershipListener implements EntityOwnershipListener {
private OvsdbConnectionManager cm;
private EntityOwnershipListenerRegistration listenerRegistration;
OvsdbDeviceEntityOwnershipListener(OvsdbConnectionManager cm, EntityOwnershipService entityOwnershipService) {
this.cm = cm;
listenerRegistration = entityOwnershipService.registerListener(ENTITY_TYPE, this);
}
public void close() {
listenerRegistration.close();
}
@Override
public void ownershipChanged(EntityOwnershipChange ownershipChange) {
cm.handleOwnershipChanged(ownershipChange);
}
}
} |
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.globus.cog.abstraction.coaster.service.job.manager;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.TimerTask;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.CoasterService;
import org.globus.cog.abstraction.impl.common.StatusEvent;
import org.globus.cog.abstraction.interfaces.Status;
import org.globus.cog.abstraction.interfaces.StatusListener;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.karajan.workflow.service.channels.ChannelContext;
public class Block implements StatusListener, Comparable<Block> {
public static final Logger logger = Logger.getLogger(Block.class);
/** milliseconds */
public static final long SHUTDOWN_WATCHDOG_DELAY = 2 * 60 * 1000;
/** milliseconds */
public static final long SUSPEND_SHUTDOWN_DELAY = 30 * 1000;
private static BlockTaskSubmitter submitter;
private synchronized static BlockTaskSubmitter getSubmitter() {
if (submitter == null) {
submitter = new BlockTaskSubmitter();
submitter.start();
}
return submitter;
}
private int workers;
private TimeInterval walltime;
private Time endtime, starttime, deadline, creationtime;
private final SortedSet<Cpu> scpus;
private final List<Cpu> cpus;
private final List<Node> nodes;
private boolean running = false, failed, shutdown, suspended;
private BlockQueueProcessor bqp;
private BlockTask task;
private final String id;
private int doneJobCount;
private long lastUsed;
private static int sid;
private static final NumberFormat IDF = new DecimalFormat("000000");
public Block(String id) {
this.id = id;
scpus = new TreeSet<Cpu>();
cpus = new ArrayList<Cpu>();
nodes = new ArrayList<Node>();
}
public Block(int workers, TimeInterval walltime, BlockQueueProcessor ap) {
this(ap.getBQPId() + "-" + IDF.format(sid++), workers, walltime, ap);
}
public Block(String id, int workers, TimeInterval walltime, BlockQueueProcessor ap) {
this(id);
this.workers = workers;
this.walltime = walltime;
this.bqp = ap;
this.creationtime = Time.now();
this.deadline = Time.now().add(ap.getSettings().getReserve());
}
public void start() {
if (logger.isInfoEnabled()) {
logger.info("Starting block: workers=" + workers + ", walltime=" + walltime);
}
bqp.getRLogger().log(
"BLOCK_REQUESTED id=" + getId() + ", w=" + getWorkerCount() + ", h="
+ getWalltime().getSeconds());
task = new BlockTask(this);
task.addStatusListener(this);
try {
task.initialize();
getSubmitter().submit(this);
}
catch (Exception e) {
taskFailed(null, e);
}
}
public BlockQueueProcessor getAllocationProcessor() {
return bqp;
}
public boolean isDone() {
if (failed) {
return true;
}
else if (running) {
Time last = getStartTime();
synchronized (cpus) {
for (Cpu cpu: cpus) {
if (cpu.getTimeLast().isGreaterThan(last)) {
last = cpu.getTimeLast();
}
}
if (cpus.isEmpty()) {
// prevent block from being done when startup of workers is
// really really slow,
// like as on the BGP where it takes a couple of minutes to
// initialize a partition
last = Time.now();
}
}
deadline =
Time.min(starttime.add(walltime),
last.add(bqp.getSettings().getMaxWorkerIdleTime()));
return Time.now().isGreaterThan(deadline);
}
else {
return false;
}
}
public boolean fits(Job j) {
if (suspended) {
return false;
}
if (!running) {
// if the block isn't running then the job might fit if its walltime
// is smaller than the block's walltime
return j.getMaxWallTime().isLessThan(walltime);
}
else if (running && j.getMaxWallTime().isGreaterThan(endtime.subtract(Time.now()))) {
// if the block is running and the job's walltime is greater than
// the blocks remaining walltime, then the job doesn't fit
return false;
}
else {
// if the simple tests before fail try to see if there is a
// cpu that can specifically fit this job.
synchronized (cpus) {
for (Cpu cpu : cpus) {
Job running = cpu.getRunning();
if (running == null) {
return true;
}
else if (j.getMaxWallTime().isLessThan(endtime.subtract(running.getEndTime()))) {
return true;
}
}
}
return false;
}
}
public void remove(Cpu cpu) {
synchronized (scpus) {
if (!scpus.remove(cpu)) {
CoasterService.error(16, "CPU was not in the block", new Throwable());
}
if (scpus.contains(cpu)) {
CoasterService.error(17, "CPU not removed", new Throwable());
}
}
}
public void add(Cpu cpu) {
synchronized (scpus) {
if (!scpus.add(cpu)) {
CoasterService.error(15, "CPU is already in the block", new Throwable());
}
Cpu last = scpus.last();
if (last != null) {
deadline =
Time.min(last.getTimeLast().add(bqp.getSettings().getReserve()),
getEndTime());
}
}
}
public void shutdownIfEmpty(Cpu cpu) {
synchronized (scpus) {
if (scpus.isEmpty()) {
if (logger.isInfoEnabled() && !shutdown) {
logger.info(this + ": all cpus are clear");
}
shutdown(false);
}
}
}
private static final TimeInterval NO_TIME = TimeInterval.fromSeconds(0);
public double sizeLeft() {
if (failed) {
return 0;
}
else if (running) {
return bqp.getMetric().size(
workers,
(int) TimeInterval.max(endtime.subtract(Time.max(Time.now(), starttime)), NO_TIME).getSeconds());
}
else {
return bqp.getMetric().size(workers, (int) walltime.getSeconds());
}
}
public Time getEndTime() {
if (starttime == null) {
return Time.now().add(walltime);
}
else {
return starttime.add(walltime);
}
}
public void setEndTime(Time t) {
this.endtime = t;
}
public int getWorkerCount() {
return workers;
}
public void setWorkerCount(int v) {
this.workers = v;
}
public TimeInterval getWalltime() {
return walltime;
}
public void setWalltime(TimeInterval t) {
this.walltime = t;
}
public void shutdown(boolean now) {
synchronized (cpus) {
if (shutdown) {
return;
}
logger.info("Shutting down block " + this);
bqp.getRLogger().log("BLOCK_SHUTDOWN id=" + getId());
shutdown = true;
long busyTotal = 0;
long idleTotal = 0;
int count = 0;
if (running) {
for (Cpu cpu : cpus) {
idleTotal = cpu.idleTime;
busyTotal = cpu.busyTime;
if (!failed) {
cpu.shutdown();
}
count++;
}
if (!failed) {
if (count < workers || now) {
addForcedShutdownWatchdog(100);
}
else {
addForcedShutdownWatchdog(SHUTDOWN_WATCHDOG_DELAY);
}
}
if (idleTotal > 0) {
double u = (busyTotal * 10000) / (busyTotal + idleTotal);
u /= 100;
logger.info("Average utilization: " + u + "%");
bqp.getRLogger().log("BLOCK_UTILIZATION id=" + getId() + ", u=" + u);
}
}
else {
logger.info("Block " + this + " not running. Cancelling job.");
forceShutdown();
}
cpus.clear();
}
}
private void addForcedShutdownWatchdog(long delay) {
CoasterService.addWatchdog(new TimerTask() {
@Override
public void run() {
if (running) {
logger.info("Watchdog: forceShutdown: " + this);
forceShutdown();
}
}
}, delay);
}
public void forceShutdown() {
if (task != null) {
try {
getSubmitter().cancel(this);
}
catch (Exception e) {
logger.warn("Failed to shut down block: " + this, e);
}
bqp.blockTaskFinished(this);
}
}
public BlockTask getTask() {
return task;
}
public void taskFailed(String msg, Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Worker task failed: " + msg, e);
}
synchronized (cpus) {
synchronized (scpus) {
failed = true;
running = false;
for (int j = cpus.size(); j < workers; j++) {
Cpu cpu = new Cpu(j, new Node(j, this, null));
scpus.add(cpu);
cpus.add(cpu);
}
for (Cpu cpu : cpus) {
cpu.taskFailed(msg, e);
}
}
}
}
public String getId() {
return id;
}
public String workerStarted(String workerID,
String workerHostname,
ChannelContext channelContext) {
synchronized (cpus) {
synchronized (scpus) {
int wid = Integer.parseInt(workerID);
Node n = new Node(wid, this, workerHostname,
channelContext);
nodes.add(n);
int jobsPerNode = bqp.getSettings().getJobsPerNode();
for (int i = 0; i < jobsPerNode; i++) {
//this id scheme works out because the sid is based on the
//number of cpus already added (i.e. cpus.size()).
Cpu cpu = new Cpu(wid + i, n);
scpus.add(cpu);
cpus.add(cpu);
n.add(cpu);
cpu.workerStarted();
logger.info("Started CPU " + cpu);
}
if (logger.isInfoEnabled()) {
logger.info("Started worker " + this.id + ":" + IDF.format(wid));
}
return workerID;
}
}
}
private int seq;
public String nextId() {
synchronized (this) {
int n = seq;
seq += bqp.getSettings().getJobsPerNode();
return IDF.format(n);
}
}
@Override
public String toString() {
return "Block " + id + " (" + workers + "x" + walltime + ")";
}
public void statusChanged(StatusEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Block task status changed: " + event.getStatus());
}
try {
Status s = event.getStatus();
if (s.isTerminal()) {
synchronized (cpus) {
if (!shutdown) {
if (s.getStatusCode() == Status.FAILED) {
logger.info("Failed task spec: "
+ ((Task) event.getSource()).getSpecification());
taskFailed(prettifyOut(task.getStdOutput())
+ prettifyOut(task.getStdError()), s.getException());
}
else {
taskFailed(id + " Block task ended prematurely\n"
+ prettifyOut(task.getStdOutput())
+ prettifyOut(task.getStdError()), null);
}
}
bqp.blockTaskFinished(this);
running = false;
}
logger.info(id + " stdout: " + prettifyOut(task.getStdOutput()));
logger.info(id + " stderr: " + prettifyOut(task.getStdError()));
}
else if (s.getStatusCode() == Status.ACTIVE) {
starttime = Time.now();
endtime = starttime.add(walltime);
deadline = starttime.add(bqp.getSettings().getReserve());
running = true;
bqp.getRLogger().log("BLOCK_ACTIVE id=" + getId());
bqp.getSettings().getHook().blockActive(event);
}
}
catch (Exception e) {
CoasterService.error(14, "Failed to process block task status change", e);
}
}
private String prettifyOut(String out) {
if (out == null) {
return "";
}
else {
return out + "\n";
}
}
public Time getStartTime() {
return starttime;
}
public void setStartTime(Time t) {
this.starttime = t;
}
public Time getDeadline() {
return deadline;
}
public void setDeadline(Time t) {
this.deadline = t;
}
public Time getCreationTime() {
return creationtime;
}
public void setCreationTime(Time t) {
this.creationtime = t;
}
public Collection<Cpu> getCpus() {
return cpus;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public void increaseDoneJobCount() {
doneJobCount++;
}
public void suspend() {
suspended = true;
// ensure we still shut down if no jobs are running
shutdownIfEmpty(null);
}
public boolean isSuspended() {
return suspended;
}
public synchronized boolean isShutDown() {
return shutdown;
}
public void jobPulled() {
lastUsed = System.currentTimeMillis();
}
public long getLastUsed() {
return lastUsed;
}
public int compareTo(Block o) {
return id.compareTo(o.id);
}
public void removeNode(Node node) {
synchronized(cpus) {
synchronized(scpus) {
nodes.remove(node);
for (Cpu cpu : node.getCpus()) {
scpus.remove(cpu);
cpus.remove(cpu);
}
}
}
bqp.nodeRemoved(node);
}
} |
package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.gml;
import com.sensia.relaxNG.RNGElement;
import com.sensia.tools.client.swetools.editors.sensorml.panels.AbstractPanel;
import com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.element.EditSimpleElementPanel;
import com.sensia.tools.client.swetools.editors.sensorml.utils.Utils;
public class GMLEditNamePanel extends EditSimpleElementPanel{
public GMLEditNamePanel(RNGElement element) {
super(element,Utils.findLabel(element));
}
@Override
protected AbstractPanel<RNGElement> newInstance() {
// TODO Auto-generated method stub
return null;
}
} |
package com.github.platan.idea.dependencies.intentions;
import static com.github.platan.idea.dependencies.sort.DependencyUtil.*;
import com.github.platan.idea.dependencies.gradle.Coordinate;
import com.github.platan.idea.dependencies.gradle.PsiElementCoordinate;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.intentions.base.Intention;
import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.arguments.GrArgumentListImpl;
import java.util.Map;
public class MapNotationToStringNotationIntention extends Intention {
@Override
protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) {
GrArgumentList argumentList = (GrArgumentList) element.getParent().getParent();
GrNamedArgument[] namedArguments = argumentList.getNamedArguments();
String stringNotation = toStringNotation(namedArguments);
for (GrNamedArgument namedArgument : namedArguments) {
namedArgument.delete();
}
GrExpression expressionFromText = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(stringNotation);
argumentList.add(expressionFromText);
}
private String toStringNotation(GrNamedArgument[] namedArguments) {
Map<String, PsiElement> map = toMapWithPsiElementValues(namedArguments);
PsiElementCoordinate coordinate = PsiElementCoordinate.fromMap(map);
return coordinate.toGrStringNotation();
}
@NotNull
@Override
protected PsiElementPredicate getElementPredicate() {
return new PsiElementPredicate() {
@Override
public boolean satisfiedBy(PsiElement element) {
if (element == null || element.getParent() == null || !(element.getParent().getParent() instanceof GrArgumentListImpl)) {
return false;
}
GrArgumentListImpl parent = (GrArgumentListImpl) element.getParent().getParent();
GrNamedArgument[] namedArguments = parent.getNamedArguments();
if (namedArguments.length == 0) {
return false;
}
Map<String, String> map = toSimpleMap(namedArguments);
return Coordinate.isValidMap(map);
}
};
}
@NotNull
@Override
public String getText() {
return "Convert to string notation";
}
@NotNull
@Override
public String getFamilyName() {
return "Convert map notation to string notation";
}
} |
package org.springframework.security.samples.contacts.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.samples.contacts.dao.UserDao;
import org.springframework.security.samples.contacts.entity.Role;
import org.springframework.security.samples.contacts.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* A custom {@link UserDetailsService} where user information
* is retrieved from a JPA repository
*/
@Service("customUserDetailsService")
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
/**
* Returns a populated {@link UserDetails} object.
* The username is first retrieved from the database and then mapped to
* a {@link UserDetails} object.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
org.springframework.security.samples.contacts.entity.User domainUser = userRepository.findByUsername(username);
if(domainUser==null) throw new UsernameNotFoundException("user not found!");
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
domainUser.getUsername(),
domainUser.getPassword(),
domainUser.isEnabled(),
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getGrantedAuthorities(domainUser.getRoles()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Wraps {@link String} roles to {@link SimpleGrantedAuthority} objects
* @param roles {@link String} of roles
* @return list of granted authorities
*/
public static List<GrantedAuthority> getGrantedAuthorities(List<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
} |
package dr.math;
import dr.math.matrixAlgebra.CholeskyDecomposition;
import dr.math.matrixAlgebra.IllegalDimension;
import dr.math.matrixAlgebra.Matrix;
/**
* @author Marc Suchard
*/
public class WishartDistribution implements MultivariateDistribution {
public static final String TYPE = "Wishart";
private int df;
private int dim;
private double[][] inverseScaleMatrix;
private Matrix S;
private Matrix Sinv;
private double logNormalizationConstant;
/**
* A Wishart distribution class for \nu degrees of freedom and inverse scale matrix S
* Expectation = \nu * S
*
* @param df
* @param inverseScaleMatrix
*/
public WishartDistribution(int df, double[][] inverseScaleMatrix) {
this.df = df;
this.inverseScaleMatrix = inverseScaleMatrix;
this.dim = inverseScaleMatrix.length;
S = new Matrix(inverseScaleMatrix);
Sinv = S.inverse();
computeNormalizationConstant();
}
private void computeNormalizationConstant() {
logNormalizationConstant = computeNormalizationConstant(new Matrix(inverseScaleMatrix), df, dim);
}
public static double computeNormalizationConstant(Matrix Sinv, int df, int dim) {
double logNormalizationConstant = 0;
try {
logNormalizationConstant = -df / 2.0 * Math.log(Sinv.determinant());
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace();
}
logNormalizationConstant -= df * dim / 2.0 * Math.log(2);
logNormalizationConstant -= dim * (dim - 1) / 4.0 * Math.log(Math.PI);
for (int i = 1; i <= dim; i++) {
logNormalizationConstant -= GammaFunction.lnGamma((df + 1 - i) / 2.0);
}
return logNormalizationConstant;
}
public String getType() {
return TYPE;
}
public double[][] getScaleMatrix() {
return inverseScaleMatrix;
}
public double[] getMean() {
return null;
}
private void testMe() {
int length = 100000;
double save1 = 0;
double save2 = 0;
double save3 = 0;
double save4 = 0;
for (int i = 0; i < length; i++) {
double[][] draw = nextWishart();
save1 += draw[0][0];
save2 += draw[0][1];
save3 += draw[1][0];
save4 += draw[1][1];
}
save1 /= length;
save2 /= length;
save3 /= length;
save4 /= length;
System.err.println("S1: " + save1);
System.err.println("S2: " + save2);
System.err.println("S3: " + save3);
System.err.println("S4: " + save4);
}
public int df() {
return df;
}
public double[][] inverseScaleMatrix() {
return inverseScaleMatrix;
}
public double[][] nextWishart() {
return nextWishart(df, inverseScaleMatrix);
}
/**
* Generate a random draw from a Wishart distribution
* Follows Odell and Feiveson (1996) JASA 61, 199-203
*
* @param df
* @param inverseScaleMatrix
* @return
*/
public static double[][] nextWishart(int df, double[][] inverseScaleMatrix) {
int dim = inverseScaleMatrix.length;
double[][] draw = new double[dim][dim];
double[][] z = new double[dim][dim];
for (int i = 0; i < dim; i++) {
for (int j = 0; j < i; j++) {
z[i][j] = MathUtils.nextGaussian();
}
}
for (int i = 0; i < dim; i++)
z[i][i] = Math.sqrt(MathUtils.nextGamma((df - i) * 0.5, 0.5)); // sqrt of chisq with df-i dfs
double[][] cholesky = new double[dim][dim];
for (int i = 0; i < dim; i++) {
for (int j = i; j < dim; j++)
cholesky[i][j] = cholesky[j][i] = inverseScaleMatrix[i][j];
}
try {
cholesky = (new CholeskyDecomposition(cholesky)).getL();
// caution: this returns the lower triangular form
} catch (IllegalDimension illegalDimension) {
}
double[][] result = new double[dim][dim];
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) { // lower triangular
for (int k = 0; k < dim; k++) // can also be shortened
result[i][j] += cholesky[i][k] * z[k][j];
}
}
for (int i = 0; i < dim; i++) { // lower triangular, so more efficiency is possible
for (int j = 0; j < dim; j++) {
for (int k = 0; k < dim; k++)
draw[i][j] += result[i][k] * result[j][k]; // transpose of 2nd element
}
}
return draw;
}
public double logPdf(double[] x) {
Matrix W = new Matrix(x, dim, dim);
return logPdf(W, Sinv, df, dim, logNormalizationConstant);
}
public static double logPdf(Matrix W, Matrix Sinv, int df, int dim, double logNormalizationConstant) {
double logDensity = 0;
// System.err.println("yoyo "+df+" "+dim);
// double det = 0;
try {
if (!W.isPD())
return Double.NEGATIVE_INFINITY;
final double det = W.determinant();
if (det <= 0) {
// System.err.println("Not PD:\n"+W);
// System.err.println("det = "+det);
// System.exit(-1);
return Double.NEGATIVE_INFINITY;
}
// try {
// logDensity = Math.log(W.determinant());
logDensity = Math.log(det);
logDensity *= 0.5;
logDensity *= df - dim - 1;
// need only diagonal, no? seems a waste to compute
// the whole matrix
Matrix product = Sinv.product(W);
for (int i = 0; i < dim; i++)
logDensity -= 0.5 * product.component(i, i);
} catch (IllegalDimension illegalDimension) {
illegalDimension.printStackTrace();
}
logDensity += logNormalizationConstant;
return logDensity;
}
} |
package dr.stats;
import dr.util.HeapSort;
/**
* simple discrete statistics (mean, variance, cumulative probability, quantiles etc.)
*
* @version $Id: DiscreteStatistics.java,v 1.11 2006/07/02 21:14:53 rambaut Exp $
*
* @author Korbinian Strimmer
* @author Alexei Drummond
*/
public class DiscreteStatistics {
// Public stuff
/**
* compute mean
*
* @param x list of numbers
*
* @return mean
*/
public static double mean(double[] x)
{
double m = 0;
int len = x.length;
for (int i = 0; i < len; i++)
{
m += x[i];
}
return m/(double) len;
}
/**
* compute median
*
* @param x list of numbers
* @param indices index sorting x
*
* @return median
*/
public static double median(double[] x, int[] indices) {
int pos = x.length/2;
if (x.length % 2 == 1) {
return x[indices[pos]];
} else {
return (x[indices[pos-1]]+x[indices[pos]])/2.0;
}
}
/**
* compute median
*
* @param x list of numbers
*
* @return median
*/
public static double median(double[] x) {
if (x == null || x.length == 0) {
throw new IllegalArgumentException();
}
int[] indices = new int[x.length];
HeapSort.sort(x, indices);
return median(x, indices);
}
/**
* compute variance (ML estimator)
*
* @param x list of numbers
* @param mean assumed mean of x
*
* @return variance of x (ML estimator)
*/
public static double variance(double[] x, double mean)
{
double var = 0;
int len = x.length;
for (int i = 0; i < len; i++)
{
double diff = x[i]-mean;
var += diff*diff;
}
int n;
if (len < 2)
{
n = 1; // to avoid division by zero
}
else
{
n = len-1; // for ML estimate
}
return var/ (double) n;
}
/**
* compute covariance
*
* @param x list of numbers
* @param y list of numbers
*
* @return covariance of x and y
*/
public static double covariance(double[] x, double[] y) {
return covariance(x, y, mean(x), mean(y), stdev(x), stdev(y));
}
/**
* compute covariance
*
* @param x list of numbers
* @param y list of numbers
* @param xmean assumed mean of x
* @param ymean assumed mean of y
* @param xstdev assumed stdev of x
* @param ystdev assumed stdev of y
*
* @return covariance of x and y
*/
public static double covariance(double[] x, double[] y, double xmean, double ymean, double xstdev, double ystdev) {
if (x.length != y.length) throw new IllegalArgumentException("x and y arrays must be same length!");
double covar = 0.0;
for (int i =0; i < x.length; i++) {
covar += (x[i]-xmean)*(y[i]-ymean);
}
covar /= x.length;
covar /= (xstdev*ystdev);
return covar;
}
/**
* compute fisher skewness
*
* @param x list of numbers
*
* @return skewness of x
*/
public static double skewness(double[] x) {
double mean = mean(x);
double stdev = stdev(x);
double skew = 0.0;
double len = x.length;
for (double xv : x) {
double diff = xv - mean;
diff /= stdev;
skew += (diff * diff * diff);
}
skew *= (len / ((len - 1) * (len - 2)));
return skew;
}
/**
* compute standard deviation
*
* @param x list of numbers
*
* @return standard deviation of x
*/
public static double stdev(double[] x) {
return Math.sqrt(variance(x));
}
/**
* compute variance (ML estimator)
*
* @param x list of numbers
*
* @return variance of x (ML estimator)
*/
public static double variance(double[] x)
{
double m = mean(x);
return variance(x, m);
}
/**
* compute variance of sample mean (ML estimator)
*
* @param x list of numbers
* @param mean assumed mean of x
*
* @return variance of x (ML estimator)
*/
public static double varianceSampleMean(double[] x, double mean)
{
return variance(x, mean)/(double) x.length;
}
/**
* compute variance of sample mean (ML estimator)
*
* @param x list of numbers
*
* @return variance of x (ML estimator)
*/
public static double varianceSampleMean(double[] x)
{
return variance(x)/(double) x.length;
}
/**
* compute the q-th quantile for a distribution of x
* (= inverse cdf)
*
* @param q quantile (0 < q <= 1)
* @param x discrete distribution (an unordered list of numbers)
* @param indices index sorting x
*
* @return q-th quantile
*/
public static double quantile(double q, double[] x, int[] indices)
{
if (q < 0.0 || q > 1.0) throw new IllegalArgumentException("Quantile out of range");
if (q == 0.0)
{
// for q==0 we have to "invent" an entry smaller than the smallest x
return x[indices[0]] - 1.0;
}
return x[indices[(int) Math.ceil(q*indices.length)-1]];
}
/**
* compute the q-th quantile for a distribution of x
* (= inverse cdf)
*
* @param q quantile (0 <= q <= 1)
* @param x discrete distribution (an unordered list of numbers)
*
* @return q-th quantile
*/
public static double quantile(double q, double[] x)
{
int[] indices = new int[x.length];
HeapSort.sort(x, indices);
return quantile(q, x, indices);
}
/**
* compute the q-th quantile for a distribution of x
* (= inverse cdf)
*
* @param q quantile (0 <= q <= 1)
* @param x discrete distribution (an unordered list of numbers)
* @param count use only first count entries in x
*
* @return q-th quantile
*/
public static double quantile(double q, double[] x, int count)
{
int[] indices = new int[count];
HeapSort.sort(x, indices);
return quantile(q, x, indices);
}
/**
* Determine the highest posterior density for a list of values.
* The HPD is the smallest interval containing the required amount of elements.
*
* @param proportion of elements inside the interval
* @param x values
* @param indices index sorting x
* @return the interval, an array of {low, high} values.
*/
public static double[] HPDInterval(double proportion, double[] x, int[] indices) {
double minRange = Double.MAX_VALUE;
int hpdIndex = 0;
final int diff = (int) Math.round(proportion * (double) x.length);
for (int i = 0; i <= (x.length - diff); i++) {
final double minValue = x[indices[i]];
final double maxValue = x[indices[i + diff - 1]];
final double range = Math.abs(maxValue - minValue);
if (range < minRange) {
minRange = range;
hpdIndex = i;
}
}
return new double[] { x[indices[hpdIndex]] , x[indices[hpdIndex + diff - 1]] };
}
/**
* compute the cumulative probability Pr(x <= z) for a given z
* and a distribution of x
*
* @param z threshold value
* @param x discrete distribution (an unordered list of numbers)
* @param indices index sorting x
*
* @return cumulative probability
*/
public static double cdf(double z, double[] x, int[] indices)
{
int i;
for (i = 0; i < x.length; i++)
{
if (x[indices[i]] > z) break;
}
return (double) i/ (double) x.length;
}
/**
* compute the cumulative probability Pr(x <= z) for a given z
* and a distribution of x
*
* @param z threshold value
* @param x discrete distribution (an unordered list of numbers)
*
* @return cumulative probability
*/
public static double cdf(double z, double[] x)
{
int[] indices = new int[x.length];
HeapSort.sort(x, indices);
return cdf(z, x, indices);
}
public static double max(double[] x) {
double max = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] > max) max = x[i];
}
return max;
}
public static double min(double[] x) {
double min = x[0];
for (int i = 1; i < x.length; i++) {
if (x[i] < min) min = x[i];
}
return min;
}
} |
package ca.corefacility.bioinformatics.irida.ria.integration.analysis;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig;
import ca.corefacility.bioinformatics.irida.exceptions.IridaWorkflowException;
import ca.corefacility.bioinformatics.irida.model.workflow.IridaWorkflow;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.TestAnalysis;
import ca.corefacility.bioinformatics.irida.model.workflow.config.IridaWorkflowIdSet;
import ca.corefacility.bioinformatics.irida.model.workflow.config.IridaWorkflowSet;
import ca.corefacility.bioinformatics.irida.ria.integration.AbstractIridaUIITChromeDriver;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.LoginPage;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.analysis.AnalysesUserPage;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.analysis.AnalysisDetailsPage;
import ca.corefacility.bioinformatics.irida.ria.integration.utilities.FileUtilities;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowLoaderService;
import ca.corefacility.bioinformatics.irida.service.workflow.IridaWorkflowsService;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.google.common.collect.Sets;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiServicesConfig.class })
@ActiveProfiles("it")
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/ria/web/analysis/AnalysisAdminView.xml")
public class AnalysisDetailsPageIT extends AbstractIridaUIITChromeDriver {
private static final Logger logger = LoggerFactory.getLogger(AnalysisDetailsPageIT.class);
private FileUtilities fileUtilities = new FileUtilities();
@Autowired
@Qualifier("outputFileBaseDirectory")
private Path outputFileBaseDirectory;
@Autowired
private IridaWorkflowLoaderService iridaWorkflowLoaderService;
@Before
// Tree file used by multiple tests
public void setFile() throws IOException {
fileUtilities.copyFileToDirectory(outputFileBaseDirectory, "src/test/resources/files/snp_tree.tree");
}
@Test
public void testAnalysisDetails() {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
assertEquals("There should be 7 labels for analysis details", 7, page.getNumberOfListItems());
// Analysis Description doesn't have a value
assertEquals("There should be only 6 values for these labels", 6, page.getNumberOfListItemValues());
String expectedAnalysisDetails[] = new String[] { "My Completed Submission", "4",
"SNVPhyl Phylogenomics Pipeline (1.0.1)", "MEDIUM", "Oct 6, 2013 10:01 AM", "a few seconds" };
assertTrue("The correct details are displayed for the analysis",
page.analysisDetailsEqual(expectedAnalysisDetails));
}
@Test
public void testBioHanselOutput() throws IOException {
fileUtilities.copyFileToDirectory(outputFileBaseDirectory, "src/test/resources/files/bio_hansel-results.json");
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 12L, "");
assertTrue("Page title should equal", page.comparePageTitle("Bio Hansel Information"));
assertTrue("Has 5 list items for Bio Hansel Information", page.expectedNumberOfListItemsEqualsActual(5));
page = AnalysisDetailsPage.initPage(driver(), 12L, "output");
assertTrue("Page title should equal", page.comparePageTitle("Output File Preview"));
assertEquals("There should be one output file", 1, page.getNumberOfFilesDisplayed());
assertTrue("There should be exactly one download all files button", page.downloadAllFilesButtonVisible());
assertTrue("There should be a download button for the file that is displayed",
page.downloadOutputFileButtonVisible());
}
@Test
public void testDeleteAnalysis() {
LoginPage.loginAsManager(driver());
AnalysesUserPage analysesPage = AnalysesUserPage.initializeAdminPage(driver());
analysesPage.clickPagination(2);
assertEquals("Should have 4 analyses displayed originally", 4, analysesPage.getNumberOfAnalysesDisplayed());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 9L, "settings/delete");
assertTrue("Page title should equal", page.compareTabTitle("Delete Analysis"));
assertTrue(page.deleteButtonExists());
page.deleteAnalysis();
analysesPage = AnalysesUserPage.initializeAdminPage(driver());
page.clickPagination(2);
assertEquals("Should have 3 analyses displayed", 3, analysesPage.getNumberOfAnalysesDisplayed());
}
@Test
public void testEditPriorityVisibility() throws URISyntaxException, IOException {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
// As this analysis is not in NEW state the
// edit priority dropdown should not be visible
assertFalse("priority edit should be visible", page.priorityEditVisible());
page = AnalysisDetailsPage.initPage(driver(), 8L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
// As this analysis is in NEW state the
// edit priority dropdown should be visible
assertTrue("priority edit should be visible", page.priorityEditVisible());
}
@Test
public void testOutputFiles() {
LoginPage.loginAsManager(driver());
// Has output files
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "output");
assertTrue("Page title should equal", page.compareTabTitle("Output File Preview"));
assertEquals("There should be one output file", 1, page.getNumberOfFilesDisplayed());
assertTrue("There should be exactly one download all files button", page.downloadAllFilesButtonVisible());
assertTrue("There should be exactly one download individual files dropdown button", page.downloadIndividualFilesMenuButtonVisible());
assertTrue("There should be exactly one download individual files dropdown menu", page.downloadIndividualFilesMenuVisible());
assertTrue("There should be a download button for the file that is displayed",
page.downloadOutputFileButtonVisible());
// Has no output files
page = AnalysisDetailsPage.initPage(driver(), 10L, "output");
assertTrue("Page title should equal", page.compareTabTitle("Output File Preview"));
assertEquals("There should be no output files", 0, page.getNumberOfFilesDisplayed());
assertEquals("Has a no output files alert", "No outputs available to display", page.getWarningAlertText());
}
@Test
public void testPageSetUp() throws URISyntaxException, IOException {
logger.debug("Testing 'Analysis Details Page'");
LoginPage.loginAsManager(driver());
// Submissions with trees and not sistr or biohansel
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "");
assertTrue("Page title should equal", page.comparePageTitle("Tree Preview"));
assertTrue("Has horizontal tab links", page.hasHorizontalTabLinks());
// Completed submission should not display steps component
assertTrue("Analysis steps are not visible since the analysis is in completed state",
!page.analysisStepsVisible());
// Submissions without trees and not sistr or biohansel
page = AnalysisDetailsPage.initPage(driver(), 6L, "");
assertTrue("Page title should equal", page.comparePageTitle("Output File Preview"));
assertTrue("Has horizontal tab links", page.hasHorizontalTabLinks());
// Any other submission state should display steps component
page = AnalysisDetailsPage.initPage(driver(), 2L, "");
assertTrue("Analysis steps are visible since the analysis isn't in completed state",
page.analysisStepsVisible());
}
@Test
// Has no specific results output tab (for example tree, biohansel, sistr) so the output file preview
// page is the default view
public void testPipelineResultsWithoutSpecialTab() throws IOException {
fileUtilities.copyFileToDirectory(outputFileBaseDirectory,
"src/test/resources/files/refseq-masher-matches.tsv");
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 13L, "");
assertTrue("Page title should equal", page.compareTabTitle("Output File Preview"));
assertEquals("There should be one output file", 1, page.getNumberOfFilesDisplayed());
assertTrue("There should be exactly one download all files button", page.downloadAllFilesButtonVisible());
assertTrue("There should be a download button for the file that is displayed",
page.downloadOutputFileButtonVisible());
}
@Test
public void testProvenance() throws IOException {
fileUtilities.copyFileToDirectory(outputFileBaseDirectory, "src/test/resources/files/filterStats.txt");
LoginPage.loginAsManager(driver());
// Has output files so display a provenance
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "provenance");
assertTrue("Page title should equal", page.compareTabTitle("Provenance"));
assertEquals("There should be two files", 2, page.getProvenanceFileCount());
page.getFileProvenance(0);
assertEquals("Should have 1 tool associated with filterStats", 1, page.getToolCount());
page.displayToolExecutionParameters();
assertEquals("Tool should have 2 parameters", 2, page.getGalaxyParametersCount());
page.getFileProvenance(1);
assertEquals("Should have 2 tools associated with the tree", 2, page.getToolCount());
page.displayToolExecutionParameters();
assertEquals("First tool should have 1 parameter", 1, page.getGalaxyParametersCount());
// We click the first file again and check for tools and execution parameters
page.getFileProvenance(0);
assertEquals("Should have 1 tool associated with filterStats", 1, page.getToolCount());
page.displayToolExecutionParameters();
assertEquals("Tool should have 2 parameter", 2, page.getGalaxyParametersCount());
// Has no output files so no provenance displayed
page = AnalysisDetailsPage.initPage(driver(), 10L, "provenance");
assertTrue("Page title should equal", page.compareTabTitle("Provenance"));
assertEquals("There should be no file", 0, page.getProvenanceFileCount());
assertEquals("Has a no provenance available alert",
"Unable to display provenance as no output files were found for analysis.", page.getWarningAlertText());
}
@Test
public void testSamplesPage() {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/samples");
assertTrue("Page title should equal", page.compareTabTitle("Samples"));
assertEquals("Should display 2 pairs of paired end files", 2, page.getNumberOfSamplesInAnalysis());
// Filter samples by search string
page.filterSamples("01-");
assertEquals("Should display 1 pair of paired end files", 1, page.getNumberOfSamplesInAnalysis());
// Download reference file button if file exists
assertTrue("Should have a download reference file button", page.referenceFileDownloadButtonVisible());
}
@Test
public void testSharedProjects() {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/share");
assertTrue("Page title should equal", page.compareTabTitle("Manage Results"));
assertTrue("Analysis shared projects", page.hasSharedWithProjects());
page.removeSharedProjects();
assertTrue("Analysis no longer shared with any projects", !page.hasSharedWithProjects());
page.addSharedProjects();
assertTrue("Analysis shared with projects", page.hasSharedWithProjects());
}
@Test
public void testSistrOutput() throws IOException {
fileUtilities.copyFileToDirectory(outputFileBaseDirectory,
"src/test/resources/files/sistr-predictions-pass.json");
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 11L, "");
assertTrue("Page title should equal", page.comparePageTitle("SISTR Information"));
assertTrue("Has vertical tabs for SISTR results and output files", page.hasSideBarTabLinks());
assertTrue("Has 9 list items for SISTR Information", page.expectedNumberOfListItemsEqualsActual(9));
page = AnalysisDetailsPage.initPage(driver(), 11L, "sistr/cgmlst");
assertTrue("Page title should equal", page.comparePageTitle("cgMLST330"));
assertTrue("Has 5 list items for cgMLST330", page.expectedNumberOfListItemsEqualsActual(5));
page = AnalysisDetailsPage.initPage(driver(), 11L, "sistr/mash");
assertTrue("Page title should equal", page.comparePageTitle("Mash"));
assertTrue("Has 4 list items for Mash", page.expectedNumberOfListItemsEqualsActual(4));
page = AnalysisDetailsPage.initPage(driver(), 11L, "sistr/citation");
assertTrue("Page title should equal", page.comparePageTitle("Citation"));
assertTrue("Page has a citation", page.citationVisible());
page = AnalysisDetailsPage.initPage(driver(), 11L, "output");
assertTrue("Page title should equal", page.comparePageTitle("Output File Preview"));
assertEquals("There should be one output file", 1, page.getNumberOfFilesDisplayed());
assertTrue("There should be exactly one download all files button", page.downloadAllFilesButtonVisible());
assertTrue("There should be a download button for the file that is displayed",
page.downloadOutputFileButtonVisible());
}
@Test
// Successfully completed analysis (COMPLETED state)
public void testTabRoutingAnalysisCompleted() throws URISyntaxException, IOException {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "");
assertTrue("Page title should equal", page.comparePageTitle("Tree Preview"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "output");
assertTrue("Page title should equal", page.comparePageTitle("Output File Preview"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "provenance");
assertTrue("Page title should equal", page.comparePageTitle("Provenance"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "settings");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/samples");
assertTrue("Page title should equal", page.compareTabTitle("Samples"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/share");
assertTrue("Page title should equal", page.compareTabTitle("Manage Results"));
page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/delete");
assertTrue("Page title should equal", page.compareTabTitle("Delete Analysis"));
}
@Test
//Analysis which did not complete successfully (ERROR State)
public void testTabRoutingAnalysisError() throws URISyntaxException, IOException {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 7L, "job-error");
assertTrue("No job error information available alert visible", page.jobErrorAlertVisible());
// Should not be able to view output files page if analysis errored
page = AnalysisDetailsPage.initPage(driver(), 7L, "output");
assertFalse("Page title should not equal", page.comparePageTitle("Output File Preview"));
// Should not be able to view provenance page if analysis errored
page = AnalysisDetailsPage.initPage(driver(), 7L, "provenance");
assertFalse("Page title should not equal", page.comparePageTitle("Provenance"));
page = AnalysisDetailsPage.initPage(driver(), 7L, "settings");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
page = AnalysisDetailsPage.initPage(driver(), 7L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
page = AnalysisDetailsPage.initPage(driver(), 7L, "settings/samples");
assertTrue("Page title should equal", page.compareTabTitle("Samples"));
// Should not be able to share results if analysis errored
page = AnalysisDetailsPage.initPage(driver(), 7L, "settings/share");
assertFalse("Page title should not equal", page.compareTabTitle("Manage Results"));
page = AnalysisDetailsPage.initPage(driver(), 7L, "settings/delete");
assertTrue("Page title should equal", page.compareTabTitle("Delete Analysis"));
}
@Test
public void testTreeOutput() {
LoginPage.loginAsManager(driver());
// Has tree file
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "");
assertTrue("Page title should equal", page.comparePageTitle("Tree Preview"));
assertTrue("Tree shape tools are visible", page.treeToolsVisible());
assertTrue("Advanced Phylogenetic Tree button is visible", page.advancedPhylogeneticTreeButtonVisible());
assertTrue("Tree wrapper is visible", page.phylocanvasWrapperVisible());
assertTrue("Tree is visible", page.treeVisible());
// Has no tree file
page = AnalysisDetailsPage.initPage(driver(), 10L, "");
assertTrue("Tree shape tools are not visible", page.treeToolsNotFound());
assertTrue("Advanced Phylogenetic Tree button is not visible", page.advancedPhylogeneticTreeButtonNotFound());
assertTrue("Tree wrapper is not visible", page.phylocanvasWrapperNotFound());
assertTrue("Tree is not visible", page.treeNotFound());
assertEquals("No outputs available to display", page.getWarningAlertText());
}
@Test
public void testUnknownPipelineOutput() throws IOException, URISyntaxException, IridaWorkflowException {
IridaWorkflowsService iridaWorkflowsService;
IridaWorkflow unknownWorkflow;
// Register an UNKNOWN workflow
Path workflowVersion1DirectoryPath = Paths.get(TestAnalysis.class.getResource("workflows/TestAnalysis/1.0")
.toURI());
iridaWorkflowsService = new IridaWorkflowsService(new IridaWorkflowSet(Sets.newHashSet()),
new IridaWorkflowIdSet(Sets.newHashSet()));
unknownWorkflow = iridaWorkflowLoaderService.loadIridaWorkflowFromDirectory(workflowVersion1DirectoryPath);
logger.debug("Registering workflow: " + unknownWorkflow.toString());
iridaWorkflowsService.registerWorkflow(unknownWorkflow);
fileUtilities.copyFileToDirectory(outputFileBaseDirectory, "src/test/resources/files/snp_tree_2.tree");
LoginPage.loginAsManager(driver());
// Has an UNKNOWN analysis type so the view should default to the Output File Preview page.
// This submission is setup with refseq_masher parameters and output file
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 14L, "");
assertTrue("Page title should equal", page.compareTabTitle("Output File Preview"));
assertEquals("There should be one output file", 1, page.getNumberOfFilesDisplayed());
assertTrue("There should be exactly one download all files button", page.downloadAllFilesButtonVisible());
assertTrue("There should be a download button for the file that is displayed",
page.downloadOutputFileButtonVisible());
page = AnalysisDetailsPage.initPage(driver(), 14L, "provenance");
assertTrue("Page title should equal", page.compareTabTitle("Provenance"));
assertEquals("There should be one file", 1, page.getProvenanceFileCount());
page.getFileProvenance(0);
assertEquals("Should have 2 tools associated with the tree", 1, page.getToolCount());
page.displayToolExecutionParameters();
assertEquals("First tool should have 2 parameter", 2, page.getGalaxyParametersCount());
page = AnalysisDetailsPage.initPage(driver(), 14L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
assertEquals("There should be 7 labels for analysis details", 7, page.getNumberOfListItems());
// Analysis Description doesn't have a value
assertEquals("There should be only 6 values for these labels", 6, page.getNumberOfListItemValues());
String expectedAnalysisDetails[] = new String[] { "My Completed Submission UNKNOWN PIPELINE", "14",
"Unknown Pipeline (Unknown Version)", "MEDIUM", "Oct 6, 2013, 10:01:00 AM", "a few seconds" };
assertTrue("The correct details are displayed for the analysis",
page.analysisDetailsEqual(expectedAnalysisDetails));
}
@Test
public void testUpdateEmailPipelineResultVisibilty() throws URISyntaxException, IOException {
LoginPage.loginAsManager(driver());
AnalysisDetailsPage page = AnalysisDetailsPage.initPage(driver(), 4L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
// As this analysis is in COMPLETED state the
// Receive Email Upon Pipeline Completion section
// should not be visible
assertFalse("email pipeline result upon completion should be visible", page.emailPipelineResultVisible());
page = AnalysisDetailsPage.initPage(driver(), 8L, "settings/details");
assertTrue("Page title should equal", page.compareTabTitle("Details"));
// As this analysis is not in COMPLETED state the
// Receive Email Upon Pipeline Completion section
// should be visible
assertTrue("email pipeline result upon completion should be visible", page.emailPipelineResultVisible());
}
} |
package ca.corefacility.bioinformatics.irida.ria.integration.projects;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import ca.corefacility.bioinformatics.irida.ria.integration.AbstractIridaUIITChromeDriver;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.LoginPage;
import ca.corefacility.bioinformatics.irida.ria.integration.pages.projects.ProjectLineListPage;
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/ria/web/projects/ProjectSampleMetadataView.xml")
public class ProjectLineListPageIT extends AbstractIridaUIITChromeDriver {
@Before
public void init() {
LoginPage.loginAsManager(driver());
}
@Test
public void testDefaultTable() {
ProjectLineListPage page = ProjectLineListPage.goToPage(driver());
// Should have the default project view displayed
}
} |
package eu.fbk.phd;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class featureSelection {
static LinkedList<row> trainingF = new LinkedList<row>();
static Hashtable<Integer, Integer> featues = new Hashtable<Integer, Integer>();
public static void main(String args[]) throws IOException {
parse(args);
}
static void parse(String args[]) throws IOException {
check(args);
String fileName = args[0];
String metric = args[1];
String outputFile = args[2];
readFile(fileName);
if (args.length > 3) {
String active = args[3];
deactiveFeatures(active);
}
adjustMatrixes();
if (metric.equalsIgnoreCase("avg")) {
Hashtable<Integer, Double> avg = avg();
// System.out.println("**AVG**");
// System.out.println(avg);
Map<Integer, Double> sortedMapAsc = sortByComparator(avg, false);
outputFile(outputFile, sortedMapAsc);
} else if (metric.equalsIgnoreCase("pmi")) {
// System.out.println("**PMI**");
Hashtable<Integer, Double> pmi = pmi();
// System.out.println(pmi);
Map<Integer, Double> sortedMapAsc = sortByComparator(pmi, false);
outputFile(outputFile, sortedMapAsc);
} else {
// System.out.println("**chi2**");
Hashtable<Integer, Double> chi2 = chisquare();
// System.out.println(chi2);
Map<Integer, Double> sortedMapAsc = sortByComparator(chi2, false);
outputFile(outputFile, sortedMapAsc);
}
}
private static void adjustMatrixes() {
//TODO all the other features should be zeros
for(row r :trainingF){
for(Entry<Integer, Integer> f: featues.entrySet()){
if(!r.values.containsKey(f.getKey())){
r.values.put(f.getKey(), 0);
}
}
}
}
private static void deactiveFeatures(String active) {
active = "," + active + ",";
for (row r : trainingF) {
Iterator<Integer> rit = r.values.keySet().iterator();
while (rit.hasNext()) {
Integer rtmp = rit.next();
String tmp = "," + rtmp + ",";
if (!active.contains(tmp)) {
rit.remove();
}
}
}
Iterator<Integer> fit = featues.keySet().iterator();
while (fit.hasNext()) {
Integer ftmp = fit.next();
String tmp = "," + ftmp + ",";
if (!active.contains(tmp)) {
fit.remove();
}
}
}
private static void check(String[] args) {
if (args.length < 3) {
System.err.println("There are missed args!\n" + args);
usage();
System.exit(0);
}
String fn = args[0];
File f = new File(fn);
if (!f.isFile() || !f.exists()) {
System.err.println("Input training file doesn't exist."
+ f.getPath());
usage();
System.exit(0);
}
String feature = args[1];
if (!feature.equals("chi") && !feature.equals("pmi")
&& !feature.equals("avg")) {
System.err
.println("Please choose a correct metric to run between: [chi|avg|pmi]");
usage();
System.exit(0);
}
String fn1 = args[2];
File f1 = new File(fn1);
if (fn1 == null) {
System.err.println("Output file doesn't exist." + f1.getPath());
usage();
System.exit(0);
}
}
private static void usage() {
System.out
.println(">java eu.fbk.phd.featureSelection <arg1> <arg2> <arg3> [<arg4>]");
System.out.println("<arg1> Input file name.");
System.out
.println("<arg2> Choose the feature selection metric[chi|avg|pmi].");
System.out.println("<arg3> Output file name.");
System.out
.println("<arg4> Select the active feature index(s): ex.(0,2,3), otherwise all the features will be considered.");
}
public static Hashtable<Integer, Double> chisquare() {
Hashtable<Integer, Double> selectedFeatures = new Hashtable<Integer, Double>();
Integer feature;
String category;
int N1dot, N0dot, N00, N01, N10, N11;
double chisquareScore;
Double previousScore;
for (Entry<Integer, Integer> entry1 : featues.entrySet()) {
feature = entry1.getKey();
int count = entry1.getValue();
N1dot = count;
N0dot = trainingF.size() - N1dot;
for (row entry2 : trainingF) {
category = entry2.id;
N11 = countLabelWithFeatureX(category, feature);
N01 = countLabelWithNotFeatureX(category, feature);
N00 = N0dot - N01;
N10 = N1dot - N11;
chisquareScore = trainingF.size()
* Math.pow(N11 * N00 - N10 * N01, 2)
/ ((N11 + N01) * (N11 + N10) * (N10 + N00) * (N01 + N00));
previousScore = selectedFeatures.get(feature);
double in=0.0;
if(previousScore != null){
chisquareScore+=previousScore;
}
if (!Double.isNaN(chisquareScore)){
in+=chisquareScore;
}
selectedFeatures.put(feature, in);
/*if (previousScore == null || chisquareScore > previousScore) {
if (Double.isNaN(chisquareScore))
chisquareScore = 0.0;
selectedFeatures.put(feature, chisquareScore);
}*/
}
}
return selectedFeatures;
}
private static Map<Integer, Double> sortByComparator(
Hashtable<Integer, Double> in, final boolean order) {
List<Entry<Integer, Double>> list = new LinkedList<Entry<Integer, Double>>(
in.entrySet());
Collections.sort(list, new Comparator<Entry<Integer, Double>>() {
public int compare(Entry<Integer, Double> o1,
Entry<Integer, Double> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
Map<Integer, Double> sortedMap = new LinkedHashMap<Integer, Double>();
for (Entry<Integer, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
private static Hashtable<Integer, Double> avg() {
Hashtable<Integer, Double> results = new Hashtable<Integer, Double>();
for (Entry<Integer, Integer> ff : featues.entrySet()) {
double avg = (float) ff.getValue() / trainingF.size();
results.put(ff.getKey(), avg);
}
return results;
}
private static Hashtable<Integer, Double> pmi() {
Hashtable<Integer, Double> results = new Hashtable<Integer, Double>();
Hashtable<String, String> resultsHH = new Hashtable<String, String>();
for (row r : trainingF) {
if (!resultsHH.containsKey(r.id)) {
double py = (float) countLabel(r.id) / trainingF.size();
for (Entry<Integer, Integer> ff : featues.entrySet()) {
double px = (float) ff.getValue() / trainingF.size();
double pxy = (float) countLabelWithFeatureX(r.id,
ff.getKey())
/ trainingF.size();
double mi = Math.log(((float) pxy / (px * py)));
double score = ((float)mi/Math.log(2));
if(!Double.isInfinite(mi)){
if (results.containsKey(ff.getKey())) {
score += results.get(ff.getKey());
results.put(ff.getKey(), score);
} else {
results.put(ff.getKey(), score);
}
resultsHH.put(r.id, "");
}
}
}
}
return results;
}
private static int countLabelWithNotFeatureX(String id, Integer featurekey) {
int sum = 0;
for (row r : trainingF) {
if (r.id.equals(id) &&r.values.containsKey(featurekey)&& r.values.get(featurekey) == 0)
sum += 1;
}
return sum;
}
private static int countLabelWithFeatureX(String id, Integer featurekey) {
int sum = 0;
for (row r : trainingF) {
if (r.id.equals(id) && r.values.containsKey(featurekey)&&r.values.get(featurekey) == 1)
sum += 1;
}
return sum;
}
private static int countLabel(String id) {
int sum = 0;
for (row r : trainingF) {
if (r.id.equals(id))
sum += 1;
}
return sum;
}
public static void outputFile(String FileName,
Map<Integer, Double> sortedMapAsc) {
try {
FileOutputStream OutputFile = new FileOutputStream(FileName);
OutputStreamWriter Output = new OutputStreamWriter(OutputFile,
"utf-8");
System.out.println("File is writing...");
for (Entry<Integer, Double> val : sortedMapAsc.entrySet()) {
double chisquareScore = val.getValue();
if (Double.isNaN(chisquareScore))
chisquareScore = 0.0;
Output.write(val.getKey() + "\t" + chisquareScore);
Output.write("\n");
Output.flush();
}
Output.close();
System.out.println("Output file is written sucessfully!");
} catch (Exception e) {
}
}
static void readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = "";
while ((line = br.readLine()) != null) {
String[] cols = line.split(" ");
LinkedHashMap<Integer, Integer> values = new LinkedHashMap<Integer, Integer>();
for (int i = 1; i < cols.length; i++) {
String[] cc2 = cols[i].split(":");
// libsvm format test3
Integer c = 1;
int a1 = Integer.parseInt(cc2[0]);
int a2 = Integer.parseInt(cc2[1]);
if (a2 == 1) {
if (featues.containsKey(a1)) {
c = featues.get(a1) + 1;
}
featues.put(a1, c);
} else {
if (!featues.containsKey(a1))
featues.put(a1, 0);
}
values.put(a1, a2);
/*
* MY test File Integer c =1; if(Integer.parseInt(cols[i])==1){
* if(featues.containsKey(i)){ c = featues.get(i)+1; }
* featues.put(i, c); }else{ if(!featues.containsKey(i))
* featues.put(i, 0); }
*
*
* values.put(i,Integer.parseInt(cols[i]));
*/
}
row e = new row();
e.id = cols[0];
e.values = values;
trainingF.addLast(e);
}
br.close();
}
}
class group {
String label;
Integer featureId;
}
class row {
String id;
LinkedHashMap<Integer, Integer> values;
} |
package org.neo4j.ha;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;
import org.junit.Ignore;
import org.neo4j.test.SubProcess;
import org.neo4j.test.TargetDirectory;
@Ignore
public final class LocalhostZooKeeperCluster
{
private final Object[] keeper;
private final String connection;
public LocalhostZooKeeperCluster( Class<?> owningTest, int... ports )
{
this( TargetDirectory.forTest( owningTest ), ports );
}
public LocalhostZooKeeperCluster( TargetDirectory target, int... ports )
{
keeper = new Object[ports.length];
ZooKeeperProcess subprocess = new ZooKeeperProcess();
StringBuilder connection = new StringBuilder();
for ( int i = 0; i < keeper.length; i++ )
{
keeper[i] = subprocess.start( new String[] { config( target, i + 1, ports[i] ) } );
if ( connection.length() > 0 ) connection.append( "," );
connection.append( "localhost:" + ports[i] );
}
this.connection = connection.toString();
}
@Override
public String toString()
{
return getClass().getSimpleName() + "[" + getConnectionString() + "]";
}
public synchronized String getConnectionString()
{
return connection;
}
private String config( TargetDirectory target, int id, int port )
{
File config = target.file( "zookeeper" + id + ".cfg" );
File dataDir = target.directory( "zk" + id + "data", true );
try
{
PrintWriter conf = new PrintWriter( config );
try
{
conf.println( "tickTime=2000" );
conf.println( "initLimit=10" );
conf.println( "syncLimit=5" );
conf.println( "dataDir=" + dataDir.getAbsolutePath() );
conf.println( "clientPort=" + port );
for ( int j = 0; j < keeper.length; j++ )
{
conf.println( "server." + ( j + 1 ) + "=localhost:" + ( 2888 + j ) + ":"
+ ( 3888 + j ) );
}
}
finally
{
conf.close();
}
PrintWriter myid = new PrintWriter( new File( dataDir, "myid" ) );
try
{
myid.println( Integer.toString( id ) );
}
finally
{
myid.close();
}
}
catch ( IOException e )
{
throw new IllegalStateException( "Could not write ZooKeeper configuration", e );
}
return config.getAbsolutePath();
}
public synchronized void shutdown()
{
if ( keeper.length > 0 && keeper[0] == null ) return;
for ( Object zk : keeper )
{
SubProcess.stop( zk );
}
Arrays.fill( keeper, null );
}
private static class ZooKeeperProcess extends SubProcess<Object, String[]>
{
@Override
protected void startup( String[] parameters )
{
System.out.println( "parameters=" + Arrays.toString( parameters ) );
QuorumPeerMain.main( parameters );
}
}
} |
package com.opencv.camera;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.opencv.camera.NativeProcessor.NativeProcessorCallback;
import com.opencv.camera.NativeProcessor.PoolCallback;
public class NativePreviewer extends SurfaceView implements
SurfaceHolder.Callback, Camera.PreviewCallback, NativeProcessorCallback {
private String whitebalance_mode = "auto";
/**
* Constructor useful for defining a NativePreviewer in android layout xml
*
* @param context
* @param attributes
*/
public NativePreviewer(Context context, AttributeSet attributes) {
super(context, attributes);
listAllCameraMethods();
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
/*
* TODO get this working! Can't figure out how to define these in xml
*/
preview_width = attributes.getAttributeIntValue("opencv",
"preview_width", 600);
preview_height = attributes.getAttributeIntValue("opencv",
"preview_height", 600);
Log.d("NativePreviewer", "Trying to use preview size of "
+ preview_width + " " + preview_height);
processor = new NativeProcessor();
setZOrderMediaOverlay(false);
}
/**
*
* @param context
* @param preview_width
* the desired camera preview width - will attempt to get as
* close to this as possible
* @param preview_height
* the desired camera preview height
*/
public NativePreviewer(Context context, int preview_width,
int preview_height) {
super(context);
listAllCameraMethods();
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.preview_width = preview_width;
this.preview_height = preview_height;
processor = new NativeProcessor();
setZOrderMediaOverlay(false);
}
/**
* Only call in the oncreate function of the instantiating activity
*
* @param width
* desired width
* @param height
* desired height
*/
public void setPreviewSize(int width, int height) {
preview_width = width;
preview_height = height;
Log.d("NativePreviewer", "Trying to use preview size of "
+ preview_width + " " + preview_height);
}
public void setParamsFromPrefs(Context ctx) {
int size[] = { 0, 0 };
CameraConfig.readImageSize(ctx, size);
int mode = CameraConfig.readCameraMode(ctx);
setPreviewSize(size[0], size[1]);
setGrayscale(mode == CameraConfig.CAMERA_MODE_BW ? true : false);
whitebalance_mode = CameraConfig.readWhitebalace(ctx);
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
try {
initCamera(mHolder);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> pvsizes = mCamera.getParameters()
.getSupportedPreviewSizes();
int best_width = 1000000;
int best_height = 1000000;
int bdist = 100000;
for (Size x : pvsizes) {
if (Math.abs(x.width - preview_width) < bdist) {
bdist = Math.abs(x.width - preview_width);
best_width = x.width;
best_height = x.height;
}
}
preview_width = best_width;
preview_height = best_height;
Log.d("NativePreviewer", "Determined compatible preview size is: ("
+ preview_width + "," + preview_height + ")");
Log.d("NativePreviewer", "Supported params: "
+ mCamera.getParameters().flatten());
// this is available in 8+
// parameters.setExposureCompensation(0);
if (parameters.getSupportedWhiteBalance().contains(whitebalance_mode)) {
parameters.setWhiteBalance(whitebalance_mode);
}
if (parameters.getSupportedAntibanding().contains(
Camera.Parameters.ANTIBANDING_OFF)) {
parameters.setAntibanding(Camera.Parameters.ANTIBANDING_OFF);
}
List<String> fmodes = mCamera.getParameters().getSupportedFocusModes();
// for(String x: fmodes){
if (parameters.get("meter-mode") != null)
parameters.set("meter-mode", "meter-average");
int idx = fmodes.indexOf(Camera.Parameters.FOCUS_MODE_INFINITY);
if (idx != -1) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
} else if (fmodes.indexOf(Camera.Parameters.FOCUS_MODE_FIXED) != -1) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED);
}
if (fmodes.indexOf(Camera.Parameters.FOCUS_MODE_AUTO) != -1) {
hasAutoFocus = true;
}
List<String> scenemodes = mCamera.getParameters()
.getSupportedSceneModes();
if (scenemodes != null)
if (scenemodes.indexOf(Camera.Parameters.SCENE_MODE_ACTION) != -1) {
parameters.setSceneMode(Camera.Parameters.SCENE_MODE_ACTION);
Log.d("NativePreviewer", "set scenemode to action");
}
parameters.setPreviewSize(preview_width, preview_height);
mCamera.setParameters(parameters);
pixelinfo = new PixelFormat();
pixelformat = mCamera.getParameters().getPreviewFormat();
PixelFormat.getPixelFormatInfo(pixelformat, pixelinfo);
Size preview_size = mCamera.getParameters().getPreviewSize();
preview_width = preview_size.width;
preview_height = preview_size.height;
int bufSize = preview_width * preview_height * pixelinfo.bitsPerPixel
/ 8;
// Must call this before calling addCallbackBuffer to get all the
// reflection variables setup
initForACB();
initForPCWB();
// Use only one buffer, so that we don't preview to many frames and bog
// down system
byte[] buffer = new byte[bufSize];
addCallbackBuffer(buffer);
setPreviewCallbackWithBuffer();
mCamera.startPreview();
}
public void postautofocus(int delay) {
if (hasAutoFocus)
handler.postDelayed(autofocusrunner, delay);
}
/**
* Demonstration of how to use onPreviewFrame. In this case I'm not
* processing the data, I'm just adding the buffer back to the buffer queue
* for re-use
*/
public void onPreviewFrame(byte[] data, Camera camera) {
if (start == null) {
start = new Date();
}
processor.post(data, preview_width, preview_height, pixelformat,
System.nanoTime(), this);
fcount++;
if (fcount % 100 == 0) {
double ms = (new Date()).getTime() - start.getTime();
Log.i("NativePreviewer", "fps:" + fcount / (ms / 1000.0));
start = new Date();
fcount = 0;
}
}
@Override
public void onDoneNativeProcessing(byte[] buffer) {
addCallbackBuffer(buffer);
}
public void addCallbackStack(LinkedList<PoolCallback> callbackstack) {
processor.addCallbackStack(callbackstack);
}
/**
* This must be called when the activity pauses, in Activity.onPause This
* has the side effect of clearing the callback stack.
*
*/
public void onPause() {
releaseCamera();
addCallbackStack(null);
processor.stop();
}
public void onResume() {
processor.start();
}
private Method mPCWB;
private void initForPCWB() {
try {
mPCWB = Class.forName("android.hardware.Camera").getMethod(
"setPreviewCallbackWithBuffer", PreviewCallback.class);
} catch (Exception e) {
Log.e("NativePreviewer",
"Problem setting up for setPreviewCallbackWithBuffer: "
+ e.toString());
}
}
private void addCallbackBuffer(byte[] b) {
try {
mAcb.invoke(mCamera, b);
} catch (Exception e) {
Log.e("NativePreviewer",
"invoking addCallbackBuffer failed: " + e.toString());
}
}
/**
* Use this method instead of setPreviewCallback if you want to use manually
* allocated buffers. Assumes that "this" implements Camera.PreviewCallback
*/
private void setPreviewCallbackWithBuffer() {
// mCamera.setPreviewCallback(this);
// return;
try {
// If we were able to find the setPreviewCallbackWithBuffer method
// of Camera,
// we can now invoke it on our Camera instance, setting 'this' to be
// the
// callback handler
mPCWB.invoke(mCamera, this);
// Log.d("NativePrevier","setPreviewCallbackWithBuffer: Called method");
} catch (Exception e) {
Log.e("NativePreviewer", e.toString());
}
}
@SuppressWarnings("unused")
private void clearPreviewCallbackWithBuffer() {
// mCamera.setPreviewCallback(this);
// return;
try {
// If we were able to find the setPreviewCallbackWithBuffer method
// of Camera,
// we can now invoke it on our Camera instance, setting 'this' to be
// the
// callback handler
mPCWB.invoke(mCamera, (PreviewCallback) null);
// Log.d("NativePrevier","setPreviewCallbackWithBuffer: cleared");
} catch (Exception e) {
Log.e("NativePreviewer", e.toString());
}
}
/**
* These variables are re-used over and over by addCallbackBuffer
*/
private Method mAcb;
private void initForACB() {
try {
mAcb = Class.forName("android.hardware.Camera").getMethod(
"addCallbackBuffer", byte[].class);
} catch (Exception e) {
Log.e("NativePreviewer",
"Problem setting up for addCallbackBuffer: " + e.toString());
}
}
private Runnable autofocusrunner = new Runnable() {
@Override
public void run() {
mCamera.autoFocus(autocallback);
}
};
private Camera.AutoFocusCallback autocallback = new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (!success)
postautofocus(1000);
}
};
/**
* This method will list all methods of the android.hardware.Camera class,
* even the hidden ones. With the information it provides, you can use the
* same approach I took below to expose methods that were written but hidden
* in eclair
*/
private void listAllCameraMethods() {
try {
Class<?> c = Class.forName("android.hardware.Camera");
Method[] m = c.getMethods();
for (int i = 0; i < m.length; i++) {
Log.d("NativePreviewer", " method:" + m[i].toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("NativePreviewer", e.toString());
}
}
private void initCamera(SurfaceHolder holder) throws InterruptedException {
if (mCamera == null) {
// The Surface has been created, acquire the camera and tell it
// where
// to draw.
int i = 0;
while (i++ < 5) {
try {
mCamera = Camera.open();
break;
} catch (RuntimeException e) {
Thread.sleep(200);
}
}
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
} catch (RuntimeException e) {
Log.e("camera", "stacktrace", e);
}
}
}
private void releaseCamera() {
if (mCamera != null) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's
// very
// important to release it when the activity is paused.
mCamera.stopPreview();
mCamera.release();
}
// processor = null;
mCamera = null;
mAcb = null;
mPCWB = null;
}
private Handler handler = new Handler();
private Date start;
private int fcount = 0;
private boolean hasAutoFocus = false;
private SurfaceHolder mHolder;
private Camera mCamera;
private NativeProcessor processor;
private int preview_width, preview_height;
private int pixelformat;
private PixelFormat pixelinfo;
public void setGrayscale(boolean b) {
processor.setGrayscale(b);
}
} |
package ti.modules.titanium.map;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiDict;
import org.appcelerator.titanium.TiProperties;
import org.appcelerator.titanium.TiProxy;
import org.appcelerator.titanium.TiContext.OnLifecycleEvent;
import org.appcelerator.titanium.io.TiBaseFile;
import org.appcelerator.titanium.io.TiFileFactory;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiUIHelper;
import org.appcelerator.titanium.view.TiUIView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
interface TitaniumOverlayListener {
public void onTap(int index);
}
public class TiMapView extends TiUIView
implements Handler.Callback, TitaniumOverlayListener
{
private static final String LCAT = "TiMapView";
private static final boolean DBG = TiConfig.LOGD;
private static final String TI_DEVELOPMENT_KEY = "0Rq5tT4bUSXcVQ3F0gt8ekVBkqgn05ZJBQMj6uw";
private static final String OLD_API_KEY = "ti.android.google.map.api.key";
private static final String DEVELOPMENT_API_KEY = "ti.android.google.map.api.key.development";
private static final String PRODUCTION_API_KEY = "ti.android.google.map.api.key.production";
public static final String EVENT_CLICK = "click";
public static final String EVENT_REGION_CHANGED = "regionChanged";
public static final int MAP_VIEW_STANDARD = 1;
public static final int MAP_VIEW_SATELLITE = 2;
public static final int MAP_VIEW_HYBRID = 3;
private static final int MSG_SET_LOCATION = 300;
private static final int MSG_SET_MAPTYPE = 301;
private static final int MSG_SET_REGIONFIT = 302;
private static final int MSG_SET_ANIMATE = 303;
private static final int MSG_SET_USERLOCATION = 304;
private static final int MSG_SET_SCROLLENABLED = 305;
private static final int MSG_CHANGE_ZOOM = 306;
private static final int MSG_ADD_ANNOTATION = 307;
private static final int MSG_REMOVE_ANNOTATION = 308;
private static final int MSG_SELECT_ANNOTATION = 309;
private static final int MSG_REMOVE_ALL_ANNOTATIONS = 310;
//private MapView view;
private boolean scrollEnabled;
private boolean regionFit;
private boolean animate;
private boolean userLocation;
private LocalMapView view;
private Window mapWindow;
private TitaniumOverlay overlay;
private MyLocationOverlay myLocation;
private TiOverlayItemView itemView;
private ArrayList<AnnotationProxy> annotations;
private Handler handler;
class LocalMapView extends MapView
{
private boolean scrollEnabled;
private int lastLongitude;
private int lastLatitude;
private int lastLatitudeSpan;
private int lastLongitudeSpan;
public LocalMapView(Context context, String apiKey) {
super(context, apiKey);
scrollEnabled = false;
}
public void setScrollable(boolean enable) {
scrollEnabled = enable;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (!scrollEnabled && ev.getAction() == MotionEvent.ACTION_MOVE) {
return true;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent ev) {
if (!scrollEnabled && ev.getAction() == MotionEvent.ACTION_MOVE) {
return true;
}
return super.dispatchTrackballEvent(ev);
}
@Override
public void computeScroll() {
super.computeScroll();
GeoPoint center = getMapCenter();
if (lastLatitude != center.getLatitudeE6() || lastLongitude != center.getLongitudeE6() ||
lastLatitudeSpan != getLatitudeSpan() || lastLongitudeSpan != getLongitudeSpan())
{
lastLatitude = center.getLatitudeE6();
lastLongitude = center.getLongitudeE6();
lastLatitudeSpan = getLatitudeSpan();
lastLongitudeSpan = getLongitudeSpan();
TiDict d = new TiDict();
d.put("latitude", scaleFromGoogle(lastLatitude));
d.put("longitude", scaleFromGoogle(lastLongitude));
d.put("latitudeDelta", scaleFromGoogle(lastLatitudeSpan));
d.put("longitudeDelta", scaleFromGoogle(lastLongitudeSpan));
proxy.fireEvent("regionChanged", d);
}
}
}
class TitaniumOverlay extends ItemizedOverlay<TiOverlayItem>
{
ArrayList<AnnotationProxy> annotations;
TitaniumOverlayListener listener;
public TitaniumOverlay(Drawable defaultDrawable, TitaniumOverlayListener listener) {
super(defaultDrawable);
this.listener = listener;
}
public void setAnnotations(ArrayList<AnnotationProxy> annotations) {
this.annotations = new ArrayList<AnnotationProxy>(annotations);
populate();
}
@Override
protected TiOverlayItem createItem(int i) {
TiOverlayItem item = null;
AnnotationProxy p = annotations.get(i);
TiDict a = p.getDynamicProperties();
if (a.containsKey("latitude") && a.containsKey("longitude")) {
String title = a.optString("title", "");
String subtitle = a.optString("subtitle", "");
GeoPoint location = new GeoPoint(scaleToGoogle(a.getDouble("latitude")), scaleToGoogle(a.getDouble("longitude")));
item = new TiOverlayItem(location, title, subtitle, p);
//prefer pinImage to pincolor.
if (a.containsKey("image") || a.containsKey("pinImage"))
{
String imagePath = a.getString("image");
if (imagePath == null) {
imagePath = a.getString("pinImage");
}
Drawable marker = makeMarker(imagePath);
boundCenterBottom(marker);
item.setMarker(marker);
} else if (a.containsKey("pincolor")) {
Object value = a.get("pincolor");
try {
if (value instanceof String) {
// Supported strings: Supported formats are:
// #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'
int markerColor = TiConvert.toColor((String) value);
item.setMarker(makeMarker(markerColor));
} else {
// Assume it's a numeric
switch(a.getInt("pincolor")) {
case 1 : // RED
item.setMarker(makeMarker(Color.RED));
break;
case 2 : // GRE
item.setMarker(makeMarker(Color.GREEN));
break;
case 3 : // PURPLE
item.setMarker(makeMarker(Color.argb(255,192,0,192)));
break;
}
}
} catch (Exception e) {
// May as well catch all errors
Log.w(LCAT, "Unable to parse color [" + a.getString("pincolor")+"] for item ["+i+"]");
}
}
if (a.containsKey("leftButton")) {
item.setLeftButton(proxy.getTiContext().resolveUrl(null, a.getString("leftButton")));
}
if (a.containsKey("rightButton")) {
item.setRightButton(proxy.getTiContext().resolveUrl(null, a.getString("rightButton")));
}
} else {
Log.w(LCAT, "Skipping annotation: No coordinates
}
return item;
}
@Override
public int size() {
return (annotations == null) ? 0 : annotations.size();
}
@Override
protected boolean onTap(int index)
{
boolean handled = super.onTap(index);
if(!handled ) {
listener.onTap(index);
}
return handled;
}
}
public TiMapView(TiViewProxy proxy, Window mapWindow)
{
super(proxy);
this.mapWindow = mapWindow;
this.handler = new Handler(this);
this.annotations = new ArrayList<AnnotationProxy>();
//TODO MapKey
TiApplication app = proxy.getTiContext().getTiApp();
TiProperties appProperties = app.getSystemProperties();
String oldKey = appProperties.getString(OLD_API_KEY, TI_DEVELOPMENT_KEY);
String developmentKey = appProperties.getString(DEVELOPMENT_API_KEY, oldKey);
String productionKey = appProperties.getString(PRODUCTION_API_KEY, oldKey);
String apiKey = developmentKey;
if (app.getDeployType().equals(TiApplication.DEPLOY_TYPE_PRODUCTION)) {
apiKey = productionKey;
}
view = new LocalMapView(mapWindow.getContext(), apiKey);
TiMapActivity ma = (TiMapActivity) mapWindow.getContext();
ma.setLifecycleListener(new OnLifecycleEvent()
{
public void onPause() {
if (myLocation != null) {
if (DBG) {
Log.d(LCAT, "onPause: Disabling My Location");
}
myLocation.disableMyLocation();
}
}
public void onResume() {
if (myLocation != null && userLocation) {
if (DBG) {
Log.d(LCAT, "onResume: Enabling My Location");
}
myLocation.enableMyLocation();
}
}
public void onDestroy() {
}
public void onStart() {
}
public void onStop() {
}
});
view.setBuiltInZoomControls(true);
view.setScrollable(true);
view.setClickable(true);
setNativeView(view);
this.regionFit =true;
this.animate = false;
final TiViewProxy fproxy = proxy;
itemView = new TiOverlayItemView(proxy.getContext());
itemView.setOnOverlayClickedListener(new TiOverlayItemView.OnOverlayClicked(){
public void onClick(int lastIndex, String clickedItem) {
TiOverlayItem item = overlay.getItem(lastIndex);
if (item != null) {
TiDict d = new TiDict();
d.put("title", item.getTitle());
d.put("subtitle", item.getSnippet());
d.put("latitude", scaleFromGoogle(item.getPoint().getLatitudeE6()));
d.put("longitude", scaleFromGoogle(item.getPoint().getLongitudeE6()));
d.put("annotation", item.getProxy());
d.put("clicksource", clickedItem);
fproxy.fireEvent(EVENT_CLICK, d);
}
}
});
}
private LocalMapView getView() {
return view;
}
public boolean handleMessage(Message msg) {
switch(msg.what) {
case MSG_SET_LOCATION : {
doSetLocation((TiDict) msg.obj);
return true;
}
case MSG_SET_MAPTYPE : {
doSetMapType(msg.arg1);
return true;
}
case MSG_SET_REGIONFIT :
regionFit = msg.arg1 == 1 ? true : false;
return true;
case MSG_SET_ANIMATE :
animate = msg.arg1 == 1 ? true : false;
return true;
case MSG_SET_SCROLLENABLED :
animate = msg.arg1 == 1 ? true : false;
if (view != null) {
view.setScrollable(scrollEnabled);
}
return true;
case MSG_SET_USERLOCATION :
userLocation = msg.arg1 == 1 ? true : false;
doUserLocation(userLocation);
return true;
case MSG_CHANGE_ZOOM :
MapController mc = view.getController();
if (mc != null) {
mc.setZoom(view.getZoomLevel() + msg.arg1);
}
return true;
case MSG_ADD_ANNOTATION :
doAddAnnotation((AnnotationProxy) msg.obj);
return true;
case MSG_REMOVE_ANNOTATION :
doRemoveAnnotation((String) msg.obj);
return true;
case MSG_SELECT_ANNOTATION :
boolean select = msg.arg1 == 1 ? true : false;
boolean animate = msg.arg2 == 1 ? true : false;
String title = (String) msg.obj;
doSelectAnnotation(select, title, animate);
return true;
case MSG_REMOVE_ALL_ANNOTATIONS :
annotations.clear();
doSetAnnotations(annotations);
return true;
}
return false;
}
private void hideAnnotation()
{
if (view != null && itemView != null) {
view.removeView(itemView);
itemView.clearLastIndex();
}
}
private void showAnnotation(int index, TiOverlayItem item)
{
if (view != null && itemView != null && item != null) {
itemView.setItem(index, item);
//Make sure the atonnation is always on top of the marker
int y = -1*item.getMarker(TiOverlayItem.ITEM_STATE_FOCUSED_MASK).getIntrinsicHeight();
MapView.LayoutParams params = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, item.getPoint(), 0, y, MapView.LayoutParams.BOTTOM_CENTER);
params.mode = MapView.LayoutParams.MODE_MAP;
view.addView(itemView, params);
}
}
public void onTap(int index)
{
if (overlay != null) {
synchronized(overlay) {
TiOverlayItem item = overlay.getItem(index);
if (itemView != null && index == itemView.getLastIndex() && itemView.getVisibility() == View.VISIBLE) {
hideAnnotation();
return;
}
if (item.hasData())
{
hideAnnotation();
showAnnotation(index, item);
} else {
Toast.makeText(proxy.getContext(), "No information for location", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void processProperties(TiDict d)
{
LocalMapView view = getView();
if (d.containsKey("mapType")) {
doSetMapType(TiConvert.toInt(d, "mapType"));
}
if (d.containsKey("zoomEnabled")) {
view.setBuiltInZoomControls(TiConvert.toBoolean(d,"zoomEnabled"));
}
if (d.containsKey("scrollEnabled")) {
view.setScrollable(TiConvert.toBoolean(d, "scrollEnabled"));
}
if (d.containsKey("region")) {
doSetLocation(d.getTiDict("region"));
}
if (d.containsKey("regionFit")) {
regionFit = d.getBoolean("regionFit");
}
if (d.containsKey("animate")) {
animate = d.getBoolean("animate");
}
if (d.containsKey("userLocation")) {
doUserLocation(d.getBoolean("userLocation"));
}
if (d.containsKey("annotations")) {
proxy.internalSetDynamicValue("annotations", d.get("annotations"), false);
Object [] annotations = (Object[]) d.get("annotations");
for(int i = 0; i < annotations.length; i++) {
AnnotationProxy ap = (AnnotationProxy) annotations[i];
this.annotations.add(ap);
}
doSetAnnotations(this.annotations);
}
super.processProperties(d);
}
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, TiProxy proxy)
{
if (key.equals("location")) {
if (newValue != null) {
if (newValue instanceof AnnotationProxy) {
AnnotationProxy ap = (AnnotationProxy) newValue;
doSetLocation(ap.getDynamicProperties());
} else if (newValue instanceof TiDict) {
doSetLocation((TiDict) newValue);
}
}
} else if (key.equals("mapType")) {
if (newValue == null) {
doSetMapType(MAP_VIEW_STANDARD);
} else {
doSetMapType(TiConvert.toInt(newValue));
}
} else {
super.propertyChanged(key, oldValue, newValue, proxy);
}
}
public void doSetLocation(TiDict d)
{
LocalMapView view = getView();
if (d.containsKey("longitude") && d.containsKey("latitude")) {
GeoPoint gp = new GeoPoint(scaleToGoogle(d.getDouble("latitude")), scaleToGoogle(d.getDouble("longitude")));
boolean anim = false;
if (d.containsKey("animate")) {
anim = TiConvert.toBoolean(d, "animate");
}
if (anim) {
view.getController().animateTo(gp);
} else {
view.getController().setCenter(gp);
}
}
if (regionFit && d.containsKey("longitudeDelta") && d.containsKey("latitudeDelta")) {
view.getController().zoomToSpan(scaleToGoogle(d.getDouble("latitudeDelta")), scaleToGoogle(d.getDouble("longitudeDelta")));
} else {
Log.w(LCAT, "span must have longitudeDelta and latitudeDelta");
}
}
public void doSetMapType(int type)
{
if (view != null) {
switch(type) {
case MAP_VIEW_STANDARD :
view.setSatellite(false);
view.setTraffic(false);
view.setStreetView(false);
break;
case MAP_VIEW_SATELLITE:
view.setSatellite(true);
view.setTraffic(false);
view.setStreetView(false);
break;
case MAP_VIEW_HYBRID :
view.setSatellite(false);
view.setTraffic(false);
view.setStreetView(true);
break;
}
}
}
public void doSetAnnotations(ArrayList<AnnotationProxy> annotations)
{
if (annotations != null) {
this.annotations = annotations;
List<Overlay> overlays = view.getOverlays();
synchronized(overlays) {
if (overlays.contains(overlay)) {
overlays.remove(overlay);
overlay = null;
}
if (annotations.size() > 0) {
overlay = new TitaniumOverlay(makeMarker(Color.BLUE), this);
overlay.setAnnotations(annotations);
overlays.add(overlay);
}
view.invalidate();
}
}
}
public void addAnnotation(AnnotationProxy annotation) {
handler.obtainMessage(MSG_ADD_ANNOTATION, annotation).sendToTarget();
};
public void doAddAnnotation(AnnotationProxy annotation)
{
if (annotation != null && view != null) {
annotations.add(annotation);
doSetAnnotations(annotations);
}
};
public void removeAnnotation(String title) {
handler.obtainMessage(MSG_REMOVE_ANNOTATION, title).sendToTarget();
};
public void removeAllAnnotations() {
handler.obtainMessage(MSG_REMOVE_ALL_ANNOTATIONS).sendToTarget();
}
private int findAnnotation(String title)
{
int existsIndex = -1;
// Check for existence
int len = annotations.size();
for(int i = 0; i < len; i++) {
AnnotationProxy a = annotations.get(i);
String t = (String) a.getDynamicValue("title");
if (t != null) {
if (title.equals(t)) {
if (DBG) {
Log.d(LCAT, "Annotation found at index: " + " with title: " + title);
}
existsIndex = i;
break;
}
}
}
return existsIndex;
}
public void doRemoveAnnotation(String title)
{
if (title != null && view != null && annotations != null) {
int existsIndex = findAnnotation(title);
// If found, build a new annotation list
if (existsIndex > -1) {
annotations.remove(existsIndex);
doSetAnnotations(annotations);
}
}
};
public void selectAnnotation(boolean select, String title, boolean animate)
{
if (title != null) {
handler.obtainMessage(MSG_SELECT_ANNOTATION, select ? 1 : 0, animate ? 1 : 0, title).sendToTarget();
}
}
public void doSelectAnnotation(boolean select, String title, boolean animate)
{
if (title != null && view != null && annotations != null && overlay != null) {
int index = findAnnotation(title);
if (index > -1) {
if (overlay != null) {
synchronized(overlay) {
TiOverlayItem item = overlay.getItem(index);
if (select) {
if (itemView != null && index == itemView.getLastIndex() && itemView.getVisibility() != View.VISIBLE) {
showAnnotation(index, item);
return;
}
hideAnnotation();
MapController controller = view.getController();
if (animate) {
controller.animateTo(item.getPoint());
} else {
controller.setCenter(item.getPoint());
}
showAnnotation(index, item);
} else {
hideAnnotation();
}
}
}
}
}
}
public void doUserLocation(boolean userLocation)
{
if (view != null) {
if (userLocation) {
if (myLocation == null) {
myLocation = new MyLocationOverlay(proxy.getContext(), view);
}
List<Overlay> overlays = view.getOverlays();
synchronized(overlays) {
if (!overlays.contains(myLocation)) {
overlays.add(myLocation);
}
}
myLocation.enableMyLocation();
} else {
if (myLocation != null) {
List<Overlay> overlays = view.getOverlays();
synchronized(overlays) {
if (overlays.contains(myLocation)) {
overlays.remove(myLocation);
}
myLocation.disableMyLocation();
}
}
}
}
}
public void changeZoomLevel(int delta) {
handler.obtainMessage(MSG_CHANGE_ZOOM, delta, 0).sendToTarget();
}
private Drawable makeMarker(int c)
{
OvalShape s = new OvalShape();
s.resize(1.0f, 1.0f);
ShapeDrawable d = new ShapeDrawable(s);
d.setBounds(0, 0, 15, 15);
d.getPaint().setColor(c);
return d;
}
private Drawable makeMarker(String pinImage)
{
String url = proxy.getTiContext().resolveUrl(null, pinImage);
TiBaseFile file = TiFileFactory.createTitaniumFile(proxy.getTiContext(), new String[] { url }, false);
try {
Drawable d = new BitmapDrawable(TiUIHelper.createBitmap(file.getInputStream()));
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
} catch (IOException e) {
Log.e(LCAT, "Error creating drawable from path: " + pinImage.toString(), e);
}
return null;
}
private double scaleFromGoogle(int value) {
return (double)value / 1000000.0;
}
private int scaleToGoogle(double value) {
return (int)(value * 1000000);
}
} |
package com.mapswithme.maps.editor;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mapswithme.maps.MwmActivity;
import com.mapswithme.maps.MwmApplication;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmToolbarFragment;
import com.mapswithme.maps.base.OnBackPressListener;
import com.mapswithme.maps.editor.data.Language;
import com.mapswithme.maps.editor.data.LocalizedName;
import com.mapswithme.maps.editor.data.LocalizedStreet;
import com.mapswithme.maps.widget.SearchToolbarController;
import com.mapswithme.maps.widget.ToolbarController;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.statistics.Statistics;
import com.mapswithme.maps.editor.data.NamesDataSource;
import java.util.ArrayList;
import java.util.List;
public class EditorHostFragment extends BaseMwmToolbarFragment
implements OnBackPressListener, View.OnClickListener, LanguagesFragment.Listener
{
private boolean mIsNewObject;
enum Mode
{
MAP_OBJECT,
OPENING_HOURS,
STREET,
CUISINE,
LANGUAGE
}
private Mode mMode;
/**
* A list of localized names added by a user and those that were in metadata.
*/
private static final List<LocalizedName> sNames = new ArrayList<>();
/**
* Count of names which should always be shown.
*/
private int mMandatoryNamesCount = 0;
private static final String NOOB_ALERT_SHOWN = "Alert_for_noob_was_shown";
/**
* Used in MultilanguageAdapter to show, select and remove items.
*/
List<LocalizedName> getNames()
{
return sNames;
}
public LocalizedName[] getNamesAsArray()
{
return sNames.toArray(new LocalizedName[sNames.size()]);
}
void setNames(LocalizedName[] names)
{
sNames.clear();
for (LocalizedName name : names)
{
addName(name);
}
}
/**
* Sets .name of an index item to name.
*/
void setName(String name, int index)
{
sNames.get(index).name = name;
}
void addName(LocalizedName name)
{
sNames.add(name);
}
public int getMandatoryNamesCount()
{
return mMandatoryNamesCount;
}
public void setMandatoryNamesCount(int mandatoryNamesCount)
{
mMandatoryNamesCount = mandatoryNamesCount;
}
private void fillNames(boolean needFakes)
{
NamesDataSource namesDataSource = Editor.nativeGetNamesDataSource(needFakes);
setNames(namesDataSource.getNames());
setMandatoryNamesCount(namesDataSource.getMandatoryNamesCount());
editMapObject();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_editor_host, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
mToolbarController.findViewById(R.id.save).setOnClickListener(this);
mToolbarController.getToolbar().setNavigationOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onBackPressed();
}
});
if (getArguments() != null)
mIsNewObject = getArguments().getBoolean(EditorActivity.EXTRA_NEW_OBJECT, false);
mToolbarController.setTitle(getTitle());
fillNames(true /* addFakes */);
}
@StringRes
private int getTitle()
{
return mIsNewObject ? R.string.editor_add_place_title : R.string.editor_edit_place_title;
}
@Override
protected ToolbarController onCreateToolbarController(@NonNull View root)
{
return new SearchToolbarController(root, getActivity())
{
@Override
protected void onTextChanged(String query)
{
((CuisineFragment) getChildFragmentManager().findFragmentByTag(CuisineFragment.class.getName())).setFilter(query);
}
};
}
@Override
public boolean onBackPressed()
{
switch (mMode)
{
case OPENING_HOURS:
case STREET:
case CUISINE:
case LANGUAGE:
editMapObject();
break;
default:
Utils.navigateToParent(getActivity());
}
return true;
}
protected void editMapObject()
{
editMapObject(false /* focusToLastName */);
}
protected void editMapObject(boolean focusToLastName)
{
mMode = Mode.MAP_OBJECT;
((SearchToolbarController) mToolbarController).showControls(false);
mToolbarController.setTitle(getTitle());
UiUtils.show(mToolbarController.findViewById(R.id.save));
Bundle args = new Bundle();
if (focusToLastName)
args.putInt(EditorFragment.LAST_INDEX_OF_NAMES_ARRAY, sNames.size() - 1);
final Fragment editorFragment = Fragment.instantiate(getActivity(), EditorFragment.class.getName(), args);
getChildFragmentManager().beginTransaction()
.replace(R.id.fragment_container, editorFragment, EditorFragment.class.getName())
.commit();
}
protected void editTimetable()
{
final Bundle args = new Bundle();
args.putString(TimetableFragment.EXTRA_TIME, Editor.nativeGetOpeningHours());
editWithFragment(Mode.OPENING_HOURS, R.string.editor_time_title, args, TimetableFragment.class, false);
}
protected void editStreet()
{
editWithFragment(Mode.STREET, R.string.choose_street, null, StreetFragment.class, false);
}
protected void editCuisine()
{
editWithFragment(Mode.CUISINE, R.string.select_cuisine, null, CuisineFragment.class, true);
}
protected void addLanguage()
{
Bundle args = new Bundle();
ArrayList<String> languages = new ArrayList<>(sNames.size());
for (LocalizedName name : sNames)
languages.add(name.lang);
args.putStringArrayList(LanguagesFragment.EXISTING_LOCALIZED_NAMES, languages);
UiUtils.hide(mToolbarController.findViewById(R.id.save));
editWithFragment(Mode.LANGUAGE, R.string.choose_language, args, LanguagesFragment.class, false);
}
private void editWithFragment(Mode newMode, @StringRes int toolbarTitle, @Nullable Bundle args, Class<? extends Fragment> fragmentClass, boolean showSearch)
{
if (!setEdits())
return;
mMode = newMode;
mToolbarController.setTitle(toolbarTitle);
((SearchToolbarController) mToolbarController).showControls(showSearch);
final Fragment fragment = Fragment.instantiate(getActivity(), fragmentClass.getName(), args);
getChildFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentClass.getName())
.commit();
}
protected void editCategory()
{
if (!mIsNewObject)
return;
final Activity host = getActivity();
host.finish();
startActivity(new Intent(host, FeatureCategoryActivity.class));
}
private boolean setEdits()
{
return ((EditorFragment) getChildFragmentManager().findFragmentByTag(EditorFragment.class.getName())).setEdits();
}
@Override
public void onClick(View v)
{
if (v.getId() == R.id.save)
{
switch (mMode)
{
case OPENING_HOURS:
final String timetables = ((TimetableFragment) getChildFragmentManager().findFragmentByTag(TimetableFragment.class.getName())).getTimetable();
if (OpeningHours.nativeIsTimetableStringValid(timetables))
{
Editor.nativeSetOpeningHours(timetables);
editMapObject();
}
else
{
// TODO (yunikkk) correct translation
showMistakeDialog(R.string.editor_correct_mistake);
}
break;
case STREET:
setStreet(((StreetFragment) getChildFragmentManager().findFragmentByTag(StreetFragment.class.getName())).getStreet());
break;
case CUISINE:
String[] cuisines = ((CuisineFragment) getChildFragmentManager().findFragmentByTag(CuisineFragment.class.getName())).getCuisines();
Editor.nativeSetSelectedCuisines(cuisines);
editMapObject();
break;
case MAP_OBJECT:
if (!setEdits())
return;
// Save object edits
if (!MwmApplication.prefs().contains(NOOB_ALERT_SHOWN))
showNoobDialog();
else
saveMapObjectEdits();
break;
}
}
}
private void saveMapObjectEdits()
{
if (Editor.nativeSaveEditedFeature())
{
Statistics.INSTANCE.trackEditorSuccess(mIsNewObject);
if (OsmOAuth.isAuthorized() || !ConnectionState.isConnected())
Utils.navigateToParent(getActivity());
else
{
final Activity parent = getActivity();
Intent intent = new Intent(parent, MwmActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra(MwmActivity.EXTRA_TASK, new MwmActivity.ShowAuthorizationTask());
parent.startActivity(intent);
if (parent instanceof MwmActivity)
((MwmActivity) parent).customOnNavigateUp();
else
parent.finish();
}
}
else
{
Statistics.INSTANCE.trackEditorError(mIsNewObject);
UiUtils.showAlertDialog(getActivity(), R.string.downloader_no_space_title);
}
}
private void showMistakeDialog(@StringRes int resId)
{
new AlertDialog.Builder(getActivity())
.setMessage(resId)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void showNoobDialog()
{
new AlertDialog.Builder(getActivity())
.setTitle(R.string.editor_share_to_all_dialog_title)
.setMessage(getString(R.string.editor_share_to_all_dialog_message_1)
+ " " + getString(R.string.editor_share_to_all_dialog_message_2))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
MwmApplication.prefs().edit()
.putBoolean(NOOB_ALERT_SHOWN, true)
.apply();
// Save note
final String note = ((EditorFragment) getChildFragmentManager().findFragmentByTag(EditorFragment.class.getName())).getDescription();
if (note.length() != 0)
Editor.nativeCreateNote(note);
// Save edits
saveMapObjectEdits();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
public void setStreet(LocalizedStreet street)
{
Editor.nativeSetStreet(street);
editMapObject();
}
public boolean addingNewObject()
{
return mIsNewObject;
}
@Override
public void onLanguageSelected(Language lang)
{
String name = "";
if (lang.code.equals(Language.DEFAULT_LANG_CODE))
{
fillNames(false /* addFakes */);
name = Editor.nativeGetDefaultName();
Editor.nativeEnableNamesAdvancedMode();
}
addName(Editor.nativeMakeLocalizedName(lang.code, name));
editMapObject(true /* focusToLastName */);
}
} |
package community.revteltech.nfc;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import android.provider.Settings;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import android.app.PendingIntent;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.TagTechnology;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Parcelable;
import android.os.Bundle;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.*;
class NfcManager extends ReactContextBaseJavaModule implements ActivityEventListener, LifecycleEventListener {
private static final String LOG_TAG = "ReactNativeNfcManager";
private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
private final ArrayList<String[]> techLists = new ArrayList<String[]>();
private Context context;
private ReactApplicationContext reactContext;
private Boolean isForegroundEnabled = false;
private Boolean isResumed = false;
private WriteNdefRequest writeNdefRequest = null;
private TagTechnologyRequest techRequest = null;
private Tag tag = null;
// Use NFC reader mode instead of listening to a dispatch
private Boolean isReaderModeEnabled = false;
private int readerModeFlags = 0;
class WriteNdefRequest {
NdefMessage message;
Callback callback;
boolean format;
boolean formatReadOnly;
WriteNdefRequest(NdefMessage message, Callback callback, boolean format, boolean formatReadOnly) {
this.message = message;
this.callback = callback;
this.format = format;
this.formatReadOnly = formatReadOnly;
}
}
public NfcManager(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext;
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
reactContext.addLifecycleEventListener(this);
Log.d(LOG_TAG, "NfcManager created");
}
@Override
public String getName() {
return "NfcManager";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("MIFARE_BLOCK_SIZE", MifareClassic.BLOCK_SIZE);
constants.put("MIFARE_ULTRALIGHT_PAGE_SIZE", MifareUltralight.PAGE_SIZE);
constants.put("MIFARE_ULTRALIGHT_TYPE", MifareUltralight.TYPE_ULTRALIGHT);
constants.put("MIFARE_ULTRALIGHT_TYPE_C", MifareUltralight.TYPE_ULTRALIGHT_C);
constants.put("MIFARE_ULTRALIGHT_TYPE_UNKNOWN", MifareUltralight.TYPE_UNKNOWN);
return constants;
}
private boolean hasPendingRequest() {
return writeNdefRequest != null || techRequest != null;
}
@ReactMethod
public void cancelTechnologyRequest(Callback callback) {
synchronized(this) {
if (techRequest != null) {
techRequest.close();
techRequest.getPendingCallback().invoke("cancelled");
techRequest = null;
callback.invoke();
} else {
// explicitly allow this
callback.invoke();
}
}
}
@ReactMethod
public void requestTechnology(String tech, Callback callback) {
synchronized(this) {
if (!isForegroundEnabled) {
callback.invoke("you should requestTagEvent first");
return;
}
if (hasPendingRequest()) {
callback.invoke("You can only issue one request at a time");
} else {
techRequest = new TagTechnologyRequest(tech, callback);
}
}
}
@ReactMethod
public void requestTechnologies(ReadableArray techs, Callback callback) {
synchronized(this) {
if (!isForegroundEnabled) {
callback.invoke("you should requestTagEvent first");
return;
}
if (hasPendingRequest()) {
callback.invoke("You can only issue one request at a time");
} else {
techRequest = new TagTechnologyRequest(techs.toArrayList(), callback);
}
}
}
@ReactMethod
public void closeTechnology(Callback callback) {
synchronized(this) {
if (techRequest != null) {
techRequest.close();
techRequest = null;
callback.invoke();
} else {
// explicitly allow this
callback.invoke();
}
}
}
@ReactMethod
public void getTag(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
TagTechnology tagTech = techRequest.getTechHandle();
Tag tag = tagTech.getTag();
WritableMap parsed = tag2React(tag);
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getTag fail");
callback.invoke("getTag fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getCachedNdefMessage(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = Ndef.get(techRequest.getTechHandle().getTag());
WritableMap parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getCachedNdefMessage fail");
callback.invoke("getCachedNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getNdefMessage(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = Ndef.get(techRequest.getTechHandle().getTag());
WritableMap parsed = ndef2React(null, new NdefMessage[] { ndef.getNdefMessage() });
callback.invoke(null, parsed);
} catch (Exception ex) {
Log.d(LOG_TAG, "getNdefMessage fail");
callback.invoke("getNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void writeNdefMessage(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = (Ndef)techRequest.getTechHandle();
byte[] bytes = rnArrayToBytes(rnArray);
ndef.writeNdefMessage(new NdefMessage(bytes));
callback.invoke();
} catch (Exception ex) {
Log.d(LOG_TAG, "writeNdefMessage fail");
callback.invoke("writeNdefMessage fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
private void mifareClassicAuthenticate(char type, int sector, ReadableArray key, Callback callback) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicAuthenticate fail: TYPE_UNKNOWN");
return;
} else if (sector >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicAuthenticate fail: invalid sector %d (max %d)", sector, mifareTag.getSectorCount());
callback.invoke(msg);
return;
} else if (key.size() != 6) {
// Invalid key length
String msg = String.format("mifareClassicAuthenticate fail: invalid key (needs length 6 but has %d characters)", key.size());
callback.invoke(msg);
return;
}
boolean result = false;
if (type == 'A') {
result = mifareTag.authenticateSectorWithKeyA(sector, rnArrayToBytes(key));
} else {
result = mifareTag.authenticateSectorWithKeyB(sector, rnArrayToBytes(key));
}
if (!result) {
callback.invoke("mifareClassicAuthenticate fail: AUTH_FAIL");
return;
}
callback.invoke(null, true);
} catch (TagLostException ex) {
callback.invoke("mifareClassicAuthenticate fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicAuthenticate fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
@ReactMethod
public void mifareClassicAuthenticateA(int sector, ReadableArray key, Callback callback) {
synchronized(this) {
mifareClassicAuthenticate('A', sector, key, callback);
}
}
@ReactMethod
public void mifareClassicAuthenticateB(int sector, ReadableArray key, Callback callback) {
synchronized(this) {
mifareClassicAuthenticate('B', sector, key, callback);
}
}
@ReactMethod
public void mifareClassicGetBlockCountInSector(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicGetBlockCountInSector fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicGetBlockCountInSector fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
callback.invoke(null, mifareTag.getBlockCountInSector(sectorIndex));
} catch (Exception ex) {
callback.invoke("mifareClassicGetBlockCountInSector fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicGetSectorCount(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicGetSectorCount fail: TYPE_UNKNOWN");
return;
}
callback.invoke(null, mifareTag.getSectorCount());
} catch (Exception ex) {
callback.invoke("mifareClassicGetSectorCount fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicSectorToBlock(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicSectorToBlock fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicSectorToBlock fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
callback.invoke(null, mifareTag.sectorToBlock(sectorIndex));
} catch (Exception ex) {
callback.invoke("mifareClassicSectorToBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicReadBlock(int blockIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicReadBlock fail: TYPE_UNKNOWN");
return;
} else if (blockIndex >= mifareTag.getBlockCount()) {
// Check if in range
String msg = String.format("mifareClassicReadBlock fail: invalid block %d (max %d)", blockIndex, mifareTag.getBlockCount());
callback.invoke(msg);
return;
}
byte[] buffer = new byte[MifareClassic.BLOCK_SIZE];
buffer = mifareTag.readBlock(blockIndex);
WritableArray result = bytesToRnArray(buffer);
callback.invoke(null, result);
} catch (TagLostException ex) {
callback.invoke("mifareClassicReadBlock fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicReadBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicReadSector(int sectorIndex, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicReadSector fail: TYPE_UNKNOWN");
return;
} else if (sectorIndex >= mifareTag.getSectorCount()) {
// Check if in range
String msg = String.format("mifareClassicReadSector fail: invalid sector %d (max %d)", sectorIndex, mifareTag.getSectorCount());
callback.invoke(msg);
return;
}
WritableArray result = Arguments.createArray();
int blocks = mifareTag.getBlockCountInSector(sectorIndex);
byte[] buffer = new byte[MifareClassic.BLOCK_SIZE];
for (int i = 0; i < blocks; i++) {
buffer = mifareTag.readBlock(mifareTag.sectorToBlock(sectorIndex)+i);
appendBytesToRnArray(result, buffer);
}
callback.invoke(null, result);
} catch (TagLostException ex) {
callback.invoke("mifareClassicReadSector fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicReadSector fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareClassicWriteBlock(int blockIndex, ReadableArray block, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareClassic mifareTag = (MifareClassic) techRequest.getTechHandle();
if (mifareTag == null || mifareTag.getType() == MifareClassic.TYPE_UNKNOWN) {
// Not a mifare card, fail
callback.invoke("mifareClassicWriteBlock fail: TYPE_UNKNOWN");
return;
} else if (blockIndex >= mifareTag.getBlockCount()) {
// Check if in range
String msg = String.format("mifareClassicWriteBlock fail: invalid block %d (max %d)", blockIndex, mifareTag.getBlockCount());
callback.invoke(msg);
return;
} else if (block.size() != MifareClassic.BLOCK_SIZE) {
// Wrong block count
String msg = String.format("mifareClassicWriteBlock fail: invalid block size %d (should be %d)", block.size(), MifareClassic.BLOCK_SIZE);
callback.invoke(msg);
return;
}
byte[] buffer = rnArrayToBytes(block);
mifareTag.writeBlock(blockIndex, buffer);
callback.invoke(null, true);
} catch (TagLostException ex) {
callback.invoke("mifareClassicWriteBlock fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareClassicWriteBlock fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareUltralightReadPages(int pageOffset, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
MifareUltralight techHandle = (MifareUltralight)techRequest.getTechHandle();
byte[] resultBytes = techHandle.readPages(pageOffset);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} catch (TagLostException ex) {
callback.invoke("mifareUltralight fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareUltralight fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void mifareUltralightWritePage(int pageOffset, ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
byte[] bytes = rnArrayToBytes(rnArray);
MifareUltralight techHandle = (MifareUltralight)techRequest.getTechHandle();
techHandle.writePage(pageOffset, bytes);
callback.invoke();
return;
} catch (TagLostException ex) {
callback.invoke("mifareUltralight fail: TAG_LOST");
} catch (Exception ex) {
callback.invoke("mifareUltralight fail: " + ex.toString());
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void makeReadOnly(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
Ndef ndef = (Ndef)techRequest.getTechHandle();
boolean result = ndef.makeReadOnly();
callback.invoke(null, result);
} catch (Exception ex) {
Log.d(LOG_TAG, "makeReadOnly fail");
callback.invoke("makeReadOnly fail");
}
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void setTimeout(int timeout, Callback callback) {
synchronized (this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("MifareClassic")) {
MifareClassic techHandle = (MifareClassic) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight) baseTechHandle;
techHandle.setTimeout(timeout);
callback.invoke();
return;
}
Log.d(LOG_TAG, "setTimeout not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "setTimeout fail");
}
callback.invoke("setTimeout fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void connect(ReadableArray techs, Callback callback){
synchronized(this) {
try {
techRequest = new TagTechnologyRequest(techs.toArrayList(), callback);
techRequest.connect(this.tag);
callback.invoke(null, null);
return;
} catch (Exception ex) {
callback.invoke(ex.toString());
}
}
}
@ReactMethod
public void close(Callback callback){
synchronized(this) {
try {
techRequest.close();
callback.invoke(null, null);
return;
} catch (Exception ex) {
callback.invoke(ex.toString());
}
}
}
@ReactMethod
public void transceive(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
byte[] bytes = rnArrayToBytes(rnArray);
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcB")) {
NfcB techHandle = (NfcB)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("NfcV")) {
NfcV techHandle = (NfcV)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("MifareClassic")) {
MifareClassic techHandle = (MifareClassic) baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight)baseTechHandle;
byte[] resultBytes = techHandle.transceive(bytes);
WritableArray resultRnArray = bytesToRnArray(resultBytes);
callback.invoke(null, resultRnArray);
return;
}
Log.d(LOG_TAG, "transceive not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "transceive fail");
}
callback.invoke("transceive fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void getMaxTransceiveLength(Callback callback) {
synchronized(this) {
if (techRequest != null) {
try {
String tech = techRequest.getTechType();
TagTechnology baseTechHandle = techRequest.getTechHandle();
// TagTechnology is the base class for each tech (ex, NfcA, NfcB, IsoDep ...)
// but it doesn't provide transceive in its interface, so we need to explicitly cast it
if (tech.equals("NfcA")) {
NfcA techHandle = (NfcA)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcB")) {
NfcB techHandle = (NfcB)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcF")) {
NfcF techHandle = (NfcF)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("NfcV")) {
NfcV techHandle = (NfcV)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("IsoDep")) {
IsoDep techHandle = (IsoDep)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
} else if (tech.equals("MifareUltralight")) {
MifareUltralight techHandle = (MifareUltralight)baseTechHandle;
int max = techHandle.getMaxTransceiveLength();
callback.invoke(null, max);
return;
}
Log.d(LOG_TAG, "getMaxTransceiveLength not supported");
} catch (Exception ex) {
Log.d(LOG_TAG, "getMaxTransceiveLength fail");
}
callback.invoke("getMaxTransceiveLength fail");
} else {
callback.invoke("no tech request available");
}
}
}
@ReactMethod
public void cancelNdefWrite(Callback callback) {
synchronized(this) {
if (writeNdefRequest != null) {
writeNdefRequest.callback.invoke("cancelled");
writeNdefRequest = null;
callback.invoke();
} else {
callback.invoke("no writing request available");
}
}
}
@ReactMethod
public void requestNdefWrite(ReadableArray rnArray, ReadableMap options, Callback callback) {
synchronized(this) {
if (!isForegroundEnabled) {
callback.invoke("you should requestTagEvent first");
return;
}
if (hasPendingRequest()) {
callback.invoke("You can only issue one request at a time");
} else {
boolean format = options.getBoolean("format");
boolean formatReadOnly = options.getBoolean("formatReadOnly");
try {
NdefMessage msgToWrite;
/// the only case we allow ndef message to be null is when formatting, see:
/// https://developer.android.com/reference/android/nfc/tech/NdefFormatable.html#format(android.nfc.NdefMessage)
/// this API allows the `firstMessage` to be null
if (format && rnArray == null) {
msgToWrite = null;
} else {
byte[] bytes = rnArrayToBytes(rnArray);
msgToWrite = new NdefMessage(bytes);
}
writeNdefRequest = new WriteNdefRequest(
msgToWrite,
callback, // defer the callback
format,
formatReadOnly
);
} catch (FormatException e) {
callback.invoke("Incorrect ndef format");
}
}
}
}
@ReactMethod
public void setNdefPushMessage(ReadableArray rnArray, Callback callback) {
synchronized(this) {
if (techRequest == null && writeNdefRequest == null) {
try {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
throw new RuntimeException("cannot get current activity");
}
NdefMessage msgToPush = null;
if (rnArray != null) {
msgToPush = new NdefMessage(rnArrayToBytes(rnArray));
}
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
nfcAdapter.setNdefPushMessage(msgToPush, currentActivity);
callback.invoke();
} catch (Exception ex) {
Log.d(LOG_TAG, "sendNdefPushMessage fail, " + ex.getMessage());
callback.invoke("sendNdefPushMessage fail");
}
} else {
callback.invoke("please first cancel existing tech or write request");
}
}
}
@ReactMethod
public void start(Callback callback) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
Log.d(LOG_TAG, "start");
IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
currentActivity.registerReceiver(mReceiver, filter);
callback.invoke();
} else {
Log.d(LOG_TAG, "not support in this device");
callback.invoke("no nfc support");
}
}
@ReactMethod
public void isSupported(String tech, Callback callback){
Log.d(LOG_TAG, "isSupported");
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
if (!currentActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
callback.invoke(null, false);
return;
}
// If we ask for MifareClassic support, so some extra checks, since not all chips and devices are
// compatible with MifareClassic
// TODO: Check if it's the same case with MifareUltralight
if (tech.equals("MifareClassic")) {
if (!MifareUtil.isDeviceSupported(currentActivity)) {
callback.invoke(null, false);
return;
}
}
callback.invoke(null, true);
}
@ReactMethod
public void isEnabled(Callback callback) {
Log.d(LOG_TAG, "isEnabled");
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
if (nfcAdapter != null) {
callback.invoke(null, nfcAdapter.isEnabled());
} else {
callback.invoke(null, false);
}
}
@ReactMethod
public void goToNfcSetting(Callback callback) {
Log.d(LOG_TAG, "goToNfcSetting");
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
currentActivity.startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
callback.invoke();
}
@ReactMethod
public void getLaunchTagEvent(Callback callback) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
callback.invoke("fail to get current activity");
return;
}
Intent launchIntent = currentActivity.getIntent();
WritableMap nfcTag = parseNfcIntent(launchIntent);
callback.invoke(null, nfcTag);
}
@ReactMethod
private void registerTagEvent(String alertMessage, ReadableMap options, Callback callback) {
this.isReaderModeEnabled = options.getBoolean("isReaderModeEnabled");
this.readerModeFlags = options.getInt("readerModeFlags");
Log.d(LOG_TAG, "registerTag");
isForegroundEnabled = true;
// capture all mime-based dispatch NDEF
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
intentFilters.add(ndef);
// capture all rest NDEF, such as uri-based
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
techLists.add(new String[]{Ndef.class.getName()});
// for those without NDEF, get them as tags
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));
if (isResumed) {
enableDisableForegroundDispatch(true);
}
callback.invoke();
}
@ReactMethod
private void unregisterTagEvent(Callback callback) {
Log.d(LOG_TAG, "registerTag");
isForegroundEnabled = false;
intentFilters.clear();
if (isResumed) {
enableDisableForegroundDispatch(false);
}
callback.invoke();
}
@Override
public void onHostResume() {
Log.d(LOG_TAG, "onResume");
isResumed = true;
if (isForegroundEnabled) {
enableDisableForegroundDispatch(true);
}
}
@Override
public void onHostPause() {
Log.d(LOG_TAG, "onPause");
isResumed = false;
enableDisableForegroundDispatch(false);
}
@Override
public void onHostDestroy() {
Log.d(LOG_TAG, "onDestroy");
}
private void enableDisableForegroundDispatch(boolean enable) {
Log.i(LOG_TAG, "enableForegroundDispatch, enable = " + enable);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
Activity currentActivity = getCurrentActivity();
final NfcManager manager = this;
if (nfcAdapter != null && currentActivity != null && !currentActivity.isFinishing()) {
try {
if (isReaderModeEnabled) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
throw new RuntimeException("minSdkVersion must be Honeycomb (19) or later.");
}
if (enable) {
Log.i(LOG_TAG, "enableReaderMode");
Bundle readerModeExtras = new Bundle();
readerModeExtras.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 10000);
nfcAdapter.enableReaderMode(currentActivity, new NfcAdapter.ReaderCallback() {
@Override
public void onTagDiscovered(Tag tag) {
manager.tag = tag;
Log.d(LOG_TAG, "readerMode onTagDiscovered");
WritableMap nfcTag = null;
// if the tag contains NDEF, we want to report the content
if (Arrays.asList(tag.getTechList()).contains(Ndef.class.getName())) {
Ndef ndef = Ndef.get(tag);
nfcTag = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
} else {
nfcTag = tag2React(tag);
}
if (nfcTag != null) {
sendEvent("NfcManagerDiscoverTag", nfcTag);
}
}
}, readerModeFlags, readerModeExtras);
} else {
Log.i(LOG_TAG, "disableReaderMode");
nfcAdapter.disableReaderMode(currentActivity);
}
} else {
if (enable) {
nfcAdapter.enableForegroundDispatch(currentActivity, getPendingIntent(), getIntentFilters(), getTechLists());
} else {
nfcAdapter.disableForegroundDispatch(currentActivity);
}
}
} catch (IllegalStateException | NullPointerException e) {
Log.w(LOG_TAG, "Illegal State Exception starting NFC. Assuming application is terminating.");
}
}
}
private PendingIntent getPendingIntent() {
Activity activity = getCurrentActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
return PendingIntent.getActivity(activity, 0, intent, 0);
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
return techLists.toArray(new String[0][0]);
}
private void sendEvent(String eventName,
@Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(RCTNativeAppEventEmitter.class)
.emit(eventName, params);
}
private void sendEventWithJson(String eventName,
JSONObject json) {
try {
WritableMap map = JsonConvert.jsonToReact(json);
sendEvent(eventName, map);
} catch (JSONException ex) {
Log.d(LOG_TAG, "fireNdefEvent fail: " + ex);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "onReceive " + intent);
final String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) {
final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE,
NfcAdapter.STATE_OFF);
String stateStr = "unknown";
switch (state) {
case NfcAdapter.STATE_OFF:
stateStr = "off";
break;
case NfcAdapter.STATE_TURNING_OFF:
stateStr = "turning_off";
break;
case NfcAdapter.STATE_ON:
stateStr = "on";
break;
case NfcAdapter.STATE_TURNING_ON:
stateStr = "turning_on";
break;
}
try {
WritableMap writableMap = Arguments.createMap();
writableMap.putString("state", stateStr);
sendEvent("NfcManagerStateChanged", writableMap);
} catch (Exception ex) {
Log.d(LOG_TAG, "send nfc state change event fail: " + ex);
}
}
}
};
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
}
@Override
public void onNewIntent(Intent intent) {
Log.d(LOG_TAG, "onNewIntent " + intent);
WritableMap nfcTag = parseNfcIntent(intent);
if (nfcTag != null) {
sendEvent("NfcManagerDiscoverTag", nfcTag);
}
}
private WritableMap parseNfcIntent(Intent intent) {
Log.d(LOG_TAG, "parseIntent " + intent);
String action = intent.getAction();
Log.d(LOG_TAG, "action " + action);
if (action == null) {
return null;
}
WritableMap parsed = null;
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
synchronized(this) {
if (writeNdefRequest != null) {
writeNdef(
tag,
writeNdefRequest
);
writeNdefRequest = null;
// explicitly return null, to avoid extra detection
return null;
} else if (techRequest != null) {
if (!techRequest.isConnected()) {
boolean result = techRequest.connect(tag);
if (result) {
techRequest.getPendingCallback().invoke();
} else {
techRequest.getPendingCallback().invoke("fail to connect tag");
techRequest = null;
}
}
// explicitly return null, to avoid extra detection
return null;
}
}
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Ndef ndef = Ndef.get(tag);
Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
parsed = ndef2React(ndef, messages);
} else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
// if the tag contains NDEF, we want to report the content
if (Arrays.asList(tag.getTechList()).contains(Ndef.class.getName())) {
Ndef ndef = Ndef.get(tag);
parsed = ndef2React(ndef, new NdefMessage[] { ndef.getCachedNdefMessage() });
} else {
parsed = tag2React(tag);
}
} else if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
parsed = tag2React(tag);
}
return parsed;
}
private WritableMap tag2React(Tag tag) {
try {
JSONObject json = Util.tagToJSON(tag);
return JsonConvert.jsonToReact(json);
} catch (JSONException ex) {
return null;
}
}
private WritableMap ndef2React(Ndef ndef, Parcelable[] messages) {
try {
JSONObject json = buildNdefJSON(ndef, messages);
return JsonConvert.jsonToReact(json);
} catch (JSONException ex) {
return null;
}
}
JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
JSONObject json = Util.ndefToJSON(ndef);
// ndef is null for peer-to-peer
// ndef and messages are null for ndef format-able
if (ndef == null && messages != null) {
try {
if (messages.length > 0) {
NdefMessage message = (NdefMessage) messages[0];
json.put("ndefMessage", Util.messageToJSON(message));
// guessing type, would prefer a more definitive way to determine type
json.put("type", "NDEF");
}
if (messages.length > 1) {
Log.d(LOG_TAG, "Expected one ndefMessage but found " + messages.length);
}
} catch (JSONException e) {
// shouldn't happen
Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
}
}
return json;
}
private void writeNdef(Tag tag, WriteNdefRequest request) {
NdefMessage message = request.message;
Callback callback = request.callback;
boolean formatReadOnly = request.formatReadOnly;
boolean format = request.format;
if (format || formatReadOnly) {
try {
Log.d(LOG_TAG, "ready to writeNdef");
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable == null) {
callback.invoke("fail to apply ndef formatable tech");
} else {
Log.d(LOG_TAG, "ready to format ndef, seriously");
formatable.connect();
if (formatReadOnly) {
formatable.formatReadOnly(message);
} else {
formatable.format(message);
}
callback.invoke();
}
} catch (Exception ex) {
callback.invoke("writeNdef fail: " + ex.getMessage());
}
} else {
try {
Log.d(LOG_TAG, "ready to writeNdef");
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
callback.invoke("fail to apply ndef tech");
} else if (!ndef.isWritable()) {
callback.invoke("tag is not writeable");
} else if (ndef.getMaxSize() < message.toByteArray().length) {
callback.invoke("tag size is not enough");
} else {
Log.d(LOG_TAG, "ready to writeNdef, seriously");
ndef.connect();
ndef.writeNdefMessage(message);
callback.invoke();
}
} catch (Exception ex) {
callback.invoke("writeNdef fail: " + ex.getMessage());
}
}
}
private static byte[] rnArrayToBytes(ReadableArray rArray) {
byte[] bytes = new byte[rArray.size()];
for (int i = 0; i < rArray.size(); i++) {
bytes[i] = (byte)(rArray.getInt(i) & 0xff);
}
return bytes;
}
private static WritableArray bytesToRnArray(byte[] bytes) {
return appendBytesToRnArray(Arguments.createArray(), bytes);
}
private static WritableArray appendBytesToRnArray(WritableArray value, byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
value.pushInt((bytes[i] & 0xFF));
}
return value;
}
} |
package dog.craftz.sqlite_2;
import com.facebook.react.bridge.NativeArray;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import android.content.Context;
import android.util.Log;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Handler;
import android.os.HandlerThread;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RNSqlite2Module extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
private static final boolean DEBUG_MODE = false;
private static final String TAG = RNSqlite2Module.class.getSimpleName();
private static final Object[][] EMPTY_ROWS = new Object[][]{};
private static final String[] EMPTY_COLUMNS = new String[]{};
private static final SQLitePLuginResult EMPTY_RESULT = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null);
private static final Map<String, SQLiteDatabase> DATABASES = new HashMap<String, SQLiteDatabase>();
private final Handler backgroundHandler = createBackgroundHandler();
/**
* Linked activity
*/
protected Context context = null;
public RNSqlite2Module(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext.getApplicationContext();
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNSqlite2";
}
private Handler createBackgroundHandler() {
HandlerThread thread = new HandlerThread("SQLitePlugin BG Thread");
thread.start();
return new Handler(thread.getLooper());
}
@ReactMethod
public void test(String message, Promise promise) {
Log.d("example", "escaped: " + message.replaceAll("\u0000", "%0000").replaceAll("\u0001", "%0001"));
message = unescapeBlob(message);
Log.d("example", "unescaped: " + message.replaceAll("\u0000", "%0000").replaceAll("\u0001", "%0001"));
promise.resolve(message + "\u0000" + "hoge");
}
@ReactMethod
public void exec(final String dbName, final ReadableArray queries, final Boolean readOnly, final Promise promise) {
debug("test called: %s", dbName);
backgroundHandler.post(new Runnable() {
@Override
public void run() {
try {
int numQueries = queries.size();
SQLitePLuginResult[] results = new SQLitePLuginResult[numQueries];
SQLiteDatabase db = getDatabase(dbName);
for (int i = 0; i < numQueries; i++) {
ReadableArray sqlQuery = queries.getArray(i);
String sql = sqlQuery.getString(0);
String[] bindArgs = convertParamsToStringArray(sqlQuery.getArray(1));
try {
if (isSelect(sql)) {
results[i] = doSelectInBackgroundAndPossiblyThrow(sql, bindArgs, db);
} else { // update/insert/delete
if (readOnly) {
results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, new ReadOnlyException());
} else {
results[i] = doUpdateInBackgroundAndPossiblyThrow(sql, bindArgs, db);
}
}
} catch (Throwable e) {
if (DEBUG_MODE) {
e.printStackTrace();
}
results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e);
}
}
NativeArray data = pluginResultsToPrimitiveData(results);
promise.resolve(data);
} catch (Exception e) {
promise.reject("SQLiteError", e);
}
}
});
}
// do a update/delete/insert operation
private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
SQLiteDatabase db) {
debug("\"run\" query: %s", sql);
SQLiteStatement statement = null;
try {
statement = db.compileStatement(sql);
debug("compiled statement");
if (bindArgs != null) {
statement.bindAllArgsAsStrings(bindArgs);
}
debug("bound args");
if (isInsert(sql)) {
debug("type: insert");
long insertId = statement.executeInsert();
int rowsAffected = insertId >= 0 ? 1 : 0;
return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null);
} else if (isDelete(sql) || isUpdate(sql)) {
debug("type: update/delete");
int rowsAffected = statement.executeUpdateDelete();
return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null);
} else {
// in this case, we don't need rowsAffected or insertId, so we can have a slight
// perf boost by just executing the query
debug("type: drop/create/etc.");
statement.execute();
return EMPTY_RESULT;
}
} finally {
if (statement != null) {
statement.close();
}
}
}
// do a select operation
private SQLitePLuginResult doSelectInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
SQLiteDatabase db) {
debug("\"all\" query: %s", sql);
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, bindArgs);
int numRows = cursor.getCount();
if (numRows == 0) {
return EMPTY_RESULT;
}
int numColumns = cursor.getColumnCount();
Object[][] rows = new Object[numRows][];
String[] columnNames = cursor.getColumnNames();
for (int i = 0; cursor.moveToNext(); i++) {
Object[] row = new Object[numColumns];
for (int j = 0; j < numColumns; j++) {
row[j] = getValueFromCursor(cursor, j, cursor.getType(j));
}
rows[i] = row;
}
debug("returning %d rows", numRows);
return new SQLitePLuginResult(rows, columnNames, 0, 0, null);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Object getValueFromCursor(Cursor cursor, int index, int columnType) {
switch (columnType) {
case Cursor.FIELD_TYPE_FLOAT:
return cursor.getFloat(index);
case Cursor.FIELD_TYPE_INTEGER:
return cursor.getInt(index);
case Cursor.FIELD_TYPE_BLOB:
// convert byte[] to binary string; it's good enough, because
// WebSQL doesn't support blobs anyway
return new String(cursor.getBlob(index));
case Cursor.FIELD_TYPE_STRING:
return cursor.getString(index);
}
return null;
}
private SQLiteDatabase getDatabase(String name) {
SQLiteDatabase database = DATABASES.get(name);
if (database == null) {
if (":memory:".equals(name)) {
database = SQLiteDatabase.openOrCreateDatabase(name, null);
} else {
File file = new File(this.context.getFilesDir(), name);
database = SQLiteDatabase.openOrCreateDatabase(file, null);
}
DATABASES.put(name, database);
}
return database;
}
private static void debug(String line, Object... format) {
if (DEBUG_MODE) {
Log.d(TAG, String.format(line, format));
}
}
private static NativeArray pluginResultsToPrimitiveData(SQLitePLuginResult[] results) {
WritableNativeArray list = new WritableNativeArray();
for (int i = 0; i < results.length; i++) {
SQLitePLuginResult result = results[i];
WritableNativeArray arr = convertPluginResultToArray(result);
list.pushArray(arr);
}
return list;
}
private static WritableNativeArray convertPluginResultToArray(SQLitePLuginResult result) {
WritableNativeArray data = new WritableNativeArray();
if (result.error != null) {
data.pushString(result.error.getMessage());
} else {
data.pushNull();
}
data.pushInt((int) result.insertId);
data.pushInt(result.rowsAffected);
// column names
WritableNativeArray columnNames = new WritableNativeArray();
for (int i = 0; i < result.columns.length; i++) {
columnNames.pushString(result.columns[i]);
}
data.pushArray(columnNames);
// rows
WritableNativeArray rows = new WritableNativeArray();
for (int i = 0; i < result.rows.length; i++) {
Object[] values = result.rows[i];
// row content
WritableNativeArray rowContent = new WritableNativeArray();
for (int j = 0; j < values.length; j++) {
Object value = values[j];
if (value == null) {
rowContent.pushNull();
} else if (value instanceof String) {
rowContent.pushString((String)value);
} else if (value instanceof Boolean) {
rowContent.pushBoolean((Boolean)value);
} else {
Number v = (Number)value;
rowContent.pushDouble(v.doubleValue());
}
}
rows.pushArray(rowContent);
}
data.pushArray(rows);
return data;
}
private static boolean isSelect(String str) {
return startsWithCaseInsensitive(str, "select");
}
private static boolean isInsert(String str) {
return startsWithCaseInsensitive(str, "insert");
}
private static boolean isUpdate(String str) {
return startsWithCaseInsensitive(str, "update");
}
private static boolean isDelete(String str) {
return startsWithCaseInsensitive(str, "delete");
}
// identify an "insert"/"select" query more efficiently than with a Pattern
private static boolean startsWithCaseInsensitive(String str, String substr) {
int i = -1;
int len = str.length();
while (++i < len) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
break;
}
}
int j = -1;
int substrLen = substr.length();
while (++j < substrLen) {
if (j + i >= len) {
return false;
}
char ch = str.charAt(j + i);
if (Character.toLowerCase(ch) != substr.charAt(j)) {
return false;
}
}
return true;
}
private static String[] jsonArrayToStringArray(String jsonArray) throws JSONException {
JSONArray array = new JSONArray(jsonArray);
int len = array.length();
String[] res = new String[len];
for (int i = 0; i < len; i++) {
res[i] = array.getString(i);
}
return res;
}
private static String[] convertParamsToStringArray(ReadableArray paramArray) {
int len = paramArray.size();
String[] res = new String[len];
for (int i = 0; i < len; i++) {
ReadableType type = paramArray.getType(i);
if (type == ReadableType.String) {
String unescaped = unescapeBlob(paramArray.getString(i));
res[i] = unescaped;
} else if (type == ReadableType.Boolean) {
res[i] = paramArray.getBoolean(i) ? "0" : "1";
} else if (type == ReadableType.Null) {
res[i] = "NULL";
} else if (type == ReadableType.Number) {
res[i] = Double.toString(paramArray.getDouble(i));
}
}
return res;
}
private static String unescapeBlob(String str) {
return str.replaceAll("\u0001\u0001", "\u0000")
.replaceAll("\u0001\u0002", "\u0001")
.replaceAll("\u0002\u0002", "\u0002");
}
private static class SQLitePLuginResult {
public final Object[][] rows;
public final String[] columns;
public final int rowsAffected;
public final long insertId;
public final Throwable error;
public SQLitePLuginResult(Object[][] rows, String[] columns,
int rowsAffected, long insertId, Throwable error) {
this.rows = rows;
this.columns = columns;
this.rowsAffected = rowsAffected;
this.insertId = insertId;
this.error = error;
}
}
private static class ReadOnlyException extends Exception {
public ReadOnlyException() {
super("could not prepare statement (23 not authorized)");
}
}
} |
package com.flowpowered.caustic.api.model;
import java.util.HashSet;
import java.util.Set;
import com.flowpowered.caustic.api.Material;
import com.flowpowered.caustic.api.data.UniformHolder;
import com.flowpowered.caustic.api.gl.VertexArray;
import com.flowpowered.math.imaginary.Quaternionf;
import com.flowpowered.math.matrix.Matrix4f;
import com.flowpowered.math.vector.Vector3f;
/**
* Represents a model. Each model has it's own position and rotation and set of uniforms. The vertex array provides the vertex data (mesh), while the material provides uniforms and textures for the
* shader.
*/
public class Model implements Comparable<Model> {
// Vertex array
private VertexArray vertexArray;
// Material
private Material material;
// Position and rotation properties
private Vector3f position = new Vector3f(0, 0, 0);
private Vector3f scale = new Vector3f(1, 1, 1);
private Quaternionf rotation = new Quaternionf();
private Matrix4f matrix = new Matrix4f();
private boolean updateMatrix = true;
// Model uniforms
private final UniformHolder uniforms = new UniformHolder();
// Optional parent model
private Model parent = null;
private final Set<Model> children = new HashSet<>();
private Matrix4f lastParentMatrix = null;
private Matrix4f childMatrix = null;
/**
* An empty constructor for child classes only.
*/
protected Model() {
}
/**
* Constructs a new model from the provided one. The vertex array and material are reused. No information is copied.
*
* @param model The model to derive this one from
*/
protected Model(Model model) {
this.vertexArray = model.getVertexArray();
this.material = model.getMaterial();
uniforms.addAll(model.uniforms);
}
/**
* Constructs a new model from the vertex array and material.
*
* @param vertexArray The vertex array
* @param material The material
*/
public Model(VertexArray vertexArray, Material material) {
if (vertexArray == null) {
throw new IllegalArgumentException("Vertex array cannot be null");
}
if (material == null) {
throw new IllegalArgumentException("Material cannot be null");
}
vertexArray.checkCreated();
this.vertexArray = vertexArray;
this.material = material;
}
/**
* Uploads the model's uniforms to its material's program.
*/
public void uploadUniforms() {
material.getProgram().upload(uniforms);
}
/**
* Draws the model to the screen.
*/
public void render() {
if (vertexArray == null) {
throw new IllegalStateException("Vertex array has not been set");
}
vertexArray.draw();
}
/**
* Returns the model's vertex array.
*
* @return The vertex array
*/
public VertexArray getVertexArray() {
return vertexArray;
}
/**
* Sets the vertex array for this model.
*
* @param vertexArray The vertex array to use
*/
public void setVertexArray(VertexArray vertexArray) {
if (vertexArray == null) {
throw new IllegalArgumentException("Vertex array cannot be null");
}
vertexArray.checkCreated();
this.vertexArray = vertexArray;
}
/**
* Returns the model's material.
*
* @return The material
*/
public Material getMaterial() {
return material;
}
/**
* Sets the model's material.
*
* @param material The material
*/
public void setMaterial(Material material) {
if (material == null) {
throw new IllegalArgumentException("Material cannot be null");
}
this.material = material;
}
/**
* Returns the transformation matrix that represent the model's current scale, rotation and position.
*
* @return The transformation matrix
*/
public Matrix4f getMatrix() {
if (updateMatrix) {
final Matrix4f matrix = Matrix4f.createScaling(scale.toVector4(1)).rotate(rotation).translate(position);
if (parent == null) {
this.matrix = matrix;
} else {
childMatrix = matrix;
}
updateMatrix = false;
}
if (parent != null) {
final Matrix4f parentMatrix = parent.getMatrix();
if (parentMatrix != lastParentMatrix) {
matrix = parentMatrix.mul(childMatrix);
lastParentMatrix = parentMatrix;
}
}
return matrix;
}
/**
* Gets the model position.
*
* @return The model position
*/
public Vector3f getPosition() {
return position;
}
/**
* Sets the model position.
*
* @param position The model position
*/
public void setPosition(Vector3f position) {
this.position = position;
updateMatrix = true;
}
/**
* Gets the model rotation.
*
* @return The model rotation
*/
public Quaternionf getRotation() {
return rotation;
}
/**
* Sets the model rotation.
*
* @param rotation The model rotation
*/
public void setRotation(Quaternionf rotation) {
this.rotation = rotation;
updateMatrix = true;
}
/**
* Gets the model scale.
*
* @return The model scale
*/
public Vector3f getScale() {
return scale;
}
/**
* Sets the model scale.
*
* @param scale The model scale
*/
public void setScale(Vector3f scale) {
this.scale = scale;
updateMatrix = true;
}
/**
* Returns an instance of this model. The model shares the same vertex array and material as the original one, but different position information and uniform holder.
*
* @return The instanced model
*/
public Model getInstance() {
return new Model(this);
}
/**
* Returns the model's uniforms
*
* @return The uniforms
*/
public UniformHolder getUniforms() {
return uniforms;
}
/**
* Returns the parent model. This model's position, rotation and scale are relative to that model if not null.
*
* @return The parent model, can be null for no parent
*/
public Model getParent() {
return parent;
}
/**
* Returns the children models.
*
* @return The children models
*/
public Set<Model> getChildren() {
return children;
}
/**
* Sets the parent model. This model's position, rotation and scale will be relative to that model if not null.
*
* @param parent The parent model, or null for no parent
*/
public void setParent(Model parent) {
if (parent == this) {
throw new IllegalArgumentException("The model can't be its own parent");
}
if (parent == null) {
this.parent.children.remove(this);
} else {
parent.children.add(this);
}
this.parent = parent;
}
@Override
public int compareTo(Model that) {
return material.compareTo(that.material);
}
} |
package com.vrg.rapid;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HostAndPort;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.vrg.rapid.monitoring.ILinkFailureDetectorFactory;
import com.vrg.rapid.pb.JoinMessage;
import com.vrg.rapid.pb.JoinResponse;
import com.vrg.rapid.pb.JoinStatusCode;
import com.vrg.rapid.pb.Metadata;
import com.vrg.rapid.pb.NodeId;
import io.grpc.ClientInterceptor;
import io.grpc.ExperimentalApi;
import io.grpc.Internal;
import io.grpc.ServerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* The public API for Rapid. Users create Cluster objects using either Cluster.start()
* or Cluster.join(), depending on whether the user is starting a new cluster or not:
*
* <pre>
* {@code
* HostAndPort seedAddress = HostAndPort.fromString("127.0.0.1", 1234);
* Cluster c = Cluster.Builder(seedAddress).start();
* ...
* HostAndPort joinerAddress = HostAndPort.fromString("127.0.0.1", 1235);
* Cluster c = Cluster.Builder(joinerAddress).join(seedAddress);
* }
* </pre>
*
* The API does not yet support a node, as identified by a hostname and port, to
* be part of multiple separate clusters.
*/
public final class Cluster {
private static final Logger LOG = LoggerFactory.getLogger(Cluster.class);
private static final int K = 10;
private static final int H = 9;
private static final int L = 4;
private static final int RETRIES = 5;
private final MembershipService membershipService;
private final RpcServer rpcServer;
private final SharedResources sharedResources;
private final HostAndPort listenAddress;
private Cluster(final RpcServer rpcServer,
final MembershipService membershipService,
final SharedResources sharedResources,
final HostAndPort listenAddress) {
this.membershipService = membershipService;
this.rpcServer = rpcServer;
this.sharedResources = sharedResources;
this.listenAddress = listenAddress;
}
public static class Builder {
private final HostAndPort listenAddress;
@Nullable private ILinkFailureDetectorFactory linkFailureDetector = null;
private Metadata metadata = Metadata.getDefaultInstance();
private List<ServerInterceptor> serverInterceptors = Collections.emptyList();
private List<ClientInterceptor> clientInterceptors = Collections.emptyList();
private RpcClient.Conf conf = new RpcClient.Conf();
private final Map<ClusterEvents, List<Consumer<List<NodeStatusChange>>>> subscriptions =
new EnumMap<>(ClusterEvents.class);
/**
* Instantiates a builder for a Rapid Cluster node that will listen on the given {@code listenAddress}
*
* @param listenAddress The listen address of the node being instantiated
*/
public Builder(final HostAndPort listenAddress) {
this.listenAddress = listenAddress;
}
/**
* Set static application-specific metadata that is associated with the node being instantiated.
* This may include tags like "role":"frontend".
*
* @param metadata A map specifying a set of key-value tags.
*/
@ExperimentalApi
public Builder setMetadata(final Map<String, ByteString> metadata) {
Objects.requireNonNull(metadata);
this.metadata = Metadata.newBuilder().putAllMetadata(metadata).build();
return this;
}
/**
* Set a link failure detector to use for monitors to watch their monitorees.
*
* @param linkFailureDetector A link failure detector used as input for Rapid's failure detection.
*/
@ExperimentalApi
public Builder setLinkFailureDetectorFactory(final ILinkFailureDetectorFactory linkFailureDetector) {
Objects.requireNonNull(linkFailureDetector);
this.linkFailureDetector = linkFailureDetector;
return this;
}
/**
* This is used to register subscriptions for different events
*/
@ExperimentalApi
public Builder addSubscription(final ClusterEvents event,
final Consumer<List<NodeStatusChange>> callback) {
this.subscriptions.computeIfAbsent(event, k -> new ArrayList<>());
this.subscriptions.get(event).add(callback);
return this;
}
/**
* This is used by tests to inject message drop interceptors at the RpcServer.
*/
@Internal
Builder setServerInterceptors(final List<ServerInterceptor> interceptors) {
this.serverInterceptors = interceptors;
return this;
}
/**
* This is used by tests to inject message drop interceptors at the client channels.
*/
@Internal
Builder setClientInterceptors(final List<ClientInterceptor> interceptors) {
this.clientInterceptors = interceptors;
return this;
}
/**
* This is used to configure RpcClient properties
*/
@Internal
Builder setRpcClientConf(final RpcClient.Conf conf) {
this.conf = conf;
return this;
}
/**
* Joins an existing cluster, using {@code seedAddress} to bootstrap.
*
* @param seedAddress Seed node for the bootstrap protocol
* @throws IOException Thrown if we cannot successfully start a server
*/
public Cluster join(final HostAndPort seedAddress) throws IOException, InterruptedException {
return joinCluster(seedAddress, this.listenAddress, this.linkFailureDetector, this.metadata,
this.serverInterceptors, this.clientInterceptors, this.conf, this.subscriptions);
}
/**
* Start a cluster without joining. Required to bootstrap a seed node.
*
* @throws IOException Thrown if we cannot successfully start a server
*/
public Cluster start() throws IOException {
return startCluster(this.listenAddress, this.linkFailureDetector, this.metadata, this.serverInterceptors,
this.conf, this.subscriptions);
}
}
private static Cluster joinCluster(final HostAndPort seedAddress, final HostAndPort listenAddress,
@Nullable final ILinkFailureDetectorFactory linkFailureDetector,
final Metadata metadata,
final List<ServerInterceptor> serverInterceptors,
final List<ClientInterceptor> clientInterceptors,
final RpcClient.Conf conf,
final Map<ClusterEvents, List<Consumer<List<NodeStatusChange>>>> subscriptions)
throws IOException, InterruptedException {
NodeId currentIdentifier = Utils.nodeIdFromUUID(UUID.randomUUID());
final SharedResources sharedResources = new SharedResources(listenAddress);
final RpcServer server = new RpcServer(listenAddress, sharedResources);
final RpcClient joinerClient = new RpcClient(listenAddress, clientInterceptors, sharedResources, conf);
server.startServer(serverInterceptors);
boolean didPreviousJoinSucceed = false;
for (int attempt = 0; attempt < RETRIES; attempt++) {
// First, get the configuration ID and the monitors to contact from the seed node.
final JoinResponse joinPhaseOneResult;
try {
joinPhaseOneResult = joinerClient.sendJoinMessage(seedAddress,
listenAddress, currentIdentifier).get();
} catch (final ExecutionException e) {
LOG.error("Join message to seed {} returned an exception: {}", seedAddress, e.getCause());
continue;
}
assert joinPhaseOneResult != null;
switch (joinPhaseOneResult.getStatusCode()) {
case CONFIG_CHANGED:
case UUID_ALREADY_IN_RING:
currentIdentifier = Utils.nodeIdFromUUID(UUID.randomUUID());
continue;
case MEMBERSHIP_REJECTED:
LOG.error("Membership rejected by {}. Quitting.", joinPhaseOneResult.getSender());
throw new JoinException("Membership rejected");
case HOSTNAME_ALREADY_IN_RING:
/*
* This is a special case. If the joinPhase2 request times out before the join confirmation
* arrives from a monitor, a client may re-try a join by contacting the seed and get this response.
* It should simply get the configuration streamed to it. To do that, that client retries the
* join protocol but with a configuration id of -1.
*/
LOG.error("Hostname already in configuration {}", joinPhaseOneResult.getConfigurationId());
didPreviousJoinSucceed = true;
break;
case SAFE_TO_JOIN:
break;
default:
throw new JoinException("Unrecognized status code");
}
// -1 if we got a HOSTNAME_ALREADY_IN_RING status code in phase 1. This means we only need to ask
// monitors to stream us a configuration.
final long configurationToJoin = didPreviousJoinSucceed ? -1 : joinPhaseOneResult.getConfigurationId();
if (attempt > 0) {
LOG.info("{} is retrying a join under a new configuration {}",
listenAddress, configurationToJoin);
}
// We have the list of monitors. Now contact them as part of phase 2.
final List<HostAndPort> monitorList = joinPhaseOneResult.getHostsList().stream()
.map(HostAndPort::fromString)
.collect(Collectors.toList());
final Map<HostAndPort, List<Integer>> ringNumbersPerMonitor = new HashMap<>(K);
// Batch together requests to the same node.
int ringNumber = 0;
for (final HostAndPort monitor: monitorList) {
ringNumbersPerMonitor.computeIfAbsent(monitor, k -> new ArrayList<>()).add(ringNumber);
ringNumber++;
}
final List<ListenableFuture<JoinResponse>> responseFutures = new ArrayList<>();
for (final Map.Entry<HostAndPort, List<Integer>> entry: ringNumbersPerMonitor.entrySet()) {
final JoinMessage msg = JoinMessage.newBuilder()
.setSender(listenAddress.toString())
.setNodeId(currentIdentifier)
.setMetadata(metadata)
.setConfigurationId(configurationToJoin)
.addAllRingNumber(entry.getValue()).build();
LOG.trace("{} is sending a join-p2 to {} for configuration {}",
listenAddress, entry.getKey(), configurationToJoin);
final ListenableFuture<JoinResponse> call = joinerClient.sendJoinPhase2Message(entry.getKey(), msg);
responseFutures.add(call);
}
// The returned list of responses must contain the full configuration (hosts and identifiers) we just
// joined. Else, there's an error and we throw an exception.
try {
// Unsuccessful responses will be null.
final List<JoinResponse> responses = Futures.successfulAsList(responseFutures).get();
for (final JoinResponse response: responses) {
if (response == null) {
LOG.info("Received a null response.");
continue;
}
if (response.getStatusCode() == JoinStatusCode.MEMBERSHIP_REJECTED) {
LOG.info("Membership rejected by {}. Quitting.", response.getSender());
continue;
}
if (response.getStatusCode() == JoinStatusCode.SAFE_TO_JOIN
&& response.getConfigurationId() != configurationToJoin) {
// Safe to proceed. Extract the list of hosts and identifiers from the message,
// assemble a MembershipService object and start an RpcServer.
final List<HostAndPort> allHosts = response.getHostsList().stream()
.map(HostAndPort::fromString)
.collect(Collectors.toList());
final List<NodeId> identifiersSeen = response.getIdentifiersList();
final Map<String, Metadata> allMetadata = response.getClusterMetadataMap();
assert !identifiersSeen.isEmpty();
assert !allHosts.isEmpty();
final MembershipView membershipViewFinal =
new MembershipView(K, identifiersSeen, allHosts);
final WatermarkBuffer watermarkBuffer = new WatermarkBuffer(K, H, L);
MembershipService.Builder msBuilder =
new MembershipService.Builder(listenAddress, watermarkBuffer, membershipViewFinal,
sharedResources);
if (linkFailureDetector != null) {
msBuilder = msBuilder.setLinkFailureDetector(linkFailureDetector);
}
final MembershipService membershipService = msBuilder.setRpcClient(joinerClient)
.setMetadata(allMetadata)
.setSubscriptions(subscriptions)
.build();
server.setMembershipService(membershipService);
if (LOG.isTraceEnabled()) {
LOG.trace("{} has monitors {}", listenAddress,
membershipViewFinal.getMonitorsOf(listenAddress));
LOG.trace("{} has monitorees {}", listenAddress,
membershipViewFinal.getMonitorsOf(listenAddress));
}
return new Cluster(server, membershipService, sharedResources, listenAddress);
}
}
} catch (final ExecutionException e) {
LOG.error("JoinPhaseTwo request by {} for configuration {} threw an exception. Retrying. {}",
listenAddress, configurationToJoin, e.getMessage());
}
}
server.stopServer();
throw new JoinException("Join attempt unsuccessful " + listenAddress);
}
/**
* Start a cluster without joining. Required to bootstrap a seed node.
*
* @param listenAddress Address to bind to after successful bootstrap
* @param linkFailureDetector a list of checks to perform before a monitor processes a join phase two message
* @throws IOException Thrown if we cannot successfully start a server
*/
@VisibleForTesting
static Cluster startCluster(final HostAndPort listenAddress,
@Nullable final ILinkFailureDetectorFactory linkFailureDetector,
final Metadata metadata, final List<ServerInterceptor> interceptors,
final RpcClient.Conf conf,
final Map<ClusterEvents, List<Consumer<List<NodeStatusChange>>>> subscriptions)
throws IOException {
Objects.requireNonNull(listenAddress);
// This is the single-threaded protocolExecutor that handles all the protocol messaging.
final SharedResources sharedResources = new SharedResources(listenAddress);
final RpcServer rpcServer = new RpcServer(listenAddress, sharedResources);
final RpcClient rpcClient = new RpcClient(listenAddress, Collections.emptyList(), sharedResources, conf);
final NodeId currentIdentifier = Utils.nodeIdFromUUID(UUID.randomUUID());
final MembershipView membershipView = new MembershipView(K, Collections.singletonList(currentIdentifier),
Collections.singletonList(listenAddress));
final WatermarkBuffer watermarkBuffer = new WatermarkBuffer(K, H, L);
MembershipService.Builder builder = new MembershipService.Builder(listenAddress, watermarkBuffer,
membershipView, sharedResources)
.setRpcClient(rpcClient)
.setSubscriptions(subscriptions);
// If linkFailureDetector == null, the system defaults to using the PingPongFailureDetector
if (linkFailureDetector != null) {
builder = builder.setLinkFailureDetector(linkFailureDetector);
}
final MembershipService membershipService = metadata.getMetadataCount() > 0
? builder.setMetadata(Collections.singletonMap(listenAddress.toString(), metadata)).build()
: builder.build();
rpcServer.setMembershipService(membershipService);
rpcServer.startServer(interceptors);
return new Cluster(rpcServer, membershipService, sharedResources, listenAddress);
}
/**
* Returns the list of hosts currently in the membership set.
*
* @return list of hosts in the membership set
*/
public List<HostAndPort> getMemberlist() {
return membershipService.getMembershipView();
}
/**
* Returns the number of hosts currently in the membership set.
*
* @return the number of hosts in the membership set
*/
public int getMembershipSize() {
return membershipService.getMembershipSize();
}
/**
* Returns the list of hosts currently in the membership set.
*
* @return list of hosts in the membership set
*/
public Map<String, Metadata> getClusterMetadata() {
return membershipService.getMetadata();
}
/**
* Register callbacks for cluster events.
*
* @param event Cluster event to subscribe to
* @param callback Callback to be executed when {@code event} occurs.
*/
public void registerSubscription(final ClusterEvents event,
final Consumer<List<NodeStatusChange>> callback) {
membershipService.registerSubscription(event, callback);
}
/**
* Shutdown the RpcServer
*/
public void shutdown() {
LOG.debug("Shutting down RpcServer and MembershipService");
rpcServer.stopServer();
membershipService.shutdown();
sharedResources.shutdown();
}
@Override
public String toString() {
return "Cluster:" + listenAddress;
}
public static final class JoinException extends RuntimeException {
JoinException(final String msg) {
super(msg);
}
}
} |
package org.lapanen.stealth.si.subversion.config;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.Splitter;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.SubscribableChannel;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
@Configuration
@EnableIntegration
public class SubversionComponents {
public static final String REGEX_CAPTURE_GROUP_INDEX_HEADER_NAME = "subversion_regex_capture_group_index";
public static final String REGEX_HEADER_NAME = "subversion_path_regex";
private static final Logger LOG = LoggerFactory.getLogger(SubversionComponents.class);
@Bean
public SubscribableChannel subversionLogChannel() {
return new PublishSubscribeChannel();
}
@Bean
public SubscribableChannel subversionBasePathChannel() {
return new PublishSubscribeChannel();
}
@Splitter(inputChannel = "subversionLogChannel", outputChannel = "subversionBasePathChannel")
public List<String> extractUniqueBasePathsByRegexMatching(final Message<SVNLogEntry> logEntryMessage) {
final Integer regexCaptureGroupIndex = getMandatoryHeader(logEntryMessage, REGEX_CAPTURE_GROUP_INDEX_HEADER_NAME, Integer.class);
final Pattern pattern = getRegexPattern(logEntryMessage);
final SVNLogEntry logEntry = logEntryMessage.getPayload();
final Map<String, SVNLogEntryPath> paths = logEntry.getChangedPaths();
final Set<String> matchingPaths = new HashSet<>();
for (final Map.Entry<String, SVNLogEntryPath> path : paths.entrySet()) {
final Matcher matcher = pattern.matcher(path.getValue().getPath());
if (matcher.matches()) {
final int groupCount = matcher.groupCount();
if (groupCount >= regexCaptureGroupIndex) {
String group = matcher.group(regexCaptureGroupIndex);
LOG.debug("Found candidate '{}'", group);
matchingPaths.add(group);
} else {
LOG.warn("capture group index set at {}, but only {} groups found in {}", new Object[] { regexCaptureGroupIndex, groupCount, pattern });
}
} else {
LOG.debug("'{}' is no match for {}", path, pattern);
}
}
return new ArrayList<String>(matchingPaths);
}
private static <T> T getMandatoryHeader(final Message<?> message, final String name, final Class<T> type) {
if (!message.getHeaders().containsKey(name)) {
throw new MessagingException(message, String.format("Mandatory header '%s' missing", name));
}
return message.getHeaders().get(name, type);
}
private static Pattern getRegexPattern(final Message<SVNLogEntry> message) {
final String regex = getMandatoryHeader(message, REGEX_HEADER_NAME, String.class);
try {
return Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new MessagingException(String.format("While compiling regex '%s'", regex), e);
}
}
} |
package step.plugins.quotamanager;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.codehaus.groovy.runtime.InvokerHelper;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import step.plugins.quotamanager.config.Quota;
public class QuotaHandler {
private ConcurrentHashMap<String, QuotaSemaphore> semaphores = new ConcurrentHashMap<>();
private Quota config;
private Class<?> scriptClass;
public QuotaHandler(Quota config) {
super();
this.config = config;
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
try {
scriptClass = groovyClassLoader.parseClass(config.getQuotaKeyFunction());
} finally {
try {
groovyClassLoader.close();
} catch (IOException e) {}
}
}
public Quota getConfig() {
return config;
}
public String acquirePermit(Map<String, Object> bindingVariables) throws Exception {
String quotaKey = computeQuotaKey(bindingVariables);
if(quotaKey!=null) {
QuotaSemaphore semaphore = getOrCreateSemaphore(quotaKey);
Long acquireTimeoutMs = config.getAcquireTimeoutMs();
if(acquireTimeoutMs!=null) {
boolean acquired;
if(acquireTimeoutMs<0) {
semaphore.acquire();
acquired = true;
} else {
acquired = semaphore.tryAcquire(acquireTimeoutMs, TimeUnit.MILLISECONDS);
}
if(!acquired) {
throw new TimeoutException("A timeout occurred while trying to acquire permit for quota: " + config.toString());
} else {
semaphore.incrementLoad();
}
} else {
semaphore.acquire();
semaphore.incrementLoad();
}
}
return quotaKey;
}
public String tryAcquirePermit(Map<String, Object> bindingVariables, long timeout) throws Exception {
String quotaKey = computeQuotaKey(bindingVariables);
if(quotaKey!=null) {
QuotaSemaphore semaphore = getOrCreateSemaphore(quotaKey);
boolean acquired = semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
if(!acquired) {
throw new TimeoutException("A timeout occurred while trying to acquire permit for quota: " + config.toString());
} else {
semaphore.incrementLoad();
}
}
return quotaKey;
}
public void releasePermit(String quotaKey) {
QuotaSemaphore semaphore = getOrCreateSemaphore(quotaKey);
semaphore.decrementLoad();
semaphore.release();
}
private QuotaSemaphore getOrCreateSemaphore(String key) {
QuotaSemaphore semaphore = semaphores.get(key);
if(semaphore == null) {
QuotaSemaphore newInstance = new QuotaSemaphore(config.getPermits(), false);
semaphore = semaphores.putIfAbsent(key, newInstance);
if(semaphore == null) {
semaphore = newInstance;
}
}
return semaphore;
}
protected String computeQuotaKey(Map<String, Object> bindingVariables) throws Exception {
Binding binding = new Binding(bindingVariables);
Script script = InvokerHelper.createScript(scriptClass, binding);
Object result = script.run();
if(result!=null) {
return result.toString();
} else {
return null;
}
}
public QuotaHandlerStatus getStatus() {
QuotaHandlerStatus status = new QuotaHandlerStatus();
status.permitsByQuotaKey = config.getPermits();
status.configuration = config;
for(Entry<String, QuotaSemaphore> entry:semaphores.entrySet()) {
int peak = entry.getValue().getPeak();
int usage = config.getPermits()-entry.getValue().availablePermits();
status.addEntry(entry.getKey(),usage, peak);
}
return status;
}
} |
package org.carlspring.strongbox.security.certificates;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class KeyStoresTest
{
private File f;
@Before
public void init()
throws IOException,
CertificateException,
NoSuchAlgorithmException,
KeyStoreException
{
//noinspection ResultOfMethodCallIgnored
new File("target/test-resources").mkdirs();
f = new File("target/test-resources/test.jks");
}
@Test
public void testAll()
throws IOException,
CertificateException,
NoSuchAlgorithmException,
KeyStoreException,
KeyManagementException
{
KeyStores.createNew(f, "12345".toCharArray());
final KeyStore ks = KeyStores.addCertificates(f, "12345".toCharArray(), InetAddress.getLocalHost(), 40636);
assertEquals("localhost should have three certificates in the chain", 1, ks.size());
Map<String, Certificate> certs = KeyStores.listCertificates(f, "12345".toCharArray());
for (final Map.Entry<String, Certificate> cert : certs.entrySet())
{
System.out.println(cert.getKey() + " : " + ((X509Certificate)cert.getValue()).getSubjectDN());
}
KeyStores.changePassword(f, "12345".toCharArray(), "666".toCharArray());
KeyStores.removeCertificates(f, "666".toCharArray(), InetAddress.getLocalHost(), 40636);
certs = KeyStores.listCertificates(f, "666".toCharArray());
assertTrue(certs.isEmpty());
}
} |
package upparse.cli;
import java.io.*;
import java.util.*;
import upparse.corpus.*;
import upparse.corpus.BIOEncoder.*;
import upparse.eval.*;
import upparse.model.*;
/**
* Main class manages command-line interface to UPP
* @author ponvert@mail.utexas.edu (Elias Ponvert)
*/
public class Main {
private static enum ChunkingStrategy { TWOSTAGE, SOFT; }
private static String VERSION = "101:35180c7a9bc3";
private final Alpha alpha = new Alpha();
private OutputManager outputManager = OutputManager.nullOutputManager();
private EvalManager evalManager = new EvalManager(alpha);
private String factor = "2,1,1";
private int iter = -1;
private double emdelta = .001;
private String[] args = new String[0];
private BIOEncoder encoder =
BIOEncoder.getBIOEncoder(EncoderType.BIO, KeepStop.STOP, alpha);
private String[] trainCorpusString = null;
private CorpusType trainFileType = CorpusType.WSJ;
private int trainSents = -1;
private StopSegmentCorpus trainStopSegmentCorpus;
private double smooth = 0.1;
private SequenceModelType chunkerType = SequenceModelType.PRLG;
private ChunkingStrategy chunkingStrategy = ChunkingStrategy.TWOSTAGE;
private int filterTrain = -1;
private final String action;
private Main(String[] args)
throws CommandLineError, IOException, EvalError, EncoderError, CorpusError {
int i = 0;
String arg;
boolean outputAll = false;
OutputType outputType = OutputType.CLUMP;
String eval = "";
String[] testCorpusString = new String[0];
if (args.length < 1)
throw new CommandLineError("Please specify an action");
try {
List<String> otherArgs = new ArrayList<String>();
encoder =
BIOEncoder.getBIOEncoder(EncoderType.BIO, KeepStop.STOP, alpha);
int filterTest = -1;
while (i < args.length) {
arg = args[i++];
if (arg.equals("-output"))
outputManager = OutputManager.fromDirname(args[i++]);
else if (arg.equals("-filterTrain"))
filterTrain = Integer.parseInt(args[i++]);
else if (arg.equals("-filterTest"))
filterTest = Integer.parseInt(args[i++]);
else if (arg.equals("-chunkingStrategy"))
chunkingStrategy = ChunkingStrategy.valueOf(args[i++]);
else if (arg.equals("-chunkerType"))
chunkerType = SequenceModelType.valueOf(args[i++]);
else if (arg.equals("-smooth"))
smooth = Double.parseDouble(args[i++]);
else if (arg.equals("-outputType"))
outputType = OutputType.valueOf(args[i++]);
else if (arg.equals("-numtrain"))
trainSents = Integer.parseInt(args[i++]);
else if (arg.equals("-test")) {
List<String> sb = new ArrayList<String>();
while (i < args.length && args[i].charAt(0) != '-') sb.add(args[i++]);
testCorpusString = sb.toArray(new String[0]);
}
else if (arg.equals("-train")) {
List<String> sb = new ArrayList<String>();
while (i < args.length && args[i].charAt(0) != '-') sb.add(args[i++]);
trainCorpusString = sb.toArray(new String[0]);
}
else if (args.equals("-testFileType"))
evalManager.setTestFileType(CorpusType.valueOf(args[i++]));
else if (arg.equals("-trainFileType"))
trainFileType = CorpusType.valueOf(args[i++]);
else if (arg.equals("-factor") || arg.equals("-F"))
factor = args[i++];
else if (arg.equals("-iterations")) iter = Integer.parseInt(args[i++]);
else if (arg.equals("-emdelta")) emdelta = Float.parseFloat(args[i++]);
else if (arg.equals("-G") || arg.equals("-encoderType"))
encoder = BIOEncoder.getBIOEncoder(
EncoderType.valueOf(args[i++]), KeepStop.STOP, alpha);
else if (arg.equals("-E") || arg.equals("-evalReportType")) {
evalManager.setEvalReportType(EvalReportType.valueOf(args[i++]));
}
else if (arg.equals("-e") || arg.equals("-evalTypes"))
eval = args[i++];
else if (arg.equals("-outputAll")) outputManager.setOutputAll(true);
else otherArgs.add(arg);
}
this.args = otherArgs.toArray(new String[0]);
this.action = this.args[0];
// Setup outputManager
outputManager.setOutputAllIter(outputAll);
outputManager.setOutputType(outputType);
// Setup evalManager
if (testCorpusString.length == 1 &&
testCorpusString[0].startsWith("subset")) {
int len = Integer.parseInt(testCorpusString[0].substring(6));
evalManager.setFilterLen(len);
evalManager.setTestCorpusString(trainCorpusString);
} else {
evalManager.setTestCorpusString(testCorpusString);
evalManager.setFilterLen(filterTest);
}
evalManager.setParserEvaluationTypes(eval);
// don't run EM more than 200 iterations
if (iter < 0) iter = 200;
outputManager.writeMetadata(this);
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace(System.err);
throw new CommandLineError();
}
}
public void writeMetadata(PrintStream s) {
if (action.equals("chunk")) {
s.println(currentDate());
s.println(" Version: " + VERSION);
s.println("Chunk experiment");
s.println(" Experiment strategy: " + chunkingStrategy);
s.println(" Chunker type: " + chunkerType);
if (chunkingStrategy == ChunkingStrategy.TWOSTAGE)
s.println(" Stage 1 factor: " + factor);
s.println(" EM iter delta cutoff: " + emdelta);
if (iter > 0) s.println(" EM iter num cutoff: " + iter);
s.println(" BIO encoder: " + encoder.getClass().getSimpleName());
if (filterTrain > 0) s.println(" Filter train by len: " + filterTrain);
s.println(" Smoothing param: " + smooth);
s.println(" Train files:");
for (String f: trainCorpusString) s.println(" " + f);
s.println(" Train file type: " + trainFileType);
evalManager.writeMetadata(s);
}
}
private String currentDate() { return (new Date()).toString(); }
private double[] getFactor() {
String[] fpieces = factor.split(",");
double[] f = new double[fpieces.length];
for (int i = 0; i < fpieces.length; i++)
f[i] = Double.parseDouble(fpieces[i]);
return f;
}
/**
* Print program usage to stream
* @param stream
*/
private static void printUsage(PrintStream stream) {
String prog = Main.class.getName();
stream.println(
"Usage: java " + prog + " action [options] [args]\n" +
"\n" +
"Actions:\n" +
" chunk\n" +
"\n" +
"Options:\n" +
" -train FILES Train using specified files\n" +
" -test FILES Evaluated on specified files\n" +
" -trainFileType X Train files file type (eg wsj)\n" +
" -testFileType X Test files file type (eg wsj)\n" +
" -output FILE Set output file/template\n" +
" -outputType T Output type (see eval types)\n" +
" -outputAll Produce model output for all EM iterations\n"+
" -F|-factor N1,N2... Factors for Stage 1 chunking\n" +
" -G|-encoderType T Use chunk-encoder type T\n" +
" -GG|-grandparentsN Use pseudo 2nd order tagset without altering STOP tag\n" +
" -E|-evalreort EVAL Evaluation report (eg PRL)\n" +
" -e|-evaltypes E1,E2 Evaluation types \n" +
" -iterations N Iterations of EM\n" +
" -emdelta D Halt EM when data perplexity change is less than\n" +
" -dontCheckTerms Don't check that the eval and output terms are equal\n" +
" -onlyLast Only show evaluation of last itertation of EM\n" +
"\n" +
"File types:\n" +
" wsj : WSJ/Penn Treebank corpus\n" +
" negra : Negra Treebank (Penn Treebank like)\n" +
" ctb : Penn Chinese Treebank corpus\n" +
" spl : Sentence per line\n" +
" wpl : Word per line (sentences seperated by blank lines)\n" +
"\n" +
OutputType.outputTypesHelp() +
"\n\n" +
Eval.evalReportHelp() +
"\n\n" +
BIOEncoder.EncoderType.encoderTypeHelp()
);
}
private StopSegmentCorpus getTrainStopSegmentCorpus() throws CorpusError {
if (trainStopSegmentCorpus == null) makeTrainStopSegmentCorpus();
return trainStopSegmentCorpus;
}
private void makeTrainStopSegmentCorpus() throws CorpusError {
trainStopSegmentCorpus = CorpusUtil.stopSegmentCorpus(
alpha, trainCorpusString, trainFileType, trainSents, filterTrain);
assert trainStopSegmentCorpus != null;
}
private SimpleChunker getSimpleChunker() throws CorpusError {
return SimpleChunker.fromStopSegmentCorpus(
alpha,
getTrainStopSegmentCorpus(),
getFactor());
}
private void evalChunker(final String comment, final Chunker chunker)
throws IOException, EvalError, ChunkerError, CorpusError {
if (outputManager.isNull() && evalManager.isNull()) return;
final ChunkedSegmentedCorpus chunkerOutput =
chunker.getChunkedCorpus(evalManager.getEvalStopSegmentCorpus());
evalManager.addChunkerOutput(comment, chunkerOutput);
if (!outputManager.isNull())
outputManager.addChunkerOutput(chunkerOutput);
}
private static void usageError() {
printUsage(System.err);
System.exit(1);
}
private void writeOutput() throws EvalError, IOException, CorpusError {
evalManager.writeEval(outputManager.getResultsStream());
outputManager.writeOutput();
}
private void chunkerEval(final SequenceModelChunker model)
throws IOException, EvalError, ChunkerError, CorpusError {
evalChunker("Iter 0", model.getCurrentChunker());
while (model.anotherIteration()) {
model.updateWithEM(outputManager.getStatusStream());
evalChunker(
String.format("Iter %d", model.getCurrentIter()),
model.getCurrentChunker());
}
writeOutput();
}
private SequenceModel getSequenceModel()
throws EncoderError, SequenceModelError, CorpusError, CommandLineError {
final StopSegmentCorpus train = getTrainStopSegmentCorpus();
switch (chunkingStrategy) {
case TWOSTAGE:
final SimpleChunker c = getSimpleChunker();
final ChunkedSegmentedCorpus psuedoTraining = c.getChunkedCorpus(train);
return SequenceModel.mleEstimate(
chunkerType, psuedoTraining, encoder, smooth);
case SOFT:
return SequenceModel.softEstimate(
chunkerType, train, encoder, smooth);
default:
throw new CommandLineError(
"Unexpected chunking strategy: " + chunkingStrategy);
}
}
private void chunk()
throws CommandLineError, IOException, EvalError, ChunkerError, CorpusError,
EncoderError, SequenceModelError {
chunkerEval(new SequenceModelChunker(getSequenceModel(), emdelta));
}
public static void main(String[] argv) {
try {
Main prog = new Main(argv);
if (prog.args.length == 0) {
System.err.println("Please specify an action\n");
usageError();
}
if (prog.action.equals("chunk")) prog.chunk();
else {
System.err.println("Unexpected action: " + prog.action);
usageError();
}
} catch (CommandLineError e) {
System.err.println("Bad command line error: " + e.getMessage());
usageError();
} catch (IOException e) {
System.err.println("IO problem");
e.printStackTrace(System.err);
usageError();
} catch (EvalError e) {
System.err.println("Eval problem");
e.printStackTrace(System.err);
usageError();
} catch (EncoderError e) {
System.err.println("Encoder problem");
e.printStackTrace(System.err);
usageError();
} catch (ChunkerError e) {
System.err.println("Problem with the chunker");
e.printStackTrace(System.err);
usageError();
} catch (CorpusError e) {
System.err.println("Problem with corpus");
e.printStackTrace(System.err);
} catch (SequenceModelError e) {
System.err.println("Problem with sequence model");
e.printStackTrace(System.err);
}
}
} |
package fredboat.command.fun;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import fredboat.Config;
import fredboat.commandmeta.abs.Command;
import fredboat.commandmeta.abs.IFunCommand;
import fredboat.util.rest.CacheUtil;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fredboat.FredBoat;
import fredboat.feature.I18n;
import org.slf4j.LoggerFactory;
import fredboat.util.rest.CloudFlareScraper;
public class E9Command extends Command {
private static final Pattern IMAGE_PATTERN = Pattern.compile(\"file_url\":\"((\\"|[^"])*)");
private static final String BASE_URL = "https:
private static final org.slf4j.Logger log = LoggerFactory.getLogger(E9Command.class);
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
channel.sendTyping().queue();
try {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(BASE_URL);
stringBuilder.append(args[1]);
stringBuilder.append(",order:random,rating:s?limit=1");
String finalstring = stringBuilder.toString();
String str = Unirest.get(finalstring).asString().getBody();;
Matcher m = IMAGE_PATTERN.matcher(str);
if (!m.find()) {
//channel.sendMessage(MessageFormat.format(I18n.get(guild).getString("e926Fail"), BASE_URL)).queue();
//log.info("str: " + m);
//log.info("finalsearchstring: " + finalstring);
//channel.sendMessage(str).queue();
//channel.sendMessage(finalstring).queue();
return;
}
File tmp = CacheUtil.getImageFromURL(m.group(1));
channel.sendFile(tmp, null).queue();
log.info("///////////////////" + m.group(1) + "////////////////////////////////");
channel.sendMessage(m.group(1)).queue();
} catch (IOException e) {
throw new RuntimeException(e);
}
catch (UnirestException e) {
throw new RuntimeException(e);
}
}
@Override
public String help(Guild guild) {
return "{0}{1}\n#Takes in tags and searches on e926.net";
}
} |
package com.rgi.geopackage.tiles;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import utility.DatabaseUtility;
import com.rgi.common.BoundingBox;
import com.rgi.common.util.jdbc.ResultSetStream;
import com.rgi.geopackage.core.GeoPackageCore;
import com.rgi.geopackage.verification.Assert;
import com.rgi.geopackage.verification.AssertionError;
import com.rgi.geopackage.verification.ColumnDefinition;
import com.rgi.geopackage.verification.ForeignKeyDefinition;
import com.rgi.geopackage.verification.Requirement;
import com.rgi.geopackage.verification.Severity;
import com.rgi.geopackage.verification.TableDefinition;
import com.rgi.geopackage.verification.VerificationLevel;
import com.rgi.geopackage.verification.Verifier;
/**
* @author Jenifer Cochran
*
*/
public class TilesVerifier extends Verifier
{
/**
* This Epsilon is the greatest difference we allow when comparing doubles
*/
public static final double EPSILON = 0.0001;
/**
* Constructor
*
* @param sqliteConnection
* the connection to the database
* @param verificationLevel
* Controls the level of verification testing performed
* @throws SQLException
* throws if the method {@link DatabaseUtility#tableOrViewExists(Connection, String) tableOrViewExists} throws
*/
public TilesVerifier(final Connection sqliteConnection, final VerificationLevel verificationLevel) throws SQLException
{
super(sqliteConnection, verificationLevel);
final String queryTables = "SELECT tbl_name FROM sqlite_master " +
"WHERE tbl_name NOT LIKE 'gpkg_%' " +
"AND (type = 'table' OR type = 'view');";
try(Statement createStmt = this.getSqliteConnection().createStatement();
ResultSet possiblePyramidTables = createStmt.executeQuery(queryTables);)
{
this.allPyramidUserDataTables = ResultSetStream.getStream(possiblePyramidTables)
.map(resultSet -> { try
{
final TableDefinition possiblePyramidTable = new TilePyramidUserDataTableDefinition(resultSet.getString("tbl_name"));
this.verifyTable(possiblePyramidTable);
return possiblePyramidTable.getName();
}
catch(final SQLException | AssertionError ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.allPyramidUserDataTables = Collections.emptySet();
}
final String query2 = String.format("SELECT table_name FROM %s WHERE data_type = 'tiles';",
GeoPackageCore.ContentsTableName);
try(Statement createStmt2 = this.getSqliteConnection().createStatement();
ResultSet contentsPyramidTables = createStmt2.executeQuery(query2))
{
this.pyramidTablesInContents = ResultSetStream.getStream(contentsPyramidTables)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.pyramidTablesInContents = Collections.emptySet();
}
final String query3 = String.format("SELECT DISTINCT table_name FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement createStmt3 = this.getSqliteConnection().createStatement();
ResultSet tileMatrixPyramidTables = createStmt3.executeQuery(query3))
{
this.pyramidTablesInTileMatrix = ResultSetStream.getStream(tileMatrixPyramidTables)
.map(resultSet -> { try
{
final String pyramidName = resultSet.getString("table_name");
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(),
pyramidName) ? pyramidName
: null;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.pyramidTablesInTileMatrix = Collections.emptySet();
}
this.hasTileMatrixSetTable = this.tileMatrixSetTableExists();
this.hasTileMatrixTable = this.tileMatrixTableExists();
}
/**
* Requirement 34
*
* <blockquote>
* The <code>gpkg_contents</code> table SHALL contain a row with a <code>
* data_type</code> column value of 'tiles' for each tile pyramid user data
* table or view.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(reference = "Requirement 34",
text = "The gpkg_contents table SHALL contain a row with a "
+ "data_type column value of \"tiles\" for each "
+ "tile pyramid user data table or view.")
public void Requirement34() throws AssertionError
{
for(final String tableName: this.allPyramidUserDataTables)
{
Assert.assertTrue(String.format("The Tile Pyramid User Data table that is not refrenced in %2$s table is: %1$s. This table needs to be referenced in the %2$s table.",
tableName,
GeoPackageCore.ContentsTableName),
this.pyramidTablesInContents.contains(tableName),
Severity.Warning);
}
}
/**
* Requirement 35
*
* <blockquote>
* In a GeoPackage that contains a tile pyramid user data table that
* contains tile data, by default, zoom level pixel sizes for that table
* SHALL vary by a factor of 2 between adjacent zoom levels in the tile
* matrix metadata table.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement(reference = "Requirement 35",
text = "In a GeoPackage that contains a tile pyramid user data table "
+ "that contains tile data, by default, zoom level pixel sizes for that "
+ "table SHALL vary by a factor of 2 between zoom levels in tile matrix metadata table.")
public void Requirement35() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for(final String tableName : this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT table_name, "
+ "zoom_level, "
+ "pixel_x_size, "
+ "pixel_y_size,"
+ "matrix_width,"
+ "matrix_height,"
+ "tile_width,"
+ "tile_height "
+ "FROM %s "
+ "WHERE table_name = ? "
+ "ORDER BY zoom_level ASC;", GeoPackageTiles.MatrixTableName);
try(final PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1))
{
stmt.setString(1, tableName);
try(final ResultSet pixelInfo = stmt.executeQuery())
{
final List<TileData> tileDataSet = ResultSetStream.getStream(pixelInfo)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.pixelXSize = resultSet.getDouble("pixel_x_size");
tileData.pixelYSize = resultSet.getDouble("pixel_y_size");
tileData.zoomLevel = resultSet.getInt("zoom_level");
tileData.matrixHeight = resultSet.getInt("matrix_height");
tileData.matrixWidth = resultSet.getInt("matrix_width");
tileData.tileHeight = resultSet.getInt("tile_height");
tileData.tileWidth = resultSet.getInt("tile_width");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
for(int index = 0; index < tileDataSet.size()-1; ++index)
{
final TileData current = tileDataSet.get(index);
final TileData next = tileDataSet.get(index + 1);
if(current.zoomLevel == next.zoomLevel - 1)
{
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not vary by factors of 2"
+ " between adjacent zoom levels in the tile matrix metadata table: %f, %f",
next.pixelXSize,
next.pixelYSize),
TilesVerifier.isEqual((current.pixelXSize / 2.0), next.pixelXSize) &&
TilesVerifier.isEqual((current.pixelYSize / 2.0), next.pixelYSize),
Severity.Warning);
}
}
//TODO Test will be moved on later release//This tests if the pixel x values and pixel y values are valid based on their bounding box in the tile matrix set
}
}
}
}
}
@Requirement(reference = "Requirement 36",
text = "In a GeoPackage that contains a tile pyramid user data table that contains tile data SHALL store that tile data in MIME type image/jpeg or image/png")
public void Requirement36() throws AssertionError
{
Assert.assertTrue("Test skipped when verification level is not set to " + VerificationLevel.Full,
this.verificationLevel == VerificationLevel.Full,
Severity.Skipped);
for(final String tableName : this.allPyramidUserDataTables)
{
final String selectTileDataQuery = String.format("SELECT tile_data, id FROM %s;", tableName);
try(final PreparedStatement stmt = this.getSqliteConnection().prepareStatement(selectTileDataQuery);
final ResultSet tileDataResultSet = stmt.executeQuery())
{
final List<String> errorMessage = ResultSetStream.getStream(tileDataResultSet)
.map(resultSet -> { try
{
final byte[] tileData = resultSet.getBytes("tile_data");
return TilesVerifier.verifyData(tileData) ? null
: String.format("column id %d", resultSet.getInt("id"));
}
catch(final SQLException | IOException ex)
{
return ex.getMessage();
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
Assert.assertTrue(String.format("The following columns named \"id\" in table '%s' are not in the correct image format:\n\t\t%s.",
tableName,
errorMessage.stream().collect(Collectors.joining("\n"))),
errorMessage.isEmpty(),
Severity.Warning);
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(), Severity.Error);
}
}
}
@Requirement(reference = "Requirement 37",
text = "In a GeoPackage that contains a tile pyramid user data table that "
+ "contains tile data that is not MIME type image png, "
+ "by default SHALL store that tile data in MIME type image jpeg")
public void Requirement37()
{
// This requirement is tested through Requirement 35 test in TilesVerifier.
}
@Requirement(reference = "Requirement 38",
text = "A GeoPackage that contains a tile pyramid user data table SHALL "
+ "contain gpkg_tile_matrix_set table or view per Table Definition, "
+ "Tile Matrix Set Table or View Definition and gpkg_tile_matrix_set Table Creation SQL. ")
public void Requirement38() throws AssertionError, SQLException
{
if(!this.allPyramidUserDataTables.isEmpty())
{
Assert.assertTrue(String.format("The GeoPackage does not contain a %1$s. Every GeoPackage with a Pyramid User Data Table must also have a %1$s table.",
GeoPackageTiles.MatrixSetTableName),
this.hasTileMatrixSetTable,
Severity.Error);
this.verifyTable(TilesVerifier.TileMatrixSetTableDefinition);
}
}
/**
* Requirement 39
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix_set</code> <code>table_name</code>
* column SHALL reference values in the gpkg_contents table_name column for
* rows with a data type of "tiles".
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(reference = "Requirement 39",
text = "Values of the gpkg_tile_matrix_set table_name column "
+ "SHALL reference values in the gpkg_contents table_name "
+ "column for rows with a data type of \"tiles\".")
public void Requirement39() throws AssertionError
{
if(this.hasTileMatrixSetTable)
{
final String queryMatrixSetPyramid = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet tileTablesInTileMatrixSet = stmt.executeQuery(queryMatrixSetPyramid))
{
final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch(final SQLException ex1)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final String table: this.pyramidTablesInContents)
{
Assert.assertTrue(String.format("The table_name %1$s in the %2$s is not referenced in the %3$s table. Either delete the table %1$s or create a record for that table in the %3$s table",
table,
GeoPackageTiles.MatrixSetTableName,
GeoPackageCore.ContentsTableName),
tileMatrixSetTables.contains(table),
Severity.Warning);
}
}
catch(final Exception ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 40
*
* <blockquote>
* The gpkg_tile_matrix_set table or view SHALL contain one row record for
* each tile pyramid user data table.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(reference = "Requirement 40",
text = "The gpkg_tile_matrix_set table or view SHALL "
+ "contain one row record for each tile "
+ "pyramid user data table.")
public void Requirement40() throws AssertionError
{
if(this.hasTileMatrixSetTable)
{
final String queryMatrixSet = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet tileTablesInTileMatrixSet = stmt.executeQuery(queryMatrixSet))
{
final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch(final SQLException ex1)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final String table: this.allPyramidUserDataTables)
{
Assert.assertTrue(String.format("The Pyramid User Data Table %s is not referenced in %s.",
table,
GeoPackageTiles.MatrixSetTableName),
tileMatrixSetTables.contains(table),
Severity.Error);
}
}
catch(final Exception ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 41
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix_set</code> <code>srs_id</code>
* column SHALL reference values in the <code>gpkg_spatial_ref_sys</code>
* <code> srs_id</code> column.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 41",
text = "Values of the gpkg_tile_matrix_set srs_id column "
+ "SHALL reference values in the gpkg_spatial_ref_sys srs_id column. ")
public void Requirement41() throws AssertionError
{
if(this.hasTileMatrixSetTable)
{
final String query1 = String.format("SELECT srs_id from %s AS tms " +
"WHERE srs_id NOT IN" +
"(SELECT srs_id " +
"FROM %s);",
GeoPackageTiles.MatrixSetTableName,
GeoPackageCore.SpatialRefSysTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet unreferencedSRS = stmt.executeQuery(query1))
{
if(unreferencedSRS.next())
{
Assert.fail(String.format("The %s table contains a reference to an srs_id that is not defined in the %s Table. Unreferenced srs_id: %s",
GeoPackageTiles.MatrixSetTableName,
GeoPackageCore.SpatialRefSysTableName,
unreferencedSRS.getInt("srs_id")),
Severity.Error);
}
}
catch(final Exception ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
@Requirement (reference = "Requirement 42",
text = "A GeoPackage that contains a tile pyramid user data table "
+ "SHALL contain a gpkg_tile_matrix table or view per clause "
+ "2.2.7.1.1 Table Definition, Table Tile Matrix Metadata Table "
+ "or View Definition and Table gpkg_tile_matrix Table Creation SQL. ")
public void Requirement42() throws AssertionError, SQLException
{
if(!this.allPyramidUserDataTables.isEmpty())
{
Assert.assertTrue(String.format("The GeoPackage does not contain a %1$s table. Every GeoPackage with a Pyramid User Data Table must also have a %1$s table.",
GeoPackageTiles.MatrixTableName),
this.hasTileMatrixTable,
Severity.Error);
this.verifyTable(TilesVerifier.TileMatrixTableDefinition);
}
}
/**
* Requirement 43
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix</code> <code>table_name</code>
* column SHALL reference values in the <code>gpkg_contents</code> <code>
* table_name</code> column for rows with a <code>data_type</code> of
* 'tiles'.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 43",
text = "Values of the gpkg_tile_matrix table_name column "
+ "SHALL reference values in the gpkg_contents table_name "
+ "column for rows with a data_type of 'tiles'. ")
public void Requirement43() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT table_name FROM %s AS tm " +
"WHERE table_name NOT IN" +
"(SELECT table_name " +
"FROM %s AS gc " +
"WHERE tm.table_name = gc.table_name AND gc.data_type = 'tiles');",
GeoPackageTiles.MatrixTableName,
GeoPackageCore.ContentsTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet unreferencedTables = stmt.executeQuery(query))
{
if(unreferencedTables.next())
{
Assert.fail(String.format("There are Pyramid user data tables in %s table_name field such that the table_name does not"
+ " reference values in the %s table_name column for rows with a data type of 'tiles'."
+ " Unreferenced table: %s",
GeoPackageTiles.MatrixTableName,
GeoPackageCore.ContentsTableName,
unreferencedTables.getString("table_name")),
Severity.Warning);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 44
*
* <blockquote>
* The <code>gpkg_tile_matrix</code> table or view SHALL contain one row
* record for each zoom level that contains one or more tiles in each tile
* pyramid user data table or view.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 44",
text = "The gpkg_tile_matrix table or view SHALL contain "
+ "one row record for each zoom level that contains "
+ "one or more tiles in each tile pyramid user data table or view. ")
public void Requirement44() throws AssertionError
{
if(this.hasTileMatrixTable)
{
for(final String tableName : this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT DISTINCT zoom_level FROM %s WHERE table_name = ? ORDER BY zoom_level;", GeoPackageTiles.MatrixTableName);
final String query2 = String.format("SELECT DISTINCT zoom_level FROM %s ORDER BY zoom_level;", tableName);
try(PreparedStatement stmt1 = this.getSqliteConnection().prepareStatement(query1))
{
stmt1.setString(1, tableName);
try(ResultSet gm_zoomLevels = stmt1.executeQuery();
PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2);
ResultSet py_zoomLevels = stmt2.executeQuery())
{
final Set<Integer> tileMatrixZooms = ResultSetStream.getStream(gm_zoomLevels)
.map(resultSet -> { try
{
return resultSet.getInt("zoom_level");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
final Set<Integer> tilePyramidZooms = ResultSetStream.getStream(py_zoomLevels)
.map(resultSet -> { try
{
return resultSet.getInt("zoom_level");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final Integer zoom: tilePyramidZooms)
{
Assert.assertTrue(String.format("The %s does not contain a row record for zoom level %d in the Pyramid User Data Table %s.",
GeoPackageTiles.MatrixTableName,
zoom,
tableName),
tileMatrixZooms.contains(zoom),
Severity.Error);
}
}
}
catch(final Exception ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
}
/**
* Requirement 45
*
* <blockquote>
* The <code>zoom_level</code> column value in a <code>gpkg_tile_matrix
* </code> table row SHALL not be negative.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 45",
text = "The zoom_level column value in a gpkg_tile_matrix table row SHALL not be negative.")
public void Requirement45() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(zoom_level) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minZoom = stmt.executeQuery(query))
{
final int minZoomLevel = minZoom.getInt("min(zoom_level)");
if(!minZoom.wasNull())
{
Assert.assertTrue(String.format("The zoom_level in %s must be greater than 0. Invalid zoom_level: %d", GeoPackageTiles.MatrixTableName, minZoomLevel),
minZoomLevel >= 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 46
*
* <blockquote>
* <code>matrix_width</code> column value in a <code>gpkg_tile_matrix
* </code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 46",
text = "The matrix_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement46() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(matrix_width) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minMatrixWidthRS = stmt.executeQuery(query);)
{
final int minMatrixWidth = minMatrixWidthRS.getInt("min(matrix_width)");
if(!minMatrixWidthRS.wasNull())
{
Assert.assertTrue(String.format("The matrix_width in %s must be greater than 0. Invalid matrix_width: %d",
GeoPackageTiles.MatrixTableName,
minMatrixWidth),
minMatrixWidth > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 47
*
* <blockquote>
* <code>matrix_height</code> column value in a <code>gpkg_tile_matrix
* </code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 47",
text = "The matrix_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement47() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(matrix_height) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minMatrixHeightRS = stmt.executeQuery(query);)
{
final int minMatrixHeight = minMatrixHeightRS.getInt("min(matrix_height)");
if(!minMatrixHeightRS.wasNull())
{
Assert.assertTrue(String.format("The matrix_height in %s must be greater than 0. Invalid matrix_height: %d",
GeoPackageTiles.MatrixTableName,
minMatrixHeight),
minMatrixHeight > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 48
*
* <blockquote>
* <code>tile_width</code> column value in a <code>gpkg_tile_matrix</code>
* table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 48",
text = "The tile_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement48() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(tile_width) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minTileWidthRS = stmt.executeQuery(query);)
{
final int minTileWidth = minTileWidthRS.getInt("min(tile_width)");
if(!minTileWidthRS.wasNull())
{
Assert.assertTrue(String.format("The tile_width in %s must be greater than 0. Invalid tile_width: %d",
GeoPackageTiles.MatrixTableName,
minTileWidth),
minTileWidth > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 49
*
* <blockquote>
* <code>tile_height</code> column value in a <code>gpkg_tile_matrix</code>
* table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(reference = "Requirement 49",
text = "The tile_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement49() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(tile_height) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minTileHeightRS = stmt.executeQuery(query);)
{
final int testMinTileHeight = minTileHeightRS.getInt("min(tile_height)");
if(!minTileHeightRS.wasNull())
{
Assert.assertTrue(String.format("The tile_height in %s must be greater than 0. Invalid tile_height: %d",
GeoPackageTiles.MatrixTableName,
testMinTileHeight),
testMinTileHeight > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 50
*
* <blockquote>
* <code>pixel_x_size</code> column value in a <code>gpkg_tile_matrix
* </code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 50",
text = "The pixel_x_size column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement50() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(pixel_x_size) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minPixelXSizeRS = stmt.executeQuery(query);)
{
final double minPixelXSize = minPixelXSizeRS.getDouble("min(pixel_x_size)");
if(!minPixelXSizeRS.wasNull())
{
Assert.assertTrue(String.format("The pixel_x_size in %s must be greater than 0. Invalid pixel_x_size: %f",
GeoPackageTiles.MatrixTableName,
minPixelXSize),
minPixelXSize > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 51
*
* <blockquote>
* <code>pixel_y_size</code> column value in a <code>gpkg_tile_matrix
* </code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 51",
text = "The pixel_y_size column value in a gpkg_tile_matrix table row SHALL be greater than 0.")
public void Requirement51() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(pixel_y_size) FROM %s;", GeoPackageTiles.MatrixTableName);
try(Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minPixelYSizeRS = stmt.executeQuery(query);)
{
final double minPixelYSize = minPixelYSizeRS.getDouble("min(pixel_y_size)");
if(!minPixelYSizeRS.wasNull())
{
Assert.assertTrue(String.format("The pixel_y_size in %s must be greater than 0. Invalid pixel_y_size: %f",
GeoPackageTiles.MatrixTableName,
minPixelYSize),
minPixelYSize > 0,
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 52
*
* <blockquote>
* The <code>pixel_x_size</code> and <code>pixel_y_size</code> column
* values for <code>zoom_level</code> column values in a <code>
* gpkg_tile_matrix</code> table sorted in ascending order SHALL be sorted
* in descending order.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (reference = "Requirement 52",
text = "The pixel_x_size and pixel_y_size column values for zoom_level "
+ "column values in a gpkg_tile_matrix table sorted in ascending "
+ "order SHALL be sorted in descending order.")
public void Requirement52() throws AssertionError
{
if(this.hasTileMatrixTable)
{
for(final String pyramidTable : this.allPyramidUserDataTables)
{
final String query2 = String.format("SELECT pixel_x_size, pixel_y_size "
+ "FROM %s WHERE table_name = ? ORDER BY zoom_level ASC;",
GeoPackageTiles.MatrixTableName);
Double pixelX2 = null;
Double pixelY2 = null;
try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2))
{
stmt2.setString(1, pyramidTable);
try(ResultSet zoomPixxPixy = stmt2.executeQuery())
{
while (zoomPixxPixy.next())
{
final Double pixelX = zoomPixxPixy.getDouble("pixel_x_size");
final Double pixelY = zoomPixxPixy.getDouble("pixel_y_size");
if(pixelX2 != null && pixelY2 != null)
{
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.",
pixelX.toString(),
pixelY.toString()),
pixelX2 > pixelX && pixelY2 > pixelY,
Severity.Error);
pixelX2 = pixelX;
pixelY2 = pixelY;
}
else if(zoomPixxPixy.next())
{
pixelX2 = zoomPixxPixy.getDouble("pixel_x_size");
pixelY2 = zoomPixxPixy.getDouble("pixel_y_size");
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.",
pixelX2.toString(),
pixelY2.toString()),
pixelX > pixelX2 && pixelY > pixelY2,
Severity.Error);
}
}
}
}
catch(final Exception ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
}
@Requirement (reference = "Requirement 53",
text = "Each tile matrix set in a GeoPackage SHALL "
+ "be stored in a different tile pyramid user "
+ "data table or updateable view with a unique "
+ "name that SHALL have a column named \"id\" with"
+ " column type INTEGER and PRIMARY KEY AUTOINCREMENT"
+ " column constraints per Clause 2.2.8.1.1 Table Definition,"
+ " Tiles Table or View Definition and EXAMPLE: tiles table "
+ "Insert Statement (Informative). ")
public void Requirement53() throws AssertionError, SQLException
{
// Verify the tables are defined correctly
for(final String table: this.pyramidTablesInContents)
{
if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), table))
{
this.verifyTable(new TilePyramidUserDataTableDefinition(table));
}
else
{
throw new AssertionError(String.format("The tiles table %1$s does not exist even though it is defined in the %2$s table. Either create the table %1$s or delete the record in %2$s table referring to table %1$s.",
table,
GeoPackageCore.ContentsTableName),
Severity.Error);
}
}
// Ensure that the pyramid tables are referenced in tile matrix set
if(this.hasTileMatrixSetTable)
{
final String query2 = String.format("SELECT DISTINCT table_name "
+ "FROM %s WHERE data_type = 'tiles' "
+ "AND table_name NOT IN"
+ " (SELECT DISTINCT table_name "
+ " FROM %s);",
GeoPackageCore.ContentsTableName,
GeoPackageTiles.MatrixSetTableName);
try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2);
ResultSet unreferencedPyramidTableInTMS = stmt2.executeQuery())
{
// Verify that all the pyramid user data tables are referenced in the Tile Matrix Set table
if(unreferencedPyramidTableInTMS.next())
{
Assert.fail(String.format("There are Pyramid User Data Tables that do not contain a record in the %s. Unreferenced Pyramid table: %s",
GeoPackageTiles.MatrixSetTableName,
unreferencedPyramidTableInTMS.getString("table_name")),
Severity.Error);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage(),
Severity.Error);
}
}
}
/**
* Requirement 54
*
* <blockquote>
* For each distinct <code>table_name</code> from the <code>
* gpkg_tile_matrix</code> (tm) table, the tile pyramid (tp) user data
* table <code>zoom_level</code> column value in a GeoPackage SHALL be in
* the range min(tm.zoom_level) <= tp.zoom_level <= max(tm.zoom_level).
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement (reference = "Requirement 54",
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, "
+ "the tile pyramid (tp) user data table zoom_level column value in a "
+ "GeoPackage SHALL be in the range min(tm.zoom_level) less than or equal "
+ "to tp.zoom_level less than or equal to max(tm.zoom_level).")
public void Requirement54() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for(final String pyramidName: this.pyramidTablesInTileMatrix)
{
final String query2 = String.format("SELECT MIN(zoom_level) AS min_gtm_zoom, MAX(zoom_level) AS max_gtm_zoom FROM %s WHERE table_name = ?",
GeoPackageTiles.MatrixTableName);
try(PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2))
{
stmt2.setString(1, pyramidName);
try(ResultSet minMaxZoom = stmt2.executeQuery())
{
final int minZoom = minMaxZoom.getInt("min_gtm_zoom");
final int maxZoom = minMaxZoom.getInt("max_gtm_zoom");
if(!minMaxZoom.wasNull())
{
final String query3 = String.format("SELECT id FROM %s WHERE zoom_level < ? OR zoom_level > ?", pyramidName);
try(PreparedStatement stmt3 = this.getSqliteConnection().prepareStatement(query3))
{
stmt3.setInt(1, minZoom);
stmt3.setInt(2, maxZoom);
try(ResultSet invalidZooms = stmt3.executeQuery())
{
if(invalidZooms.next())
{
Assert.fail(String.format("There are zoom_levels in the Pyramid User Data Table: %1$s such that the zoom level "
+ "is bigger than the maximum zoom level: %2$d or smaller than the minimum zoom_level: %3$d"
+ " that was determined by the %4$s Table. Invalid tile with an id of %5$d from table %6$s",
pyramidName,
maxZoom,
minZoom,
GeoPackageTiles.MatrixTableName,
invalidZooms.getInt("id"),
pyramidName),
Severity.Error);
}
}
}
}
}
}
}
}
}
/**
* Requirement 55
*
* <blockquote>
* For each distinct <code>table_name</code> from the <code>
* gpkg_tile_matrix</code> (tm) table, the tile pyramid (tp) user data
* table <code>tile_column</code> column value in a GeoPackage SHALL be in
* the range 0 <= tp.tile_column <= tm.matrix_width - 1 where the tm and tp
* <code>zoom_level</code> column values are equal.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement(reference = "Requirement 55",
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, "
+ "the tile pyramid (tp) user data table tile_column column value in a "
+ "GeoPackage SHALL be in the range 0 <= tp.tile_column <= tm.matrix_width - 1 "
+ "where the tm and tp zoom_level column values are equal. ")
public void Requirement55() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for(final String pyramidName : this.pyramidTablesInTileMatrix)
{
// This query will only pull the incorrect values for the
// pyramid user data table's column width, the value
// of the tile_column value for the pyramid user data table
// SHOULD be null otherwise those fields are in violation
// of the range
final String query2 = String.format("SELECT zoom_level as zl, " +
"matrix_width as width " +
"FROM %1$s " +
"WHERE table_name = ? " +
"AND" +
"(" +
"zoom_level in (SELECT zoom_level FROM %2$s WHERE tile_column < 0) " +
"OR " +
"(" +
"EXISTS(SELECT NULL FROM %2$s WHERE zoom_level = zl AND tile_column > width - 1)" +
" )" +
" );",
GeoPackageTiles.MatrixTableName,
pyramidName);
try(final PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2))
{
stmt2.setString(1, pyramidName);
try(final ResultSet incorrectColumns = stmt2.executeQuery())
{
final List<TileData> incorrectColumnSet = ResultSetStream.getStream(incorrectColumns)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.matrixWidth = resultSet.getInt("width");
tileData.zoomLevel = resultSet.getInt("zl");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
Assert.assertTrue(String.format("The table '%s' there are tiles with a tile_column values oustide the ranges for a particular zoom_level. \n%s",
pyramidName,
incorrectColumnSet.stream()
.map(tileData -> String.format("\tZoom level %d Expected Range tile_column: [0, %d].",
tileData.zoomLevel, tileData.matrixWidth -1))
.collect(Collectors.joining("\n"))),
incorrectColumnSet.isEmpty(),
Severity.Warning);
}
}
}
}
}
/**
* Requirement 56
*
* <blockquote>
* For each distinct <code>table_name</code> from the <code>
* gpkg_tile_matrix</code> (tm) table, the tile pyramid (tp) user data
* table <code>tile_row</code> column value in a GeoPackage SHALL be in the
* range 0 <= tp.tile_row <= tm.matrix_height - 1 where the tm and tp
* <code>zoom_level</code> column values are equal.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement (reference = "Requirement 56",
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, the tile pyramid (tp) "
+ "user data table tile_row column value in a GeoPackage SHALL be in the range 0 <= tp.tile_row <= tm.matrix_height - 1 "
+ "where the tm and tp zoom_level column values are equal. ")
public void Requirement56() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for(final String pyramidName: this.pyramidTablesInTileMatrix)
{
// this query will only pull the incorrect values for the
// pyramid user data table's column height, the value
// of the tile_row value for the pyramid user data table
// SHOULD be null otherwise those fields are in violation
// of the range
final String query2 = String.format("SELECT zoom_level as zl, " +
"matrix_height as height " +
"FROM %1$s " +
"WHERE table_name = ? " +
"AND" +
"(" +
"zoom_level in (SELECT zoom_level FROM %2$s WHERE tile_row < 0) " +
"OR " +
"(" +
"EXISTS(SELECT NULL FROM %2$s WHERE zoom_level = zl AND tile_row > height - 1)" +
" )" +
" );",
GeoPackageTiles.MatrixTableName,
pyramidName);
try(final PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2))
{
stmt2.setString(1, pyramidName);
try(final ResultSet incorrectTileRow = stmt2.executeQuery())
{
final List<TileData> incorrectTileRowSet = ResultSetStream.getStream(incorrectTileRow)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.matrixHeight = resultSet.getInt("height");
tileData.zoomLevel = resultSet.getInt("zl");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
Assert.assertTrue(String.format("The table '%s' there are tiles with a tile_row values oustide the ranges for a particular zoom_level. \n%s",
pyramidName,
incorrectTileRowSet.stream()
.map(tileData -> String.format("\tZoom level %d Expected Range tile_row: [0, %d].",
tileData.zoomLevel,
tileData.matrixHeight - 1))
.collect(Collectors.joining("\n"))),
incorrectTileRowSet.isEmpty(),
Severity.Warning);
}
}
}
}
}
/**
* Reference 2.2.6.1.1 Table 8. TileMatrix Set Table or View Definition para. 1
* <blockquote>
* The gpkg_tile_matrix_set table or updateable view defines the minimum bounding box (<code>min_x, min_y, max_x, max_y</code>)
* and spatial reference system (<code>srs_id</code>) for all content in a tile pyramid user data table.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement (reference = "Reference 2.2.6.1.1 Table 8.",
text = "The gpkg_tile_matrix_set table or updateable view defines the minimum bounding box (min_x, min_y, max_x, max_y)"
+" and spatial reference system (srs_id) for all content in a tile pyramid user data table. ")
public void reference22611Table8() throws SQLException, AssertionError
{
if(this.hasTileMatrixTable)
{
for(final String pyramidTable: this.allPyramidUserDataTables)
{
String tileRowMaxQuery = String.format("SELECT matrix_height as height, " +
"zoom_level as zoom, " +
"table_name " +
"FROM gpkg_tile_matrix " +
"WHERE table_name = ? " +
"AND ( " +
"EXISTS( SELECT NULL FROM %1$s WHERE tile_row = (height - 1) AND zoom_level = zoom ) " +
");",
pyramidTable);
String tileColumnMaxQuery = String.format("SELECT matrix_width as width, " +
"zoom_level as zoom, " +
"table_name " +
"FROM gpkg_tile_matrix " +
"WHERE table_name = ? " +
"AND ( " +
"EXISTS( SELECT NULL FROM %1$s WHERE tile_column = (width - 1) AND zoom_level = zoom ) " +
");",
pyramidTable);
String tileRowMinQuery = String.format("SELECT tile_row FROM %s WHERE tile_row = 0;", pyramidTable);
String tileColumnMinQuery = String.format("SELECT tile_column FROM %s WHERE tile_column = 0;", pyramidTable);
try(PreparedStatement maxRowStatement = this.getSqliteConnection().prepareStatement(tileRowMaxQuery);
PreparedStatement maxColumnStatement = this.getSqliteConnection().prepareStatement(tileColumnMaxQuery))
{
maxRowStatement.setString(1, pyramidTable);
maxColumnStatement.setString(1, pyramidTable);
try(Statement minRowStatement = this.getSqliteConnection().createStatement();
Statement minColumnStatement = this.getSqliteConnection().createStatement();
ResultSet maxRowResults = maxRowStatement.executeQuery();
ResultSet maxColumnResults = maxColumnStatement.executeQuery();
ResultSet minRowResult = minRowStatement.executeQuery(tileRowMinQuery);
ResultSet minColumnResult = minColumnStatement.executeQuery(tileColumnMinQuery))
{
StringBuilder errorMessage = new StringBuilder();
boolean hasCorrectMinRow = minRowResult.isBeforeFirst();
boolean hasCorrectMinColumn = minColumnResult.isBeforeFirst();
boolean hasCorrectMaxRow = maxRowResults.isBeforeFirst();
boolean hasCorrectMaxColumn = maxColumnResults.isBeforeFirst();
if(!hasCorrectMinRow)
{
errorMessage.append("\tdoes not contain a tile where its tile_row = 0.\n");
}
if(!hasCorrectMinColumn)
{
errorMessage.append("\tdoes not contain a tile where its tile_column = 0.\n");
}
if(!hasCorrectMaxRow)
{
errorMessage.append("\tdoes not contain a tile where its tile_row = matrix_height - 1.\n");
}
if(!hasCorrectMaxColumn)
{
errorMessage.append("\tdoes not contain a tile where its tile_column = matrix_width - 1.\n");
}
Assert.assertTrue(String.format("The table %1$s does not define the minimum bounding box for the data inside the table %1$s. "
+ "The results are based on the numbering in the tiles table. "
+ " Because GeoPackage requires the upper left tile to be numbered (0,0) there should exist "
+ "a tile with a tile_column value of 0 and a tile (not necessarily the same tile) with a tile_row value of 0. "
+ "As for the maximal values for tile_row and tile_column, there should exist a tile where the tile_row at a "
+ "particular zoom_level should equal its matrix_height - 1 at the same zoom_level and a tile (not necessarily the same tile) with a "
+ "tile_column at a particular zoom_level should equal its matrix_width - 1 at the same zoom_level.\n"
+ "The following messages defines which are missing:\n %2$s ",
pyramidTable,
errorMessage.toString()),
hasCorrectMinRow && hasCorrectMinColumn && hasCorrectMaxRow && hasCorrectMaxColumn,
Severity.Warning);
}
}
}
}
}
/**
* Reference 2.2.6.1.2 para. 1
* <blockquote>
* The minimum bounding box defined in the gpkg_tile_matrix_set table or view for a tile pyramid
* user data table SHALL be exact so that the bounding box coordinates for individual tiles in a
* tile pyramid MAY be calculated based on the column values for the user data table in the
* gpkg_tile_matrix table or view.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement (reference = "Reference 2.2.6.1.2 para 1.",
text = "The minimum bounding box defined in the gpkg_tile_matrix_set table or view for a "
+ "tile pyramid user data table SHALL be exact so that the bounding box coordinates "
+ "for individual tiles in a tile pyramid MAY be calculated based on the column values "
+ "for the user data table in the gpkg_tile_matrix table or view. ")
public void reference() throws SQLException, AssertionError
{
if(this.hasTileMatrixTable && this.hasTileMatrixSetTable)
{
for(final String tableName : this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT table_name, "
+ "zoom_level, "
+ "pixel_x_size, "
+ "pixel_y_size,"
+ "matrix_width,"
+ "matrix_height,"
+ "tile_width,"
+ "tile_height "
+ "FROM %s "
+ "WHERE table_name = ? "
+ "ORDER BY zoom_level ASC;", GeoPackageTiles.MatrixTableName);
try(final PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1))
{
stmt.setString(1, tableName);
try(final ResultSet pixelInfo = stmt.executeQuery())
{
final List<TileData> tileDataSet = ResultSetStream.getStream(pixelInfo)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.pixelXSize = resultSet.getDouble("pixel_x_size");
tileData.pixelYSize = resultSet.getDouble("pixel_y_size");
tileData.zoomLevel = resultSet.getInt("zoom_level");
tileData.matrixHeight = resultSet.getInt("matrix_height");
tileData.matrixWidth = resultSet.getInt("matrix_width");
tileData.tileHeight = resultSet.getInt("tile_height");
tileData.tileWidth = resultSet.getInt("tile_width");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
final String query2 = String.format("SELECT min_x, min_y, max_x, max_y FROM %s WHERE table_name = ?",
GeoPackageTiles.MatrixSetTableName);
try(final PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2))
{
stmt2.setString(1, tableName);
try(ResultSet boundingBoxRS = stmt2.executeQuery())
{
if(boundingBoxRS.next())
{
final double minX = boundingBoxRS.getDouble("min_x");
final double minY = boundingBoxRS.getDouble("min_y");
final double maxX = boundingBoxRS.getDouble("max_x");
final double maxY = boundingBoxRS.getDouble("max_y");
final BoundingBox boundingBox = new BoundingBox(minX, minY, maxX, maxY);
final List<TileData> invalidPixelValues = tileDataSet.stream()
.filter(tileData -> !validPixelValues(tileData, boundingBox))
.collect(Collectors.toList());
Assert.assertTrue(String.format("The pixel_x_size and pixel_y_size should satisfy these two equations:"
+ "\n\tpixel_x_size = (bounding box width / matrix_width) / tile_width "
+ "AND \n\tpixel_y_size = (bounding box height / matrix_height)/ tile_height. "
+ "\nBased on these two equations, the following pixel values are invalid for the table '%s'.:\n%s ",
tableName,
invalidPixelValues.stream()
.map(tileData -> String.format("\tInvalid pixel_x_size: %f, Invalid pixel_y_size: %f at zoom_level %d",
tileData.pixelXSize,
tileData.pixelYSize,
tileData.zoomLevel))
.collect(Collectors.joining("\n"))),
invalidPixelValues.isEmpty(),
Severity.Warning);
}
}
}
}
}
}
}
}
private static boolean verifyData(final byte[] tileData) throws IOException
{
if(tileData == null)
{
return false;
}
try(ByteArrayInputStream byteArray = new ByteArrayInputStream(tileData);
MemoryCacheImageInputStream cacheImage = new MemoryCacheImageInputStream(byteArray))
{
return TilesVerifier.canReadImage(pngImageReaders, cacheImage) || TilesVerifier.canReadImage(jpegImageReaders, cacheImage);
}
}
private static boolean validPixelValues(final TileData tileData, final BoundingBox boundingBox)
{
return isEqual(tileData.pixelXSize, (boundingBox.getWidth() / tileData.matrixWidth) / tileData.tileWidth) &&
isEqual(tileData.pixelYSize, (boundingBox.getHeight() / tileData.matrixHeight) / tileData.tileHeight);
}
private static boolean isEqual(final double first, final double second)
{
return Math.abs(first - second) < TilesVerifier.EPSILON;
}
private static <T> Collection<T> iteratorToCollection(final Iterator<T> iterator)
{
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This Verifies if the Tile Matrix Table exists.
*
* @return true if the gpkg_tile_matrix table exists
* @throws AssertionError
* throws an assertion error if the gpkg_tile_matrix table
* doesn't exist and the GeoPackage contains a tiles table
*/
private boolean tileMatrixTableExists() throws SQLException
{
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixTableName);
}
private boolean tileMatrixSetTableExists() throws SQLException
{
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixSetTableName);
}
private static boolean canReadImage(final Collection<ImageReader> imageReaders, final ImageInputStream image)
{
return imageReaders.stream()
.anyMatch(imageReader -> { try
{
image.mark();
return imageReader.getOriginatingProvider().canDecodeInput(image);
}
catch(final Exception ex)
{
return false;
}
finally
{
try
{
image.reset();
}
catch(final Exception e)
{
e.printStackTrace();
}
}
});
}
private class TileData implements Comparable<TileData>
{
int matrixWidth;
int matrixHeight;
int zoomLevel;
Integer tileID;
double pixelXSize;
double pixelYSize;
int tileWidth;
int tileHeight;
@Override
public int compareTo(final TileData other)
{
return this.tileID.compareTo(other.tileID);
}
}
private Set<String> allPyramidUserDataTables;
private Set<String> pyramidTablesInContents;
private Set<String> pyramidTablesInTileMatrix;
private boolean hasTileMatrixTable;
private boolean hasTileMatrixSetTable;
private static final TableDefinition TileMatrixSetTableDefinition;
private static final TableDefinition TileMatrixTableDefinition;
private static final Collection<ImageReader> jpegImageReaders;
private static final Collection<ImageReader> pngImageReaders;
static
{
jpegImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/jpeg"));
pngImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/png"));
final Map<String, ColumnDefinition> tileMatrixSetColumns = new HashMap<>();
tileMatrixSetColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null));
tileMatrixSetColumns.put("srs_id", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixSetColumns.put("min_x", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("min_y", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("max_x", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("max_y", new ColumnDefinition("DOUBLE", true, false, false, null));
TileMatrixSetTableDefinition = new TableDefinition(GeoPackageTiles.MatrixSetTableName,
tileMatrixSetColumns,
new HashSet<>(Arrays.asList(new ForeignKeyDefinition(GeoPackageCore.SpatialRefSysTableName, "srs_id", "srs_id"),
new ForeignKeyDefinition(GeoPackageCore.ContentsTableName, "table_name", "table_name"))));
final Map<String, ColumnDefinition> tileMatrixColumns = new HashMap<>();
tileMatrixColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null));
tileMatrixColumns.put("zoom_level", new ColumnDefinition("INTEGER", true, true, true, null));
tileMatrixColumns.put("matrix_width", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("matrix_height", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("tile_width", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("tile_height", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("pixel_x_size", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixColumns.put("pixel_y_size", new ColumnDefinition("DOUBLE", true, false, false, null));
TileMatrixTableDefinition = new TableDefinition(GeoPackageTiles.MatrixTableName,
tileMatrixColumns,
new HashSet<>(Arrays.asList(new ForeignKeyDefinition(GeoPackageCore.ContentsTableName, "table_name", "table_name"))));
}
} |
package com.parc.ccn.data.content;
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import com.parc.ccn.Library;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.ContentObject;
import com.parc.ccn.data.security.PublisherKeyID;
import com.parc.ccn.data.util.EncodableObject;
import com.parc.ccn.data.util.GenericXMLEncodable;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.io.CCNInputStream;
import com.parc.ccn.library.io.CCNOutputStream;
import com.parc.ccn.library.profiles.SegmentationProfile;
import com.parc.ccn.library.profiles.VersionMissingException;
import com.parc.ccn.library.profiles.VersioningProfile;
/**
* Takes a class E, and backs it securely to CCN.
* @author smetters
*
* @param <E>
*/
public class CCNEncodableObject<E extends GenericXMLEncodable> extends EncodableObject<E> {
ContentName _currentName;
CCNLibrary _library;
public CCNEncodableObject(Class<E> type, CCNLibrary library) {
super(type);
_library = library;
}
public CCNEncodableObject(Class<E> type, E data, CCNLibrary library) {
super(type, data);
_library = library;
}
/**
* Construct an object from stored CCN data.
* @param type
* @param content The object to recover, or one of its fragments.
* @param library
* @throws XMLStreamException
* @throws IOException
*/
public CCNEncodableObject(Class<E> type, ContentObject content, CCNLibrary library) throws XMLStreamException, IOException {
super(type);
_library = library;
CCNInputStream is = new CCNInputStream(content, library);
is.seek(0); // In case we start with something other than the first fragment.
update(is);
}
/**
* Ambiguous. Are we supposed to pull this object based on its name,
* or merely attach the name to the object which we will then construct
* and save. Let's assume the former, and allow the name to be specified
* for save() for the latter.
* @param type
* @param name
* @param library
* @throws XMLStreamException
* @throws IOException
*/
public CCNEncodableObject(Class<E> type, ContentName name, PublisherKeyID publisher, CCNLibrary library) throws XMLStreamException, IOException {
super(type);
_library = library;
// DKS TODO need to use an input stream type that given a specific version
// will pull it, but given an unversioned name will pull the latest version.
CCNInputStream is = new CCNInputStream(name, publisher, library);
update(is);
}
public CCNEncodableObject(Class<E> type, ContentName name, CCNLibrary library) throws XMLStreamException, IOException {
this(type, name, null, library);
}
public void update() throws XMLStreamException, IOException {
if (null == _currentName) {
throw new IllegalStateException("Cannot retrieve an object without giving a name!");
}
// Look for latest version.
update(VersioningProfile.versionRoot(_currentName));
}
/**
* Load data into object. If name is versioned, load that version. If
* name is not versioned, look for latest version. CCNInputStream doesn't
* have that property at the moment.
* @param name
* @throws IOException
* @throws XMLStreamException
*/
public void update(ContentName name) throws XMLStreamException, IOException {
// Either get the latest version name and call CCNInputStream, or
// better yet, use the appropriate versioning stream.
CCNInputStream is = new CCNInputStream(name, _library);
update(is);
_currentName = is.baseName();
}
public void update(ContentObject object) throws XMLStreamException, IOException {
CCNInputStream is = new CCNInputStream(object, _library);
update(is);
_currentName = SegmentationProfile.segmentRoot(object.name());
}
/**
* Save to existing name, if content is dirty. Update version.
* @throws IOException
* @throws XMLStreamException
*/
public void save() throws XMLStreamException, IOException {
if (null == _currentName) {
throw new IllegalStateException("Cannot save an object without giving it a name!");
}
save(VersioningProfile.versionName(_currentName));
}
/**
* Save content to specific name. If versioned, assume that is the desired
* version. If not, add a version to it.
* @param name
* @throws IOException
* @throws XMLStreamException
*/
public void save(ContentName name) throws XMLStreamException, IOException {
// move object to this name
// TODO
// need to make sure we get back the actual name we're using,
// even if output stream does automatic versioning
// probably need to refactor save behavior -- right now, internalWriteObject
// either writes the object or not; we need to only make a new name if we do
// write the object, and figure out if that's happened. Also need to make
// parent behavior just write, put the dirty check higher in the state.
if (!isDirty()) { // Should we check potentially dirty?
Library.logger().info("Object not dirty. Not saving.");
}
if (null == name) {
throw new IllegalStateException("Cannot save an object without giving it a name!");
}
// CCNOutputStream will currently version an unversioned name, but dont'
// expect it should continue doing that. If it gets a versioned name, will respect it.
CCNOutputStream cos = new CCNOutputStream(name, _library);
save(cos); // superclass stream save. calls flush and close on a wrapping
// digest stream; want to make sure we end up with a single non-MHT signed
// block and no header on small objects
cos.close();
_currentName = name;
setPotentiallyDirty(false);
}
/**
* DKS TODO -- return timestamp instead of name?
* @return
*/
public Long getVersion() {
if ((null == _currentName) || (null == _lastSaved)) {
return null;
}
try {
return VersioningProfile.getVersionNumber(_currentName);
} catch (VersionMissingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new Long(0);
}
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-03-17");
this.setApiVersion("15.19.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-03-31");
this.setApiVersion("14.17.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-01-02");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-04-20");
this.setApiVersion("18.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-03-05");
this.setApiVersion("14.15.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-07-08");
this.setApiVersion("14.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-06-27");
this.setApiVersion("15.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-09-13");
this.setApiVersion("14.6.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
} |
package chat21.android.demo;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import chat21.android.core.ChatManager;
import chat21.android.core.users.models.ChatUser;
import chat21.android.core.users.models.IChatUser;
import chat21.android.ui.ChatUI;
import chat21.android.ui.contacts.activites.ContactListActivity;
import chat21.android.ui.contacts.listeners.OnCreateGroupClickListener;
import chat21.android.ui.conversations.listeners.OnNewConversationClickListener;
import chat21.android.ui.messages.listeners.OnAttachClickListener;
public class AppContext extends Application {
private static final String TAG = AppContext.class.getName();
private static AppContext instance;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
initChatSDK();
}
private void initChatSDK() {
//enable persistence must be made before any other usage of FirebaseDatabase instance.
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
// it creates the chat configurations
ChatManager.Configuration mChatConfiguration =
new ChatManager.Configuration.Builder(getString(R.string.tenant))
.firebaseUrl("https://chat-v2-dev.firebaseio.com/")
.build();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
// assuming you have a login, check if the logged user (converted to IChatUser) is valid
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
IChatUser iChatUser = new ChatUser();
iChatUser.setId(currentUser.getUid());
iChatUser.setEmail(currentUser.getEmail());
ChatManager.start(this, mChatConfiguration, iChatUser);
Log.i(TAG, "chat has been initialized with success");
ChatUI.getInstance().setContext(instance);
ChatUI.getInstance().enableGroups(true);
// set on new conversation click listener
// final IChatUser support = new ChatUser("support", "Chat21 Support");
final IChatUser support = null;
ChatUI.getInstance().setOnNewConversationClickListener(new OnNewConversationClickListener() {
@Override
public void onNewConversationClicked() {
if (support != null) {
ChatUI.getInstance().showDirectConversationActivity(support);
} else {
Intent intent = new Intent(instance, ContactListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // start activity from context
startActivity(intent);
}
}
});
// on attach button click listener
ChatUI.getInstance().setOnAttachClickListener(new OnAttachClickListener() {
@Override
public void onAttachClicked(Object object) {
Toast.makeText(instance, "onAttachClickListener", Toast.LENGTH_SHORT).show();
}
});
// on create group button click listener
ChatUI.getInstance().setOnCreateGroupClickListener(new OnCreateGroupClickListener() {
@Override
public void onCreateGroupClicked() {
Toast.makeText(instance, "setOnCreateGroupClickListener", Toast.LENGTH_SHORT).show();
}
});
Log.i(TAG, "ChatUI has been initialized with success");
} else {
Log.w(TAG, "chat can't be initialized because chatUser is null");
}
}
} |
package com.example.baard;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.util.Stack;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, CreateNewHabitFragment.OnFragmentInteractionListener,
AllHabitsFragment.OnFragmentInteractionListener, AllHabitEventsFragment.OnFragmentInteractionListener,
CreateNewHabitEventFragment.OnFragmentInteractionListener, DailyHabitsFragment.OnFragmentInteractionListener,
HelpFragment.OnFragmentInteractionListener {
private Stack<String> headerStack = new Stack<>();
private String nextHeader;
/**
* On create method for entire activity. Sets up navigation and listener for fragments
*
* @param savedInstanceState Bundle for the saved state
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// view all habits -- front screen to view
Fragment fragment = new DailyHabitsFragment();
nextHeader = getResources().getString(R.string.daily_habits);
getSupportFragmentManager().beginTransaction()
.replace(R.id.relativelayout_for_fragment, fragment, fragment.getTag())
.addToBackStack(null)
.commit();
setActionBarTitle(getString(R.string.daily_habits));
}
private void setActionBarTitle(String str) {
String fontPath = "Raleway-Regular.ttf";
SpannableString s = new SpannableString(str);
s.setSpan(new TypefaceSpan(this, fontPath), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
getSupportActionBar().setTitle(s);
}
/**
* Hides navigation bar when back button is pressed
*/
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (headerStack.empty()) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
sharedPrefs.edit().remove("username").apply();
finish();
} else {
String name=headerStack.pop();
System.out.println(name);
setActionBarTitle(name);
super.onBackPressed();
}
}
/**
* Sets up action bar and menu.
* Auto-generated method by the navigation menu activity.
*
* @param menu the menu pop up
* @return boolean true for success
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* Handle action bar item clicks here. The action bar will
* automatically handle clicks on the Home/Up button, so long
* as you specify a parent activity in AndroidManifest.xml.
* Auto-generated method by the navigation menu activity.
*
* @param item the item in the options menu seleted
* @return boolean true if successful
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivityForResult(intent, 1);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
finish();
}
}
}
/**
* When navigation menu item is selected, it compares the id to send the
* user to a specific fragment.
*
* @param item The item selected in the navigation menu
* @return boolean true if successful
*/
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
headerStack.push(nextHeader);
Fragment fragment = null;
FileController fileController = new FileController();
// Send user to selected fragment
if (id == R.id.nav_dailyHabits) {
fragment = new DailyHabitsFragment();
nextHeader = getResources().getString(R.string.daily_habits);
}
else if (id == R.id.nav_allHabits) {
fragment = new AllHabitsFragment();
nextHeader = getResources().getString(R.string.all_habits);
} else if (id == R.id.nav_newHabit) {
fragment = new CreateNewHabitFragment();
nextHeader = getResources().getString(R.string.create_habit);
} else if (id == R.id.nav_allHabitEvents) {
fragment = new AllHabitEventsFragment();
nextHeader = getResources().getString(R.string.habit_history);
} else if (id == R.id.nav_newHabitEvent) {
fragment = new CreateNewHabitEventFragment();
nextHeader = getResources().getString(R.string.create_event);
} else if (id == R.id.nav_viewMap) {
if (fileController.isNetworkAvailable(getApplicationContext())) {
Intent intent = new Intent(MainActivity.this, ViewMapActivity.class);
startActivity(intent);
} else {
Toast.makeText(this, R.string.no_network, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.nav_viewFriends) {
Intent intent = new Intent(MainActivity.this, ExploreFriends.class);
startActivity(intent);
} else if (id == R.id.nav_help) {
fragment = new HelpFragment();
nextHeader = getResources().getString(R.string.help);
} else if (id == R.id.nav_logout) {
// End this session and take users back to the login screen
Toast.makeText(this, "Logged Out", Toast.LENGTH_SHORT).show();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
sharedPrefsEditor.clear();
sharedPrefsEditor.commit();
finish();
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.relativelayout_for_fragment, fragment, fragment.getTag())
.addToBackStack(null)
.commit();
setActionBarTitle(nextHeader);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Auto-generated method by the navigation menu activity.
*
* @param uri Uri of the fragment
*/
@Override
public void onFragmentInteraction(Uri uri) {
}
} |
package com.pr0gramm.app.feed;
/**
* Type of the feed - like "new" or "top".
*/
public enum FeedType {
NEW {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
@Override
public boolean sortable() {
return true;
}
},
PROMOTED {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
@Override
public boolean sortable() {
return true;
}
},
PREMIUM {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
@Override
public boolean sortable() {
return true;
}
},
CONTROVERSIAL {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
@Override
public boolean sortable() {
return false;
}
},
RANDOM {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return false;
}
@Override
public boolean sortable() {
return false;
}
},
BESTOF {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
public boolean sortable() {
return true;
}
},
TEXT {
@Override
public boolean searchable() {
return true;
}
@Override
public boolean preloadable() {
return true;
}
public boolean sortable() {
return true;
}
};
public abstract boolean searchable();
public abstract boolean preloadable();
public abstract boolean sortable();
} |
package mlxy.tumplar.model;
import android.net.Uri;
import com.squareup.okhttp.HttpUrl;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;
import mlxy.tumplar.global.App;
import mlxy.tumplar.model.service.AvatarService;
import retrofit.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class AvatarModel {
private static class Instance {
private static final AvatarModel instance = new AvatarModel();
}
@Inject
AvatarService service;
private static ConcurrentHashMap<String, Observable<Uri>> observableCache;
private static ConcurrentHashMap<String, Uri> cache;
private AvatarModel() {
App.graph.inject(this);
observableCache = new ConcurrentHashMap<>();
cache = new ConcurrentHashMap<>();
}
public static AvatarModel getInstance() {
return Instance.instance;
}
public Observable<Uri> get(final String blogName) {
if (cache.containsKey(blogName)) {
return fromCache(blogName);
}
Observable<Uri> cachedObservable = observableCache.get(blogName);
if (cachedObservable != null) {
return cachedObservable;
}
// XXX try something like Observable.cache(blogName)?
Observable<Uri> uriObservable =fromNet(blogName)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnTerminate(new Action0() {
@Override
public void call() {
observableCache.remove(blogName);
}
});
Observable<Uri> doubleCheck = observableCache.putIfAbsent(blogName, uriObservable);
if (doubleCheck != null) {
return doubleCheck;
}
return uriObservable;
}
private Observable<Uri> fromCache(final String blogName) {
return Observable.create(new Observable.OnSubscribe<Uri>() {
@Override
public void call(Subscriber<? super Uri> subscriber) {
subscriber.onNext(cache.get(blogName));
subscriber.onCompleted();
}
});
}
private Observable<Uri> fromNet(final String blogName) {
return service.avatar(blogName)
.flatMap(new Func1<Response, Observable<Uri>>() {
@Override
public Observable<Uri> call(Response response) {
HttpUrl avatarUrl = response.raw().request().httpUrl();
return Observable.just(Uri.parse(avatarUrl.toString()));
}
}).doOnNext(new Action1<Uri>() {
@Override
public void call(Uri uri) {
cache.putIfAbsent(blogName, uri);
}
});
}
} |
package team.tr.permitlog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.firebase.ui.auth.IdpResponse;
import com.firebase.ui.auth.ResultCodes;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import android.support.multidex.*;
import java.util.Arrays;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
// For logging
private static final String TAG = "MainActivity";
// Firebase variables:
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private static boolean isPersistenceEnabled = false;
// In order to test the tutorial, set this to true:
private static boolean testingTutorial = false;
// For menu
private String[] menuItems;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public static final int HOME_MENU_INDEX = 0;
public static final int LOG_MENU_INDEX = 1;
public static final int DRIVERS_MENU_INDEX = 2;
public static final int GOALS_MENU_INDEX = 3;
public static final int ABOUT_MENU_INDEX = 4;
public static final int SIGN_OUT_MENU_INDEX = 5;
// Fragments, titles, and arguments for menu items
private Class menuFragmentClasses[] = {HomeFragment.class, LogFragment.class, DriversFragment.class, SettingsFragment.class, AboutFragment.class};
private String menuTitles[] = {"Permit Log", "Driving Log", "Drivers", "Goals", "About"};
private Bundle menuArgs[] = {null, null, null, null, null};
// Keeps track of previous menus:
private LinkedList<Integer> fragmentsStack = new LinkedList<>();
// Sign in request code
private static final int RC_SIGN_IN = 123;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup menu
menuItems = getResources().getStringArray(R.array.menu_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, menuItems));
//When the user clicks on one of the items in the menu:
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Transition based off of position:
transitionFragment(position);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
// Show the menu button in the title bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24px);
getSupportActionBar().setHomeButtonEnabled(true);
// Set persistence if not set:
// isPersistenceEnabled stays after Instant Run, so Instant Run does not call setPersistenceEnabled() again
// as if it did, the app would crash.
if (!isPersistenceEnabled) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
isPersistenceEnabled = true;
}
// Highlight the home menu item by default
mDrawerList.setItemChecked(HOME_MENU_INDEX, true);
// Get the current user from Firebase.
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
// Log whether currentUser is null or not:
Log.d(TAG, "Is the user not signed in? " + Boolean.toString(currentUser == null));
if (savedInstanceState == null) navigateBasedOnUser();
// Initialize ad network
MobileAds.initialize(getApplicationContext(), "ca-app-pub-1631603318674332~4854746404");
// If we are testing the tutorial, delete the goals and set the tutorial preference to true:
if (testingTutorial) {
FirebaseDatabase.getInstance().getReference().child(currentUser.getUid()).child("goals").removeValue();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("tutorial", true);
editor.commit();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save menuArgs during an orientation change:
outState.putParcelableArray("menuArgs", menuArgs);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Get menuArgs from when we previously saved it during an orientation change:
Parcelable savedMenuArgs[] = savedInstanceState.getParcelableArray("menuArgs");
// Try to cast this Parceable[] to a Bundle[]:
try {
menuArgs = (Bundle[])savedMenuArgs;
}
//If this cast fails for some unknown reason, log the error:
catch (ClassCastException e) {
Log.e(TAG, e.getMessage());
}
super.onRestoreInstanceState(savedInstanceState);
}
public void transitionFragment(int position, boolean pushFragmentOnStack) {
/* This function switches the current fragment according to the menu position passed in. */
// Assuming the user is signed in:
if (currentUser != null) {
// Sign out button clicked -> Sign out and return
if (position == SIGN_OUT_MENU_INDEX) {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// Set currentUser:
currentUser = null;
// Show the sign in now that they are signed out:
showSignIn();
}
});
return;
}
// We need to instantiate the fragment and get the title based off position:
String title = menuTitles[position];
// This error message will be shown if there is an error with fragment:
Toast fragmentError = Toast.makeText(this, "There was an error when making the " + title + " part of the app. Sorry!", Toast.LENGTH_SHORT);
Fragment fragment;
try {
fragment = (Fragment) menuFragmentClasses[position].newInstance();
}
// If there is an error, notify the user, log it, and return:
catch (IllegalAccessException | InstantiationException e) {
fragmentError.show();
Log.e(TAG, "While making " + title + " fragment: " + e);
return;
}
// Set fragment's arguments:
fragment.setArguments(menuArgs[position]);
// Transition fragments:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
// Change the title
getSupportActionBar().setTitle(title);
// Highlight the menu item:
mDrawerList.setItemChecked(position, true);
// Add this fragment to the stack if we should:
if (pushFragmentOnStack) fragmentsStack.push(position);
}
//Otherwise, force the user to sign in:
else showSignIn();
}
// By default, push fragments onto the stack:
public void transitionFragment(int position) {
transitionFragment(position, true);
}
public void saveArguments(int position, Bundle args) {
/* Saves args for fragment where position represents the index of the fragment in the menu */
menuArgs[position] = args;
}
private void navigateBasedOnUser() {
// If no user is logged in, show the FirebaseUI login screen.
if (currentUser == null) {
showSignIn();
} else {
// Transition to the home fragment
transitionFragment(HOME_MENU_INDEX);
}
}
// Show the sign in screen using Firebase UI
public void showSignIn() {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()
))
.build(),
RC_SIGN_IN
);
}
// When back button is pressed, go back to previous fragment if possible:
@Override
public void onBackPressed() {
if (fragmentsStack.size() > 1) {
fragmentsStack.pop();
transitionFragment(fragmentsStack.peek(), false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// If the home button is clicked and it is enabled, open/close the menu
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
} else {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
}
return super.onOptionsItemSelected(item);
}
// This is for when we start an activity and then want a result from it back:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// If this is for the sign in activity:
if (requestCode == RC_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == ResultCodes.OK) {
Log.d(TAG, "Login was successful");
// Now that the user is signed in, update currentUser:
currentUser = mAuth.getCurrentUser();
// Transition to the home/settings fragment based on what the user needs to do from here:
navigateBasedOnUser();
} else {
// If there is not a success, try to figure out what went wrong:
if (response == null) Log.e(TAG, "User pressed back button");
else if (response.getErrorCode() == ErrorCodes.NO_NETWORK) {
Log.e(TAG, "Network connection error");
Toast.makeText(this, R.string.network_connection_error, Toast.LENGTH_SHORT).show();
} else if (response.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Log.e(TAG, "Unknown error");
Toast.makeText(this, R.string.unknown_auth_error, Toast.LENGTH_SHORT).show();
showSignIn();
} else Log.e(TAG, "Unknown response");
}
// Debug currentUser again:
Log.d(TAG, "Is the user not signed in? " + Boolean.toString(currentUser == null));
}
}
} |
package uk.orgen.doughnut;
import com.squareup.picasso.Target;
import java.util.Random;
import java.util.Map;
import java.util.HashMap;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import android.provider.Settings.Secure;
import android.os.Handler;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.indooratlas.android.sdk.IALocation;
import com.indooratlas.android.sdk.IALocationListener;
import com.indooratlas.android.sdk.IALocationManager;
import com.indooratlas.android.sdk.IALocationRequest;
import com.indooratlas.android.sdk.IARegion;
import com.firebase.client.Firebase;
import com.indooratlas.android.sdk.resources.IAFloorPlan;
import com.indooratlas.android.sdk.resources.IALatLng;
import com.indooratlas.android.sdk.resources.IALocationListenerSupport;
import com.indooratlas.android.sdk.resources.IAResourceManager;
import com.indooratlas.android.sdk.resources.IAResult;
import com.indooratlas.android.sdk.resources.IAResultCallback;
import com.indooratlas.android.sdk.resources.IATask;
import com.firebase.client.ValueEventListener;
import com.firebase.client.FirebaseError;
import com.firebase.client.DataSnapshot;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import java.io.File;
import java.util.Map;
public class MapsActivity extends FragmentActivity {
private static final int MAX_DIMENSION = 2048;
private static final float[] colors = {BitmapDescriptorFactory.HUE_AZURE, BitmapDescriptorFactory.HUE_CYAN,
BitmapDescriptorFactory.HUE_GREEN, BitmapDescriptorFactory.HUE_MAGENTA,
BitmapDescriptorFactory.HUE_ORANGE, BitmapDescriptorFactory.HUE_RED,
BitmapDescriptorFactory.HUE_ROSE, BitmapDescriptorFactory.HUE_VIOLET,
BitmapDescriptorFactory.HUE_YELLOW};
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Marker mMarker;
private IALocationManager mIALocationManager;
private GroundOverlay mGroundOverlay;
private IAResourceManager mFloorPlanManager;
private IATask<IAFloorPlan> mPendingAsyncResult;
private IAFloorPlan mFloorPlan;
private long mDownloadId;
private DownloadManager mDownloadManager;
private Target mLoadTarget;
private boolean mCameraPositionNeedsUpdating;
private IAResourceManager mResourceManager;
private IATask<IAFloorPlan> mFetchFloorPlanTask;
private Firebase fireRef;
private String android_id;
private Runnable runnable;
private Handler handler;
String TAG = "MapsActivity";
private IALocationListener mListener = new IALocationListenerSupport() {
/**
* Location changed, move marker and camera position.
*/
@Override
public void onLocationChanged(IALocation location) {
Log.d(TAG, "new location received with coordinates: " + location.getLatitude()
+ "," + location.getLongitude());
if (mMap == null) {
// location received before map is initialized, ignoring update here
return;
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (mMarker == null) {
// first location, add marker
mMarker = mMap.addMarker(new MarkerOptions().position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
} else {
// move existing markers position to received location
mMarker.setPosition(latLng);
}
// our camera position needs updating if location has significantly changed
if (mCameraPositionNeedsUpdating) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.5f));
mCameraPositionNeedsUpdating = false;
}
}
};
/**
* Region listener that when:
* <ul>
* <li>region has entered; marks need to move camera and starts
* loading floor plan bitmap</li>
* <li>region has existed; clears marker</li>
* </ul>.
*/
private IARegion.Listener mRegionListener = new IARegion.Listener() {
@Override
public void onEnterRegion(IARegion region) {
if (region.getType() == IARegion.TYPE_UNKNOWN) {
Toast.makeText(MapsActivity.this, "Moved out of map",
Toast.LENGTH_LONG).show();
return;
}
// entering new region, mark need to move camera
mCameraPositionNeedsUpdating = true;
final String newId = region.getId();
Toast.makeText(MapsActivity.this, newId, Toast.LENGTH_SHORT).show();
fetchFloorPlan(newId);
}
@Override
public void onExitRegion(IARegion region) {
if (mMarker != null) {
mMarker.remove();
mMarker = null;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mIALocationManager = IALocationManager.create(this);
mFloorPlanManager = IAResourceManager.create(this);
mResourceManager = IAResourceManager.create(this);
Firebase.setAndroidContext(this);
fireRef = new Firebase("https://donat.firebaseio.com/");
android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
Random r = new Random();
Map<String, Double> pos = new HashMap<String, Double>();
pos.put("x", new Double(r.nextDouble()));
pos.put("y", new Double(r.nextDouble()));
fireRef.child(android_id).setValue(pos);
handler.postDelayed(this, 1000);
}
};
}
@Override
protected void onResume() {
super.onResume();
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
// start receiving location updates & monitor region changes
mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mListener);
mIALocationManager.registerRegionListener(mRegionListener);
Firebase.setAndroidContext(this);
Firebase myFirebaseRef = new Firebase("https://donat.firebaseio.com/");
myFirebaseRef.child("message").setValue("BIENE ALESSIO!");
handler.postDelayed(runnable, 1000);
}
@Override
protected void onPause() {
super.onPause();
mIALocationManager.removeLocationUpdates(mListener);
mIALocationManager.unregisterRegionListener(mRegionListener);
handler.removeCallbacks(runnable);
}
@Override
protected void onDestroy() {
mIALocationManager.destroy();
handler.removeCallbacks(runnable);
super.onDestroy();
}
/**
* Sets bitmap of floor plan as ground overlay on Google Maps
*/
private void setupGroundOverlay(IAFloorPlan floorPlan, Bitmap bitmap) {
if (mGroundOverlay != null) {
mGroundOverlay.remove();
}
if (mMap != null) {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
IALatLng iaLatLng = floorPlan.getCenter();
LatLng center = new LatLng(iaLatLng.latitude, iaLatLng.longitude);
GroundOverlayOptions fpOverlay = new GroundOverlayOptions()
.image(bitmapDescriptor)
.position(center, floorPlan.getWidthMeters(), floorPlan.getHeightMeters())
.bearing(floorPlan.getBearing());
mGroundOverlay = mMap.addGroundOverlay(fpOverlay);
}
}
/**
* Download floor plan using Picasso library.
*/
private void fetchFloorPlanBitmap(final IAFloorPlan floorPlan) {
final String url = floorPlan.getUrl();
if (mLoadTarget == null) {
mLoadTarget = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d(TAG, "onBitmap loaded with dimensions: " + bitmap.getWidth() + "x"
+ bitmap.getHeight());
setupGroundOverlay(floorPlan, bitmap);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
@Override
public void onBitmapFailed(Drawable placeHolderDraweble) {
Toast.makeText(MapsActivity.this, "Failed to load bitmap",
Toast.LENGTH_SHORT).show();
}
};
}
RequestCreator request = Picasso.with(this).load(url);
final int bitmapWidth = floorPlan.getBitmapWidth();
final int bitmapHeight = floorPlan.getBitmapHeight();
if (bitmapHeight > MAX_DIMENSION) {
request.resize(0, MAX_DIMENSION);
} else if (bitmapWidth > MAX_DIMENSION) {
request.resize(MAX_DIMENSION, 0);
}
request.into(mLoadTarget);
}
/**
* Fetches floor plan data from IndoorAtlas server.
*/
private void fetchFloorPlan(String id) {
// if there is already running task, cancel it
cancelPendingNetworkCalls();
final IATask<IAFloorPlan> task = mResourceManager.fetchFloorPlanWithId(id);
task.setCallback(new IAResultCallback<IAFloorPlan>() {
@Override
public void onResult(IAResult<IAFloorPlan> result) {
if (result.isSuccess() && result.getResult() != null) {
// retrieve bitmap for this floor plan metadata
fetchFloorPlanBitmap(result.getResult());
} else {
// ignore errors if this task was already canceled
if (!task.isCancelled()) {
// do something with error
Toast.makeText(MapsActivity.this,
"loading floor plan failed: " + result.getError(), Toast.LENGTH_LONG)
.show();
// remove current ground overlay
if (mGroundOverlay != null) {
mGroundOverlay.remove();
mGroundOverlay = null;
}
}
}
}
}, Looper.getMainLooper()); // deliver callbacks using main looper
// keep reference to task so that it can be canceled if needed
mFetchFloorPlanTask = task;
}
/**
* Helper method to cancel current task if any.
*/
private void cancelPendingNetworkCalls() {
if (mFetchFloorPlanTask != null && !mFetchFloorPlanTask.isCancelled()) {
mFetchFloorPlanTask.cancel();
}
}
} |
package org.commcare.activities;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.SearchView;
import android.widget.TextView;
import org.commcare.CommCareApplication;
import org.commcare.android.database.user.models.ACase;
import org.commcare.fragments.BreadcrumbBarFragment;
import org.commcare.fragments.ContainerFragment;
import org.commcare.fragments.TaskConnectorFragment;
import org.commcare.interfaces.WithUIController;
import org.commcare.logging.AndroidLogger;
import org.commcare.session.SessionFrame;
import org.commcare.session.SessionInstanceBuilder;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.StackFrameStep;
import org.commcare.tasks.templates.CommCareTask;
import org.commcare.tasks.templates.CommCareTaskConnector;
import org.commcare.utils.AndroidUtil;
import org.commcare.utils.ConnectivityStatus;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.SessionStateUninitException;
import org.commcare.views.ManagedUiFramework;
import org.commcare.views.dialogs.StandardAlertDialog;
import org.commcare.views.dialogs.AlertDialogFragment;
import org.commcare.views.dialogs.CommCareAlertDialog;
import org.commcare.views.dialogs.CustomProgressDialog;
import org.commcare.views.dialogs.DialogController;
import org.commcare.views.media.AudioController;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.NoLocalizedTextException;
/**
* Base class for CommCareActivities to simplify
* common localization and workflow tasks
*
* @author ctsims
*/
public abstract class CommCareActivity<R> extends FragmentActivity
implements CommCareTaskConnector<R>, DialogController, OnGestureListener {
private static final String TAG = CommCareActivity.class.getSimpleName();
private static final String KEY_PROGRESS_DIALOG_FRAG = "progress-dialog-fragment";
private static final String KEY_ALERT_DIALOG_FRAG = "alert-dialog-fragment";
private int invalidTaskIdMessageThrown = -2;
private TaskConnectorFragment<R> stateHolder;
// Fields for implementing task transitions for CommCareTaskConnector
private boolean inTaskTransition;
/**
* Used to indicate that the (progress) dialog associated with a task
* should be dismissed because the task has completed or been canceled.
*/
private boolean dismissLastDialogAfterTransition = true;
private AlertDialogFragment alertDialogToShowOnResume;
private GestureDetector mGestureDetector;
protected String lastQueryString;
/**
* Activity has been put in the background. Flag prevents dialogs
* from being shown while activity isn't active.
*/
private boolean areFragmentsPaused = true;
/**
* Mark when task tried to show progress dialog before fragments have resumed,
* so that the dialog can be shown when fragments have fully resumed.
*/
private boolean triedBlockingWhilePaused;
private boolean triedDismissingWhilePaused;
/**
* Store the id of a task progress dialog so it can be disabled/enabled
* on activity pause/resume.
*/
private int dialogId = -1;
private ContainerFragment<Bundle> managedUiState;
private boolean isMainScreenBlocked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = this.getSupportFragmentManager();
stateHolder = (TaskConnectorFragment<R>) fm.findFragmentByTag("state");
// stateHolder and its previous state aren't null if the activity is
// being created due to an orientation change.
if (stateHolder == null) {
stateHolder = new TaskConnectorFragment<>();
fm.beginTransaction().add(stateHolder, "state").commit();
// entering new activity, not just rotating one, so release old
// media
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
// For activities using a uiController, this must be called before persistManagedUiState()
if (usesUIController()) {
((WithUIController)this).initUIController();
}
persistManagedUiState(fm);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && shouldShowBreadcrumbBar()) {
getActionBar().setDisplayShowCustomEnabled(true);
// Add breadcrumb bar
BreadcrumbBarFragment bar = (BreadcrumbBarFragment) fm.findFragmentByTag("breadcrumbs");
// If the state holder is null, create a new one for this activity
if (bar == null) {
bar = new BreadcrumbBarFragment();
fm.beginTransaction().add(bar, "breadcrumbs").commit();
} else {
// If we rotated while the persistent tile was expanded, it will not have gotten
// re-expanded, so reset the tracking variable to reflect that
bar.persistentCaseTileIsExpanded = false;
}
}
mGestureDetector = new GestureDetector(this, this);
}
private void persistManagedUiState(FragmentManager fm) {
if (isManagedUiActivity()) {
managedUiState = (ContainerFragment)fm.findFragmentByTag("ui-state");
if (managedUiState == null) {
managedUiState = new ContainerFragment<>();
fm.beginTransaction().add(managedUiState, "ui-state").commit();
loadUiElementState(null);
} else {
loadUiElementState(managedUiState.getData());
}
}
}
private void loadUiElementState(Bundle savedInstanceState) {
ManagedUiFramework.setContentView(this);
if (savedInstanceState != null) {
ManagedUiFramework.restoreUiElements(this, savedInstanceState);
} else {
ManagedUiFramework.loadUiElements(this);
}
}
/**
* Call this method from an implementing activity to request a new event trigger for any time
* the available space for the core content view changes significantly, for instance when the
* soft keyboard is displayed or hidden.
*
* This method will also be reliably triggered upon the end of the first layout pass, so it
* can be used to do the initial setup for adaptive layouts as well as their updates.
*
* After this is called, major layout size changes will be triggered in the onMajorLayoutChange
* method.
*/
protected void requestMajorLayoutUpdates() {
final View decorView = getWindow().getDecorView();
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int mPreviousDecorViewFrameHeight = 0;
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that are visible after the
//recent change.
decorView.getWindowVisibleDisplayFrame(r);
int mainContentHeight = r.height();
int previousMeasurementDifference = Math.abs(mainContentHeight - mPreviousDecorViewFrameHeight);
if (previousMeasurementDifference > 100) {
onMajorLayoutChange(r);
}
mPreviousDecorViewFrameHeight = mainContentHeight;
}
});
}
/**
* This method is called when the root view size available to the activity has changed
* significantly. It is the appropriate place to trigger adaptive layout behaviors.
*
* Note for performance that changes to declarative view properties here will trigger another
* layout pass.
*
* This callback is only triggered if the parent view has called requestMajorLayoutUpdates
*
* @param newRootViewDimensions The dimensions of the new root screen view that is available
* to the activity.
*/
protected void onMajorLayoutChange(Rect newRootViewDimensions) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected boolean isTopNavEnabled() {
return false;
}
/**
* If a message for the user has been set in CommCareApplication, show it and then clear it
*/
private void showPendingUserMessage() {
String[] messageAndTitle = CommCareApplication.instance().getPendingUserMessage();
if (messageAndTitle != null) {
showAlertDialog(StandardAlertDialog.getBasicAlertDialog(
this, messageAndTitle[1], messageAndTitle[0], null));
CommCareApplication.instance().clearPendingUserMessage();
}
}
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// In honeycomb and above the fragment takes care of this
this.setTitle(getTitle(this, getActivityTitle()));
}
AudioController.INSTANCE.playPreviousAudio();
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
areFragmentsPaused = false;
syncTaskBlockingWithDialogFragment();
showPendingAlertDialog();
}
@Override
protected void onPause() {
super.onPause();
if (isManagedUiActivity()) {
managedUiState.setData(ManagedUiFramework.saveUiStateToBundle(this));
}
areFragmentsPaused = true;
AudioController.INSTANCE.systemInducedPause();
}
@Override
public <A, B, C> void connectTask(CommCareTask<A, B, C, R> task) {
stateHolder.connectTask(task, this);
// If we've left an old dialog showing during the task transition and it was from the same
// task as the one that is starting, we want to just leave it up for the next task too
CustomProgressDialog currDialog = getCurrentProgressDialog();
if (currDialog != null && currDialog.getTaskId() == task.getTaskId()) {
dismissLastDialogAfterTransition = false;
}
}
/**
* @return wakelock level for an activity with a running task attached to
* it; defaults to not using wakelocks.
*/
public int getWakeLockLevel() {
return CommCareTask.DONT_WAKELOCK;
}
/**
* Sync progress dialog fragment with any task state changes that may have
* occurred while the activity was paused.
*/
private void syncTaskBlockingWithDialogFragment() {
if (triedDismissingWhilePaused) {
triedDismissingWhilePaused = false;
dismissProgressDialog();
} else if (triedBlockingWhilePaused) {
triedBlockingWhilePaused = false;
showNewProgressDialog();
}
}
@Override
public void startBlockingForTask(int id) {
dialogId = id;
if (areFragmentsPaused) {
// post-pone dialog transactions until after fragments have fully resumed.
triedBlockingWhilePaused = true;
} else {
showNewProgressDialog();
}
}
private void showNewProgressDialog() {
// Only show a new dialog if we chose to dismiss the old one; If
// dismissLastDialogAfterTransition is false, that means we left the last dialog up and do
// not need to create a new one
if (dismissLastDialogAfterTransition) {
dismissProgressDialog();
showProgressDialog(dialogId);
}
}
@Override
public void stopBlockingForTask(int id) {
dialogId = -1;
if (id >= 0) {
if (inTaskTransition) {
dismissLastDialogAfterTransition = true;
} else {
dismissProgressDialog();
}
}
stateHolder.releaseWakeLock();
}
@Override
public R getReceiver() {
return (R) this;
}
@Override
public void startTaskTransition() {
inTaskTransition = true;
}
@Override
public void stopTaskTransition() {
inTaskTransition = false;
if (dismissLastDialogAfterTransition) {
dismissProgressDialog();
// Re-set shouldDismissDialog to true after this transition cycle is over
dismissLastDialogAfterTransition = true;
}
}
/**
* Display exception details as a pop-up to the user.
*/
private void displayException(String title, String message) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
}
}
};
showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this, title,
message, android.R.drawable.ic_dialog_info, listener));
}
public void displayCaseListFilterException(Exception e) {
displayException(
Localization.get("notification.case.predicate.title"),
Localization.get("notification.case.predicate.action", new String[]{e.getMessage()}));
}
@Override
public void taskCancelled() {
}
public void cancelCurrentTask() {
stateHolder.cancelTask();
}
protected void restoreLastQueryString() {
lastQueryString = (String)CommCareApplication.instance().getCurrentSession().getCurrentFrameStepExtra(SessionInstanceBuilder.KEY_LAST_QUERY_STRING);
}
protected void saveLastQueryString() {
CommCareApplication.instance().getCurrentSession().addExtraToCurrentFrameStep(SessionInstanceBuilder.KEY_LAST_QUERY_STRING, lastQueryString);
}
//Graphical stuff below, needs to get modularized
protected void transplantStyle(TextView target, int resource) {
//get styles from here
TextView tv = (TextView) View.inflate(this, resource, null);
int[] padding = {target.getPaddingLeft(), target.getPaddingTop(), target.getPaddingRight(), target.getPaddingBottom()};
target.setTextColor(tv.getTextColors().getDefaultColor());
target.setTypeface(tv.getTypeface());
target.setBackgroundDrawable(tv.getBackground());
target.setPadding(padding[0], padding[1], padding[2], padding[3]);
}
/**
* The right-hand side of the title associated with this activity.
* <p/>
* This will update dynamically as the activity loads/updates, but if
* it will ever have a value it must return a blank string when one
* isn't available.
*/
protected String getActivityTitle() {
return null;
}
public static String getTopLevelTitleName(Context c) {
try {
return Localization.get("app.display.name");
} catch (NoLocalizedTextException nlte) {
return c.getString(org.commcare.dalvik.R.string.title_bar_name);
}
}
protected static String getTitle(Context c, String local) {
String topLevel = getTopLevelTitleName(c);
String[] stepTitles = new String[0];
try {
stepTitles = CommCareApplication.instance().getCurrentSession().getHeaderTitles();
//See if we can insert any case hacks
int i = 0;
for (StackFrameStep step : CommCareApplication.instance().getCurrentSession().getFrame().getSteps()) {
try {
if (SessionFrame.STATE_DATUM_VAL.equals(step.getType())) {
//Haaack
if (step.getId() != null && step.getId().contains("case_id")) {
ACase foundCase = CommCareApplication.instance().getUserStorage(ACase.STORAGE_KEY, ACase.class).getRecordForValue(ACase.INDEX_CASE_ID, step.getValue());
stepTitles[i] = Localization.get("title.datum.wrapper", new String[]{foundCase.getName()});
}
}
} catch (Exception e) {
//TODO: Your error handling is bad and you should feel bad
}
++i;
}
} catch (SessionStateUninitException e) {
}
StringBuilder titleBuf = new StringBuilder(topLevel);
for (String title : stepTitles) {
if (title != null) {
titleBuf.append(" > ").append(title);
}
}
if (local != null) {
titleBuf.append(" > ").append(local);
}
return titleBuf.toString();
}
protected boolean isNetworkNotConnected() {
return !ConnectivityStatus.isNetworkAvailable(this);
}
// region - All methods for implementation of DialogController
@Override
public void updateProgress(String newMessage, String newTitle, int taskId) {
updateDialogContent(newMessage, newTitle, taskId);
}
@Override
public void updateProgress(String newMessage, int taskId) {
updateDialogContent(newMessage, null, taskId);
}
private void updateDialogContent(String newMessage, String newTitle, int taskId) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
if (mProgressDialog.getTaskId() == taskId) {
mProgressDialog.updateMessage(newMessage);
if (newTitle != null) {
mProgressDialog.updateTitle(newTitle);
}
} else {
warnInvalidProgressUpdate(taskId);
}
}
}
@Override
public void hideTaskCancelButton() {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null) {
mProgressDialog.removeCancelButton();
}
}
@Override
public void updateProgressBarVisibility(boolean visible) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
mProgressDialog.updateProgressBarVisibility(visible);
}
}
@Override
public void updateProgressBar(int progress, int max, int taskId) {
CustomProgressDialog mProgressDialog = getCurrentProgressDialog();
if (mProgressDialog != null && !areFragmentsPaused) {
if (mProgressDialog.getTaskId() == taskId) {
mProgressDialog.updateProgressBar(progress, max);
} else {
warnInvalidProgressUpdate(taskId);
}
}
}
private void warnInvalidProgressUpdate(int taskId) {
String message = "Attempting to update a progress dialog whose taskId (" + taskId +
" does not match the task for which the update message was intended.";
if(invalidTaskIdMessageThrown != taskId) {
invalidTaskIdMessageThrown = taskId;
Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, message);
} else {
Log.w(TAG, message);
}
}
@Override
public void showProgressDialog(int taskId) {
if (taskId >= 0) {
CustomProgressDialog dialog = generateProgressDialog(taskId);
if (dialog != null) {
dialog.show(getSupportFragmentManager(), KEY_PROGRESS_DIALOG_FRAG);
}
}
}
@Override
public CustomProgressDialog getCurrentProgressDialog() {
return (CustomProgressDialog) getSupportFragmentManager().
findFragmentByTag(KEY_PROGRESS_DIALOG_FRAG);
}
@Override
public void dismissProgressDialog() {
CustomProgressDialog progressDialog = getCurrentProgressDialog();
if (progressDialog != null && progressDialog.isAdded()) {
if (areFragmentsPaused) {
triedDismissingWhilePaused = true;
} else {
progressDialog.dismiss();
}
}
}
@Override
public CustomProgressDialog generateProgressDialog(int taskId) {
//dummy method for compilation, implementation handled in those subclasses that need it
return null;
}
@Override
public AlertDialogFragment getCurrentAlertDialog() {
return (AlertDialogFragment) getSupportFragmentManager().
findFragmentByTag(KEY_ALERT_DIALOG_FRAG);
}
@Override
public void showPendingAlertDialog() {
if (alertDialogToShowOnResume != null) {
alertDialogToShowOnResume.show(getSupportFragmentManager(), KEY_ALERT_DIALOG_FRAG);
alertDialogToShowOnResume = null;
} else {
showPendingUserMessage();
}
}
@Override
public void dismissAlertDialog() {
DialogFragment alertDialog = getCurrentAlertDialog();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
@Override
public void showAlertDialog(CommCareAlertDialog d) {
AlertDialogFragment dialog = AlertDialogFragment.fromCommCareAlertDialog(d);
if (areFragmentsPaused) {
alertDialogToShowOnResume = dialog;
} else {
if (getCurrentAlertDialog() != null) {
// replace existing dialog by dismissing it
dismissAlertDialog();
}
dialog.show(getSupportFragmentManager(), KEY_ALERT_DIALOG_FRAG);
}
}
// endregion
public Pair<Detail, TreeReference> requestEntityContext() {
return null;
}
/**
* Interface to perform additional setup code when adding an ActionBar
*/
public interface ActionBarInstantiator {
void onActionBarFound(MenuItem searchItem, SearchView searchView, MenuItem barcodeItem);
}
/**
* Tries to add a SearchView action to the app bar of the current Activity. If it is added,
* the alternative search widget is removed, and ActionBarInstantiator is run, if it exists.
* Used in EntitySelectActivity and FormRecordListActivity.
*
* @param activity Current activity
* @param menu Menu passed through onCreateOptionsMenu
* @param instantiator Optional ActionBarInstantiator for additional setup code.
*/
protected void tryToAddSearchActionToAppBar(Activity activity, Menu menu,
ActionBarInstantiator instantiator) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(org.commcare.dalvik.R.menu.action_bar_search_view, menu);
MenuItem searchMenuItem = menu.findItem(org.commcare.dalvik.R.id.search_action_bar);
SearchView searchView =
(SearchView) searchMenuItem.getActionView();
MenuItem barcodeItem = menu.findItem(org.commcare.dalvik.R.id.barcode_scan_action_bar);
if (searchView != null) {
int[] searchViewStyle =
AndroidUtil.getThemeColorIDs(this,
new int[]{org.commcare.dalvik.R.attr.searchbox_action_bar_color});
int id = searchView.getContext()
.getResources()
.getIdentifier("android:id/search_src_text", null, null);
TextView textView = (TextView) searchView.findViewById(id);
textView.setTextColor(searchViewStyle[0]);
if (instantiator != null) {
instantiator.onActionBarFound(searchMenuItem, searchView, barcodeItem);
}
}
View bottomSearchWidget = activity.findViewById(org.commcare.dalvik.R.id.searchfooter);
if (bottomSearchWidget != null) {
bottomSearchWidget.setVisibility(View.GONE);
}
}
}
/**
* Whether or not the "Back" action makes sense for this activity.
*
* @return True if "Back" is a valid concept for the Activity and should be shown
* in the action bar if available. False otherwise.
*/
public boolean isBackEnabled() {
return true;
}
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
return !(mGestureDetector == null || !mGestureDetector.onTouchEvent(mv)) || super.dispatchTouchEvent(mv);
}
@Override
public boolean onDown(MotionEvent arg0) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (isHorizontalSwipe(this, e1, e2) && !isMainScreenBlocked) {
if (velocityX <= 0) {
return onForwardSwipe();
}
return onBackwardSwipe();
}
return false;
}
/**
* Action to take when user swipes forward during activity.
*
* @return Whether or not the swipe was handled
*/
protected boolean onForwardSwipe() {
return false;
}
/**
* Action to take when user swipes backward during activity.
*
* @return Whether or not the swipe was handled
*/
protected boolean onBackwardSwipe() {
return false;
}
@Override
public void onBackPressed() {
FragmentManager fm = this.getSupportFragmentManager();
BreadcrumbBarFragment bar = (BreadcrumbBarFragment)fm.findFragmentByTag("breadcrumbs");
if (bar != null && bar.persistentCaseTileIsExpanded) {
bar.collapsePersistentCaseTile(this);
} else {
super.onBackPressed();
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
}
@Override
public void onLongPress(MotionEvent arg0) {
// ignore
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// ignore
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
return false;
}
/**
* Decide if two given MotionEvents represent a swipe.
*
* @return True iff the movement is a definitive horizontal swipe.
*/
private static boolean isHorizontalSwipe(Activity activity, MotionEvent e1, MotionEvent e2) {
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
//details of the motion itself
float xMov = Math.abs(e1.getX() - e2.getX());
float yMov = Math.abs(e1.getY() - e2.getY());
double angleOfMotion = ((Math.atan(yMov / xMov) / Math.PI) * 180);
// for all screens a swipe is left/right of at least .25" and at an angle of no more than 30
//degrees
int xPixelLimit = (int) (dm.xdpi * .25);
return xMov > xPixelLimit && angleOfMotion < 30;
}
/**
* Rebuild the activity's menu options based on the current state of the activity.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void rebuildOptionsMenu() {
if (CommCareApplication.instance().getCurrentApp() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
invalidateOptionsMenu();
} else {
supportInvalidateOptionsMenu();
}
}
}
public Spannable localize(String key) {
return MarkupUtil.localizeStyleSpannable(this, key);
}
public Spannable localize(String key, String arg) {
return MarkupUtil.localizeStyleSpannable(this, key, arg);
}
public Spannable localize(String key, String[] args) {
return MarkupUtil.localizeStyleSpannable(this, key, args);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void refreshActionBar() {
if (shouldShowBreadcrumbBar()) {
FragmentManager fm = this.getSupportFragmentManager();
BreadcrumbBarFragment bar = (BreadcrumbBarFragment) fm.findFragmentByTag("breadcrumbs");
bar.refresh(this);
}
}
/**
* Activity has been put in the background. Useful in knowing when to not
* perform dialog or fragment transactions
*/
protected boolean areFragmentsPaused() {
return areFragmentsPaused;
}
public void setMainScreenBlocked(boolean isBlocked) {
isMainScreenBlocked = isBlocked;
}
private boolean usesUIController() {
return this instanceof WithUIController;
}
public Object getUIManager() {
if (usesUIController()) {
return ((WithUIController)this).getUIController();
} else {
return this;
}
}
private boolean isManagedUiActivity() {
return ManagedUiFramework.isManagedUi(getUIManager().getClass());
}
public void setStateHolder(TaskConnectorFragment<R> stateHolder) {
this.stateHolder = stateHolder;
}
protected String getLastQueryString() {
return lastQueryString;
}
protected void setLastQueryString(String lastQueryString) {
this.lastQueryString = lastQueryString;
}
protected boolean shouldShowBreadcrumbBar() {
return true;
}
} |
package restaurants.tests;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class LoginTests extends TestBase {
@Test (enabled = false)
public void buttonLoginPresentTest(){
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.log-in")), true);
}
@Test(enabled = true)
public void formLoginPresentTest(){
app.getMainPageHelper().click(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.log-in"));
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.popup-modal-inner.popup-modal-login")),true);
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.log-block a.login-link.soc.fb")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block a.login-link.soc.fb > span")),"ВОЙТИ ЧЕРЕЗ FACEBOOK");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.log-block a.login-link.soc.google")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block a.login-link.soc.google > span")),"ВОЙТИ ЧЕРЕЗ GOOGLE+");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.log-block a.login-link.soc.tw")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block a.login-link.soc.tw > span")),"ВОЙТИ ЧЕРЕЗ TWITTER");
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block div.divider")),"ИЛИ");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.log-block div.input-wrap label[for='email']")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block div.input-wrap label[for='email'] > span")),"Email");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.log-block div.input-wrap label[for='pass']")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.log-block div.input-wrap label[for='pass'] > span")),"Пароль");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.popup-modal-inner.popup-modal-login a.login-link.email.login-form")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.popup-modal-inner.popup-modal-login a.login-link.email.login-form > span")),"ЛОГИН");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.popup-modal-inner.popup-modal-login div.popup-footer div.line.log")),true);
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.popup-modal-inner.popup-modal-login div.popup-footer div.line.log > p")),"Вы еще не с нами? Присоединяйтесь!");
}
@Test(enabled = false)
public void loginManagerTestPosTroughEmailTest (){
app.getSessionHelper().login(usernameAdmin, passwordAdmin);
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.user-profile-link")), true);
assertEquals(app.getMainPageHelper()
.attribute(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.user-profile-link"),"href"),"http://lptest.bigdig.com.ua/manager/restaurants");
assertEquals(app.getMainPageHelper()
.text(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.user-profile-link")), "MANAGER");
assertEquals(app.getMainPageHelper()
.elementPresent(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.user-profile-link > i.fa.fa-user")),true);
}
@Test(enabled = false)
public void loginClientTestPosThroughEmailTest(){
app.getSessionHelper().login(usernameGuest, passwordGuest);
assertEquals(app.getMainPageHelper()
.attribute(By.cssSelector("div.header-top.clear div.wrap div.to-right > a.user-profile-link"),"href"),"http://lptest.bigdig.com.ua/user/profile");
}
} |
package com.intellij.util;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.NotNullFactory;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Proxy;
import java.util.Comparator;
import java.util.List;
/**
* @author peter
*/
public class ObjectUtils {
private ObjectUtils() {
}
/**
* @see NotNullizer
*/
public static final Object NULL = sentinel("ObjectUtils.NULL");
/**
* Creates a new object which could be used as sentinel value (special value to distinguish from any other object). It does not equal
* to any other object. Usually should be assigned to the static final field.
*
* @param name an object name, returned from {@link #toString()} to simplify the debugging or heap dump analysis
* (guaranteed to be stored as sentinel object field). If sentinel is assigned to the static final field,
* it's recommended to supply that field name (possibly qualified with the class name).
* @return a new sentinel object
*/
@NotNull
public static Object sentinel(@NotNull String name) {
return new Sentinel(name);
}
public static void reachabilityFence(@SuppressWarnings("unused") Object o) {}
private static class Sentinel {
private final String myName;
Sentinel(@NotNull String name) {
myName = name;
}
@Override
public String toString() {
return myName;
}
}
/**
* Creates an instance of class {@code ofInterface} with its {@link Object#toString()} method returning {@code name}.
* No other guarantees about return value behaviour.
* {@code ofInterface} must represent an interface class.
* Useful for stubs in generic code, e.g. for storing in {@code List<T>} to represent empty special value.
*/
@NotNull
public static <T> T sentinel(@NotNull final String name, @NotNull Class<T> ofInterface) {
if (!ofInterface.isInterface()) {
throw new IllegalArgumentException("Expected interface but got: " + ofInterface);
}
// java.lang.reflect.Proxy.ProxyClassFactory fails if the class is not available via the classloader.
// We must use interface own classloader because classes from plugins are not available via ObjectUtils' classloader.
//noinspection unchecked
return (T)Proxy.newProxyInstance(ofInterface.getClassLoader(), new Class[]{ofInterface}, (proxy, method, args) -> {
if ("toString".equals(method.getName()) && args.length == 0) {
return name;
}
throw new AbstractMethodError();
});
}
@NotNull
public static <T> T assertNotNull(@Nullable T t) {
return notNull(t);
}
public static <T> void assertAllElementsNotNull(@NotNull T[] array) {
for (int i = 0; i < array.length; i++) {
T t = array[i];
if (t == null) {
throw new NullPointerException("Element [" + i + "] is null");
}
}
}
@Contract(value = "!null, _ -> !null; _, !null -> !null; null, null -> null", pure = true)
public static <T> T chooseNotNull(@Nullable T t1, @Nullable T t2) {
return t1 == null? t2 : t1;
}
@Contract(value = "!null, _ -> !null; _, !null -> !null; null, null -> null", pure = true)
public static <T> T coalesce(@Nullable T t1, @Nullable T t2) {
return chooseNotNull(t1, t2);
}
@Contract(value = "!null, _, _ -> !null; _, !null, _ -> !null; _, _, !null -> !null; null,null,null -> null", pure = true)
public static <T> T coalesce(@Nullable T t1, @Nullable T t2, @Nullable T t3) {
return t1 != null ? t1 : t2 != null ? t2 : t3;
}
@Nullable
public static <T> T coalesce(@Nullable Iterable<? extends T> o) {
if (o == null) return null;
for (T t : o) {
if (t != null) return t;
}
return null;
}
@NotNull
public static <T> T notNull(@Nullable T value) {
//noinspection ConstantConditions
return notNull(value, value);
}
@NotNull
@Contract(pure = true)
public static <T> T notNull(@Nullable T value, @NotNull T defaultValue) {
return value == null ? defaultValue : value;
}
@NotNull
public static <T> T notNull(@Nullable T value, @NotNull NotNullFactory<? extends T> defaultValue) {
return value == null ? defaultValue.create() : value;
}
@Contract(value = "null, _ -> null", pure = true)
@Nullable
public static <T> T tryCast(@Nullable Object obj, @NotNull Class<T> clazz) {
if (clazz.isInstance(obj)) {
return clazz.cast(obj);
}
return null;
}
@Nullable
public static <T, S> S doIfCast(@Nullable Object obj, @NotNull Class<T> clazz, final Convertor<? super T, ? extends S> convertor) {
if (clazz.isInstance(obj)) {
//noinspection unchecked
return convertor.convert((T)obj);
}
return null;
}
@Contract("null, _ -> null")
@Nullable
public static <T, S> S doIfNotNull(@Nullable T obj, @NotNull Function<? super T, ? extends S> function) {
return obj == null ? null : function.fun(obj);
}
public static <T> void consumeIfNotNull(@Nullable T obj, @NotNull Consumer<? super T> consumer) {
if (obj != null) {
consumer.consume(obj);
}
}
public static <T> void consumeIfCast(@Nullable Object obj, @NotNull Class<T> clazz, final Consumer<? super T> consumer) {
if (clazz.isInstance(obj)) {
//noinspection unchecked
consumer.consume((T)obj);
}
}
@Nullable
@Contract("null, _ -> null")
public static <T> T nullizeByCondition(@Nullable final T obj, @NotNull final Condition<? super T> condition) {
if (condition.value(obj)) {
return null;
}
return obj;
}
/**
* Performs binary search on the range [fromIndex, toIndex)
* @param indexComparator a comparator which receives a middle index and returns the result of comparision of the value at this index and the goal value
* (e.g 0 if found, -1 if the value[middleIndex] < goal, or 1 if value[middleIndex] > goal)
* @return index for which {@code indexComparator} returned 0 or {@code -insertionIndex-1} if wasn't found
* @see java.util.Arrays#binarySearch(Object[], Object, Comparator)
* @see java.util.Collections#binarySearch(List, Object, Comparator)
*/
public static int binarySearch(int fromIndex, int toIndex, @NotNull IntIntFunction indexComparator) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int cmp = indexComparator.fun(mid);
if (cmp < 0) low = mid + 1;
else if (cmp > 0) high = mid - 1;
else return mid;
}
return -(low + 1);
}
} |
package com.restfb;
import static com.restfb.util.EncodingUtils.decodeBase64;
import static com.restfb.util.EncodingUtils.encodeHex;
import static com.restfb.util.StringUtils.isBlank;
import static com.restfb.util.StringUtils.join;
import static com.restfb.util.StringUtils.toBytes;
import static com.restfb.util.StringUtils.toInteger;
import static com.restfb.util.StringUtils.trimToEmpty;
import static com.restfb.util.StringUtils.trimToNull;
import static com.restfb.util.UrlUtils.urlEncode;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.restfb.WebRequestor.Response;
import com.restfb.batch.BatchRequest;
import com.restfb.batch.BatchResponse;
import com.restfb.exception.FacebookException;
import com.restfb.exception.FacebookExceptionMapper;
import com.restfb.exception.FacebookGraphException;
import com.restfb.exception.FacebookJsonMappingException;
import com.restfb.exception.FacebookNetworkException;
import com.restfb.exception.FacebookOAuthException;
import com.restfb.exception.FacebookQueryParseException;
import com.restfb.exception.FacebookResponseContentException;
import com.restfb.exception.FacebookResponseStatusException;
import com.restfb.exception.FacebookSignedRequestParsingException;
import com.restfb.exception.FacebookSignedRequestVerificationException;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonException;
import com.restfb.json.JsonObject;
import com.restfb.util.StringUtils;
public class DefaultFacebookClient extends BaseFacebookClient implements FacebookClient {
/**
* Graph API access token.
*/
protected String accessToken;
/**
* Graph API app secret.
*/
private String appSecret;
/**
* Knows how to map Graph API exceptions to formal Java exception types.
*/
protected FacebookExceptionMapper graphFacebookExceptionMapper;
/**
* API endpoint URL.
*/
protected static final String FACEBOOK_GRAPH_ENDPOINT_URL = "https://graph.facebook.com";
/**
* Read-only API endpoint URL.
*/
protected static final String FACEBOOK_READ_ONLY_ENDPOINT_URL = "https://api-read.facebook.com/method";
/**
* Video Upload API endpoint URL.
*
* @since 1.6.5
*/
protected static final String FACEBOOK_GRAPH_VIDEO_ENDPOINT_URL = "https://graph-video.facebook.com";
/**
* Reserved method override parameter name.
*/
protected static final String METHOD_PARAM_NAME = "method";
/**
* Reserved "multiple IDs" parameter name.
*/
protected static final String IDS_PARAM_NAME = "ids";
/**
* Reserved legacy FQL query parameter name.
*/
protected static final String QUERY_PARAM_NAME = "query";
/**
* Reserved legacy FQL multiquery parameter name.
*/
protected static final String QUERIES_PARAM_NAME = "queries";
/**
* Reserved FQL query parameter name.
*/
protected static final String FQL_QUERY_PARAM_NAME = "q";
/**
* Reserved "result format" parameter name.
*/
protected static final String FORMAT_PARAM_NAME = "format";
/**
* API error response 'error' attribute name.
*/
protected static final String ERROR_ATTRIBUTE_NAME = "error";
/**
* API error response 'type' attribute name.
*/
protected static final String ERROR_TYPE_ATTRIBUTE_NAME = "type";
/**
* API error response 'error_user_title' attribute name.
*/
protected static final String ERROR_USER_TITLE_ATTRIBUTE_NAME = "error_user_title";
/**
* API error response 'error_user_msg' attribute name.
*/
protected static final String ERROR_USER_MSG_ATTRIBUTE_NAME = "error_user_msg";
/**
* API error response 'message' attribute name.
*/
protected static final String ERROR_MESSAGE_ATTRIBUTE_NAME = "message";
/**
* API error response 'code' attribute name.
*/
protected static final String ERROR_CODE_ATTRIBUTE_NAME = "code";
/**
* API error response 'error_subcode' attribute name.
*/
protected static final String ERROR_SUBCODE_ATTRIBUTE_NAME = "error_subcode";
/**
* Batch API error response 'error' attribute name.
*/
protected static final String BATCH_ERROR_ATTRIBUTE_NAME = "error";
/**
* Batch API error response 'error_description' attribute name.
*/
protected static final String BATCH_ERROR_DESCRIPTION_ATTRIBUTE_NAME = "error_description";
/**
* Version of API endpoint.
*/
protected Version apiVersion = Version.UNVERSIONED;
/**
* By default this is <code>false</code>, so real http DELETE is used
*/
protected boolean httpDeleteFallback = false;
/**
* Creates a Facebook Graph API client with no access token.
* <p>
* Without an access token, you can view and search public graph data but can't do much else.
*
* @deprecated As of release 1.7.1, replaced by {@link #DefaultFacebookClient(com.restfb.Version) }
*/
@Deprecated
public DefaultFacebookClient() {
this((String) null);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @deprecated As of release 1.7.1 replaced by {@link #DefaultFacebookClient(java.lang.String, com.restfb.Version) }
*/
@Deprecated
public DefaultFacebookClient(String accessToken) {
this(accessToken, null, new DefaultWebRequestor(), new DefaultJsonMapper(), null);
}
/**
* Creates a Facebook Graph API client with the given {@code apiVersion}.
*
* @param apiVersion
* Version of the api endpoint
*/
public DefaultFacebookClient(Version apiVersion) {
this(null, null, new DefaultWebRequestor(), new DefaultJsonMapper(), apiVersion);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param apiVersion
* Version of the api endpoint
* @since 1.6.14
*/
public DefaultFacebookClient(String accessToken, Version apiVersion) {
this(accessToken, null, new DefaultWebRequestor(), new DefaultJsonMapper(), apiVersion);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param appSecret
* A Facebook application secret.
* @since 1.6.13
* @deprecated As of release 1.7.1, replaced by
* {@link #DefaultFacebookClient(java.lang.String, java.lang.String, com.restfb.Version) }
*/
@Deprecated
public DefaultFacebookClient(String accessToken, String appSecret) {
this(accessToken, appSecret, new DefaultWebRequestor(), new DefaultJsonMapper(), null);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param appSecret
* A Facebook application secret.
* @param apiVersion
* Version of the api endpoint
* @since 1.6.14
*/
public DefaultFacebookClient(String accessToken, String appSecret, Version apiVersion) {
this(accessToken, appSecret, new DefaultWebRequestor(), new DefaultJsonMapper(), apiVersion);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param webRequestor
* The {@link WebRequestor} implementation to use for sending requests to the API endpoint.
* @param jsonMapper
* The {@link JsonMapper} implementation to use for mapping API response JSON to Java objects.
* @throws NullPointerException
* If {@code jsonMapper} or {@code webRequestor} is {@code null}.
* @deprecated As of release 1.7.1, replaced by
* {@link #DefaultFacebookClient(java.lang.String, com.restfb.WebRequestor, com.restfb.JsonMapper, com.restfb.Version) }
*/
@Deprecated
public DefaultFacebookClient(String accessToken, WebRequestor webRequestor, JsonMapper jsonMapper) {
this(accessToken, null, webRequestor, jsonMapper, null);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param webRequestor
* The {@link WebRequestor} implementation to use for sending requests to the API endpoint.
* @param jsonMapper
* The {@link JsonMapper} implementation to use for mapping API response JSON to Java objects.
* @param apiVersion
* Version of the api endpoint
* @throws NullPointerException
* If {@code jsonMapper} or {@code webRequestor} is {@code null}.
* @since 1.6.14
*/
public DefaultFacebookClient(String accessToken, WebRequestor webRequestor, JsonMapper jsonMapper, Version apiVersion) {
this(accessToken, null, webRequestor, jsonMapper, apiVersion);
}
/**
* Creates a Facebook Graph API client with the given {@code accessToken}, {@code webRequestor}, and
* {@code jsonMapper}.
*
* @param accessToken
* A Facebook OAuth access token.
* @param appSecret
* A Facebook application secret.
* @param webRequestor
* The {@link WebRequestor} implementation to use for sending requests to the API endpoint.
* @param jsonMapper
* The {@link JsonMapper} implementation to use for mapping API response JSON to Java objects.
* @param apiVersion
* Version of the api endpoint
* @throws NullPointerException
* If {@code jsonMapper} or {@code webRequestor} is {@code null}.
*/
public DefaultFacebookClient(String accessToken, String appSecret, WebRequestor webRequestor, JsonMapper jsonMapper,
Version apiVersion) {
super();
verifyParameterPresence("jsonMapper", jsonMapper);
verifyParameterPresence("webRequestor", webRequestor);
this.accessToken = trimToNull(accessToken);
this.appSecret = trimToNull(appSecret);
this.webRequestor = webRequestor;
this.jsonMapper = jsonMapper;
this.apiVersion = (null == apiVersion) ? Version.UNVERSIONED : apiVersion;
graphFacebookExceptionMapper = createGraphFacebookExceptionMapper();
illegalParamNames.addAll(Arrays
.asList(new String[] { ACCESS_TOKEN_PARAM_NAME, METHOD_PARAM_NAME, FORMAT_PARAM_NAME }));
}
/**
* @see com.restfb.FacebookClient#deleteObject(java.lang.String, com.restfb.Parameter[])
*/
@Override
public boolean deleteObject(String object, Parameter... parameters) {
verifyParameterPresence("object", object);
String responseString = makeRequest(object, true, true, null, parameters);
String cmpString;
try {
JsonObject jObj = new JsonObject(responseString);
cmpString = jObj.getString("success");
} catch (JsonException jex) {
cmpString = responseString;
}
return "true".equals(cmpString);
}
/**
* @see com.restfb.FacebookClient#fetchConnection(java.lang.String, java.lang.Class, com.restfb.Parameter[])
*/
@Override
public <T> Connection<T> fetchConnection(String connection, Class<T> connectionType, Parameter... parameters) {
verifyParameterPresence("connection", connection);
verifyParameterPresence("connectionType", connectionType);
return new Connection<T>(this, makeRequest(connection, parameters), connectionType);
}
/**
* @see com.restfb.FacebookClient#fetchConnectionPage(java.lang.String, java.lang.Class)
*/
@Override
public <T> Connection<T> fetchConnectionPage(final String connectionPageUrl, Class<T> connectionType) {
String connectionJson = null;
if (!isBlank(accessToken) && !isBlank(appSecret)) {
connectionJson = makeRequestAndProcessResponse(new Requestor() {
@Override
public Response makeRequest() throws IOException {
return webRequestor.executeGet(String.format("%s&%s=%s", connectionPageUrl,
urlEncode(APP_SECRET_PROOF_PARAM_NAME), obtainAppSecretProof(accessToken, appSecret)));
}
});
} else {
connectionJson = makeRequestAndProcessResponse(new Requestor() {
@Override
public Response makeRequest() throws IOException {
return webRequestor.executeGet(connectionPageUrl);
}
});
}
return new Connection<T>(this, connectionJson, connectionType);
}
/**
* @see com.restfb.FacebookClient#fetchObject(java.lang.String, java.lang.Class, com.restfb.Parameter[])
*/
@Override
public <T> T fetchObject(String object, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("object", object);
verifyParameterPresence("objectType", objectType);
return jsonMapper.toJavaObject(makeRequest(object, parameters), objectType);
}
/**
* @see com.restfb.FacebookClient#fetchObjects(java.util.List, java.lang.Class, com.restfb.Parameter[])
*/
@Override
@SuppressWarnings("unchecked")
public <T> T fetchObjects(List<String> ids, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("ids", ids);
verifyParameterPresence("connectionType", objectType);
if (ids.isEmpty())
throw new IllegalArgumentException("The list of IDs cannot be empty.");
for (Parameter parameter : parameters)
if (IDS_PARAM_NAME.equals(parameter.name))
throw new IllegalArgumentException("You cannot specify the '" + IDS_PARAM_NAME + "' URL parameter yourself - "
+ "RestFB will populate this for you with " + "the list of IDs you passed to this method.");
// Normalize the IDs
for (int i = 0; i < ids.size(); i++) {
String id = ids.get(i).trim().toLowerCase();
if ("".equals(id))
throw new IllegalArgumentException("The list of IDs cannot contain blank strings.");
ids.set(i, id);
}
try {
String jsonString =
makeRequest("", parametersWithAdditionalParameter(Parameter.with(IDS_PARAM_NAME, join(ids)), parameters));
return jsonMapper.toJavaObject(jsonString, objectType);
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to map connection JSON to Java objects", e);
}
}
/**
* @see com.restfb.FacebookClient#publish(java.lang.String, java.lang.Class, com.restfb.BinaryAttachment,
* com.restfb.Parameter[])
*/
public <T> T publish(String connection, Class<T> objectType, List<BinaryAttachment> binaryAttachments,
Parameter... parameters) {
verifyParameterPresence("connection", connection);
List<BinaryAttachment> attachments = new ArrayList<BinaryAttachment>();
if (binaryAttachments != null) {
attachments = binaryAttachments;
}
return jsonMapper.toJavaObject(makeRequest(connection, true, false, attachments, parameters), objectType);
}
/**
* @see com.restfb.FacebookClient#publish(java.lang.String, java.lang.Class, com.restfb.BinaryAttachment,
* com.restfb.Parameter[])
*/
@Override
public <T> T publish(String connection, Class<T> objectType, BinaryAttachment binaryAttachment,
Parameter... parameters) {
List<BinaryAttachment> attachments = new ArrayList<BinaryAttachment>();
if (binaryAttachment != null) {
attachments.add(binaryAttachment);
}
return publish(connection, objectType, attachments, parameters);
}
/**
* @see com.restfb.FacebookClient#publish(java.lang.String, java.lang.Class, com.restfb.Parameter[])
*/
@Override
public <T> T publish(String connection, Class<T> objectType, Parameter... parameters) {
return publish(connection, objectType, (List<BinaryAttachment>) null, parameters);
}
@Override
@Deprecated
@SuppressWarnings("unchecked")
public <T> T executeMultiquery(Map<String, String> queries, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("objectType", objectType);
for (Parameter parameter : parameters)
if (QUERIES_PARAM_NAME.equals(parameter.name))
throw new IllegalArgumentException("You cannot specify the '" + QUERIES_PARAM_NAME
+ "' URL parameter yourself - " + "RestFB will populate this for you with "
+ "the queries you passed to this method.");
try {
JsonArray jsonArray =
new JsonArray(makeRequest("fql.multiquery", false, false, null,
parametersWithAdditionalParameter(Parameter.with(QUERIES_PARAM_NAME, queriesToJson(queries)), parameters)));
JsonObject normalizedJson = new JsonObject();
for (int i = 0; i < jsonArray.length(); i++) {
JsonObject jsonObject = jsonArray.getJsonObject(i);
// For empty resultsets, Facebook will return an empty object instead of
// an empty list. Hack around that here.
JsonArray resultsArray =
jsonObject.get("fql_result_set") instanceof JsonArray ? jsonObject.getJsonArray("fql_result_set")
: new JsonArray();
normalizedJson.put(jsonObject.getString("name"), resultsArray);
}
return objectType.equals(JsonObject.class) ? (T) normalizedJson : jsonMapper.toJavaObject(
normalizedJson.toString(), objectType);
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process fql.multiquery JSON response", e);
}
}
/**
* @see com.restfb.FacebookClient#executeQuery(java.lang.String, java.lang.Class, com.restfb.Parameter[])
*/
@Override
@Deprecated
public <T> List<T> executeQuery(String query, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("query", query);
verifyParameterPresence("objectType", objectType);
for (Parameter parameter : parameters)
if (QUERY_PARAM_NAME.equals(parameter.name))
throw new IllegalArgumentException("You cannot specify the '" + QUERY_PARAM_NAME
+ "' URL parameter yourself - " + "RestFB will populate this for you with "
+ "the query you passed to this method.");
return jsonMapper.toJavaList(
makeRequest("fql.query", false, false, null,
parametersWithAdditionalParameter(Parameter.with(QUERY_PARAM_NAME, query), parameters)), objectType);
}
/**
* @see com.restfb.FacebookClient#executeFqlQuery(java.lang.String, java.lang.Class, com.restfb.Parameter[])
*/
@Override
public <T> List<T> executeFqlQuery(String query, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("query", query);
verifyParameterPresence("objectType", objectType);
for (Parameter parameter : parameters)
if (FQL_QUERY_PARAM_NAME.equals(parameter.name))
throw new IllegalArgumentException("You cannot specify the '" + FQL_QUERY_PARAM_NAME
+ "' URL parameter yourself - " + "RestFB will populate this for you with "
+ "the query you passed to this method.");
return jsonMapper.toJavaList(
makeRequest("fql", false, false, null,
parametersWithAdditionalParameter(Parameter.with(FQL_QUERY_PARAM_NAME, query), parameters)), objectType);
}
/**
* @see com.restfb.FacebookClient#executeFqlMultiquery(java.util.Map, java.lang.Class, com.restfb.Parameter[])
*/
@Override
@SuppressWarnings("unchecked")
public <T> T executeFqlMultiquery(Map<String, String> queries, Class<T> objectType, Parameter... parameters) {
verifyParameterPresence("objectType", objectType);
for (Parameter parameter : parameters)
if (FQL_QUERY_PARAM_NAME.equals(parameter.name))
throw new IllegalArgumentException("You cannot specify the '" + FQL_QUERY_PARAM_NAME
+ "' URL parameter yourself - " + "RestFB will populate this for you with "
+ "the queries you passed to this method.");
try {
List<JsonObject> jsonObjects =
jsonMapper.toJavaList(
makeRequest(
"fql",
false,
false,
null,
parametersWithAdditionalParameter(Parameter.with(FQL_QUERY_PARAM_NAME, queriesToJson(queries)),
parameters)), JsonObject.class);
JsonObject normalizedJson = new JsonObject();
for (int i = 0; i < jsonObjects.size(); i++) {
JsonObject jsonObject = jsonObjects.get(i);
// For empty resultsets, Facebook will return an empty object instead of
// an empty list. Hack around that here.
JsonArray resultsArray =
jsonObject.get("fql_result_set") instanceof JsonArray ? jsonObject.getJsonArray("fql_result_set")
: new JsonArray();
normalizedJson.put(jsonObject.getString("name"), resultsArray);
}
return objectType.equals(JsonObject.class) ? (T) normalizedJson : jsonMapper.toJavaObject(
normalizedJson.toString(), objectType);
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process fql.multiquery JSON response", e);
}
}
/**
* @see com.restfb.FacebookClient#executeBatch(com.restfb.batch.BatchRequest[])
*/
@Override
public List<BatchResponse> executeBatch(BatchRequest... batchRequests) {
return executeBatch(asList(batchRequests), Collections.<BinaryAttachment> emptyList());
}
/**
* @see com.restfb.FacebookClient#executeBatch(java.util.List)
*/
@Override
public List<BatchResponse> executeBatch(List<BatchRequest> batchRequests) {
return executeBatch(batchRequests, Collections.<BinaryAttachment> emptyList());
}
/**
* @see com.restfb.FacebookClient#executeBatch(java.util.List, java.util.List)
*/
@Override
public List<BatchResponse> executeBatch(List<BatchRequest> batchRequests, List<BinaryAttachment> binaryAttachments) {
verifyParameterPresence("binaryAttachments", binaryAttachments);
if (batchRequests == null || batchRequests.size() == 0)
throw new IllegalArgumentException("You must specify at least one batch request.");
return jsonMapper.toJavaList(
makeRequest("", true, false, binaryAttachments, Parameter.with("batch", jsonMapper.toJson(batchRequests, true))),
BatchResponse.class);
}
/**
* @see com.restfb.FacebookClient#convertSessionKeysToAccessTokens(java.lang.String, java.lang.String,
* java.lang.String[])
*/
@Override
public List<AccessToken> convertSessionKeysToAccessTokens(String appId, String secretKey, String... sessionKeys) {
verifyParameterPresence("appId", appId);
verifyParameterPresence("secretKey", secretKey);
if (sessionKeys == null || sessionKeys.length == 0)
return emptyList();
String json =
makeRequest("/oauth/exchange_sessions", true, false, null, Parameter.with("client_id", appId),
Parameter.with("client_secret", secretKey), Parameter.with("sessions", join(sessionKeys)));
return jsonMapper.toJavaList(json, AccessToken.class);
}
/**
* @see com.restfb.FacebookClient#obtainAppAccessToken(java.lang.String, java.lang.String)
*/
@Override
public AccessToken obtainAppAccessToken(String appId, String appSecret) {
verifyParameterPresence("appId", appId);
verifyParameterPresence("appSecret", appSecret);
String response =
makeRequest("oauth/access_token", Parameter.with("grant_type", "client_credentials"),
Parameter.with("client_id", appId), Parameter.with("client_secret", appSecret));
try {
return AccessToken.fromQueryString(response);
} catch (Throwable t) {
throw new FacebookResponseContentException("Unable to extract access token from response.", t);
}
}
public AccessToken obtainExtendedAccessToken(String appId, String appSecret) {
if (accessToken == null)
throw new IllegalStateException(format(
"You cannot call this method because you did not construct this instance of %s with an access token.",
getClass().getSimpleName()));
return obtainExtendedAccessToken(appId, appSecret, accessToken);
}
/**
* @see com.restfb.FacebookClient#obtainExtendedAccessToken(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public AccessToken obtainExtendedAccessToken(String appId, String appSecret, String accessToken) {
verifyParameterPresence("appId", appId);
verifyParameterPresence("appSecret", appSecret);
verifyParameterPresence("accessToken", accessToken);
String response =
makeRequest("/oauth/access_token", false, false, null, Parameter.with("client_id", appId),
Parameter.with("client_secret", appSecret), Parameter.with("grant_type", "fb_exchange_token"),
Parameter.with("fb_exchange_token", accessToken));
try {
return AccessToken.fromQueryString(response);
} catch (Throwable t) {
throw new FacebookResponseContentException("Unable to extract access token from response.", t);
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T parseSignedRequest(String signedRequest, String appSecret, Class<T> objectType) {
verifyParameterPresence("signedRequest", signedRequest);
verifyParameterPresence("appSecret", appSecret);
verifyParameterPresence("objectType", objectType);
String[] signedRequestTokens = signedRequest.split("[.]");
if (signedRequestTokens.length != 2)
throw new FacebookSignedRequestParsingException(format(
"Signed request '%s' is expected to be signature and payload strings separated by a '.'", signedRequest));
String encodedSignature = signedRequestTokens[0];
String urlDecodedSignature = urlDecodeSignedRequestToken(encodedSignature);
byte[] signature = decodeBase64(urlDecodedSignature);
String encodedPayload = signedRequestTokens[1];
String urlDecodedPayload = urlDecodeSignedRequestToken(encodedPayload);
String payload = StringUtils.toString(decodeBase64(urlDecodedPayload));
// Convert payload to a JsonObject so we can pull algorithm data out of it
JsonObject payloadObject = getJsonMapper().toJavaObject(payload, JsonObject.class);
if (!payloadObject.has("algorithm"))
throw new FacebookSignedRequestParsingException("Unable to detect algorithm used for signed request");
String algorithm = payloadObject.getString("algorithm");
if (!verifySignedRequest(appSecret, algorithm, encodedPayload, signature))
throw new FacebookSignedRequestVerificationException(
"Signed request verification failed. Are you sure the request was made for the app identified by the app secret you provided?");
// Marshal to the user's preferred type.
// If the user asked for a JsonObject, send back the one we already parsed.
return objectType.equals(JsonObject.class) ? (T) payloadObject : getJsonMapper().toJavaObject(payload, objectType);
}
/**
* Decodes a component of a signed request received from Facebook using FB's special URL-encoding strategy.
*
* @param signedRequestToken
* Token to decode.
* @return The decoded token.
*/
protected String urlDecodeSignedRequestToken(String signedRequestToken) {
verifyParameterPresence("signedRequestToken", signedRequestToken);
return signedRequestToken.replace("-", "+").replace("_", "/").trim();
}
/**
* Verifies that the signed request is really from Facebook.
*
* @param appSecret
* The secret for the app that can verify this signed request.
* @param algorithm
* Signature algorithm specified by FB in the decoded payload.
* @param encodedPayload
* The encoded payload used to generate a signature for comparison against the provided {@code signature}.
* @param signature
* The decoded signature extracted from the signed request. Compared against a signature generated from
* {@code encodedPayload}.
* @return {@code true} if the signed request is verified, {@code false} if not.
*/
protected boolean verifySignedRequest(String appSecret, String algorithm, String encodedPayload, byte[] signature) {
verifyParameterPresence("appSecret", appSecret);
verifyParameterPresence("algorithm", algorithm);
verifyParameterPresence("encodedPayload", encodedPayload);
verifyParameterPresence("signature", signature);
// Normalize algorithm name...FB calls it differently than Java does
if ("HMAC-SHA256".equalsIgnoreCase(algorithm))
algorithm = "HMACSHA256";
try {
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(toBytes(appSecret), algorithm));
byte[] payloadSignature = mac.doFinal(toBytes(encodedPayload));
return Arrays.equals(signature, payloadSignature);
} catch (Exception e) {
throw new FacebookSignedRequestVerificationException("Unable to perform signed request verification", e);
}
}
/**
* @see com.restfb.FacebookClient#debugToken(java.lang.String)
*/
@Override
public DebugTokenInfo debugToken(String inputToken) {
verifyParameterPresence("inputToken", inputToken);
String response = makeRequest("/debug_token", Parameter.with("input_token", inputToken));
JsonObject json = new JsonObject(response);
JsonObject data = json.getJsonObject("data");
try {
return getJsonMapper().toJavaObject(data.toString(), DebugTokenInfo.class);
} catch (Throwable t) {
throw new FacebookResponseContentException("Unable to parse JSON from response.", t);
}
}
/**
* @see com.restfb.FacebookClient#getJsonMapper()
*/
@Override
public JsonMapper getJsonMapper() {
return jsonMapper;
}
/**
* @see com.restfb.FacebookClient#getWebRequestor()
*/
@Override
public WebRequestor getWebRequestor() {
return webRequestor;
}
/**
* Coordinates the process of executing the API request GET/POST and processing the response we receive from the
* endpoint.
*
* @param endpoint
* Facebook Graph API endpoint.
* @param parameters
* Arbitrary number of parameters to send along to Facebook as part of the API call.
* @return The JSON returned by Facebook for the API call.
* @throws FacebookException
* If an error occurs while making the Facebook API POST or processing the response.
*/
protected String makeRequest(String endpoint, Parameter... parameters) {
return makeRequest(endpoint, false, false, null, parameters);
}
/**
* Coordinates the process of executing the API request GET/POST and processing the response we receive from the
* endpoint.
*
* @param endpoint
* Facebook Graph API endpoint.
* @param executeAsPost
* {@code true} to execute the web request as a {@code POST}, {@code false} to execute as a {@code GET}.
* @param executeAsDelete
* {@code true} to add a special 'treat this request as a {@code DELETE}' parameter.
* @param binaryAttachments
* A list of binary files to include in a {@code POST} request. Pass {@code null} if no attachment should be
* sent.
* @param parameters
* Arbitrary number of parameters to send along to Facebook as part of the API call.
* @return The JSON returned by Facebook for the API call.
* @throws FacebookException
* If an error occurs while making the Facebook API POST or processing the response.
*/
protected String makeRequest(String endpoint, final boolean executeAsPost, final boolean executeAsDelete,
final List<BinaryAttachment> binaryAttachments, Parameter... parameters) {
verifyParameterLegality(parameters);
if (executeAsDelete && isHttpDeleteFallback()) {
parameters = parametersWithAdditionalParameter(Parameter.with(METHOD_PARAM_NAME, "delete"), parameters);
}
trimToEmpty(endpoint).toLowerCase();
if (!endpoint.startsWith("/"))
endpoint = "/" + endpoint;
final String fullEndpoint =
createEndpointForApiCall(endpoint, binaryAttachments != null && binaryAttachments.size() > 0);
final String parameterString = toParameterString(parameters);
return makeRequestAndProcessResponse(new Requestor() {
/**
* @see com.restfb.DefaultFacebookClient.Requestor#makeRequest()
*/
public Response makeRequest() throws IOException {
if (executeAsDelete && !isHttpDeleteFallback()) {
return webRequestor.executeDelete(fullEndpoint + "?" + parameterString);
} else {
return executeAsPost ? webRequestor.executePost(fullEndpoint, parameterString,
binaryAttachments == null ? null : binaryAttachments.toArray(new BinaryAttachment[] {})) : webRequestor
.executeGet(fullEndpoint + "?" + parameterString);
}
}
});
}
/**
* @see com.restfb.FacebookClient#obtainAppSecretProof(java.lang.String, java.lang.String)
*/
@Override
public String obtainAppSecretProof(String accessToken, String appSecret) {
verifyParameterPresence("accessToken", accessToken);
verifyParameterPresence("appSecret", appSecret);
try {
byte[] key = appSecret.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] raw = mac.doFinal(accessToken.getBytes());
byte[] hex = encodeHex(raw);
return new String(hex, "UTF-8");
} catch (Exception e) {
throw new IllegalStateException("Creation of appsecret_proof has failed", e);
}
}
/**
* returns if the fallback post method (<code>true</code>) is used or the http delete (<code>false</code>)
*
* @return
*/
public boolean isHttpDeleteFallback() {
return httpDeleteFallback;
}
/**
* Set to <code>true</code> if the facebook http delete fallback should be used. Facebook allows to use the http POST
* with the parameter "method=delete" to override the post and use delete instead. This feature allow http client that
* do not support the whole http method set, to delete objects from facebook
*
* @param httpDeleteFallback
*/
public void setHttpDeleteFallback(boolean httpDeleteFallback) {
this.httpDeleteFallback = httpDeleteFallback;
}
protected static interface Requestor {
Response makeRequest() throws IOException;
}
protected String makeRequestAndProcessResponse(Requestor requestor) {
Response response = null;
// Perform a GET or POST to the API endpoint
try {
response = requestor.makeRequest();
} catch (Throwable t) {
throw new FacebookNetworkException("Facebook request failed", t);
}
// If we get any HTTP response code other than a 200 OK or 400 Bad Request
// or 401 Not Authorized or 403 Forbidden or 404 Not Found or 500 Internal
// Server Error,
// throw an exception.
if (HTTP_OK != response.getStatusCode() && HTTP_BAD_REQUEST != response.getStatusCode()
&& HTTP_UNAUTHORIZED != response.getStatusCode() && HTTP_NOT_FOUND != response.getStatusCode()
&& HTTP_INTERNAL_ERROR != response.getStatusCode() && HTTP_FORBIDDEN != response.getStatusCode())
throw new FacebookNetworkException("Facebook request failed", response.getStatusCode());
String json = response.getBody();
// If the response contained an error code, throw an exception.
throwFacebookResponseStatusExceptionIfNecessary(json, response.getStatusCode());
// If there was no response error information and this was a 500 or 401
// error, something weird happened on Facebook's end. Bail.
if (HTTP_INTERNAL_ERROR == response.getStatusCode() || HTTP_UNAUTHORIZED == response.getStatusCode())
throw new FacebookNetworkException("Facebook request failed", response.getStatusCode());
return json;
}
/**
* Throws an exception if Facebook returned an error response. Using the Graph API, it's possible to see both the new
* Graph API-style errors as well as Legacy API-style errors, so we have to handle both here. This method extracts
* relevant information from the error JSON and throws an exception which encapsulates it for end-user consumption.
* <p>
* For Graph API errors:
* <p>
* If the {@code error} JSON field is present, we've got a response status error for this API call.
* <p>
* For Legacy errors (e.g. FQL):
* <p>
* If the {@code error_code} JSON field is present, we've got a response status error for this API call.
*
* @param json
* The JSON returned by Facebook in response to an API call.
* @param httpStatusCode
* The HTTP status code returned by the server, e.g. 500.
* @throws FacebookGraphException
* If the JSON contains a Graph API error response.
* @throws FacebookResponseStatusException
* If the JSON contains an Legacy API error response.
* @throws FacebookJsonMappingException
* If an error occurs while processing the JSON.
*/
protected void throwFacebookResponseStatusExceptionIfNecessary(String json, Integer httpStatusCode) {
// If we have a legacy exception, throw it.
throwLegacyFacebookResponseStatusExceptionIfNecessary(json, httpStatusCode);
// If we have a batch API exception, throw it.
throwBatchFacebookResponseStatusExceptionIfNecessary(json, httpStatusCode);
try {
// If the result is not an object, bail immediately.
if (!json.startsWith("{"))
return;
int subStrEnd = Math.min(50, json.length());
if (!json.substring(0, subStrEnd).contains("\"error\"")) {
return; // no need to parse json
}
JsonObject errorObject = new JsonObject(json);
if (errorObject == null || !errorObject.has(ERROR_ATTRIBUTE_NAME))
return;
JsonObject innerErrorObject = errorObject.getJsonObject(ERROR_ATTRIBUTE_NAME);
// If there's an Integer error code, pluck it out.
Integer errorCode =
innerErrorObject.has(ERROR_CODE_ATTRIBUTE_NAME) ? toInteger(innerErrorObject
.getString(ERROR_CODE_ATTRIBUTE_NAME)) : null;
Integer errorSubcode =
innerErrorObject.has(ERROR_SUBCODE_ATTRIBUTE_NAME) ? toInteger(innerErrorObject
.getString(ERROR_SUBCODE_ATTRIBUTE_NAME)) : null;
throw graphFacebookExceptionMapper.exceptionForTypeAndMessage(errorCode, errorSubcode, httpStatusCode,
innerErrorObject.getString(ERROR_TYPE_ATTRIBUTE_NAME),
innerErrorObject.getString(ERROR_MESSAGE_ATTRIBUTE_NAME),
innerErrorObject.optString(ERROR_USER_TITLE_ATTRIBUTE_NAME),
innerErrorObject.optString(ERROR_USER_MSG_ATTRIBUTE_NAME));
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process the Facebook API response", e);
}
}
/**
* If the {@code error} and {@code error_description} JSON fields are present, we've got a response status error for
* this batch API call. Extracts relevant information from the JSON and throws an exception which encapsulates it for
* end-user consumption.
*
* @param json
* The JSON returned by Facebook in response to a batch API call.
* @param httpStatusCode
* The HTTP status code returned by the server, e.g. 500.
* @throws FacebookResponseStatusException
* If the JSON contains an error code.
* @throws FacebookJsonMappingException
* If an error occurs while processing the JSON.
* @since 1.6.5
*/
protected void throwBatchFacebookResponseStatusExceptionIfNecessary(String json, Integer httpStatusCode) {
try {
// If this is not an object, it's not an error response.
if (!json.startsWith("{"))
return;
int subStrEnd = Math.min(50, json.length());
if (!json.substring(0, subStrEnd).contains("\"error\"")) {
return; // no need to parse json
}
JsonObject errorObject = null;
// We need to swallow exceptions here because it's possible to get a legit
// users.getLoggedInUser returning 1240077) - we're only interested in
// whether or not there's an error_code field present.
try {
errorObject = new JsonObject(json);
} catch (JsonException e) {}
if (errorObject == null || !errorObject.has(BATCH_ERROR_ATTRIBUTE_NAME)
|| !errorObject.has(BATCH_ERROR_DESCRIPTION_ATTRIBUTE_NAME))
return;
throw legacyFacebookExceptionMapper.exceptionForTypeAndMessage(errorObject.getInt(BATCH_ERROR_ATTRIBUTE_NAME),
null, httpStatusCode, null, errorObject.getString(BATCH_ERROR_DESCRIPTION_ATTRIBUTE_NAME), null, null);
} catch (JsonException e) {
throw new FacebookJsonMappingException("Unable to process the Facebook API response", e);
}
}
/**
* Specifies how we map Graph API exception types/messages to real Java exceptions.
* <p>
* Uses an instance of {@link DefaultGraphFacebookExceptionMapper} by default.
*
* @return An instance of the exception mapper we should use.
* @since 1.6
*/
protected FacebookExceptionMapper createGraphFacebookExceptionMapper() {
return new DefaultGraphFacebookExceptionMapper();
}
protected static class DefaultGraphFacebookExceptionMapper implements FacebookExceptionMapper {
/**
* @see com.restfb.exception.FacebookExceptionMapper#exceptionForTypeAndMessage(java.lang.Integer,
* java.lang.Integer, java.lang.String, java.lang.String)
*/
public FacebookException exceptionForTypeAndMessage(Integer errorCode, Integer errorSubcode,
Integer httpStatusCode, String type, String message, String errorUserTitle, String errorUserMessage) {
if ("OAuthException".equals(type) || "OAuthAccessTokenException".equals(type))
return new FacebookOAuthException(type, message, errorCode, errorSubcode, httpStatusCode, errorUserTitle,
errorUserMessage);
if ("QueryParseException".equals(type))
return new FacebookQueryParseException(type, message, errorCode, errorSubcode, httpStatusCode, errorUserTitle,
errorUserMessage);
// Don't recognize this exception type? Just go with the standard
// FacebookGraphException.
return new FacebookGraphException(type, message, errorCode, errorSubcode, httpStatusCode, errorUserTitle,
errorUserMessage);
}
}
/**
* Generate the parameter string to be included in the Facebook API request.
*
* @param parameters
* Arbitrary number of extra parameters to include in the request.
* @return The parameter string to include in the Facebook API request.
* @throws FacebookJsonMappingException
* If an error occurs when building the parameter string.
*/
protected String toParameterString(Parameter... parameters) {
if (!isBlank(accessToken))
parameters = parametersWithAdditionalParameter(Parameter.with(ACCESS_TOKEN_PARAM_NAME, accessToken), parameters);
if (!isBlank(accessToken) && !isBlank(appSecret))
parameters =
parametersWithAdditionalParameter(
Parameter.with(APP_SECRET_PROOF_PARAM_NAME, obtainAppSecretProof(accessToken, appSecret)), parameters);
parameters = parametersWithAdditionalParameter(Parameter.with(FORMAT_PARAM_NAME, "json"), parameters);
StringBuilder parameterStringBuilder = new StringBuilder();
boolean first = true;
for (Parameter parameter : parameters) {
if (first)
first = false;
else
parameterStringBuilder.append("&");
parameterStringBuilder.append(urlEncode(parameter.name));
parameterStringBuilder.append("=");
parameterStringBuilder.append(urlEncodedValueForParameterName(parameter.name, parameter.value));
}
return parameterStringBuilder.toString();
}
/**
* @see com.restfb.BaseFacebookClient#createEndpointForApiCall(java.lang.String,boolean)
*/
@Override
protected String createEndpointForApiCall(String apiCall, boolean hasAttachment) {
trimToEmpty(apiCall).toLowerCase();
while (apiCall.startsWith("/"))
apiCall = apiCall.substring(1);
String baseUrl = getFacebookGraphEndpointUrl();
if (readOnlyApiCalls.contains(apiCall))
baseUrl = getFacebookReadOnlyEndpointUrl();
else if (hasAttachment && apiCall.endsWith("/videos"))
baseUrl = getFacebookGraphVideoEndpointUrl();
return format("%s/%s", baseUrl, apiCall);
}
/**
* Returns the base endpoint URL for the Graph API.
*
* @return The base endpoint URL for the Graph API.
*/
protected String getFacebookGraphEndpointUrl() {
if (apiVersion.isUrlElementRequired()) {
return FACEBOOK_GRAPH_ENDPOINT_URL + '/' + apiVersion.getUrlElement();
} else {
return FACEBOOK_GRAPH_ENDPOINT_URL;
}
}
/**
* Returns the base endpoint URL for the Graph API's video upload functionality.
*
* @return The base endpoint URL for the Graph API's video upload functionality.
* @since 1.6.5
*/
protected String getFacebookGraphVideoEndpointUrl() {
if (apiVersion.isUrlElementRequired()) {
return FACEBOOK_GRAPH_VIDEO_ENDPOINT_URL + '/' + apiVersion.getUrlElement();
} else {
return FACEBOOK_GRAPH_VIDEO_ENDPOINT_URL;
}
}
@Override
protected String getFacebookReadOnlyEndpointUrl() {
if (apiVersion.isUrlElementRequired()) {
return FACEBOOK_READ_ONLY_ENDPOINT_URL + '/' + apiVersion.getUrlElement();
} else {
return FACEBOOK_READ_ONLY_ENDPOINT_URL;
}
}
} |
// MonitorController.java
// Open XAL
package xal.app.launcher;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import xal.application.Application;
import xal.tools.bricks.*;
import xal.tools.swing.KeyValueFilteredTableModel;
import xal.tools.dispatch.*;
/** MonitorController */
public class MonitorController implements MonitorModelListener {
/** The main model of this document */
final private LaunchModel LAUNCH_MODEL;
/** model for monitoring remote applications */
final private MonitorModel MONITOR_MODEL;
/** table of live applications to monitor */
final private JTable REMOTE_APPS_TABLE;
/** table model for displaying the applications */
final private KeyValueFilteredTableModel<RemoteAppRecord> APP_TABLE_MODEL;
/** filter field */
final private JTextField FILTER_FIELD;
/** timer for refreshing the data */
final private DispatchTimer REFRESH_TIMER;
/** Constructor */
public MonitorController( final LaunchModel launchModel, final WindowReference windowReference ) {
LAUNCH_MODEL = launchModel;
MONITOR_MODEL = new MonitorModel();
MONITOR_MODEL.addMonitorModelListener( this );
final JButton liveAppsFilterClearButton = (JButton)windowReference.getView( "LiveAppsFilterClearButton" );
liveAppsFilterClearButton.addActionListener( clearFilterAction() );
final JButton forceQuitAppButton = (JButton)windowReference.getView( "ForceQuitAppButton" );
forceQuitAppButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
for ( final RemoteAppRecord record : getSelectedRemoteAppRecords() ) {
try {
record.forceQuit( 0 );
}
catch ( Exception exception ) {
exception.printStackTrace();
Application.displayError( "Force Quit App Failed!", "Failed to force app to quit due to an internal exception!", exception );
}
}
}
});
final JButton revealAppButton = (JButton)windowReference.getView( "RevealAppButton" );
revealAppButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
for ( final RemoteAppRecord record : getSelectedRemoteAppRecords() ) {
try {
record.showAllWindows();
}
catch ( Exception exception ) {
exception.printStackTrace();
Application.displayError( "Reveal App Failed!", "Failed to reveal app due to an internal exception!", exception );
}
}
}
});
FILTER_FIELD = (JTextField)windowReference.getView( "LiveAppsFilterField" );
FILTER_FIELD.putClientProperty( "JTextField.variant", "search" );
FILTER_FIELD.putClientProperty( "JTextField.Search.Prompt", "Application Filter" );
REMOTE_APPS_TABLE = (JTable)windowReference.getView( "LiveAppsTable" );
REMOTE_APPS_TABLE.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN );
REMOTE_APPS_TABLE.setAutoCreateRowSorter( true );
REMOTE_APPS_TABLE.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
APP_TABLE_MODEL = new KeyValueFilteredTableModel<RemoteAppRecord>( new ArrayList<RemoteAppRecord>(), "applicationName", "hostName", "totalMemory", "launchTime", "lastUpdate" );
APP_TABLE_MODEL.setMatchingKeyPaths( "applicationName", "hostName" );
APP_TABLE_MODEL.setColumnName( "applicationName", "Application" );
APP_TABLE_MODEL.setInputFilterComponent( FILTER_FIELD );
REMOTE_APPS_TABLE.setModel( APP_TABLE_MODEL );
REFRESH_TIMER = new DispatchTimer( DispatchQueue.getMainQueue(), new Runnable() {
public void run() {
final int rowCount = APP_TABLE_MODEL.getRowCount();
if ( rowCount > 0 ) {
APP_TABLE_MODEL.fireTableRowsUpdated( 0, rowCount - 1 );
}
}
});
REFRESH_TIMER.startNowWithInterval( 5000, 0 ); // refresh the table every 5 seconds
final Box monitorView = (Box)windowReference.getView( "MonitorView" );
final JTabbedPane mainTabPane = (JTabbedPane)windowReference.getView( "MainTabPane" );
// monitor tab pane selection changes to monitor remote applications only when the monitor pane is selected
mainTabPane.addChangeListener( new ChangeListener() {
public void stateChanged( final ChangeEvent event ) {
if ( mainTabPane.getSelectedComponent() == monitorView ) {
REFRESH_TIMER.resume();
}
else {
REFRESH_TIMER.suspend();
}
}
});
// suspend the refresh timer if the monitor is not selected to avoid unnecessary network activity
if ( mainTabPane.getSelectedComponent() != monitorView ) { // future proofed in case the monitor view ever becomes the first tab open at launch
REFRESH_TIMER.suspend();
}
}
/** event indicating that the list of remote apps has changed */
public void remoteAppsChanged( final MonitorModel model, final List<RemoteAppRecord> remoteApps ) {
DispatchQueue.getMainQueue().dispatchAsync( new Runnable() {
public void run() {
APP_TABLE_MODEL.setRecords( remoteApps );
}
});
}
/** Get the remote app records selected by the user */
private RemoteAppRecord[] getSelectedRemoteAppRecords() {
final int[] selectedRows = REMOTE_APPS_TABLE.getSelectedRows();
final RemoteAppRecord[] selectedRecords = new RemoteAppRecord[ selectedRows.length ];
int recordIndex = 0;
for ( final int row : selectedRows ) {
final int modelRow = REMOTE_APPS_TABLE.convertRowIndexToModel( row );
selectedRecords[ recordIndex++ ] = APP_TABLE_MODEL.getRecordAtRow( modelRow );
}
return selectedRecords;
}
/** action to clear the filter field */
private AbstractAction clearFilterAction() {
return new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed( final ActionEvent event ) {
FILTER_FIELD.setText( "" );
}
};
}
} |
// $OldId: ExplicitOuterClasses.java,v 1.22 2002/10/17 12:31:56 schinz Exp $
package scalac.transformer;
import java.util.*;
import scalac.*;
import scalac.ast.*;
import scalac.util.*;
import scalac.parser.*;
import scalac.symtab.*;
import scalac.typechecker.*;
import Tree.*;
/**
* Make links from nested classes to their enclosing class explicit.
*
* @author Michel Schinz
* @version 1.0
*/
public class ExplicitOuterClasses extends Transformer {
// Mapping from class constructor symbols to owner field symbols.
protected HashMap/*<Symbol,Symbol>*/ outerMap = new HashMap();
public ExplicitOuterClasses(Global global, PhaseDescriptor descr) {
super(global, descr);
}
protected Type addValueParam(Type oldType, Symbol newValueParam) {
switch (oldType) {
case MethodType(Symbol[] vparams, Type result): {
Symbol[] newVParams = new Symbol[vparams.length + 1];
newVParams[0] = newValueParam;
System.arraycopy(vparams, 0, newVParams, 1, vparams.length);
return new Type.MethodType(newVParams, result);
}
case PolyType(Symbol[] tparams, Type result):
return new Type.PolyType(tparams, addValueParam(result, newValueParam));
default:
throw global.fail("invalid type", oldType);
}
}
protected Symbol outerSym(Symbol constSym) {
if (! outerMap.containsKey(constSym)) {
Symbol ownerSym = constSym.enclClass();
Symbol outerSym =
new TermSymbol(constSym.pos, freshOuterName(), constSym, 0);
outerSym.setInfo(ownerSym.type());
outerMap.put(constSym, outerSym);
}
return (Symbol)outerMap.get(constSym);
}
protected Type newConstType(Symbol constSym) {
return addValueParam(constSym.info(), outerSym(constSym));
}
protected LinkedList/*<Symbol>*/ classStack = new LinkedList();
protected LinkedList/*<Symbol>*/ outerLinks = new LinkedList();
protected Name freshOuterName() {
return global.freshNameCreator.newName(Names.OUTER_PREFIX);
}
// Return the given class with an explicit link to its outer
// class, if any.
protected Tree addOuterLink(ClassDef classDef) {
Symbol classSym = classDef.symbol();
Symbol constSym = classSym.constructor();
Symbol outerSym = outerSym(constSym);
assert (outerSym.owner() == constSym) : outerSym;
outerLinks.addFirst(outerSym);
// Add the outer parameter, both to the type and the tree.
Type newConstType = newConstType(constSym);
ValDef[][] vparams = classDef.vparams;
ValDef[] newVParamsI;
if (vparams.length == 0)
newVParamsI = new ValDef[] { gen.ValDef(outerSym) };
else {
newVParamsI = new ValDef[vparams[0].length + 1];
newVParamsI[0] = gen.ValDef(outerSym);
System.arraycopy(vparams[0], 0, newVParamsI, 1, vparams[0].length);
}
ValDef[][] newVParams = new ValDef[][] { newVParamsI };
constSym.updateInfo(newConstType);
int newMods = classDef.mods | Modifiers.STATIC;
classSym.flags |= Modifiers.STATIC;
return copy.ClassDef(classDef,
newMods,
classDef.name,
transform(classDef.tparams),
transform(newVParams),
transform(classDef.tpe),
(Template)transform((Tree)classDef.impl));
}
// Return a tree referencing the "level"th outer class.
protected Tree outerRef(int level) {
assert level > 0 : level;
Tree root = null;
Iterator outerIt = outerLinks.iterator();
while (level > 0) {
Symbol outerSym = (Symbol)outerIt.next();
if (root == null)
root = gen.Ident(outerSym);
else
root = gen.Select(root, outerSym);
--level;
}
return root;
}
public Tree transform(Tree tree) {
switch (tree) {
case ClassDef(int mods, _, _, _, _, _) : {
// Add outer link
ClassDef classDef = (ClassDef) tree;
Symbol sym = classDef.symbol();
Tree newTree;
classStack.addFirst(sym);
if (classStack.size() == 1 || Modifiers.Helper.isStatic(mods)) {
outerLinks.addFirst(null);
newTree = super.transform(tree);
} else
newTree = addOuterLink(classDef);
outerLinks.removeFirst();
classStack.removeFirst();
return newTree;
}
case Ident(Name name): {
if (! name.isTermName())
return super.transform(tree);
// Follow "outer" links to fetch data in outer classes.
Symbol sym = tree.symbol();
Symbol owner = sym.classOwner();
Iterator classIt = classStack.iterator();
boolean found = false;
int level = -1;
while (!found && classIt.hasNext()) {
Symbol classSym = (Symbol)classIt.next();
if (classSym.closurePos(owner) != -1)
found = true;
++level;
}
if (found && level > 0) {
Tree root = outerRef(level);
return gen.Select(root, sym);
} else {
return super.transform(tree);
}
}
case Apply(Tree fun, Tree[] args): {
// Add outer parameter to constructor calls.
Tree realFun;
Tree[] typeArgs;
switch (fun) {
case TypeApply(Tree fun2, Tree[] tArgs):
realFun = fun2; typeArgs = tArgs; break;
default:
realFun = fun; typeArgs = null; break;
}
Tree newFun = null, newArg = null;
if (realFun.hasSymbol() && realFun.symbol().isPrimaryConstructor()) {
switch (transform(realFun)) {
case Select(Tree qualifier, Name selector): {
if (! (qualifier.hasSymbol()
&& Modifiers.Helper.isNoVal(qualifier.symbol().flags))) {
newFun = make.Ident(qualifier.pos, selector)
.setType(realFun.type())
.setSymbol(realFun.symbol());
newArg = qualifier;
}
} break;
case Ident(Name name): {
Symbol owner = realFun.symbol().owner();
if (!classStack.isEmpty()
&& ((Symbol)classStack.getFirst()).closurePos(owner) != -1) {
Symbol thisSym = (Symbol)classStack.getFirst();
newFun = realFun;
newArg = gen.This(realFun.pos, thisSym);
}
} break;
default:
throw global.fail("unexpected node in constructor call");
}
if (newFun != null && newArg != null) {
Tree[] newArgs = new Tree[args.length + 1];
newArgs[0] = newArg;
System.arraycopy(args, 0, newArgs, 1, args.length);
Tree finalFun;
if (typeArgs != null)
finalFun = copy.TypeApply(fun, newFun, typeArgs);
else
finalFun = newFun;
finalFun.type = addValueParam(finalFun.type,
outerSym(realFun.symbol()));
return copy.Apply(tree, finalFun, transform(newArgs));
} else
return super.transform(tree);
} else
return super.transform(tree);
}
default:
return super.transform(tree);
}
}
} |
package org.zstack.kvm;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.compute.cluster.ClusterGlobalConfig;
import org.zstack.compute.host.*;
import org.zstack.compute.vm.*;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.MessageCommandRecorder;
import org.zstack.core.Platform;
import org.zstack.core.agent.AgentConstant;
import org.zstack.core.ansible.*;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusGlobalProperty;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.thread.*;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.Constants;
import org.zstack.header.allocator.HostAllocatorConstant;
import org.zstack.header.cluster.ClusterVO;
import org.zstack.header.cluster.ReportHostCapacityMessage;
import org.zstack.header.core.AsyncLatch;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImageArchitecture;
import org.zstack.header.image.ImageBootMode;
import org.zstack.header.image.ImagePlatform;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.vm.*;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMAgentCommands.*;
import org.zstack.kvm.KVMConstant.KvmVmState;
import org.zstack.network.l3.NetworkGlobalProperty;
import org.zstack.resourceconfig.ResourceConfig;
import org.zstack.resourceconfig.ResourceConfigFacade;
import org.zstack.tag.SystemTag;
import org.zstack.tag.SystemTagCreator;
import org.zstack.tag.TagManager;
import org.zstack.utils.*;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import org.zstack.utils.path.PathUtil;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshException;
import org.zstack.utils.ssh.SshResult;
import org.zstack.utils.ssh.SshShell;
import org.zstack.utils.tester.ZTester;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.kvm.KVMHostFactory.allGuestOsCharacter;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
public class KVMHost extends HostBase implements Host {
private static final CLogger logger = Utils.getLogger(KVMHost.class);
private static final ZTester tester = Utils.getTester();
@Autowired
@Qualifier("KVMHostFactory")
protected KVMHostFactory factory;
@Autowired
private RESTFacade restf;
@Autowired
private KVMExtensionEmitter extEmitter;
@Autowired
private TagManager tagmgr;
@Autowired
private ApiTimeoutManager timeoutManager;
@Autowired
private PluginRegistry pluginRegistry;
@Autowired
private ThreadFacade thdf;
@Autowired
private AnsibleFacade asf;
@Autowired
private ResourceConfigFacade rcf;
@Autowired
private DeviceBootOrderOperator deviceBootOrderOperator;
@Autowired
private VmNicManager nicManager;
private KVMHostContext context;
// ///////////////////// REST URL //////////////////////////
private String baseUrl;
private String connectPath;
private String pingPath;
private String updateHostConfigurationPath;
private String checkPhysicalNetworkInterfacePath;
private String startVmPath;
private String stopVmPath;
private String pauseVmPath;
private String resumeVmPath;
private String rebootVmPath;
private String destroyVmPath;
private String attachDataVolumePath;
private String detachDataVolumePath;
private String echoPath;
private String attachNicPath;
private String detachNicPath;
private String migrateVmPath;
private String snapshotPath;
private String checkSnapshotPath;
private String mergeSnapshotPath;
private String hostFactPath;
private String hostCheckFilePath;
private String attachIsoPath;
private String detachIsoPath;
private String updateNicPath;
private String checkVmStatePath;
private String getConsolePortPath;
private String onlineIncreaseCpuPath;
private String onlineIncreaseMemPath;
private String deleteConsoleFirewall;
private String updateHostOSPath;
private String updateDependencyPath;
private String shutdownHost;
private String updateVmPriorityPath;
private String updateSpiceChannelConfigPath;
private String cancelJob;
private String getVmFirstBootDevicePath;
private String getVmDeviceAddressPath;
private String scanVmPortPath;
private String getDevCapacityPath;
private String configPrimaryVmPath;
private String configSecondaryVmPath;
private String startColoSyncPath;
private String registerPrimaryVmHeartbeatPath;
private String getHostNumaPath;
private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME;
private String hostTakeOverFlagPath = KVMGlobalProperty.TAKEVOERFLAGPATH;
public KVMHost(KVMHostVO self, KVMHostContext context) {
super(self);
this.context = context;
baseUrl = context.getBaseUrl();
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONNECT_PATH);
connectPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PING_PATH);
pingPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_CONFIGURATION_PATH);
updateHostConfigurationPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH);
checkPhysicalNetworkInterfacePath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_VM_PATH);
startVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_STOP_VM_PATH);
stopVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PAUSE_VM_PATH);
pauseVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_RESUME_VM_PATH);
resumeVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REBOOT_VM_PATH);
rebootVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DESTROY_VM_PATH);
destroyVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_VOLUME);
attachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_VOLUME);
detachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ECHO_PATH);
echoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_NIC_PATH);
attachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_NIC_PATH);
detachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MIGRATE_VM_PATH);
migrateVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH);
snapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_VOLUME_SNAPSHOT_PATH);
checkSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH);
mergeSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_FACT_PATH);
hostFactPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_CHECK_FILE_PATH);
hostCheckFilePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_ISO_PATH);
attachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_ISO_PATH);
detachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_NIC_PATH);
updateNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_CHECK_STATE);
checkVmStatePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH);
getConsolePortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU);
onlineIncreaseCpuPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY);
onlineIncreaseMemPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
deleteConsoleFirewall = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH);
updateHostOSPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_UPDATE_DEPENDENCY_PATH);
updateDependencyPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_SHUTDOWN);
shutdownHost = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_UPDATE_PRIORITY_PATH);
updateVmPriorityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_UPDATE_SPICE_CHANNEL_CONFIG_PATH);
updateSpiceChannelConfigPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(AgentConstant.CANCEL_JOB);
cancelJob = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VM_FIRST_BOOT_DEVICE_PATH);
getVmFirstBootDevicePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_VM_DEVICE_ADDRESS_PATH);
getVmDeviceAddressPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_SCAN_VM_PORT_STATUS);
scanVmPortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_DEV_CAPACITY);
getDevCapacityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_PRIMARY_VM_PATH);
configPrimaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_SECONDARY_VM_PATH);
configSecondaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_COLO_SYNC_PATH);
startColoSyncPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REGISTER_PRIMARY_VM_HEARTBEAT);
registerPrimaryVmHeartbeatPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_NUMA_PATH);
getHostNumaPath = ub.build().toString();
}
class Http<T> {
String path;
AgentCommand cmd;
Class<T> responseClass;
String commandStr;
public Http(String path, String cmd, Class<T> rspClz) {
this.path = path;
this.commandStr = cmd;
this.responseClass = rspClz;
}
public Http(String path, AgentCommand cmd, Class<T> rspClz) {
this.path = path;
this.cmd = cmd;
this.responseClass = rspClz;
}
void call(ReturnValueCompletion<T> completion) {
call(null, completion);
}
void call(String resourceUuid, ReturnValueCompletion<T> completion) {
Map<String, String> header = new HashMap<>();
header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid);
runBeforeAsyncJsonPostExts(header);
if (commandStr != null) {
restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}, TimeUnit.MILLISECONDS, timeoutManager.getTimeout());
} else {
restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}); // DO NOT pass unit, timeout here, they are null
}
}
void runBeforeAsyncJsonPostExts(Map<String, String> header) {
if (commandStr == null) {
commandStr = JSONObjectUtil.toJsonString(cmd);
}
if (commandStr == null || commandStr.isEmpty()) {
logger.warn(String.format("commandStr is empty, path: %s, header: %s", path, header));
return;
}
LinkedHashMap commandMap = JSONObjectUtil.toObject(commandStr, LinkedHashMap.class);
LinkedHashMap kvmHostAddon = new LinkedHashMap();
for (KVMBeforeAsyncJsonPostExtensionPoint extp : pluginRegistry.getExtensionList(KVMBeforeAsyncJsonPostExtensionPoint.class)) {
LinkedHashMap tmpHashMap = extp.kvmBeforeAsyncJsonPostExtensionPoint(path, commandMap, header);
if (tmpHashMap != null && !tmpHashMap.isEmpty()) {
tmpHashMap.keySet().stream().forEachOrdered((key -> {
kvmHostAddon.put(key, tmpHashMap.get(key));
}));
}
}
if (commandStr.equals("{}")) {
commandStr = commandStr.replaceAll("\\}$",
String.format("\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
} else {
commandStr = commandStr.replaceAll("\\}$",
String.format(",\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
}
}
}
@Override
protected void handleApiMessage(APIMessage msg) {
super.handleApiMessage(msg);
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof CheckNetworkPhysicalInterfaceMsg) {
handle((CheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof BatchCheckNetworkPhysicalInterfaceMsg) {
handle((BatchCheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof StartVmOnHypervisorMsg) {
handle((StartVmOnHypervisorMsg) msg);
} else if (msg instanceof CreateVmOnHypervisorMsg) {
handle((CreateVmOnHypervisorMsg) msg);
} else if (msg instanceof UpdateSpiceChannelConfigMsg) {
handle((UpdateSpiceChannelConfigMsg) msg);
} else if (msg instanceof StopVmOnHypervisorMsg) {
handle((StopVmOnHypervisorMsg) msg);
} else if (msg instanceof RebootVmOnHypervisorMsg) {
handle((RebootVmOnHypervisorMsg) msg);
} else if (msg instanceof DestroyVmOnHypervisorMsg) {
handle((DestroyVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) {
handle((AttachVolumeToVmOnHypervisorMsg) msg);
} else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) {
handle((DetachVolumeFromVmOnHypervisorMsg) msg);
} else if (msg instanceof VmAttachNicOnHypervisorMsg) {
handle((VmAttachNicOnHypervisorMsg) msg);
} else if (msg instanceof VmUpdateNicOnHypervisorMsg) {
handle((VmUpdateNicOnHypervisorMsg) msg);
} else if (msg instanceof MigrateVmOnHypervisorMsg) {
handle((MigrateVmOnHypervisorMsg) msg);
} else if (msg instanceof TakeSnapshotOnHypervisorMsg) {
handle((TakeSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof CheckSnapshotOnHypervisorMsg) {
handle((CheckSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) {
handle((MergeVolumeSnapshotOnKvmMsg) msg);
} else if (msg instanceof KVMHostAsyncHttpCallMsg) {
handle((KVMHostAsyncHttpCallMsg) msg);
} else if (msg instanceof KVMHostSyncHttpCallMsg) {
handle((KVMHostSyncHttpCallMsg) msg);
} else if (msg instanceof DetachNicFromVmOnHypervisorMsg) {
handle((DetachNicFromVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachIsoOnHypervisorMsg) {
handle((AttachIsoOnHypervisorMsg) msg);
} else if (msg instanceof DetachIsoOnHypervisorMsg) {
handle((DetachIsoOnHypervisorMsg) msg);
} else if (msg instanceof CheckVmStateOnHypervisorMsg) {
handle((CheckVmStateOnHypervisorMsg) msg);
} else if (msg instanceof UpdateVmPriorityMsg) {
handle((UpdateVmPriorityMsg) msg);
} else if (msg instanceof GetVmConsoleAddressFromHostMsg) {
handle((GetVmConsoleAddressFromHostMsg) msg);
} else if (msg instanceof KvmRunShellMsg) {
handle((KvmRunShellMsg) msg);
} else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) {
handle((VmDirectlyDestroyOnHypervisorMsg) msg);
} else if (msg instanceof IncreaseVmCpuMsg) {
handle((IncreaseVmCpuMsg) msg);
} else if (msg instanceof IncreaseVmMemoryMsg) {
handle((IncreaseVmMemoryMsg) msg);
} else if (msg instanceof PauseVmOnHypervisorMsg) {
handle((PauseVmOnHypervisorMsg) msg);
} else if (msg instanceof ResumeVmOnHypervisorMsg) {
handle((ResumeVmOnHypervisorMsg) msg);
} else if (msg instanceof GetKVMHostDownloadCredentialMsg) {
handle((GetKVMHostDownloadCredentialMsg) msg);
} else if (msg instanceof ShutdownHostMsg) {
handle((ShutdownHostMsg) msg);
} else if (msg instanceof CancelHostTaskMsg) {
handle((CancelHostTaskMsg) msg);
} else if (msg instanceof GetVmFirstBootDeviceOnHypervisorMsg) {
handle((GetVmFirstBootDeviceOnHypervisorMsg) msg);
} else if (msg instanceof GetVmDeviceAddressMsg) {
handle((GetVmDeviceAddressMsg) msg);
} else if (msg instanceof CheckHostCapacityMsg) {
handle((CheckHostCapacityMsg) msg);
} else if (msg instanceof ConfigPrimaryVmMsg) {
handle((ConfigPrimaryVmMsg) msg);
} else if (msg instanceof ConfigSecondaryVmMsg) {
handle((ConfigSecondaryVmMsg) msg);
} else if (msg instanceof StartColoSyncMsg) {
handle((StartColoSyncMsg) msg);
} else if (msg instanceof RegisterColoPrimaryCheckMsg) {
handle((RegisterColoPrimaryCheckMsg) msg);
} else if (msg instanceof AllocateHostPortMsg) {
handle((AllocateHostPortMsg) msg);
} else if (msg instanceof CheckFileOnHostMsg) {
handle((CheckFileOnHostMsg) msg);
} else if (msg instanceof GetHostNumaTopologyMsg) {
handle((GetHostNumaTopologyMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
private void handle(GetHostNumaTopologyMsg msg) {
GetHostNumaTopologyReply reply = new GetHostNumaTopologyReply();
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
GetHostNUMATopologyCmd cmd = new GetHostNUMATopologyCmd();
cmd.setHostUuid(msg.getHostUuid());
new Http<>(getHostNumaPath, cmd, GetHostNUMATopologyResponse.class).call(msg.getHostUuid(), new ReturnValueCompletion<GetHostNUMATopologyResponse>(msg) {
@Override
public void success(GetHostNUMATopologyResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = Platform.err(SysErrors.OPERATION_ERROR, ret.getError());
reply.setError(err);
} else {
reply.setNuma(ret.getTopology());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(AllocateHostPortMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return String.format("allocate-host-%s-port", msg.getHostUuid());
}
@Override
public void run(SyncTaskChain chain) {
AllocateHostPortReply reply = new AllocateHostPortReply();
reply.setHostPortIds(new ArrayList<>());
HostPortGetter portGetter = new HostPortGetter();
for (int i = 0; i < msg.getAllocateCount(); i++) {
HostPortVO vo = portGetter.getNextHostPort(msg.getHostUuid(), "");
reply.getHostPortIds().add(vo.getId());
}
bus.reply(msg, reply);
chain.next();
}
@Override
public String getName() {
return String.format("allocate-host-%s-port", msg.getHostUuid());
}
});
}
private void handle(CheckHostCapacityMsg msg) {
CheckHostCapacityReply re = new CheckHostCapacityReply();
KVMHostAsyncHttpCallMsg kmsg = new KVMHostAsyncHttpCallMsg();
kmsg.setHostUuid(msg.getHostUuid());
kmsg.setPath(KVMConstant.KVM_HOST_CAPACITY_PATH);
kmsg.setNoStatusCheck(true);
kmsg.setCommand(new HostCapacityCmd());
bus.makeTargetServiceIdByResourceUuid(kmsg, HostConstant.SERVICE_ID, msg.getHostUuid());
bus.send(kmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
throw new OperationFailureException(operr("check host capacity failed, because:%s", reply.getError()));
}
KVMHostAsyncHttpCallReply r = reply.castReply();
HostCapacityResponse rsp = r.toResponse(HostCapacityResponse.class);
if (!rsp.isSuccess()) {
throw new OperationFailureException(operr("operation error, because:%s", rsp.getError()));
}
long reservedSize = SizeUtils.sizeStringToBytes(rcf.getResourceConfigValue(KVMGlobalConfig.RESERVED_MEMORY_CAPACITY, msg.getHostUuid(), String.class));
if (rsp.getTotalMemory() < reservedSize) {
throw new OperationFailureException(operr("The host[uuid:%s]'s available memory capacity[%s] is lower than the reserved capacity[%s]",
msg.getHostUuid(), rsp.getTotalMemory(), reservedSize));
}
ReportHostCapacityMessage rmsg = new ReportHostCapacityMessage();
rmsg.setHostUuid(msg.getHostUuid());
rmsg.setCpuNum((int) rsp.getCpuNum());
rmsg.setUsedCpu(rsp.getUsedCpu());
rmsg.setTotalMemory(rsp.getTotalMemory());
rmsg.setUsedMemory(rsp.getUsedMemory());
rmsg.setCpuSockets(rsp.getCpuSockets());
rmsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID));
bus.send(rmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
re.setError(reply.getError());
}
bus.reply(msg, re);
}
});
}
});
}
private void handle(RegisterColoPrimaryCheckMsg msg) {
inQueue().name(String.format("register-vm-heart-beat-on-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> registerPrimaryVmHeartbeat(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void registerPrimaryVmHeartbeat(RegisterColoPrimaryCheckMsg msg, NoErrorCompletion completion) {
RegisterPrimaryVmHeartbeatCmd cmd = new RegisterPrimaryVmHeartbeatCmd();
cmd.setHostUuid(msg.getHostUuid());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setHeartbeatPort(msg.getHeartbeatPort());
cmd.setTargetHostIp(msg.getTargetHostIp());
cmd.setColoPrimary(msg.isColoPrimary());
cmd.setRedirectNum(msg.getRedirectNum());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
new Http<>(registerPrimaryVmHeartbeatPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to register colo heartbeat for vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to register colo heartbeat for vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(StartColoSyncMsg msg) {
inQueue().name(String.format("start-colo-sync-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> startColoSync(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void startColoSync(StartColoSyncMsg msg, NoErrorCompletion completion) {
StartColoSyncCmd cmd = new StartColoSyncCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setBlockReplicationPort(msg.getBlockReplicationPort());
cmd.setNbdServerPort(msg.getNbdServerPort());
cmd.setSecondaryVmHostIp(msg.getSecondaryVmHostIp());
cmd.setCheckpointDelay(msg.getCheckpointDelay());
cmd.setFullSync(msg.isFullSync());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
List<NicTO> nics = new ArrayList<>();
for (VmNicInventory nic : msg.getNics()) {
NicTO to = completeNicInfo(nic);
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
new Http<>(startColoSyncPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to start colo sync vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to start colo sync vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(ConfigSecondaryVmMsg msg) {
inQueue().name(String.format("config-secondary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configSecondaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(ConfigPrimaryVmMsg msg) {
inQueue().name(String.format("config-primary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configPrimaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void configSecondaryVm(ConfigSecondaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigSecondaryVmCmd cmd = new ConfigSecondaryVmCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setPrimaryVmHostIp(msg.getPrimaryVmHostIp());
cmd.setNbdServerPort(msg.getNbdServerPort());
new Http<>(configSecondaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config secondary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config secondary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void configPrimaryVm(ConfigPrimaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigPrimaryVmCmd cmd = new ConfigPrimaryVmCmd();
cmd.setConfigs(msg.getConfigs().stream().sorted(Comparator.comparing(VmNicRedirectConfig::getDeviceId)).collect(Collectors.toList()));
cmd.setHostIp(msg.getHostIp());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
new Http<>(configPrimaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config primary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config primary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmFirstBootDeviceOnHypervisorMsg msg) {
inQueue().name(String.format("get-first-boot-device-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmFirstBootDevice(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmFirstBootDevice(final GetVmFirstBootDeviceOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmFirstBootDeviceCmd cmd = new GetVmFirstBootDeviceCmd();
cmd.setUuid(msg.getVmInstanceUuid());
new Http<>(getVmFirstBootDevicePath, cmd, GetVmFirstBootDeviceResponse.class).call(new ReturnValueCompletion<GetVmFirstBootDeviceResponse>(msg, completion) {
@Override
public void success(GetVmFirstBootDeviceResponse ret) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to get first boot dev of vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
reply.setFirstBootDevice(ret.getFirstBootDevice());
logger.debug(String.format("first boot dev of vm[uuid:%s] on kvm host[uuid:%s] is %s",
msg.getVmInstanceUuid(), self.getUuid(), ret.getFirstBootDevice()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmDeviceAddressMsg msg) {
inQueue().name(String.format("get-device-address-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmDeviceAddress(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmDeviceAddress(final GetVmDeviceAddressMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmDeviceAddressReply reply = new GetVmDeviceAddressReply();
GetVmDeviceAddressCmd cmd = new GetVmDeviceAddressCmd();
cmd.setUuid(msg.getVmInstanceUuid());
for (Map.Entry<String, List> e : msg.getInventories().entrySet()) {
String resourceType = e.getKey();
cmd.putDevice(resourceType, KVMVmDeviceType.fromResourceType(resourceType)
.getDeviceTOs(e.getValue(), KVMHostInventory.valueOf(getSelf()))
);
}
new Http<>(getVmDeviceAddressPath, cmd, GetVmDeviceAddressRsp.class).call(new ReturnValueCompletion<GetVmDeviceAddressRsp>(msg, completion) {
@Override
public void success(GetVmDeviceAddressRsp rsp) {
for (String resourceType : msg.getInventories().keySet()) {
reply.putAddresses(resourceType, rsp.getAddresses(resourceType).stream().map(it -> {
VmDeviceAddress address = new VmDeviceAddress();
address.setAddress(it.getAddress());
address.setAddressType(it.getAddressType());
address.setDeviceType(it.getDeviceType());
address.setResourceUuid(it.getUuid());
address.setResourceType(resourceType);
return address;
}).collect(Collectors.toList()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetKVMHostDownloadCredentialMsg msg) {
final GetKVMHostDownloadCredentialReply reply = new GetKVMHostDownloadCredentialReply();
String key = asf.getPrivateKey();
String hostname = null;
if (Strings.isNotEmpty(msg.getDataNetworkCidr())) {
String dataNetworkAddress = getDataNetworkAddress(self.getUuid(), msg.getDataNetworkCidr());
if (dataNetworkAddress != null) {
hostname = dataNetworkAddress;
}
}
reply.setHostname(hostname == null ? getSelf().getManagementIp() : hostname);
reply.setUsername(getSelf().getUsername());
reply.setSshPort(getSelf().getPort());
reply.setSshKey(key);
bus.reply(msg, reply);
}
protected static String getDataNetworkAddress(String hostUuid, String cidr) {
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
hostUuid, HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.debug(String.format("Host [uuid:%s] has no IPs in data network", hostUuid));
return null;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return ip;
}
}
return null;
}
private void handle(final IncreaseVmCpuMsg msg) {
IncreaseVmCpuReply reply = new IncreaseVmCpuReply();
IncreaseCpuCmd cmd = new IncreaseCpuCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setCpuNum(msg.getCpuNum());
new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) {
@Override
public void success(IncreaseCpuResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to increase vm cpu, error details: %s", ret.getError()));
} else {
reply.setCpuNum(ret.getCpuNum());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final IncreaseVmMemoryMsg msg) {
IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply();
IncreaseMemoryCmd cmd = new IncreaseMemoryCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setMemorySize(msg.getMemorySize());
new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) {
@Override
public void success(IncreaseMemoryResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setMemorySize(ret.getMemorySize());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(msg.getVmUuid());
extEmitter.beforeDirectlyDestroyVmOnKvm(cmd);
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) {
@Override
public void success(DestroyVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
protected RunInQueue inQueue() {
return new RunInQueue(id, thdf, getHostSyncLevel());
}
private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) {
inQueue().name(String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> directlyDestroy(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private SshResult runShell(String script) {
Ssh ssh = new Ssh();
ssh.setHostname(self.getManagementIp());
ssh.setPort(getSelf().getPort());
ssh.setUsername(getSelf().getUsername());
ssh.setPassword(getSelf().getPassword());
ssh.shell(script);
return ssh.runAndClose();
}
private void handle(KvmRunShellMsg msg) {
SshResult result = runShell(msg.getScript());
KvmRunShellReply reply = new KvmRunShellReply();
if (result.isSshFailure()) {
reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," +
" please check if username/password is wrong; %s",
self.getManagementIp(), getSelf().getUsername(),
getSelf().getPort(), result.getExitErrorMessage()));
} else {
reply.setStdout(result.getStdout());
reply.setStderr(result.getStderr());
reply.setReturnCode(result.getReturnCode());
}
bus.reply(msg, reply);
}
private void handle(final GetVmConsoleAddressFromHostMsg msg) {
final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply();
GetVncPortCmd cmd = new GetVncPortCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) {
@Override
public void success(GetVncPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setHostIp(self.getManagementIp());
reply.setProtocol(ret.getProtocol());
reply.setPort(ret.getPort());
VdiPortInfo vdiPortInfo = new VdiPortInfo();
if (ret.getVncPort() != null) {
vdiPortInfo.setVncPort(ret.getVncPort());
}
if (ret.getSpicePort() != null) {
vdiPortInfo.setSpicePort(ret.getSpicePort());
}
if (ret.getSpiceTlsPort() != null) {
vdiPortInfo.setSpiceTlsPort(ret.getSpiceTlsPort());
}
reply.setVdiPortInfo(vdiPortInfo);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UpdateVmPriorityMsg msg) {
final UpdateVmPriorityReply reply = new UpdateVmPriorityReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
UpdateVmPriorityCmd cmd = new UpdateVmPriorityCmd();
cmd.priorityConfigStructs = msg.getPriorityConfigStructs();
new Http<>(updateVmPriorityPath, cmd, UpdateVmPriorityRsp.class).call(new ReturnValueCompletion<UpdateVmPriorityRsp>(msg) {
@Override
public void success(UpdateVmPriorityRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected void handle(final CheckVmStateOnHypervisorMsg msg) {
final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
// NOTE: don't run this message in the sync task
// there can be many such kind of messages
// running in the sync task may cause other tasks starved
CheckVmStateCmd cmd = new CheckVmStateCmd();
cmd.vmUuids = msg.getVmInstanceUuids();
cmd.hostUuid = self.getUuid();
extEmitter.beforeCheckVmState((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) {
@Override
public void success(CheckVmStateRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
Map<String, String> m = new HashMap<>();
for (Map.Entry<String, String> e : ret.states.entrySet()) {
m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString());
}
extEmitter.afterCheckVmState((KVMHostInventory) getSelfInventory(), m);
reply.setStates(m);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final DetachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()))
.run(chain -> detachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply();
DetachIsoCmd cmd = new DetachIsoCmd();
cmd.isoUuid = msg.getIsoUuid();
cmd.vmUuid = msg.getVmInstanceUuid();
Integer deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid());
assert deviceId != null;
cmd.deviceId = deviceId;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) {
ext.preDetachIsoExtensionPoint(inv, cmd);
}
new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) {
@Override
public void success(DetachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()))
.run(chain -> attachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply();
IsoTO iso = new IsoTO();
iso.setImageUuid(msg.getIsoSpec().getImageUuid());
iso.setPath(msg.getIsoSpec().getInstallPath());
iso.setDeviceId(msg.getIsoSpec().getDeviceId());
AttachIsoCmd cmd = new AttachIsoCmd();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.iso = iso;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) {
ext.preAttachIsoExtensionPoint(inv, cmd);
}
new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) {
@Override
public void success(AttachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachNicFromVmOnHypervisorMsg msg) {
inQueue().name("detach-nic-on-kvm-host-" + self.getUuid())
.asyncBackup(msg)
.run(chain -> detachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply();
NicTO to = completeNicInfo(msg.getNic());
DetachNicCommand cmd = new DetachNicCommand();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreDetachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreDetachNicExtensionPoint.class)) {
ext.preDetachNicExtensionPoint(inv, cmd);
}
new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) {
@Override
public void success(DetachNicRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private static int getHostMaxThreadsNum() {
int n = (int)(KVMGlobalProperty.KVM_HOST_MAX_THREDS_RATIO * ThreadGlobalProperty.MAX_THREAD_NUM);
int m = ThreadGlobalProperty.MAX_THREAD_NUM / 5;
return Math.max(n, m);
}
private void handle(final KVMHostSyncHttpCallMsg msg) {
inQueue().name(String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(outer -> new RunInQueue("host-sync-control", thdf, getHostMaxThreadsNum())
.name("sync-call-on-kvm-" + self.getUuid())
.asyncBackup(msg)
.asyncBackup(outer)
.run((chain) -> executeSyncHttpCall(msg, new NoErrorCompletion(chain, outer) {
@Override
public void done() {
chain.next();
outer.next();
}
}))
);
}
private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid());
LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class);
KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply();
reply.setResponse(rsp);
bus.reply(msg, reply);
completion.done();
}
private void handle(final KVMHostAsyncHttpCallMsg msg) {
inQueue().name(String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(outer -> new RunInQueue("host-sync-control", thdf, getHostMaxThreadsNum())
.name("async-call-on-kvm-" + self.getUuid())
.asyncBackup(msg)
.asyncBackup(outer)
.run((chain) -> executeAsyncHttpCall(msg, new NoErrorCompletion(chain, outer) {
@Override
public void done() {
chain.next();
outer.next();
}
}))
);
}
private String buildUrl(String path) {
UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME);
ub.host(self.getManagementIp());
ub.port(KVMGlobalProperty.AGENT_PORT);
if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) {
ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH);
}
ub.path(path);
return ub.build().toUriString();
}
private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
new Http<>(url, msg.getCommand(), LinkedHashMap.class)
.call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) {
@Override
public void success(LinkedHashMap ret) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
reply.setResponse(ret);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) {
reply.setError(err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "cannot do the operation on the KVM host"));
} else {
reply.setError(err);
}
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final MergeVolumeSnapshotOnKvmMsg msg) {
inQueue().name(String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply();
VolumeInventory volume = msg.getTo();
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
if (state != VmInstanceState.Stopped && state != VmInstanceState.Running && state != VmInstanceState.Paused && state != VmInstanceState.Destroyed) {
throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." +
" The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state));
}
if (state == VmInstanceState.Running) {
String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN);
if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) {
throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," +
" current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume",
KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion));
}
}
}
VolumeSnapshotInventory snapshot = msg.getFrom();
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setFullRebase(msg.isFullRebase());
cmd.setDestPath(volume.getInstallPath());
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setVmUuid(volume.getVmInstanceUuid());
cmd.setVolume(VolumeTO.valueOf(volume, (KVMHostInventory) getSelfInventory()));
cmd.setTimeout(timeoutManager.getTimeoutSeconds());
extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class)
.call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) {
@Override
public void success(MergeSnapshotRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
}
extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final CheckSnapshotOnHypervisorMsg msg) {
inQueue().name(String.format("check-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
checkSnapshot(msg);
chain.next();
});
}
private void checkSnapshot(final CheckSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(SyncTaskChain chain) {
CheckSnapshotOnHypervisorReply reply = new CheckSnapshotOnHypervisorReply();
doCheckSnapshot(msg, new Completion(chain) {
@Override
public void success() {
bus.reply(msg, reply);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
chain.next();
}
});
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.HOST_SNAPSHOT_SYNC_LEVEL.value(Integer.class);
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
});
}
private void doCheckSnapshot(final CheckSnapshotOnHypervisorMsg msg, final Completion completion) {
checkStateAndStatus();
CheckSnapshotCmd cmd = new CheckSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
}
cmd.setVolumeUuid(msg.getVolumeUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setVolumeChainToCheck(msg.getVolumeChainToCheck());
cmd.setCurrentInstallPath(msg.getCurrentInstallPath());
cmd.setExcludeInstallPaths(msg.getExcludeInstallPaths());
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("check-volume-%s-snapshot-chain", msg.getVolumeUuid()));
chain.then(new NoRollbackFlow() {
String __name__ = "before-check-volume-snapshot-extension";
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeCheckSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
String __name__ = "check-volume-snapshot";
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(checkSnapshotPath, cmd, CheckSnapshotResponse.class).call(new ReturnValueCompletion<CheckSnapshotResponse>(msg, trigger) {
@Override
public void success(CheckSnapshotResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
}).start();
}
private void handle(final TakeSnapshotOnHypervisorMsg msg) {
inQueue().name(String.format("take-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
takeSnapshot(msg);
chain.next();
});
}
private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(SyncTaskChain chain) {
doTakeSnapshot(msg, new NoErrorCompletion() {
@Override
public void done() {
chain.next();
}
});
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.HOST_SNAPSHOT_SYNC_LEVEL.value(Integer.class);
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
});
}
protected void completeTakeSnapshotCmd(final TakeSnapshotOnHypervisorMsg msg, final TakeSnapshotCmd cmd) {
}
private void doTakeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply();
TakeSnapshotCmd cmd = new TakeSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) {
if (vmState != VmInstanceState.Stopped) {
reply.setError(err(SysErrors.NO_CAPABILITY_ERROR,
"kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again",
self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()
));
bus.reply(msg, reply);
completion.done();
return;
}
}
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setVolume(VolumeTO.valueOf(msg.getVolume(), (KVMHostInventory) getSelfInventory()));
}
cmd.setVolumeInstallPath(msg.getVolume().getInstallPath());
cmd.setInstallPath(msg.getInstallPath());
cmd.setFullSnapshot(msg.isFullSnapshot());
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setTimeout(timeoutManager.getTimeout());
completeTakeSnapshotCmd(msg, cmd);
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid()));
chain.then(new NoRollbackFlow() {
String __name__ = String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid());
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
String __name__ = "do-take-snapshot-" + msg.getSnapshotName();
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) {
@Override
public void success(TakeSnapshotResponse ret) {
if (ret.isSuccess()) {
extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret);
reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath());
reply.setSnapshotInstallPath(ret.getSnapshotInstallPath());
reply.setSize(ret.getSize());
} else {
ErrorCode err = operr("operation error, because:%s", ret.getError());
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err);
reply.setError(err);
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode);
reply.setError(errorCode);
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
bus.reply(msg, reply);
completion.done();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
completion.done();
}
}).start();
}
private void migrateVm(final MigrateStruct s, final Completion completion) {
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange MIGRATE_VM_STAGE = new TaskProgressRange(0, 90);
final String dstHostMigrateIp, dstHostMnIp, dstHostUuid;
final String vmUuid;
final StorageMigrationPolicy storageMigrationPolicy;
final boolean migrateFromDestination;
final String srcHostMigrateIp, srcHostMnIp, srcHostUuid;
vmUuid = s.vmUuid;
dstHostMigrateIp = s.dstHostMigrateIp;
dstHostMnIp = s.dstHostMnIp;
dstHostUuid = s.dstHostUuid;
storageMigrationPolicy = s.storageMigrationPolicy;
migrateFromDestination = s.migrateFromDestition;
srcHostMigrateIp = s.srcHostMigrateIp;
srcHostMnIp = s.srcHostMnIp;
srcHostUuid = s.srcHostUuid;
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.internalId);
q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid);
final Long vmInternalId = q.findValue();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, s.vmUuid)
.eq(VmNicVO_.type, "vDPA")
.list();
List<NicTO> nicTos = VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList());
List<NicTO> vDPANics = new ArrayList<NicTO>();
for (NicTO nicTo : nicTos) {
if (nicTo.getType().equals("vDPA")) {
vDPANics.add(nicTo);
}
}
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "generate-vDPA-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
if (vDPANics.isEmpty()) {
trigger.next();
return;
}
GenerateVdpaCmd cmd = new GenerateVdpaCmd();
cmd.vmUuid = vmUuid;
cmd.setNics(nicTos);
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_GENERATE_VDPA_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, GenerateVdpaResponse.class).call(dstHostUuid, new ReturnValueCompletion<GenerateVdpaResponse>(trigger) {
@Override
public void success(GenerateVdpaResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("generate vDPA for %s failed, %s", vmUuid, ret.getError()));
}
data.put("vDPA_paths", ret.getVdpaPaths());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("generate vDPA for %s failed, %s", vmUuid, errorCode));
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, MIGRATE_VM_STAGE);
boolean autoConverage = KVMGlobalConfig.MIGRATE_AUTO_CONVERGE.value(Boolean.class);
if (!autoConverage) {
autoConverage = s.strategy != null && s.strategy.equals("auto-converge");
}
boolean xbzrle = KVMGlobalConfig.MIGRATE_XBZRLE.value(Boolean.class);
MigrateVmCmd cmd = new MigrateVmCmd();
cmd.setDestHostIp(dstHostMigrateIp);
cmd.setSrcHostIp(srcHostMigrateIp);
cmd.setMigrateFromDestination(migrateFromDestination);
cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString());
cmd.setVmUuid(vmUuid);
cmd.setAutoConverge(autoConverage);
cmd.setXbzrle(xbzrle);
cmd.setVdpaPaths((List<String>) data.get("vDPA_paths"));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, vmUuid, Boolean.class));
cmd.setTimeout(timeoutManager.getTimeout());
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(migrateVmPath);
ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp);
String migrateUrl = ub.build().toString();
new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) {
@Override
public void success(MigrateVmResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = err(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR,
"failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp, ret.getError()
);
trigger.fail(err);
} else {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "harden-vm-console-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
HardenVmConsoleCmd cmd = new HardenVmConsoleCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = dstHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
//TODO: add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode));
// continue
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vm-console-firewall-on-source-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = srcHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, errorCode));
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vDPA-on-src-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
if (vDPANics.isEmpty()) {
trigger.next();
return;
}
DeleteVdpaCmd cmd = new DeleteVdpaCmd();
cmd.vmUuid = vmUuid;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_VDPA_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("delete vDPA for %s failed, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("delete vDPA for %s failed, %s", vmUuid, errorCode));
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(parentStage.getEnd().toString());
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final MigrateVmOnHypervisorMsg msg) {
inQueue().name(String.format("migrate-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> migrateVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
class MigrateStruct {
String vmUuid;
String dstHostMigrateIp;
String strategy;
String dstHostMnIp;
String dstHostUuid;
StorageMigrationPolicy storageMigrationPolicy;
boolean migrateFromDestition;
String srcHostMigrateIp;
String srcHostMnIp;
String srcHostUuid;
}
private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){
MigrateStruct s = new MigrateStruct();
s.vmUuid = msg.getVmInventory().getUuid();
s.srcHostUuid = msg.getSrcHostUuid();
s.dstHostUuid = msg.getDestHostInventory().getUuid();
s.storageMigrationPolicy = msg.getStorageMigrationPolicy();
s.migrateFromDestition = msg.isMigrateFromDestination();
s.strategy = msg.getStrategy();
MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null;
for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) {
MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid);
if (r == null) {
continue;
}
migrateIpInfo = r;
}
s.dstHostMnIp = msg.getDestHostInventory().getManagementIp();
s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress;
s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue();
s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress;
return s;
}
private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
MigrateStruct s = buildMigrateStuct(msg);
final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply();
migrateVm(s, new Completion(msg, completion) {
@Override
public void success() {
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmUpdateNicOnHypervisorMsg msg) {
inQueue().name(String.format("update-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> updateNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void updateNic(VmUpdateNicOnHypervisorMsg msg, NoErrorCompletion completion) {
checkStateAndStatus();
final VmUpdateNicOnHypervisorReply reply = new VmUpdateNicOnHypervisorReply();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, msg.getVmInstanceUuid()).list();
UpdateNicCmd cmd = new UpdateNicCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setNics(VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList()));
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreUpdateNicExtensionPoint ext : pluginRgty.getExtensionList(KVMPreUpdateNicExtensionPoint.class)) {
ext.preUpdateNic(inv, cmd);
}
new Http<>(updateNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to update nic[vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmAttachNicOnHypervisorMsg msg) {
inQueue().name(String.format("attach-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
NicTO to = completeNicInfo(msg.getNicInventory());
final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply();
AttachNicCommand cmd = new AttachNicCommand();
cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) {
ext.preAttachNicExtensionPoint(inv, cmd);
}
new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
if (ret.getError().contains("Device or resource busy")) {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s, please try again or delete device[%s] by yourself", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError(), msg.getNicInventory().getInternalName()));
} else {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError()));
}
}
bus.reply(msg, reply);
if (ret.getPciAddress() != null) {
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(msg.getNicInventory().getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, ret.getPciAddress().toString())));
creator.create();
}
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) {
inQueue().name(String.format("detach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> detachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, (KVMHostInventory) getSelfInventory(), vm.getPlatform());
final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply();
final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(vm.getUuid());
extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) {
@Override
public void success(DetachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError());
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
} else {
extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
bus.reply(msg, reply);
completion.done();
}
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachVolumeToVmOnHypervisorMsg msg) {
inQueue().name(String.format("attach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
static String computeWwnIfAbsent(String volumeUUid) {
String wwn;
String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid);
if (tag != null) {
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN);
} else {
wwn = new WwnUtils().getRandomWwn();
SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid);
creator.inherent = true;
creator.setTagByTokens(Collections.singletonMap(KVMSystemTags.VOLUME_WWN_TOKEN, wwn));
creator.create();
}
DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid));
return wwn;
}
private String makeAndSaveVmSystemSerialNumber(String vmUuid) {
String serialNumber;
String tag = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTag(vmUuid);
if (tag != null) {
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(tag, VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
} else {
SystemTagCreator creator = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.newSystemTagCreator(vmUuid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN, UUID.randomUUID().toString())));
SystemTagInventory inv = creator.create();
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(inv.getTag(), VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
}
return serialNumber;
}
protected void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
KVMHostInventory host = (KVMHostInventory) getSelfInventory();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, host, vm.getPlatform());
final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply();
final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(msg.getVmInventory().getUuid());
cmd.getAddons().put("attachedDataVolumes", VolumeTO.valueOf(msg.getAttachedDataVolumes(), host));
Map data = new HashMap();
extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd, data);
new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) {
@Override
public void success(AttachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" +
" on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(),
getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()));
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError(), data);
} else {
extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err, data);
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DestroyVmOnHypervisorMsg msg) {
inQueue().name(String.format("destroy-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> destroyVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(vminv.getUuid());
try {
extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) {
@Override
public void success(DestroyVmResponse ret) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, "unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid()));
extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to destroy a vm");
}
reply.setError(err);
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final RebootVmOnHypervisorMsg msg) {
inQueue().name(String.format("reboot-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> rebootVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private List<String> toKvmBootDev(List<String> order) {
List<String> ret = new ArrayList<String>();
for (String o : order) {
if (VmBootDevice.HardDisk.toString().equals(o)) {
ret.add(BootDev.hd.toString());
} else if (VmBootDevice.CdRom.toString().equals(o)) {
ret.add(BootDev.cdrom.toString());
} else if (VmBootDevice.Network.toString().equals(o)) {
ret.add(BootDev.network.toString());
} else {
throw new CloudRuntimeException(String.format("unknown boot device[%s]", o));
}
}
return ret;
}
private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
logger.warn(err, e);
throw new OperationFailureException(operr(err));
}
RebootVmCmd cmd = new RebootVmCmd();
long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout());
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(timeout);
cmd.setBootDev(toKvmBootDev(msg.getBootOrders()));
new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) {
@Override
public void success(RebootVmResponse ret) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, "unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
reply.setError(err);
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final StopVmOnHypervisorMsg msg) {
inQueue().name(String.format("stop-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> stopVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
StopVmCmd cmd = new StopVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setType(msg.getType());
cmd.setTimeout(120);
try {
extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) {
@Override
public void success(StopVmResponse ret) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to stop a vm");
}
reply.setError(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
@Transactional
private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) {
String vmUuid = spec.getVmInventory().getUuid();
Map<String, Integer> diskOfferingUuid_Num = new HashMap<>();
List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid);
for (Map<String, String> tokens : tokenList) {
String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN);
Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN));
diskOfferingUuid_Num.put(diskOfferingUuid, num);
}
for (VolumeInventory volumeInv : spec.getDestDataVolumes()) {
if (volumeInv.getType().equals(VolumeType.Root.toString())) {
continue;
}
if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid())
&& diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) {
tagmgr.createNonInherentSystemTag(volumeInv.getUuid(),
KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(),
VolumeVO.class.getSimpleName());
diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(),
diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1);
}
}
}
@Transactional
private void setVmNicMultiqueueNum(final VmInstanceSpec spec) {
try {
if (!ImagePlatform.isType(spec.getImageSpec().getInventory().getPlatform(), ImagePlatform.Linux)) {
return;
}
if (!rcf.getResourceConfigValue(KVMGlobalConfig.AUTO_VM_NIC_MULTIQUEUE,
spec.getDestHost().getClusterUuid(), Boolean.class)) {
return;
}
ResourceConfig multiQueues = rcf.getResourceConfig(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.getIdentity());
Integer queues = spec.getVmInventory().getCpuNum() > KVMConstant.DEFAULT_MAX_NIC_QUEUE_NUMBER ? KVMConstant.DEFAULT_MAX_NIC_QUEUE_NUMBER : spec.getVmInventory().getCpuNum();
multiQueues.updateValue(spec.getVmInventory().getUuid(), queues.toString());
} catch (Exception e) {
logger.warn(String.format("got exception when trying set nic multiqueue for vm: %s, %s", spec.getVmInventory().getUuid(), e));
}
}
private void handle(final CreateVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
setDataVolumeUseVirtIOSCSI(msg.getVmSpec());
setVmNicMultiqueueNum(msg.getVmSpec());
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
});
}
private void handle(final UpdateSpiceChannelConfigMsg msg) {
UpdateSpiceChannelConfigReply reply = new UpdateSpiceChannelConfigReply();
UpdateSpiceChannelConfigCmd cmd = new UpdateSpiceChannelConfigCmd();
new Http<>(updateSpiceChannelConfigPath, cmd, UpdateSpiceChannelConfigResponse.class).call(new ReturnValueCompletion<UpdateSpiceChannelConfigResponse>(msg) {
@Override
public void success(UpdateSpiceChannelConfigResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("Host[%s] update spice channel config faild, because %s", msg.getHostUuid(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
reply.setRestartLibvirt(ret.restartLibvirt);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
});
}
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
query.setParameter("l3NetworkUuid", l3NetworkUuid);
L2NetworkVO l2vo = query.getSingleResult();
return L2NetworkInventory.valueOf(l2vo);
}
@Transactional(readOnly = true)
private NicTO completeNicInfo(VmNicInventory nic) {
/* all l3 networks of the nic has same l2 network */
L3NetworkInventory l3Inv = L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class));
L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid());
KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType()));
NicTO to = extp.completeNicInformation(l2inv, l3Inv, nic);
if (to.getUseVirtio() == null) {
to.setUseVirtio(VmSystemTags.VIRTIO.hasTag(nic.getVmInstanceUuid()));
to.setIps(getCleanTrafficIp(nic));
}
if (!nic.getType().equals(VmInstanceConstant.VIRTUAL_NIC_TYPE)) {
return to;
}
// build vhost addon
if (to.getDriverType() == null) {
if (nic.getDriverType() != null) {
to.setDriverType(nic.getDriverType());
} else {
to.setDriverType(to.getUseVirtio() ? nicManager.getDefaultPVNicDriver() : nicManager.getDefaultNicDriver());
}
}
VHostAddOn vHostAddOn = new VHostAddOn();
if (to.getDriverType().equals(nicManager.getDefaultPVNicDriver())) {
vHostAddOn.setQueueNum(rcf.getResourceConfigValue(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM, nic.getVmInstanceUuid(), Integer.class));
} else {
vHostAddOn.setQueueNum(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.defaultValue(Integer.class));
}
if (VmSystemTags.VM_VRING_BUFFER_SIZE.hasTag(nic.getVmInstanceUuid())) {
Map<String, String> tokens = VmSystemTags.VM_VRING_BUFFER_SIZE.getTokensByResourceUuid(nic.getVmInstanceUuid());
if (tokens.get(VmSystemTags.RX_SIZE_TOKEN) != null) {
vHostAddOn.setRxBufferSize(tokens.get(VmSystemTags.RX_SIZE_TOKEN));
}
if (tokens.get(VmSystemTags.TX_SIZE_TOKEN) != null) {
vHostAddOn.setTxBufferSize(tokens.get(VmSystemTags.TX_SIZE_TOKEN));
}
}
to.setvHostAddOn(vHostAddOn);
String pci = KVMSystemTags.VMNIC_PCI_ADDRESS.getTokenByResourceUuid(nic.getUuid(), KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN);
if (pci != null) {
to.setPci(PciAddressConfig.fromString(pci));
}
return to;
}
private List<String> getCleanTrafficIp(VmNicInventory nic) {
boolean isUserVm = Q.New(VmInstanceVO.class)
.eq(VmInstanceVO_.uuid, nic.getVmInstanceUuid()).select(VmInstanceVO_.type)
.findValue().equals(VmInstanceConstant.USER_VM_TYPE);
if (!isUserVm) {
return null;
}
String tagValue = VmSystemTags.CLEAN_TRAFFIC.getTokenByResourceUuid(nic.getVmInstanceUuid(), VmSystemTags.CLEAN_TRAFFIC_TOKEN);
if (Boolean.parseBoolean(tagValue) || (tagValue == null && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class))) {
return VmNicHelper.getIpAddresses(nic);
}
return null;
}
static String getVolumeTOType(VolumeInventory vol) {
DebugUtils.Assert(vol.getInstallPath() != null, String.format("volume [%s] installPath is null, it has not been initialized", vol.getUuid()));
return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE;
}
private void checkPlatformWithOther(VmInstanceSpec spec) {
int total = spec.getDestDataVolumes().size() + spec.getDestCacheVolumes().size() + spec.getCdRomSpecs().size();
if (total > 3) {
throw new OperationFailureException(operr("when the vm platform is Other, the number of dataVolumes and cdroms cannot exceed 3, currently %s", total));
}
}
protected void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final StartVmCmd cmd = new StartVmCmd();
String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() :
spec.getVmInventory().getPlatform();
if(ImagePlatform.Other.toString().equals(platform)){
checkPlatformWithOther(spec);
}
String architecture = spec.getDestHost().getArchitecture();
int cpuNum = spec.getVmInventory().getCpuNum();
cmd.setCpuNum(cpuNum);
int socket;
int cpuOnSocket;
//TODO: this is a HACK!!!
if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) {
if (cpuNum == 1) {
socket = 1;
cpuOnSocket = 1;
} else if (cpuNum % 2 == 0) {
socket = 2;
cpuOnSocket = cpuNum / 2;
} else {
socket = cpuNum;
cpuOnSocket = 1;
}
} else {
socket = 1;
cpuOnSocket = cpuNum;
}
cmd.setImagePlatform(platform);
cmd.setImageArchitecture(architecture);
cmd.setSocketNum(socket);
cmd.setCpuOnSocket(cpuOnSocket);
cmd.setVmName(spec.getVmInventory().getName());
cmd.setVmInstanceUuid(spec.getVmInventory().getUuid());
cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed());
cmd.setMemory(spec.getVmInventory().getMemorySize());
cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory());
cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc");
VmClockTrack vmClockTrack = VmClockTrack.get(rcf.getResourceConfigValue(VmGlobalConfig.VM_CLOCK_TRACK, spec.getVmInventory().getUuid(), String.class));
if (vmClockTrack == VmClockTrack.guest) {
cmd.setClockTrack(vmClockTrack.toString());
}
cmd.setVideoType(rcf.getResourceConfigValue(VmGlobalConfig.VM_VIDEO_TYPE, spec.getVmInventory().getUuid(), String.class));
if (VmSystemTags.QXL_MEMORY.hasTag(spec.getVmInventory().getUuid())) {
Map<String,String> qxlMemory = VmSystemTags.QXL_MEMORY.getTokensByResourceUuid(spec.getVmInventory().getUuid());
cmd.setQxlMemory(qxlMemory);
}
if (VmSystemTags.SOUND_TYPE.hasTag(spec.getVmInventory().getUuid())) {
cmd.setSoundType(VmSystemTags.SOUND_TYPE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmInstanceVO.class, VmSystemTags.SOUND_TYPE_TOKEN));
}
cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null);
cmd.setKvmHiddenState(rcf.getResourceConfigValue(VmGlobalConfig.KVM_HIDDEN_STATE, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class));
boolean emulateHyperV = false;
if (!ImagePlatform.isType(platform, ImagePlatform.Linux) &&
ImageArchitecture.x86_64.toString().equals(architecture)) {
emulateHyperV = rcf.getResourceConfigValue(VmGlobalConfig.EMULATE_HYPERV, spec.getVmInventory().getUuid(), Boolean.class);
}
cmd.setEmulateHyperV(emulateHyperV);
cmd.setVendorId(rcf.getResourceConfigValue(VmGlobalConfig.VENDOR_ID, spec.getVmInventory().getUuid(), String.class));
cmd.setAdditionalQmp(VmGlobalConfig.ADDITIONAL_QMP.value(Boolean.class));
cmd.setApplianceVm(spec.getVmInventory().getType().equals("ApplianceVm"));
cmd.setSystemSerialNumber(makeAndSaveVmSystemSerialNumber(spec.getVmInventory().getUuid()));
if (!NetworkGlobalProperty.CHASSIS_ASSET_TAG.isEmpty()) {
cmd.setChassisAssetTag(NetworkGlobalProperty.CHASSIS_ASSET_TAG);
}
String machineType = VmSystemTags.MACHINE_TYPE.getTokenByResourceUuid(cmd.getVmInstanceUuid(),
VmInstanceVO.class, VmSystemTags.MACHINE_TYPE_TOKEN);
cmd.setMachineType(StringUtils.isNotEmpty(machineType) ? machineType : "pc");
if (KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.hasTag(spec.getVmInventory().getUuid())) {
cmd.setPredefinedPciBridgeNum(Integer.valueOf(KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.getTokenByResourceUuid(spec.getVmInventory().getUuid(), KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM_TOKEN)));
}
if (VmMachineType.q35.toString().equals(machineType) || VmMachineType.virt.toString().equals(machineType)) {
cmd.setPciePortNums(VmGlobalConfig.PCIE_PORT_NUMS.value(Integer.class));
if (cmd.getPredefinedPciBridgeNum() == null) {
cmd.setPredefinedPciBridgeNum(1);
}
}
VmPriorityLevel level = new VmPriorityOperator().getVmPriority(spec.getVmInventory().getUuid());
VmPriorityConfigVO priorityVO = Q.New(VmPriorityConfigVO.class).eq(VmPriorityConfigVO_.level, level).find();
cmd.setPriorityConfigStruct(new PriorityConfigStruct(priorityVO, spec.getVmInventory().getUuid()));
VolumeTO rootVolume = new VolumeTO();
rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath());
rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId());
rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume()));
rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid());
rootVolume.setUseVirtio(VmSystemTags.VIRTIO.hasTag(spec.getVmInventory().getUuid()));
rootVolume.setUseVirtioSCSI(ImagePlatform.Other.toString().equals(platform) ? false : KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid()));
rootVolume.setWwn(computeWwnIfAbsent(spec.getDestRootVolume().getUuid()));
rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
cmd.setNestedVirtualization( rcf.getResourceConfigValue(KVMGlobalConfig.NESTED_VIRTUALIZATION, spec.getVmInventory().getUuid(), String.class) );
cmd.setRootVolume(rootVolume);
cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class));
List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size());
for (VolumeInventory data : spec.getDestDataVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// except for platform = Other, always use virtio driver for data volume
v.setUseVirtio(!ImagePlatform.Other.toString().equals(platform));
dataVolumes.add(v);
}
dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId));
cmd.setDataVolumes(dataVolumes);
List<VolumeTO> cacheVolumes = new ArrayList<>(spec.getDestCacheVolumes().size());
for (VolumeInventory data : spec.getDestCacheVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// except for platform = Other, always use virtio driver for data volume
v.setUseVirtio(!ImagePlatform.Other.toString().equals(platform));
cacheVolumes.add(v);
}
cmd.setCacheVolumes(cacheVolumes);
cmd.setVmInternalId(spec.getVmInventory().getInternalId());
List<NicTO> nics = new ArrayList<>(spec.getDestNics().size());
for (VmNicInventory nic : spec.getDestNics()) {
NicTO to = completeNicInfo(nic);
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
for (VmInstanceSpec.CdRomSpec cdRomSpec : spec.getCdRomSpecs()) {
CdRomTO cdRomTO = new CdRomTO();
cdRomTO.setPath(cdRomSpec.getInstallPath());
cdRomTO.setImageUuid(cdRomSpec.getImageUuid());
cdRomTO.setDeviceId(cdRomSpec.getDeviceId());
cdRomTO.setEmpty(cdRomSpec.getImageUuid() == null);
cmd.getCdRoms().add(cdRomTO);
}
String bootMode = VmSystemTags.BOOT_MODE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.BOOT_MODE_TOKEN);
cmd.setBootMode(bootMode == null ? ImageBootMode.Legacy.toString() : bootMode);
deviceBootOrderOperator.updateVmDeviceBootOrder(cmd, spec);
cmd.setBootDev(toKvmBootDev(spec.getBootOrders()));
cmd.setHostManagementIp(self.getManagementIp());
cmd.setConsolePassword(spec.getConsolePassword());
cmd.setUsbRedirect(spec.isUsbRedirect());
cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber()));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class));
cmd.setConsoleMode("vnc");
cmd.setTimeout(TimeUnit.MINUTES.toSeconds(5));
cmd.setConsoleLogToFile(!VmInstanceConstant.USER_VM_TYPE.equals(spec.getVmInventory().getType()));
if (spec.isCreatePaused()) {
cmd.setCreatePaused(true);
}
String vmArchPlatformRelease = String.format("%s_%s_%s", spec.getVmInventory().getArchitecture(), spec.getVmInventory().getPlatform(), spec.getVmInventory().getGuestOsType());
if (allGuestOsCharacter.containsKey(vmArchPlatformRelease)) {
cmd.setAcpi(allGuestOsCharacter.get(vmArchPlatformRelease).getAcpi() != null && allGuestOsCharacter.get(vmArchPlatformRelease).getAcpi());
cmd.setHygonCpu(allGuestOsCharacter.get(vmArchPlatformRelease).getHygonCpu() != null && allGuestOsCharacter.get(vmArchPlatformRelease).getHygonCpu());
}
addons(spec, cmd);
KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf());
extEmitter.beforeStartVmOnKvm(khinv, spec, cmd);
extEmitter.addOn(khinv, spec, cmd);
new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) {
@Override
public void success(StartVmResponse ret) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
if (ret.isSuccess()) {
String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp());
logger.debug(info);
extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec);
} else {
reply.setError(err(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, "failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError());
}
if (ret.getNicInfos() != null && !ret.getNicInfos().isEmpty()) {
Map<String, VmNicInventory> macNicMap = new HashMap<>();
for (VmNicInventory nic : spec.getDestNics()) {
macNicMap.put(nic.getMac(), nic);
}
for (VmNicInfo vmNicInfo : ret.getNicInfos()) {
VmNicInventory nic = macNicMap.get(vmNicInfo.getMacAddress());
if (nic == null) {
continue;
}
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(nic.getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, vmNicInfo.getPciInfo().toString())));
creator.create();
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
reply.setError(err);
reply.setSuccess(false);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void addons(final VmInstanceSpec spec, StartVmCmd cmd) {
KVMAddons.Channel chan = new KVMAddons.Channel();
chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid()));
chan.setTargetName("org.qemu.guest_agent.0");
cmd.getAddons().put(KVMAddons.Channel.NAME, chan);
logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName()));
}
private String makeChannelSocketPath(String apvmuuid) {
return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid));
}
private void handle(final StartVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> startVmInQueue(msg, chain));
}
private void startVmInQueue(StartVmOnHypervisorMsg msg, SyncTaskChain outterChain) {
thdf.chainSubmit(new ChainTask(msg, outterChain) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(final SyncTaskChain chain) {
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain, outterChain) {
@Override
public void done() {
chain.next();
outterChain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s-inner-queue", self.getUuid());
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.VM_CREATE_CONCURRENCY.value(Integer.class);
}
});
}
protected void handle(final CheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> checkPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void handle(final BatchCheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> batchCheckPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply();
PauseVmCmd cmd = new PauseVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) {
@Override
public void success(PauseVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final PauseVmOnHypervisorMsg msg) {
inQueue().name(String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> pauseVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(final ResumeVmOnHypervisorMsg msg) {
inQueue().name(String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> resumeVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply();
ResumeVmCmd cmd = new ResumeVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) {
@Override
public void success(ResumeVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void batchCheckPhysicalInterface(BatchCheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
msg.getPhysicalInterfaces().forEach(cmd::addInterfaceName);
BatchCheckNetworkPhysicalInterfaceReply reply = new BatchCheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
rsp.getFailedInterfaceNames(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
cmd.addInterfaceName(msg.getPhysicalInterface());
CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void handleMessage(Message msg) {
try {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
} catch (Exception e) {
bus.logExceptionWithMessageDump(msg, e);
bus.replyErrorByMessageType(msg, e);
}
}
@Override
public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) {
}
@Override
public void deleteHook() {
}
@Override
protected HostInventory getSelfInventory() {
return KVMHostInventory.valueOf(getSelf());
}
private void doUpdateHostConfiguration() {
thdf.chainSubmit(new ChainTask(null) {
@Override
public String getSyncSignature() {
return String.format("update-kvm-host-configuration-%s", self.getUuid());
}
@Override
public void run(SyncTaskChain chain) {
UpdateHostConfigurationCmd cmd = new UpdateHostConfigurationCmd();
cmd.hostUuid = self.getUuid();
cmd.sendCommandUrl = restf.getSendCommandUrl();
restf.asyncJsonPost(updateHostConfigurationPath, cmd, new JsonAsyncRESTCallback<UpdateHostConfigurationResponse>(chain) {
@Override
public void fail(ErrorCode err) {
String info = "Failed to update host configuration request for host reconnect";
logger.warn(info);
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
chain.next();
}
@Override
public void success(UpdateHostConfigurationResponse rsp) {
logger.debug("Update host configuration success");
chain.next();
}
@Override
public Class<UpdateHostConfigurationResponse> getReturnClass() {
return UpdateHostConfigurationResponse.class;
}
}, TimeUnit.SECONDS, 30);
}
protected int getMaxPendingTasks() {
return 1;
}
protected String getDeduplicateString() {
return getSyncSignature();
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
boolean needReconnectHost(PingResponse rsp) {
return !self.getUuid().equals(rsp.getHostUuid()) || !dbf.getDbVersion().equals(rsp.getVersion());
}
boolean needUpdateHostConfiguration(PingResponse rsp) {
// host uuid or send command url or version changed
return !restf.getSendCommandUrl().equals(rsp.getSendCommandUrl());
}
@Override
protected void pingHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("ping-kvm-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "ping-host";
@AfterDone
List<Runnable> afterDone = new ArrayList<>();
@Override
public void run(FlowTrigger trigger, Map data) {
PingCmd cmd = new PingCmd();
cmd.hostUuid = self.getUuid();
restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(PingResponse ret) {
if (ret.isSuccess()) {
if (needUpdateHostConfiguration(ret)) {
afterDone.add(KVMHost.this::doUpdateHostConfiguration);
} else if (needReconnectHost(ret)) {
afterDone.add(() -> {
String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s or agent version change, expected: %s but: %s] of kvmagent," +
"it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon",
self.getUuid(), ret.getHostUuid(), dbf.getDbVersion(), ret.getVersion());
logger.warn(info);
// when host is connecting, skip handling agent config changed issue
// and agent config change will be detected by next ping
self = dbf.reload(self);
if (self.getStatus() == HostStatus.Connecting) {
logger.debug("host status is %s, ignore version or host uuid changed issue");
return;
}
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
});
}
trigger.next();
} else {
trigger.fail(operr("%s", ret.getError()));
}
}
@Override
public Class<PingResponse> getReturnClass() {
return PingResponse.class;
}
},TimeUnit.SECONDS, HostGlobalConfig.PING_HOST_TIMEOUT.value(Long.class));
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-no-failure-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class);
if (exts.isEmpty()) {
trigger.next();
return;
}
AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
trigger.next();
}
});
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPingAgentNoFailureExtensionPoint ext : exts) {
ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) {
@Override
public void done() {
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class);
Iterator<KVMPingAgentExtensionPoint> it = exts.iterator();
callPlugin(it, trigger);
}
private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) {
if (!it.hasNext()) {
trigger.next();
return;
}
KVMPingAgentExtensionPoint ext = it.next();
logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass()));
ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) {
@Override
public void success() {
callPlugin(it, trigger);
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected void deleteTakeOverFlag(Completion completion) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
completion.success();
return;
}
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand(String.format("sudo /bin/sh -c \"rm -rf %s\"", hostTakeOverFlagPath));
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
completion.fail(operr(ret.getExitErrorMessage()));
return;
}
completion.success();
}
@Override
protected int getVmMigrateQuantity() {
return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class);
}
private ErrorCode connectToAgent() {
ErrorCode errCode = null;
try {
ConnectCmd cmd = new ConnectCmd();
cmd.setHostUuid(self.getUuid());
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES);
cmd.setIgnoreMsrs(KVMGlobalConfig.KVM_IGNORE_MSRS.value(Boolean.class));
cmd.setTcpServerPort(KVMGlobalProperty.TCP_SERVER_PORT);
cmd.setVersion(dbf.getDbVersion());
if (HostSystemTags.PAGE_TABLE_EXTENSION_DISABLED.hasTag(self.getUuid(), HostVO.class) || !KVMSystemTags.EPT_CPU_FLAG.hasTag(self.getUuid())) {
cmd.setPageTableExtensionDisabled(true);
}
ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class);
if (!rsp.isSuccess() || !rsp.isIptablesSucc()) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s",
self.getUuid(), self.getManagementIp(), connectPath, rsp.getError());
} else {
VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion());
VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion());
boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0
&& qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0;
String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN);
//liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class));
if (liveSnapshot) {
logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]",
hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion()));
recreateNonInherentTag(HostSystemTags.LIVE_SNAPSHOT);
} else {
HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid());
}
}
} catch (RestClientException e) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(),
connectPath, e.getMessage());
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
errCode = inerr(t.getMessage());
}
return errCode;
}
private KVMHostVO getSelf() {
return (KVMHostVO) self;
}
private void continueConnect(final ConnectHostInfo info, final Completion completion) {
ErrorCode errCode = connectToAgent();
if (errCode != null) {
throw new OperationFailureException(errCode);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid()));
chain.getData().put(KVMConstant.CONNECT_HOST_PRIMARYSTORAGE_ERROR, new ErrorCodeList());
chain.allowWatch();
for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) {
KVMHostConnectedContext ctx = new KVMHostConnectedContext();
ctx.setInventory((KVMHostInventory) getSelfInventory());
ctx.setNewAddedHost(info.isNewAdded());
ctx.setBaseUrl(baseUrl);
ctx.setSkipPackages(info.getSkipPackages());
chain.then(extp.createKvmHostConnectingFlow(ctx));
}
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
if (noStorageAccessible()) {
ErrorCodeList errorCodeList = (ErrorCodeList) data.get(KVMConstant.CONNECT_HOST_PRIMARYSTORAGE_ERROR);
completion.fail(operr("host can not access any primary storage, %s", errorCodeList != null && StringUtils.isNotEmpty(errorCodeList.getReadableDetails()) ? errorCodeList.getReadableDetails() : "please check network"));
} else {
if (CoreGlobalProperty.UNIT_TEST_ON) {
completion.success();
return;
}
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand(String.format("sudo /bin/sh -c \"echo uuid:%s > %s\"", self.getUuid(), hostTakeOverFlagPath));
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
completion.fail(operr(ret.getExitErrorMessage()));
return;
}
completion.success();
}
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(err(HostErrors.CONNECTION_ERROR, errCode, "connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(),
self.getManagementIp()));
}
}).start();
}
@Transactional(readOnly = true)
private boolean noStorageAccessible(){
// detach ps will delete PrimaryStorageClusterRefVO first.
List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class)
.select(PrimaryStorageClusterRefVO_.primaryStorageUuid)
.eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid())
.listValues();
long attachedPsCount = attachedPsUuids.size();
long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class)
.eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid())
.eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected)
.in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids)
.count();
return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0;
}
private void createHostVersionSystemTags(String distro, String release, String version) {
createTagWithoutNonValue(HostSystemTags.OS_DISTRIBUTION, HostSystemTags.OS_DISTRIBUTION_TOKEN, distro, true);
createTagWithoutNonValue(HostSystemTags.OS_RELEASE, HostSystemTags.OS_RELEASE_TOKEN, release, true);
createTagWithoutNonValue(HostSystemTags.OS_VERSION, HostSystemTags.OS_VERSION_TOKEN, version, true);
}
private void createTagWithoutNonValue(SystemTag tag, String token, String value, boolean inherent) {
if (value == null || value.isEmpty()) {
return;
}
recreateTag(tag, token, value, inherent);
}
private void recreateNonInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, false);
}
private void recreateNonInherentTag(SystemTag tag) {
recreateTag(tag, null, null, false);
}
private void recreateInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, true);
}
private void recreateTag(SystemTag tag, String token, String value, boolean inherent) {
SystemTagCreator creator = tag.newSystemTagCreator(self.getUuid());
Optional.ofNullable(token).ifPresent(it -> creator.setTagByTokens(Collections.singletonMap(token, value)));
creator.inherent = inherent;
creator.recreate = true;
creator.create();
}
@Override
public void connectHook(final ConnectHostInfo info, final Completion complete) {
if (!info.isNewAdded()) {
String skipPackages = KVMGlobalProperty.SKIP_PACKAGES + " " + StringUtils.trimToEmpty(info.getSkipPackages());
logger.info("connecting to KVM host and skipping these packages: " + skipPackages);
info.setSkipPackages(skipPackages);
}
if (CoreGlobalProperty.UNIT_TEST_ON) {
if (info.isNewAdded()) {
createHostVersionSystemTags("zstack", "kvmSimulator", tester.get(ZTester.KVM_HostVersion, "0.1", String.class));
if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, tester.get(ZTester.KVM_LibvirtVersion, "1.2.9", String.class), true);
}
if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, tester.get(ZTester.KVM_QemuImageVersion, "2.0.0", String.class), true);
}
if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, tester.get(ZTester.KVM_CpuModelName, "Broadwell", String.class), true);
}
if (null == KVMSystemTags.EPT_CPU_FLAG.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.EPT_CPU_FLAG_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, "ept", false);
}
if (null == self.getArchitecture()) {
ClusterVO cluster = dbf.findByUuid(self.getClusterUuid(), ClusterVO.class);
HostVO host = dbf.findByUuid(self.getUuid(), HostVO.class);
if (null == cluster.getArchitecture()){
host.setArchitecture(CpuArchitecture.x86_64.toString());
} else {
host.setArchitecture(cluster.getArchitecture());
}
dbf.update(host);
}
if (!checkQemuLibvirtVersionOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
complete.success();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
}
continueConnect(info, complete);
} else {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid()));
chain.allowWatch();
chain.then(new ShareFlow() {
boolean deployed = false;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "test-if-ssh-port-open";
@Override
public void run(FlowTrigger trigger, Map data) {
long sshTimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_OPEN_TIMEOUT.value(Long.class));
long timeout = System.currentTimeMillis() + sshTimeout;
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(trigger) {
@Override
public boolean run() {
if (testPort()) {
trigger.next();
return true;
}
return ifTimeout();
}
private boolean testPort() {
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is not ready yet", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private boolean ifTimeout() {
if (System.currentTimeMillis() > timeout) {
trigger.fail(operr("the host[%s] ssh port[%s] not open after %s seconds, connect timeout", getSelf().getManagementIp(), getSelf().getPort(), TimeUnit.MILLISECONDS.toSeconds(sshTimeout)));
return true;
} else {
return false;
}
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
if (info.isNewAdded()) {
if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) {
flow(new NoRollbackFlow() {
String __name__ = "ping-DNS-check-list";
@Override
public void run(FlowTrigger trigger, Map data) {
String checkList;
if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value();
} else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value();
} else {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value();
}
checkList = checkList.replaceAll(",", " ");
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh",
map(e("dnsCheckList", checkList)));
if (ret.isSshFailure()) {
trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList));
} else {
trigger.next();
}
}
});
}
}
flow(new NoRollbackFlow() {
String __name__ = "check-if-host-can-reach-management-node";
@Override
public void run(FlowTrigger trigger, Map data) {
ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp()));
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
sshShell.setWithSudo(false);
final String cmd = String.format("curl --connect-timeout 10 %s|| wget --spider -q --connect-timeout=10 %s|| test $? -eq 8", restf.getCallbackUrl(), restf.getCallbackUrl());
SshResult ret = sshShell.runCommand(cmd);
if (ret.getStderr() != null && ret.getStderr().contains("No route to host")) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
ret = sshShell.runCommand(cmd);
}
if (ret.isSshFailure()) {
throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," +
"please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" +
" that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), restf.getHostName(),
ret.getStderr(), ret.getExitErrorMessage()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-Host-is-taken-over";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!info.isNewAdded() || CoreGlobalProperty.UNIT_TEST_ON) {
trigger.next();
return;
}
try {
Ssh ssh = new Ssh().setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword()).setPort(getSelf().getPort())
.setHostname(getSelf().getManagementIp());
ssh.command(String.format("grep -i ^uuid %s | sed 's/uuid://g'", hostTakeOverFlagPath));
SshResult hostRet = ssh.run();
if (hostRet.isSshFailure() || hostRet.getReturnCode() != 0) {
trigger.fail(operr("unable to Check whether the host is taken over, because %s", hostRet.getExitErrorMessage()));
return;
}
String hostOutput = hostRet.getStdout().replaceAll("\r|\n","");
if (hostOutput.contains("No such file or directory")) {
trigger.next();
return;
}
ssh.command(String.format("date +%%s -r %s", hostTakeOverFlagPath));
SshResult timeRet = ssh.run();
if (timeRet.isSshFailure() || timeRet.getReturnCode() != 0) {
trigger.fail(operr("Unable to get the timestamp of the flag, because %s", timeRet.getExitErrorMessage()));
return;
}
String timestampOutput = timeRet.getStdout().replaceAll("\r|\n","");
long diff = (new Date().getTime() / 1000) - Long.parseLong(timestampOutput);
logger.debug(String.format("hostOutput is %s ,The time difference is %d(s) ", hostOutput, diff));
if (diff < HostGlobalConfig.PING_HOST_INTERVAL.value(int.class)) {
trigger.fail(operr("the host[ip:%s] has been taken over, because the takeover flag[HostUuid:%s] already exists and utime[%d] has not exceeded host ping interval[%d]",
self.getManagementIp(), hostOutput, diff, HostGlobalConfig.PING_HOST_INTERVAL.value(int.class)));
return;
}
HostVO lastHostInv = Q.New(HostVO.class).eq(HostVO_.uuid, hostOutput).find();
if (lastHostInv == null) {
trigger.next();
} else {
trigger.fail(operr("the host[ip:%s] has been taken over, because flag[HostUuid:%s] exists in the database",
self.getManagementIp(), lastHostInv.getUuid()));
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
trigger.next();
return;
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-host-cpu-arch";
@Override
public void run(FlowTrigger trigger, Map data) {
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand("uname -m");
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
trigger.fail(operr("unable to get host cpu architecture, please check if username/password is wrong; %s", ret.getExitErrorMessage()));
return;
}
String hostArchitecture = ret.getStdout().trim();
HostVO host = dbf.findByUuid(getSelf().getUuid(), HostVO.class);
host.setArchitecture(hostArchitecture);
dbf.update(host);
self.setArchitecture(hostArchitecture);
ClusterVO cluster = dbf.findByUuid(self.getClusterUuid(), ClusterVO.class);
if (cluster.getArchitecture() != null && !hostArchitecture.equals(cluster.getArchitecture()) && !cluster.getHypervisorType().equals("baremetal2")) {
trigger.fail(operr("host cpu architecture[%s] is not matched the cluster[%s]", hostArchitecture, cluster.getArchitecture()));
return;
}
// for upgrade case, prevent from add host failure.
if (cluster.getArchitecture() == null && !info.isNewAdded()) {
cluster.setArchitecture(hostArchitecture);
dbf.update(cluster);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "apply-ansible-playbook";
@Override
public void run(final FlowTrigger trigger, Map data) {
String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath();
String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName);
SshFileMd5Checker checker = new SshFileMd5Checker();
checker.setUsername(getSelf().getUsername());
checker.setPassword(getSelf().getPassword());
checker.setSshPort(getSelf().getPort());
checker.setTargetIp(getSelf().getManagementIp());
checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME));
checker.addSrcDestPair(srcPath, destPath);
SshChronyConfigChecker chronyChecker = new SshChronyConfigChecker();
chronyChecker.setTargetIp(getSelf().getManagementIp());
chronyChecker.setUsername(getSelf().getUsername());
chronyChecker.setPassword(getSelf().getPassword());
chronyChecker.setSshPort(getSelf().getPort());
SshYumRepoChecker repoChecker = new SshYumRepoChecker();
repoChecker.setTargetIp(getSelf().getManagementIp());
repoChecker.setUsername(getSelf().getUsername());
repoChecker.setPassword(getSelf().getPassword());
repoChecker.setSshPort(getSelf().getPort());
CallBackNetworkChecker callbackChecker = new CallBackNetworkChecker();
callbackChecker.setTargetIp(getSelf().getManagementIp());
callbackChecker.setUsername(getSelf().getUsername());
callbackChecker.setPassword(getSelf().getPassword());
callbackChecker.setPort(getSelf().getPort());
callbackChecker.setCallbackIp(Platform.getManagementServerIp());
callbackChecker.setCallBackPort(CloudBusGlobalProperty.HTTP_PORT);
AnsibleRunner runner = new AnsibleRunner();
runner.installChecker(checker);
runner.installChecker(chronyChecker);
runner.installChecker(repoChecker);
runner.installChecker(callbackChecker);
if (KVMGlobalConfig.ENABLE_HOST_TCP_CONNECTION_CHECK.value(Boolean.class)) {
CallBackNetworkChecker hostTcpConnectionCallbackChecker = new CallBackNetworkChecker();
hostTcpConnectionCallbackChecker.setTargetIp(getSelf().getManagementIp());
hostTcpConnectionCallbackChecker.setUsername(getSelf().getUsername());
hostTcpConnectionCallbackChecker.setPassword(getSelf().getPassword());
hostTcpConnectionCallbackChecker.setPort(getSelf().getPort());
hostTcpConnectionCallbackChecker.setCallbackIp(Platform.getManagementServerIp());
hostTcpConnectionCallbackChecker.setCallBackPort(KVMGlobalProperty.TCP_SERVER_PORT);
runner.installChecker(hostTcpConnectionCallbackChecker);
}
for (KVMHostAddSshFileMd5CheckerExtensionPoint exp : pluginRgty.getExtensionList(KVMHostAddSshFileMd5CheckerExtensionPoint.class)) {
SshFileMd5Checker sshFileMd5Checker = exp.getSshFileMd5Checker(getSelf());
if (sshFileMd5Checker != null) {
runner.installChecker(sshFileMd5Checker);
}
}
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME);
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
if (info.isNewAdded()) {
runner.putArgument("init", "true");
runner.setFullDeploy(true);
}
if (NetworkGlobalProperty.SKIP_IPV6) {
runner.putArgument("skipIpv6", "true");
}
for (CheckMiniExtensionPoint ext : pluginRegistry.getExtensionList(CheckMiniExtensionPoint.class)) {
if (ext.isMini()) {
runner.putArgument("isMini", "true");
}
}
if ("baremetal2".equals(self.getHypervisorType())) {
runner.putArgument("isBareMetal2Gateway", "true");
}
if (NetworkGlobalProperty.BRIDGE_DISABLE_IPTABLES) {
runner.putArgument("bridgeDisableIptables", "true");
}
runner.putArgument("pkg_kvmagent", agentPackageName);
runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-")));
if (CoreGlobalProperty.SYNC_NODE_TIME) {
if (CoreGlobalProperty.CHRONY_SERVERS == null || CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) {
trigger.fail(operr("chrony server not configured!"));
return;
}
runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS));
}
runner.putArgument("skip_packages", info.getSkipPackages());
runner.putArgument("update_packages", String.valueOf(CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT));
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString());
String postUrl = ub.build().toString();
runner.putArgument("post_url", postUrl);
runner.run(new ReturnValueCompletion<Boolean>(trigger) {
@Override
public void success(Boolean run) {
if (run != null) {
deployed = run;
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "configure-iptables";
@Override
public void run(FlowTrigger trigger, Map data) {
StringBuilder builder = new StringBuilder();
if (!KVMGlobalProperty.MN_NETWORKS.isEmpty()) {
builder.append(String.format("sudo bash %s -m %s -p %s -c %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class),
String.join(",", KVMGlobalProperty.MN_NETWORKS)));
} else {
builder.append(String.format("sudo bash %s -m %s -p %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class)));
}
try {
new Ssh().shell(builder.toString())
.setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword())
.setHostname(getSelf().getManagementIp())
.setPort(getSelf().getPort()).runErrorByExceptionAndClose();
} catch (SshException ex) {
throw new OperationFailureException(operr(ex.toString()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "echo-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
boolean needRestart = KVMGlobalConfig.RESTART_AGENT_IF_FAKE_DEAD.value(Boolean.class);
if (!deployed && needRestart) {
// if not deployed and echo failed, we thought it is fake dead, see: ZSTACK-18628
AnsibleRunner runner = new AnsibleRunner();
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
runner.restartAgent(AnsibleConstant.KVM_AGENT_NAME, new Completion(trigger) {
@Override
public void success() {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
} else {
trigger.fail(errorCode);
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-kvmagent-dependencies";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT) {
trigger.next();
return;
}
// new added need to update dependency if experimental repo enabled
if (info.isNewAdded() && !rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_REPO, self.getClusterUuid(), Boolean.class)) {
trigger.next();
return;
}
UpdateDependencyCmd cmd = new UpdateDependencyCmd();
cmd.hostUuid = self.getUuid();
cmd.zstackRepo = AnsibleGlobalProperty.ZSTACK_REPO;
if (info.isNewAdded()) {
cmd.enableExpRepo = true;
cmd.updatePackages = rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_UPDATE_DEPENDENCY, self.getClusterUuid(), String.class);
cmd.excludePackages = rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_EXCLUDE_DEPENDENCY, self.getClusterUuid(), String.class);
}
new Http<>(updateDependencyPath, cmd, UpdateDependencyRsp.class)
.call(new ReturnValueCompletion<UpdateDependencyRsp>(trigger) {
@Override
public void success(UpdateDependencyRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "collect-kvm-host-facts";
@Override
public void run(final FlowTrigger trigger, Map data) {
HostFactCmd cmd = new HostFactCmd();
new Http<>(hostFactPath, cmd, HostFactResponse.class)
.call(new ReturnValueCompletion<HostFactResponse>(trigger) {
@Override
public void success(HostFactResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
if (ret.getHvmCpuFlag() == null) {
trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting"));
return;
}
// create system tags of os::version etc
createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion());
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion(), false);
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion(), false);
createTagWithoutNonValue(KVMSystemTags.HVM_CPU_FLAG, KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag(), false);
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, ret.getEptFlag(), false);
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName(), false);
createTagWithoutNonValue(HostSystemTags.HOST_CPU_MODEL_NAME, HostSystemTags.HOST_CPU_MODEL_NAME_TOKEN, ret.getHostCpuModelName(), true);
createTagWithoutNonValue(HostSystemTags.CPU_GHZ, HostSystemTags.CPU_GHZ_TOKEN, ret.getCpuGHz(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_PRODUCT_NAME, HostSystemTags.SYSTEM_PRODUCT_NAME_TOKEN, ret.getSystemProductName(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_SERIAL_NUMBER, HostSystemTags.SYSTEM_SERIAL_NUMBER_TOKEN, ret.getSystemSerialNumber(), true);
if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) {
recreateNonInherentTag(KVMSystemTags.VIRTIO_SCSI);
}
List<String> ips = ret.getIpAddresses();
if (ips != null) {
ips.remove(self.getManagementIp());
if (CoreGlobalProperty.MN_VIP != null) {
ips.remove(CoreGlobalProperty.MN_VIP);
}
if (!ips.isEmpty()) {
recreateNonInherentTag(HostSystemTags.EXTRA_IPS, HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ","));
} else {
HostSystemTags.EXTRA_IPS.delete(self.getUuid());
}
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
if (info.isNewAdded()) {
flow(new NoRollbackFlow() {
String __name__ = "check-qemu-libvirt-version";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!checkQemuLibvirtVersionOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
}
});
}
flow(new NoRollbackFlow() {
String __name__ = "prepare-host-env";
@Override
public void run(FlowTrigger trigger, Map data) {
String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true";
runShell(script);
trigger.next();
}
});
error(new FlowErrorHandler(complete) {
@Override
public void handle(ErrorCode errCode, Map data) {
complete.fail(errCode);
}
});
done(new FlowDoneHandler(complete) {
@Override
public void handle(Map data) {
continueConnect(info, complete);
}
});
}
}).start();
}
}
private void handle(final ShutdownHostMsg msg) {
inQueue().name(String.format("shut-down-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> handleShutdownHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handleShutdownHost(final ShutdownHostMsg msg, final NoErrorCompletion completion) {
ShutdownHostReply reply = new ShutdownHostReply();
KVMAgentCommands.ShutdownHostCmd cmd = new KVMAgentCommands.ShutdownHostCmd();
new Http<>(shutdownHost, cmd, ShutdownHostResponse.class).call(new ReturnValueCompletion<ShutdownHostResponse>(msg, completion) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
@Override
public void success(KVMAgentCommands.ShutdownHostResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
bus.reply(msg, reply);
completion.done();
return;
}
changeConnectionState(HostStatusEvent.disconnected);
if (msg.isReturnEarly()) {
bus.reply(msg, reply);
completion.done();
} else {
waitForHostShutdown(reply, completion);
}
}
private boolean testPort() {
if (CoreGlobalProperty.UNIT_TEST_ON) {
return false;
}
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is no longer open, " +
"seem to be shutdowned", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private void waitForHostShutdown(ShutdownHostReply reply, NoErrorCompletion noErrorCompletion) {
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(msg, noErrorCompletion) {
@Override
public boolean run() {
if (testPort()) {
return false;
}
bus.reply(msg, reply);
noErrorCompletion.done();
return true;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
}
private void handle(final CancelHostTaskMsg msg) {
CancelHostTaskReply reply = new CancelHostTaskReply();
cancelJob(msg.getCancellationApiId(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void cancelJob(String apiId, Completion completion) {
CancelCmd cmd = new CancelCmd();
cmd.setCancellationApiId(apiId);
new Http<>(cancelJob, cmd, CancelRsp.class).call(new ReturnValueCompletion<CancelRsp>(completion) {
@Override
public void success(CancelRsp ret) {
if (ret.isSuccess()) {
completion.success();
} else {
completion.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
}
private void handle(CheckFileOnHostMsg msg) {
CheckFileOnHostReply reply = new CheckFileOnHostReply();
inQueue().name(String.format("check-file-on-host-%s", msg.getHostUuid())).asyncBackup(msg).run(chain -> {
CheckFileOnHostCmd cmd = new CheckFileOnHostCmd();
cmd.paths = new HashSet<>(msg.getPaths());
cmd.md5Return = msg.isMd5Return();
new Http<>(hostCheckFilePath, cmd, CheckFileOnHostResponse.class).call(new ReturnValueCompletion<CheckFileOnHostResponse>(chain, msg) {
@Override
public void success(CheckFileOnHostResponse response) {
if (response.isSuccess()) {
reply.setExistPaths(response.existPaths == null ? Collections.emptyMap() : new HashMap<>(response.existPaths));
} else {
logger.warn(String.format("failed to check file %s on host[uuid:%s]", msg.getPaths(), msg.getHostUuid()));
reply.setError(Platform.operr(response.getError(),
"fail to check file %s on host[uuid:%s]", msg.getPaths(), msg.getHostUuid()));
}
bus.reply(msg, reply);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
chain.next();
}
});
});
}
private boolean checkCpuModelOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster);
if (cpuModelNames != null && cpuModelNames.size() != 0) {
String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag(
cpuModelNames.values().iterator().next().get(0),
KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) {
return false;
}
}
return true;
}
@Override
protected void updateOsHook(UpdateHostOSMsg msg, Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
self = dbf.reload(self);
chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
// is the host in maintenance already?
final HostState oldState = self.getState();
final boolean maintenance = oldState == HostState.Maintenance;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "double-check-host-state-status";
@Override
public void run(FlowTrigger trigger, Map data) {
if (self.getState() == HostState.PreMaintenance) {
trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os"));
} else if (self.getStatus() != HostStatus.Connected) {
trigger.fail(Platform.operr("host is not in the connected status, cannot update os"));
} else {
trigger.next();
}
}
});
flow(new Flow() {
String __name__ = "make-host-in-maintenance";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// enter maintenance, but donot stop/migrate vm on the host
ChangeHostStateMsg cmsg = new ChangeHostStateMsg();
cmsg.setUuid(self.getUuid());
cmsg.setStateEvent(HostStateEvent.preMaintain.toString());
bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (maintenance) {
trigger.rollback();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-host-os";
@Override
public void run(FlowTrigger trigger, Map data) {
UpdateHostOSCmd cmd = new UpdateHostOSCmd();
cmd.hostUuid = self.getUuid();
cmd.excludePackages = msg.getExcludePackages();
cmd.updatePackages = msg.getUpdatePackages();
cmd.releaseVersion = msg.getReleaseVersion();
cmd.enableExpRepo = msg.isEnableExperimentalRepo();
new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class)
.call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) {
@Override
public void success(UpdateHostOSRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "recover-host-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "auto-reconnect-host";
@Override
public void run(FlowTrigger trigger, Map data) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info("successfully reconnected host " + self.getUuid());
} else {
logger.error("failed to reconnect host " + self.getUuid());
}
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid()));
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s",
self.getUuid(), errCode.getDetails()));
completion.fail(errCode);
}
});
}
}).start();
}
private boolean checkMigrateNetworkCidrOfHost(String cidr) {
if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) {
return true;
}
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid()));
return false;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return true;
}
}
return false;
}
private boolean checkQemuLibvirtVersionOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster);
if (qemuVersions != null && qemuVersions.size() != 0) {
String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(
qemuVersions.values().iterator().next().get(0),
KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) {
return false;
}
}
Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster);
if (libvirtVersions != null && libvirtVersions.size() != 0) {
String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag(
libvirtVersions.values().iterator().next().get(0),
KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) {
return false;
}
}
return true;
}
@Override
protected int getHostSyncLevel() {
return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class);
}
@Override
protected HostVO updateHost(APIUpdateHostMsg msg) {
if (!(msg instanceof APIUpdateKVMHostMsg)) {
return super.updateHost(msg);
}
KVMHostVO vo = (KVMHostVO) super.updateHost(msg);
vo = vo == null ? getSelf() : vo;
APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg;
if (umsg.getUsername() != null) {
vo.setUsername(umsg.getUsername());
}
if (umsg.getPassword() != null) {
vo.setPassword(umsg.getPassword());
}
if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) {
vo.setPort(umsg.getSshPort());
}
return vo;
}
@Override
protected void scanVmPorts(ScanVmPortMsg msg) {
ScanVmPortReply reply = new ScanVmPortReply();
reply.setSupportScan(true);
checkStatus();
ScanVmPortCmd cmd = new ScanVmPortCmd();
cmd.setIp(msg.getIp());
cmd.setBrname(msg.getBrName());
cmd.setPort(msg.getPort());
new Http<>(scanVmPortPath, cmd, ScanVmPortResponse.class).call(new ReturnValueCompletion<ScanVmPortResponse>(msg) {
@Override
public void success(ScanVmPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setStatus(ret.getPortStatus());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
} |
package io.spark.ddf.ml;
import io.ddf.DDF;
import io.ddf.content.IHandleRepresentations.IGetResult;
import io.ddf.content.IHandleSchema;
import io.ddf.content.Schema;
import io.ddf.exception.DDFException;
import io.ddf.ml.IModel;
import io.ddf.types.TupleMatrixVector;
import io.ddf.util.Utils.MethodInfo.ParamInfo;
import io.spark.ddf.SparkDDF;
import io.spark.ddf.analytics.CrossValidation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.recommendation.Rating;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.rdd.RDD;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class MLSupporter extends io.ddf.ml.MLSupporter implements Serializable {
public MLSupporter(DDF theDDF) {
super(theDDF);
}
/**
* Override this to return the approriate DDF representation matching that specified in {@link ParamInfo}. The base
* implementation simply returns the DDF.
*
* @param paramInfo
* @return
*/
@SuppressWarnings("unchecked")
@Override
protected Object convertDDF(ParamInfo paramInfo) throws DDFException {
mLog.info(">>>> Running ConvertDDF of io.spark.ddf.ml.MLSupporter");
if (paramInfo.argMatches(RDD.class)) {
// Yay, our target data format is an RDD!
RDD<?> rdd = null;
if (paramInfo.paramMatches(LabeledPoint.class)) {
rdd = (RDD<LabeledPoint>) this.getDDF().getRepresentationHandler().get(RDD.class, LabeledPoint.class);
} else if (paramInfo.paramMatches(Vector.class)) {
rdd = (RDD<Vector>) this.getDDF().getRepresentationHandler().get(RDD.class, Vector.class);
} else if (paramInfo.paramMatches(double[].class)) {
rdd = (RDD<double[]>) this.getDDF().getRepresentationHandler().get(RDD.class, double[].class);
} else if (paramInfo.paramMatches(io.ddf.types.Vector.class)) {
rdd = (RDD<io.ddf.types.Vector>) this.getDDF().getRepresentationHandler()
.get(RDD.class, io.ddf.types.Vector.class);
} else if (paramInfo.paramMatches(TupleMatrixVector.class)) {
rdd = (RDD<TupleMatrixVector>) this.getDDF().getRepresentationHandler().get(RDD.class, TupleMatrixVector.class);
} else if (paramInfo.paramMatches(Rating.class)) {
rdd = (RDD<Rating>) this.getDDF().getRepresentationHandler().get(RDD.class, Rating.class);
}
// else if (paramInfo.paramMatches(TablePartition.class)) {
// rdd = (RDD<TablePartition>) this.getDDF().getRepresentationHandler().get(RDD.class, TablePartition.class);
else if (paramInfo.paramMatches(Object.class)) {
rdd = (RDD<Object[]>) this.getDDF().getRepresentationHandler().get(RDD.class, Object[].class);
}
return rdd;
} else {
return super.convertDDF(paramInfo);
}
}
@Override
public DDF applyModel(IModel model) throws DDFException {
return this.applyModel(model, false, false);
}
@Override
public DDF applyModel(IModel model, boolean hasLabels) throws DDFException {
return this.applyModel(model, hasLabels, false);
}
@SuppressWarnings("unchecked")
@Override
public DDF applyModel(IModel model, boolean hasLabels, boolean includeFeatures) throws DDFException {
SparkDDF ddf = (SparkDDF) this.getDDF();
IGetResult gr = ddf.getJavaRDD(double[].class, Vector.class, LabeledPoint.class, Object[].class);
// Apply appropriate mapper
JavaRDD<?> result = null;
Class<?> resultUnitType = double[].class;
if (LabeledPoint.class.equals(gr.getTypeSpecs()[0])) {
mLog.info(">>> applyModel, inputClass= LabeledPoint");
result = ((JavaRDD<LabeledPoint>) gr.getObject()).mapPartitions(new PredictMapper<LabeledPoint, double[]>(
LabeledPoint.class, double[].class, model, hasLabels, includeFeatures));
} else if (double[].class.equals(gr.getTypeSpecs()[0])) {
mLog.info(">>> applyModel, inputClass= double[]");
result = ((JavaRDD<double[]>) gr.getObject()).mapPartitions(new PredictMapper<double[], double[]>(double[].class,
double[].class, model, hasLabels, includeFeatures));
} else if (Vector.class.equals(gr.getTypeSpecs()[0])) {
mLog.info(">>> applyModel, inputClass= Vector");
result = ((JavaRDD<Vector>) gr.getObject()).mapPartitions(new PredictMapper<Vector, double[]>(Vector.class,
double[].class, model, hasLabels, includeFeatures));
} else if (Object[].class.equals(gr.getTypeSpecs()[0])) {
result = ((JavaRDD<Object[]>) gr.getObject()).mapPartitions(new PredictMapper<Object[], Object[]>(Object[].class,
Object[].class, model, hasLabels, includeFeatures));
resultUnitType = Object[].class;
} else {
throw new DDFException(String.format("Error apply model %s", model.getRawModel().getClass().getName()));
}
// Build schema
List<Schema.Column> outputColumns = new ArrayList<Schema.Column>();
if (includeFeatures) {
outputColumns = ddf.getSchema().getColumns();
// set columns features of result ddf to Double type
for (Schema.Column col : outputColumns) {
col.setType(Schema.ColumnType.DOUBLE);
}
} else if (!includeFeatures && hasLabels) {
outputColumns.add(new Schema.Column("ytrue", "double"));
}
outputColumns.add(new Schema.Column("yPredict", "double"));
Schema schema = new Schema(null, outputColumns);
if (double[].class.equals(resultUnitType)) {
DDF resultDDF = this.getManager()
.newDDF(this.getManager(), result.rdd(), new Class<?>[] { RDD.class, double[].class },
this.getManager().getNamespace(), null, schema);
IHandleSchema schemaHandler = resultDDF.getSchemaHandler();
resultDDF.getSchema().setTableName(schemaHandler.newTableName());
this.getManager().addDDF(resultDDF);
return resultDDF;
} else if (Object[].class.equals(resultUnitType)) {
DDF resultDDF = this.getManager()
.newDDF(this.getManager(), result.rdd(), new Class<?>[] { RDD.class, Object[].class },
this.getManager().getNamespace(), null, schema);
IHandleSchema schemaHandler = resultDDF.getSchemaHandler();
resultDDF.getSchema().setTableName(schemaHandler.newTableName());
this.getManager().addDDF(resultDDF);
return resultDDF;
} else return null;
}
private static class PredictMapper<I, O> implements FlatMapFunction<Iterator<I>, O> {
private static final long serialVersionUID = 1L;
private IModel mModel;
private boolean mHasLabels;
private boolean mIncludeFeatures;
private Class<?> mInputType;
private Class<?> mOutputType;
public PredictMapper(Class<I> inputType, Class<O> outputType, IModel model, boolean hasLabels,
boolean includeFeatures) throws DDFException {
mInputType = inputType;
mOutputType = outputType;
mModel = model;
mHasLabels = hasLabels;
mIncludeFeatures = includeFeatures;
}
@SuppressWarnings("unchecked")
@Override
public Iterable<O> call(Iterator<I> samples) throws DDFException {
List<O> results = new ArrayList<O>();
while (samples.hasNext()) {
I sample = samples.next();
O outputRow = null;
try {
if (sample instanceof LabeledPoint || sample instanceof double[]) {
double label = 0;
double[] features;
if (sample instanceof LabeledPoint) {
LabeledPoint s = (LabeledPoint) sample;
label = s.label();
features = s.features().toArray();
} else if(sample instanceof Vector) {
Vector vector = (Vector) sample;
if(mHasLabels) {
label = vector.apply(vector.size() - 1);
features = Arrays.copyOf(vector.toArray(), vector.size() - 1);
} else {
features = vector.toArray();
}
} else {
double[] s = (double[]) sample;
if (mHasLabels) {
label = s[s.length - 1];
features = Arrays.copyOf(s, s.length - 1);
} else {
features = s;
}
}
if (double[].class.equals(mOutputType)) {
if (mHasLabels) {
outputRow = (O) new double[] { label, (Double) this.mModel.predict(features) };
} else {
outputRow = (O) new double[] { (Double) this.mModel.predict(features) };
}
if (mIncludeFeatures) {
outputRow = (O) ArrayUtils.addAll(features, (double[]) outputRow);
}
} else if (Object[].class.equals(mOutputType)) {
if (mHasLabels) {
outputRow = (O) new Object[] { label, this.mModel.predict(features) };
} else {
outputRow = (O) new Object[] { this.mModel.predict(features) };
}
if (mIncludeFeatures) {
Object[] oFeatures = new Object[features.length];
for (int i = 0; i < features.length; i++) {
oFeatures[i] = (Object) features[i];
}
outputRow = (O) ArrayUtils.addAll(oFeatures, (Object[]) outputRow);
}
} else {
throw new DDFException(String.format("Unsupported output type %s", mOutputType));
}
} else if (sample instanceof Object[]) {
Object label = null;
Object[] features;
Object[] s = (Object[]) sample;
if (mHasLabels) {
label = s[s.length - 1];
features = Arrays.copyOf(s, s.length - 1);
} else {
features = s;
}
double[] dFeatures = new double[features.length];
for (int i = 0; i < features.length; i++) {
dFeatures[i] = (Double) features[i];
}
if (mHasLabels) {
outputRow = (O) new Object[] { label, this.mModel.predict(dFeatures) };
} else {
outputRow = (O) new Object[] { this.mModel.predict(dFeatures) };
}
if (mIncludeFeatures) {
outputRow = (O) ArrayUtils.addAll(features, (Object[]) outputRow);
}
} else {
throw new DDFException(String.format("Unsupported input type %s", mInputType));
}
results.add(outputRow);
} catch (Exception e) {
throw new DDFException(String.format("Error predicting with model %s", this.mModel.getRawModel().getClass()
.getName()), e);
}
}
return results;
}
}
@Override
public long[][] getConfusionMatrix(IModel model, double threshold) throws DDFException {
SparkDDF ddf = (SparkDDF) this.getDDF();
SparkDDF predictions = (SparkDDF) ddf.ML.applyModel(model, true, false);
// Now get the underlying RDD to compute
JavaRDD<double[]> yTrueYPred = (JavaRDD<double[]>) predictions.getJavaRDD(double[].class);
final double threshold1 = threshold;
long[] cm = yTrueYPred.map(new Function<double[], long[]>() {
@Override
public long[] call(double[] params) {
byte isPos = toByte(params[0] > threshold1);
byte predPos = toByte(params[1] > threshold1);
long[] result = new long[] { 0L, 0L, 0L, 0L };
result[isPos << 1 | predPos] = 1L;
return result;
}
}).reduce(new Function2<long[], long[], long[]>() {
@Override
public long[] call(long[] a, long[] b) {
return new long[] { a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3] };
}
});
return new long[][] { new long[] { cm[3], cm[2] }, new long[] { cm[1], cm[0] } };
}
private byte toByte(boolean exp) {
if (exp) return 1;
else return 0;
}
public List<List<DDF>> CVKFold(int k, Long seed) throws DDFException {
return CrossValidation.DDFKFoldSplit(this.getDDF(), k, seed);
}
public List<List<DDF>> CVRandom(int k, double trainingSize, Long seed) throws DDFException {
return CrossValidation.DDFRandomSplit(this.getDDF(), k, trainingSize, seed);
}
} |
package de.charite.zpgen;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ZFINWalker {
/**
* The current file format for pheno.txt as of: 8 Sep 2013<br>
* 0 Gene ID<br>
* 1 Entrez Zebrafish Gene ID<br>
* 2 Entrez Human Gene ID<br>
* 3 ZFIN Gene Symbol<br>
* 4 Affected Structure or Process 1 subterm OBO ID<br>
* 5 Affected Structure or Process 1 subterm name<br>
* 6 Post-Composed Relationship ID<br>
* 7 Post-Composed Relationship Name<br>
* 8 Affected Structure or Process 1 superterm OBO ID<br>
* 9 Affected Structure or Process 1 superterm name<br>
* 10 Phenotype Keyword OBO ID<br>
* 11 Phenotype Quality<br>
* 12 Phenotype Tag<br>
* 13 Affected Structure or Process 2 subterm OBO ID<br>
* 14 Affected Structure or Process 2 subterm name<br>
* 15 Post-Composed Relationship ID<br>
* 16 Post-Composed Relationship Name<br>
* 17 Affected Structure or Process 2 superterm OBO ID<br>
* 18 Affected Structure or Process 2 superterm name<br>
*/
/**
* The current file format for phenotype.txt as of: 2015<br>
* 0 Genotype ID <br>
* 1 Genotype Name <br>
* 2 Start Stage ID <br>
* 3 Start Stage Name<br>
* 4 End Stage ID<br>
* 5 End Stage Name <br>
* 6 Affected Structure or Process 1 subterm ID <br>
* 7 Affected Structure or Process 1 subterm Name <br>
* 8 Post-composed Relationship ID <br>
* 9 Post-composed Relationship Name <br>
* 10 Affected Structure or Process 1 superterm ID <br>
* 11 Affected Structure or Process 1 superterm Name <br>
* 12 Phenotype Keyword ID <br>
* 13 Phenotype Keyword Name <br>
* 14 Phenotype Tag <br>
* 15 Affected Structure or Process 2 subterm ID <br>
* 16 Affected Structure or Process 2 subterm name <br>
* 17 Post-composed Relationship (rel) ID <br>
* 18 Post-composed Relationship (rel) Name <br>
* 19 Affected Structure or Process 2 superterm ID <br>
* 20 Affected Structure or Process 2 superterm name <br>
* 21 Publication ID <br>
* 22 Environment ID<br>
*/
private ZFINWalker() {
};
static int COLUMN_ZFIN_GENE_ID = 0;
static int COLUMN_TERM1_SUBTERM_ID = 4;
static int COLUMN_TERM1_SUBTERM_NAME = 5;
static int COLUMN_TERM1_SUPERTERM_ID = 8;
static int COLUMN_TERM1_SUPERTERM_NAME = 9;
static int COLUMN_TERM2_SUBTERM_ID = 13;
static int COLUMN_TERM2_SUBTERM_NAME = 14;
static int COLUMN_TERM2_SUPERTERM_ID = 17;
static int COLUMN_TERM2_SUPERTERM_NAME = 18;
static int COLUMN_PATO_ID = 10;
static int COLUMN_PATO_NAME = 11;
static int COLUMN_PATO_MODIFIER = 12;
static public void walk(InputStream input, ZFINVisitor visitor) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = in.readLine()) != null) {
try {
ZFINEntry entry = new ZFINEntry();
String[] sp = null;
if (line.contains("|"))
sp = line.split("\\|", -1);
else
sp = line.split("\t", -1);
entry.geneZfinID = sp[COLUMN_ZFIN_GENE_ID];
entry.entity1SupertermId = sp[COLUMN_TERM1_SUPERTERM_ID];
entry.entity1SupertermName = sp[COLUMN_TERM1_SUPERTERM_NAME];
entry.entity1SubtermId = sp[COLUMN_TERM1_SUBTERM_ID];
entry.entity1SubtermName = sp[COLUMN_TERM1_SUBTERM_NAME];
entry.entity2SupertermId = sp[COLUMN_TERM2_SUPERTERM_ID];
entry.entity2SupertermName = sp[COLUMN_TERM2_SUPERTERM_NAME];
entry.entity2SubtermId = sp[COLUMN_TERM2_SUBTERM_ID];
entry.entity2SubtermName = sp[COLUMN_TERM2_SUBTERM_NAME];
entry.patoID = sp[COLUMN_PATO_ID];
entry.patoName = sp[COLUMN_PATO_NAME];
entry.isAbnormal = sp[COLUMN_PATO_MODIFIER].equalsIgnoreCase("abnormal");
visitor.visit(entry);
} catch (Exception e) {
System.out.println("Problem in line: " + line);
e.printStackTrace();
System.exit(1);
}
}
}
} |
package bramble.node.controller;
import java.util.ArrayList;
import java.util.Collection;
import bramble.configuration.BrambleConfiguration;
import bramble.networking.Handshake;
public class SlaveNodeList {
private Collection<SlaveNodeInformation> slaveNodes;
/**
* Constructor, initializes an empty slave node list.
*/
public SlaveNodeList(){
this.slaveNodes = new ArrayList<SlaveNodeInformation>();
}
/**
* Gets the amount of free job slots across all nodes.
* @return the total number of free job slots
*/
public synchronized Integer getFreeJobSlots(){
Integer result = 0;
for(SlaveNodeInformation targetNode : slaveNodes){
result += targetNode.getFreeJobSlots();
}
return result;
}
/**
* Gets a suitable target node to send data to.
* @return a target node with free capacity
*/
public synchronized SlaveNodeInformation getTargetNode() {
int freeThreads = 0;
SlaveNodeInformation output = null;
for(SlaveNodeInformation targetNode : slaveNodes){
if(targetNode.getFreeJobSlots() > freeThreads){
freeThreads = targetNode.getFreeJobSlots();
output = targetNode;
}
}
if(output == null){
throw new RuntimeException("Had a job slot available but couldn't find it.");
}
return output;
}
/**
* Call when a job has been completed to remove it from the list of active jobs.
* @param jobIdentifier the job identifier which has been completed
*/
public void jobCompleted(final Integer jobIdentifier){
for(SlaveNodeInformation targetNode : slaveNodes){
if(targetNode.getJobs().contains(jobIdentifier)){
targetNode.removeJob(jobIdentifier);
return;
}
}
}
/**
* Adds a slave node to the list.
* @param slaveNode the slave node to add
*/
public synchronized void registerSlaveNode(SlaveNodeInformation slaveNode) {
slaveNode.setTimeOfLastHandshake();
slaveNodes.add(slaveNode);
}
/**
* Adds a slave node to the list by handshake.
*
* <p>If it already exists, this method will refresh it's time of last handshake
* and diagnostic information.
* If it does not exist, it will be added to the list</p>
*
* @param handshake the handshake
*/
public void registerSlaveNodeHandshake(Handshake handshake) {
String senderIpAddress = handshake.getSenderIpAddress();
for(SlaveNodeInformation slaveNode : slaveNodes){
if(slaveNode.getIpAddress().equals(senderIpAddress)){
slaveNode.setTimeOfLastHandshake();
slaveNode.setDiagnosticInfo(handshake.getDiagnostics());
return;
}
}
SlaveNodeInformation slaveNode = new SlaveNodeInformation(senderIpAddress,
BrambleConfiguration.THREADS_PER_NODE, handshake.getDiagnostics());
registerSlaveNode(slaveNode);
}
/**
* Gets all the nodes which have timed out.
* @return all the nodes which have timed out
*/
public Collection<SlaveNodeInformation> timedOutNodes(){
Collection<SlaveNodeInformation> deadNodes = new ArrayList<>();
for(SlaveNodeInformation slaveNode : slaveNodes){
if(slaveNode.millisecondsSinceLastHandshake()
> BrambleConfiguration.NODE_TIMEOUT_MS){
deadNodes.add(slaveNode);
}
}
return deadNodes;
}
/**
* Removes a slave node from the list.
* @param node the slave node to remove
*/
public synchronized void removeNode(final SlaveNodeInformation node){
slaveNodes.remove(node);
}
/**
* Gets all the slave nodes in this list.
* @return all the slave nodes in this list
*/
public Collection<SlaveNodeInformation> getSlaveNodes() {
return slaveNodes;
}
} |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import models.Button;
import models.ButtonDB;
import models.CommentDB;
import models.IndexContent;
import models.IndexContentDB;
import models.PermeablePaversDB;
import models.Plant;
import models.PlantDB;
import models.RainBarrelDB;
import models.RainGarden;
import models.RainGardenDB;
import models.Resource;
import models.ResourceDB;
import play.Application;
import play.GlobalSettings;
import models.UserInfoDB;
import views.formdata.CommentFormData;
import views.formdata.PermeablePaversFormData;
import views.formdata.RainBarrelFormData;
import views.formdata.RainGardenFormData;
/**
* Implements a Global object for the Play Framework.
*
* @author eduardgamiao
*
*/
public class Global extends GlobalSettings {
private static final int EXPECTED_PLANT_FILE_LENGTH = 5;
private static final int THREE = 3;
private static final int FOUR = 4;
/**
* Initialization method for this Play Framework web application.
*
* @param app A Play Framework application.
*/
public void onStart(Application app) {
// Populate plant database.
populatePlantDB();
populateIndexContentDB();
//Add phoney users
UserInfoDB.addUserInfo("John", "Smith", "johnsmith@gmail.com", "1234567", "pw");
UserInfoDB.addUserInfo("Jane", "Smith", "janesmith@gmail.com", "1234567", "pw");
// Add rain garden.
List<String> plants = new ArrayList<String>();
plants.add("‘Ahu‘awa");
plants.add("‘Ākulikuli");
plants.add("‘Ilie‘e");
RainGarden garden = RainGardenDB.addRainGarden(new RainGardenFormData(0, "John's Rain Garden", "Residential",
"564 Ulahala St.",
"No", "My rain garden works and you should get one!", "4", "5", "2014", plants, "25", "200",
"Water flows from roof into garden.", "0.75", "2"), UserInfoDB.getUser("johnsmith@gmail.com"));
CommentDB.addComment(new CommentFormData("This garden looks amazing!"), UserInfoDB.getUser("johnsmith@gmail.com"),
garden.getKey());
// Add rain barrel.
RainBarrelDB.addRainBarrel(new RainBarrelFormData(0, "John's Rain Barrel", "Residential", "564 Ulahala St.",
"No", "My rain garden works and you should get one!", "4", "5", "2014", "Old Drum", "50", "Orange-Red",
"Plastic", "25.00", "Gardening", "Once a year.", "Open", "Home Depot", "Self-Installed", "4+"),
UserInfoDB.getUser("johnsmith@gmail.com"));
// Add permeable paver.
PermeablePaversDB.addPermeablePavers(new PermeablePaversFormData(0, "John's Permeable Paver", "Residential",
"564 Ulahala St.", "No", "We installed a permeable pavement to replace our aging concrete driveway. The water "
+ "does not pool in front of our driveway anymore.", "4", "5", "2014", "Asphalt", "Concrete", "250",
"Self-Installed"), UserInfoDB.getUser("johnsmith@gmail.com"));
//Learn More Resource Database
ResourceDB.addGardenResource(new Resource("Hui o Ko'olaupoko Rain Garden Program", "hokprogram.jpg", "http:
ResourceDB.addGardenResource(new Resource("Hawaii Rain Garden Manual", "raingardenmanual.jpg", "http:
ResourceDB.addGardenResource(new Resource("Native Plant Care Manual", "nativeplantmanual.jpg", "http:
ResourceDB.addBarrelResource(new Resource("Honolulu Board of Water Supply Rain Barrel Program", "watersupplyprogram.jpg", "http:
ResourceDB.addPaverResource(new Resource("AquaPave", "aquapave.jpg", "http:
ResourceDB.addPaverResource(new Resource("Futura Stone of Hawaii", "futurastone.jpg", "http://futurastonehawaii.com/"));
}
/**
* Termination method for this Play Framework web application.
*
* @param app A Play Framework application.
*/
public void onStop(Application app) {
}
/**
* Populate plant database with plants from file.
*/
private static void populatePlantDB() {
String plant1 = "‘Ahu‘awa, Mariscus javanicus, Basin, sedge, Wet & Dry Climate";
String plant2 = "‘Ākia, Wikstroemia uva-ursi, Slope/berm, low shrub, Wet & Dry Climate";
String plant3 = "‘Ākulikuli, Sessuvium portulacastrum, Inlet, ground cover, Wet & Dry Climate";
String plant4 = "Carex, Carex wahuensis, Basin, sedge, Wet & Dry Climate";
String plant5 = "‘Ilie‘e, Plumbago zeylanica, Slope/berm, low shrub, Wet & Dry Climate";
String [] plantArr1 = plant1.split(", ");
String [] plantArr2 = plant2.split(", ");
String [] plantArr3 = plant3.split(", ");
String [] plantArr4 = plant4.split(", ");
String [] plantArr5 = plant5.split(", ");
PlantDB.addPlant(new Plant(plantArr1[0], plantArr1[1], plantArr1[2], plantArr1[THREE], plantArr1[FOUR]));
PlantDB.addPlant(new Plant(plantArr2[0], plantArr2[1], plantArr2[2], plantArr2[THREE], plantArr2[FOUR]));
PlantDB.addPlant(new Plant(plantArr3[0], plantArr3[1], plantArr3[2], plantArr3[THREE], plantArr3[FOUR]));
PlantDB.addPlant(new Plant(plantArr4[0], plantArr4[1], plantArr4[2], plantArr4[THREE], plantArr4[FOUR]));
PlantDB.addPlant(new Plant(plantArr5[0], plantArr5[1], plantArr5[2], plantArr5[THREE], plantArr5[FOUR]));
}
private static void populateIndexContentDB() {
ButtonDB.addButton(new Button("1", "Sign Up", "/signup"));
ButtonDB.addButton(new Button("1", "View Map", "/map"));
ButtonDB.addButton(new Button("2", "Learn More", "/learnmore#garden_resources"));
ButtonDB.addButton(new Button("2", "View Gallery", "/gallery/rain-garden"));
ButtonDB.addButton(new Button("4", "Learn More", "/learnmore#barrel_resources"));
ButtonDB.addButton(new Button("4", "View Gallery", "/gallery/rain-barrel"));
ButtonDB.addButton(new Button("3", "Learn More", "/learnmore#paver_resources"));
ButtonDB.addButton(new Button("3", "View Gallery", "/gallery/permeable-paver"));
IndexContent i = new IndexContent("1","What Harm Can A Little Rainwater Do?" ,"When it rains, the resulting rainwater runoff washes pollutants into Hawaii's streams, rivers, lakes and the ocean. Rainwater runoff solutions allow the resulting runoff to instead be collected, reused or absorbed naturually into the Earth. Share your solutions with your community and inspire your neighbors to be green!", "alawai.png",ButtonDB.getButtons());
IndexContent i1 = new IndexContent("2","Solution: Rain Garden" ,"A Rain Garden is a low-lying area populated with native plants. They reduce the amount of water diverted from roofs/driveways/parking lots into storm drains by absorbing and filtering the water.", "garden.png",ButtonDB.getButtons());
IndexContent i2 = new IndexContent("3","Solution: Permeable Paver" ,"A permeable interlocking concrete pavement is comprised of a layer of permeable pavers separated by joints filled with small stones. The stones in the joints provide 100% surface permeability while the stone base effectively filters stormwater and reduces pollutants and debris that would otherwise be washed into streams and rivers.", "paver.png",ButtonDB.getButtons());
IndexContent i3 = new IndexContent("4","Solution: Rain Barrel" ,"During the summer months it is estimated that nearly 40 percent of household water is used for lawn and garden maintenance. A rain barrel collects water and stores it for those times that you need it most --- during the dry summer months. Using rain barrels potentially helps homeowners lower water bills, while also improving the vitality of plants, flowers, trees, and lawns.", "barrel.png",ButtonDB.getButtons());
IndexContentDB.addBlock(i);
IndexContentDB.addBlock(i1);
IndexContentDB.addBlock(i2);
IndexContentDB.addBlock(i3);
}
} |
package com.bdumeljic.soniqself;
import android.content.Intent;
import android.content.IntentSender;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessActivities;
import com.google.android.gms.fitness.data.Bucket;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.request.DataReadRequest;
import com.google.android.gms.fitness.result.DataReadResult;
import org.billthefarmer.mididriver.GeneralMidiConstants;
import org.billthefarmer.mididriver.MidiConstants;
import org.billthefarmer.mididriver.MidiDriver;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class PlayDayActivity extends AppCompatActivity implements MidiDriver.OnMidiStartListener {
private static String TAG = "PlayActivity";
private static final String DATE_FORMAT = "yyyy.MM.dd HH:mm:ss";
public static final String SAMPLE_SESSION_NAME = "Afternoon run";
private static final int REQUEST_OAUTH = 1;
/**
* Track whether an authorization activity is stacking over the current activity, i.e. when
* a known auth error is being resolved, such as showing the account chooser or presenting a
* consent dialog. This avoids common duplications as might happen on screen rotations, etc.
*/
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
private GoogleApiClient mClient = null;
protected MidiDriver midi;
protected MediaPlayer player;
private PauseHandler mHandler;
private static int MINS = 2;
private static int DAY_DURATION_MS = 24 * 60 * 60 * 1000; // 86400000
private static int PLAY_DURATION_MS = MINS * 60 * 1000; // 120000
private Button mPlayButton;
private TextView mActivityText;
long endTime;
long startTime;
private ProgressBar mProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_day);
if (savedInstanceState != null) {
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
buildFitnessClient();
midi = new MidiDriver();
mHandler = new PauseHandler();
mHandler.pause();
mProgress = (ProgressBar) findViewById(R.id.progressBar);
mPlayButton = (Button) findViewById(R.id.play_button);
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.pause();
mPlayButton.setEnabled(false);
mActivityText.setText("");
new RetrieveDayDataTask().execute();
//setupIdlePlayer();
//startProgressBar();
}
});
mActivityText = (TextView) findViewById(R.id.play_activity);
if (midi != null) {
midi.setOnMidiStartListener(this);
}
}
/**
* Build a {@link GoogleApiClient} that will authenticate the user and allow the application
* to connect to Fitness APIs. The scopes included should match the scopes your app needs
* (see documentation for details). Authentication will occasionally fail intentionally,
* and in those cases, there will be a known resolution, which the OnConnectionFailedListener()
* can address. Examples of this include the user never having signed in before, or having
* multiple accounts on the device and needing to specify which account to use, etc.
*/
private void buildFitnessClient() {
// Create the Google API Client
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.SESSIONS_API)
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
// Put application specific code here.
mPlayButton.setClickable(true);
}
@Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG, "Connection lost. Reason: Service Disconnected");
}
}
}
)
.addOnConnectionFailedListener(
new GoogleApiClient.OnConnectionFailedListener() {
// Called whenever the API client fails to connect.
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed. Cause: " + result.toString());
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
PlayDayActivity.this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!authInProgress) {
try {
Log.i(TAG, "Attempting to resolve failed connection");
authInProgress = true;
result.startResolutionForResult(PlayDayActivity.this,
REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG,
"Exception while starting resolution activity", e);
}
}
}
}
)
.build();
}
@Override
protected void onStart() {
super.onStart();
// Connect to the Fitness API
Log.i(TAG, "Connecting...");
mClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mClient.isConnected()) {
mClient.disconnect();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mClient.isConnecting() && !mClient.isConnected()) {
mClient.connect();
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(AUTH_PENDING, authInProgress);
}
/**
* Create a {@link DataSet} to insert data into the History API, and
* then create and execute a {@link DataReadRequest} to verify the insertion succeeded.
* By using an {@link AsyncTask}, we can schedule synchronous calls, so that we can query for
* data after confirming that our insert was successful. Using asynchronous calls and callbacks
* would not guarantee that the insertion had concluded before the read request was made.
* An example of an asynchronous call using a callback can be found in the example
* on deleting data below.
*/
private class RetrieveDayDataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
// Set a start and end time for our query, using a start time of 1 week before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
endTime = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, -1);
startTime = cal.getTimeInMillis();
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Log.i(TAG, "Range Start: " + dateFormat.format(startTime) + " ms: " + startTime);
Log.i(TAG, "Range End: " + dateFormat.format(endTime) + " ms: " + endTime);
DataReadRequest dayDataReadRequest = queryDataForDay();
DataReadResult dayDataReadResult = Fitness.HistoryApi.readData(mClient, dayDataReadRequest).await(1, TimeUnit.MINUTES);
handleActivitySegment(dayDataReadResult);
//mHandler.resume();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//setupIdlePlayer();
mHandler.resume();
startProgressBar();
}
}
private DataReadRequest queryDataForDay() {
DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.aggregate(DataType.TYPE_ACTIVITY_SEGMENT, DataType.AGGREGATE_ACTIVITY_SUMMARY)
.aggregate(DataType.TYPE_CALORIES_EXPENDED, DataType.AGGREGATE_CALORIES_EXPENDED)
.aggregate(DataType.TYPE_DISTANCE_DELTA, DataType.AGGREGATE_DISTANCE_DELTA)
.aggregate(DataType.TYPE_SPEED, DataType.AGGREGATE_SPEED_SUMMARY)
.bucketByActivitySegment(3, TimeUnit.MINUTES)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
return readRequest;
}
private void handleActivitySegment(DataReadResult dataReadResult) {
if (dataReadResult.getBuckets().size() > 0) {
Log.i(TAG, "Number of returned buckets of DataSets is: "
+ dataReadResult.getBuckets().size());
for (Bucket bucket : dataReadResult.getBuckets()) {
Log.i(TAG, "Bucket: " + bucket.getActivity());
switch (bucket.getActivity()) {
case FitnessActivities.STILL:
case FitnessActivities.UNKNOWN:
case FitnessActivities.TILTING:
case FitnessActivities.ON_FOOT:
case FitnessActivities.IN_VEHICLE:
Log.i(TAG, "Ignore");
break;
case FitnessActivities.WALKING:
Log.i(TAG, "Walking");
readStepsBucket(bucket);
break;
case FitnessActivities.SLEEP:
case FitnessActivities.SLEEP_LIGHT:
case FitnessActivities.SLEEP_DEEP:
case FitnessActivities.SLEEP_REM:
Log.i(TAG, "Sleeping");
readSleepBucket(bucket);
break;
default:
Log.i(TAG, "Activity");
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
dumpDataSet(dataSet);
}
readActBucket(bucket);
break;
}
}
}
}
private void readStepsBucket(Bucket bucket) {
Log.i(TAG, "Reading steps bucket ");
long startActSeg = bucket.getStartTime(TimeUnit.MILLISECONDS);
long endActSeg = bucket.getEndTime(TimeUnit.MILLISECONDS);
int steps = 0;
float distance = 0;
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
for (DataPoint dp : dataSet.getDataPoints()) {
for (final Field field : dp.getDataType().getFields()) {
if (field.equals(Field.FIELD_STEPS)) {
steps = dp.getValue(field).asInt();
} else if (field.equals(Field.FIELD_DISTANCE)) {
distance = dp.getValue(field).asFloat();
}
}
}
}
long duration = calculateDurationPlay(startActSeg, endActSeg);
if (steps > 20 && (steps / duration > 0.0001)) {
Log.i(TAG, "Bucket step " + steps + " dist " + distance + " duration " + (endActSeg - startActSeg) + " d play " + calculateDurationPlay(startActSeg, endActSeg));
playSteps(startActSeg, duration, steps, distance);
}
}
private void readSleepBucket(Bucket bucket) {
Log.i(TAG, "Reading sleep bucket " + bucket.getActivity());
long startActSeg = bucket.getStartTime(TimeUnit.MILLISECONDS);
long endActSeg = bucket.getEndTime(TimeUnit.MILLISECONDS);
long duration = calculateDurationPlay(startActSeg, endActSeg);
// 0: Default, 1: Light, 2: Deep, 3: REM
int type = -1;
switch (bucket.getActivity()) {
case FitnessActivities.SLEEP:
type = 0;
break;
case FitnessActivities.SLEEP_LIGHT:
type = 1;
break;
case FitnessActivities.SLEEP_DEEP:
type = 2;
break;
case FitnessActivities.SLEEP_REM:
type = 3;
break;
}
playSleep(startActSeg, duration, type);
}
private void readActBucket(Bucket bucket) {
Log.i(TAG, "Reading act bucket: " + bucket.getActivity());
long startActSeg = bucket.getStartTime(TimeUnit.MILLISECONDS);
long endActSeg = bucket.getEndTime(TimeUnit.MILLISECONDS);
long duration = calculateDurationPlay(startActSeg, endActSeg);
int steps = 0;
float distance = 0;
float speed = 0;
float calories = 0;
List<DataSet> dataSets = bucket.getDataSets();
for (DataSet dataSet : dataSets) {
for (DataPoint dp : dataSet.getDataPoints()) {
for (final Field field : dp.getDataType().getFields()) {
if (field.equals(Field.FIELD_STEPS)) {
steps = dp.getValue(field).asInt();
} else if (field.equals(Field.FIELD_DISTANCE)) {
distance = dp.getValue(field).asFloat();
} else if (field.equals(Field.FIELD_SPEED)) {
speed = dp.getValue(field).asFloat();
} else if (field.equals(Field.FIELD_CALORIES)) {
calories = dp.getValue(field).asFloat();
}
}
}
}
playAct(startActSeg, duration, bucket.getActivity(), steps, distance, speed, calories);
}
private void playSleep(long start, final long duration, final int type) {
mHandler.postPausedDelayed(new Runnable() {
@Override
public void run() {
switchToSleep();
mActivityText.append("\n" + "Sleeping");
int note = 48;
int velocity = 50;
int min = 0;
int max = 120;
// Map type of sleep to pitch range
// 0: Default, 1: Light, 2: Deep, 3: REM
switch (type) {
case 1:
min = 20;
max = 120;
mActivityText.append(" (Light)");
break;
case 2:
min = 0;
max = 39;
mActivityText.append(" (Deep)");
break;
case 3:
min = 50;
max = 69;
mActivityText.append(" (REM)");
break;
}
Random random = new Random();
for (int i = 0; i < duration; i = i + 166) {
note = random.nextInt(max - min + 1) + min;
sendMidi(MidiConstants.NOTE_ON, note, velocity);
sendMidi(MidiConstants.NOTE_ON, note + 4, velocity);
sendMidi(MidiConstants.NOTE_ON, note + 7, velocity);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendMidi(MidiConstants.NOTE_OFF, note, 0);
sendMidi(MidiConstants.NOTE_OFF, note + 4, 0);
sendMidi(MidiConstants.NOTE_OFF, note + 7, 0);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
switchToFootSteps();
}
}, calculateDelay(start));
}
private void playAct(long start, final long duration, final String activity, final int steps, final float distance, final float speed, final float calories) {
mHandler.postPausedDelayed(new Runnable() {
@Override
public void run() {
switchToActive();
String act = activity.substring(0,1).toUpperCase() + activity.substring(1).toLowerCase();
mActivityText.append("\n" + act);
int note;
int velocity;
// Map speed to note
// If there is no speed, then use calories
// If there is neither, improvise using random
if (speed > 0) {
note = (int) (speed / (MAX_SPEED / 40f) + 30);
} else if (calories > 0) {
note = (int) (calories / (MAX_CALORIES / 40f) + 30);
} else {
note = new Random(40).nextInt() + 31;
}
// Map steps to velocity
// If there is no steps data, use distance
// If there is neither, use random
if (steps > 0) {
velocity = (int) (steps / (MAX_STEPS / 40f) + 40);
} else if (distance > 0) {
velocity = (int) (distance / (MAX_DIST / 40f) + 40);
} else {
velocity = new Random(40).nextInt() + 41;
}
Random random = new Random();
for (int i = 0; i < duration; i = i + 125) {
int randomness = random.nextInt(15);
sendMidi(MidiConstants.NOTE_ON, note + randomness, velocity);
sendMidi(MidiConstants.NOTE_ON, note + randomness + 4, velocity);
sendMidi(MidiConstants.NOTE_ON, note + randomness + 7, velocity);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendMidi(MidiConstants.NOTE_OFF, note + randomness, 0);
sendMidi(MidiConstants.NOTE_OFF, note + randomness + 4, 0);
sendMidi(MidiConstants.NOTE_OFF, note + randomness + 7, 0);
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
switchToFootSteps();
}
}, calculateDelay(start));
}
int MAX_STEPS = 2000;
float MAX_DIST = 1000;
float MAX_SPEED = 6;
float MAX_CALORIES = 450;
private void playSteps(long start, final long duration, final int steps, final float distance) {
mHandler.postPausedDelayed(new Runnable() {
@Override
public void run() {
mActivityText.append("\n Walking (" + steps + " steps)");
// Map number of steps to pitch between 10 and 50
int note = (int) (steps / (MAX_STEPS / 40f) + 30);
// Map distance to volume between 40 and 80
int velocity = (int) (distance / (MAX_DIST / 40f) + 40);
Log.e(TAG, "steps " + steps + " to velocity " + velocity + " dist " + distance + " to note " + note);
Random random = new Random();
for (int i = 0; i < duration; i = i + 125) {
int randomness = random.nextInt(15);
sendMidi(MidiConstants.NOTE_ON, note + randomness, velocity);
sendMidi(MidiConstants.NOTE_ON, note + randomness + 4, velocity);
sendMidi(MidiConstants.NOTE_ON, note + randomness + 7, velocity);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendMidi(MidiConstants.NOTE_OFF, note + randomness, 0);
sendMidi(MidiConstants.NOTE_OFF, note + randomness + 4, 0);
sendMidi(MidiConstants.NOTE_OFF, note + randomness + 7, 0);
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, calculateDelay(start));
}
private long calculateDurationPlay(long start, long end) {
return (end - start) / (DAY_DURATION_MS / PLAY_DURATION_MS);
}
private long calculateDelay(long dpStartTime) {
float floating = (dpStartTime - startTime) / (float) DAY_DURATION_MS;
float result = floating * PLAY_DURATION_MS;
return (long) result;
}
private void setupIdlePlayer() {
player = MediaPlayer.create(this, R.raw.heartbeat2);
player.setVolume(1.0f, 1.0f);
player.setLooping(true);
player.start();
mHandler.postPausedDelayed(new Runnable() {
@Override
public void run() {
if (player != null && player.isPlaying()) {
player.pause();
player.seekTo(0);
}
mPlayButton.setEnabled(true);
}
}, PLAY_DURATION_MS);
}
private void playTestSound() {
mHandler.postPausedDelayed(new Runnable() {
@Override
public void run() {
mActivityText.append("\n test");
switchToFootSteps();
sendMidi(MidiConstants.NOTE_ON, 48, 35);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendMidi(MidiConstants.NOTE_ON, 52, 35);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendMidi(MidiConstants.NOTE_ON, 55, 35);
/* try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
switchToSleep();
sendMidi(MidiConstants.NOTE_ON, 48, 35);
sendMidi(MidiConstants.NOTE_ON, 52, 35);
sendMidi(MidiConstants.NOTE_ON, 55, 35);
sendMidi(MidiConstants.NOTE_OFF, 48, 0);
sendMidi(MidiConstants.NOTE_OFF, 52, 0);
sendMidi(MidiConstants.NOTE_OFF, 55, 0);
switchToFootSteps();*/
}
}, 0);
}
private void startProgressBar() {
mProgress.setVisibility(View.VISIBLE);
mProgress.setMax(100);
new CountDownTimer(PLAY_DURATION_MS, 1000) {
public void onTick(long millisUntilFinished) {
float progress = (PLAY_DURATION_MS - millisUntilFinished) / (float) PLAY_DURATION_MS * 100f;
mProgress.setProgress((int) progress);
}
public void onFinish() {
mProgress.setVisibility(View.INVISIBLE);
}
}.start();
}
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
for (DataPoint dp : dataSet.getDataPoints()) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Log.i(TAG, "Data point:");
Log.i(TAG, "\tType: " + dp.getDataType().getName());
Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " ms: " + dp.getStartTime(TimeUnit.MILLISECONDS));
Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " ms: " + dp.getEndTime(TimeUnit.MILLISECONDS));
for (final Field field : dp.getDataType().getFields()) {
Log.i(TAG, "\tField: " + field.getName() + " Value: " + dp.getValue(field));
}
}
}
@Override
protected void onResume() {
super.onResume();
// Start midi
if (midi != null)
midi.start();
}
@Override
protected void onPause() {
super.onPause();
// Stop midi
if (midi != null)
midi.stop();
// Stop player
if (player != null)
player.stop();
}
// Listener for sending initial midi messages when the Sonivox
// synthesizer has been started, such as program change.
@Override
public void onMidiStart() {
// Program change
switchToFootSteps();
}
public void switchToFootSteps() {
sendMidi(MidiConstants.PROGRAM_CHANGE, GeneralMidiConstants.SYNTH_DRUM);
}
public void switchToActive() {
sendMidi(MidiConstants.PROGRAM_CHANGE, GeneralMidiConstants.SLAP_BASS_0);
}
public void switchToSleep() {
sendMidi(MidiConstants.PROGRAM_CHANGE, GeneralMidiConstants.LEAD_1_SAWTOOTH);
}
// Send a midi message
protected void sendMidi(int m, int p) {
byte msg[] = new byte[2];
msg[0] = (byte) m;
msg[1] = (byte) p;
midi.queueEvent(msg);
}
// Send a midi message
protected void sendMidi(int m, int n, int v) {
byte msg[] = new byte[3];
msg[0] = (byte) m;
msg[1] = (byte) n;
msg[2] = (byte) v;
midi.queueEvent(msg);
}
} |
package com.justdoit.pics.fragment;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.justdoit.pics.R;
public class EditFragment extends DialogFragment {
public EditFragment() {
super();
}
static EditFragment newInstance() {
return new EditFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_edit,container,false);
return v;
}
@Override
public Dialog getDialog() {
return super.getDialog();
}
} |
package com.liuguangqiang.download;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.liuguangqiang.download.core.AsyncDownload;
import com.liuguangqiang.download.core.DownloadConfiguration;
import com.liuguangqiang.download.core.DownloadListener;
import com.liuguangqiang.download.core.DownloadParams;
public class MainActivity extends Activity {
private String TAG = "AsyncDownload";
private String filePath;
private String testUrl = "http://dl.fishsaying.com/fishsaying_1.8.1.apk";
private TextView tvProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvProgress = (TextView) this.findViewById(R.id.tv_progress);
init();
testDownload();
}
private void init() {
AsyncDownload.getInstance().init(
new DownloadConfiguration.Builder().setFixedThreadPool(3).build());
filePath = FileUtils.getSdcardPath() + "/AsyncDownload";
File file = new File(filePath);
if (!file.exists()) file.mkdirs();
}
DownloadParams params;
private void testDownload() {
String pathFormat = filePath + "/t%s.apk";
String savePath;
for (int i = 0; i < 5; i++) {
savePath = String.format(pathFormat, i + 1);
params = new DownloadParams(testUrl, savePath);
params.setTag("Tag" + (i + 1));
AsyncDownload.getInstance().download(params, new DownloadListener() {
@Override
public void onStart() {
Log.i(TAG, getDownloadParams().getTag() + " download start");
}
@Override
public void onSuccess() {
Log.i(TAG, getDownloadParams().getTag() + " download success");
}
@Override
public void onProgressUpdate(int progress) {
Log.i(TAG, getDownloadParams().getTag() + " progress" + progress);
tvProgress.setText("progress--->" + progress);
}
@Override
public void onFailure(String msg) {
Log.i(TAG, getDownloadParams().getTag() + " : " + msg);
}
});
}
}
} |
package VASSAL.chat.ui;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import VASSAL.chat.HybridClient;
import VASSAL.chat.LockableRoom;
import VASSAL.chat.Room;
import VASSAL.chat.node.NodeClient;
import VASSAL.chat.node.NodeRoom;
import VASSAL.i18n.Resources;
/**
* @author rkinney
*/
public class LockableRoomControls extends RoomInteractionControlsInitializer {
public LockableRoomControls(NodeClient client) {
super(client);
}
public void doubleClickRoom(Room room, JTree tree) {
if (!(room instanceof LockableRoom)
|| !((LockableRoom) room).isLocked()) {
super.doubleClickRoom(room, tree);
}
}
public JPopupMenu buildPopupForRoom(Room target, JTree tree) {
JPopupMenu popup = new JPopupMenu();
JoinRoomAction joinAction = new JoinRoomAction(target, client);
popup.add(joinAction);
NodeClient c = getNodeClient();
if (c != null) {
if (target instanceof LockableRoom) {
LockableRoom nr = (LockableRoom) target;
if (nr.isLocked()) {
joinAction.setEnabled(false);
}
}
popup.add(new LockRoomAction((NodeRoom) target, c));
}
return popup;
}
private NodeClient getNodeClient() {
NodeClient c = null;
if (client instanceof NodeClient) {
c = (NodeClient) client;
}
else if (client instanceof HybridClient
&& ((HybridClient) client).getDelegate() instanceof NodeClient) {
c = (NodeClient) ((HybridClient) client).getDelegate();
}
return c;
}
protected void createRoom(String name) {
Room existing = null;
Room[] rooms = client.getAvailableRooms();
for (int i = 0; existing == null && i < rooms.length; i++) {
if (rooms[i].getName().equals(name)) {
existing = rooms[i];
}
}
NodeClient nodeClient = getNodeClient();
if (existing instanceof NodeRoom) {
// Join existing room if it is not locked
if (!((NodeRoom) existing).isLocked()) {
client.setRoom(existing);
}
}
else if (existing == null
&& nodeClient != null) {
// If running hierarchical server, create new room and set myself as the owner
NodeRoom room = new NodeRoom(name);
room.setOwner(nodeClient.getMyInfo().getId());
client.setRoom(room);
nodeClient.sendRoomInfo(room);
}
else {
// Default behavior
super.createRoom(name);
}
}
public static class LockRoomAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private NodeClient client;
private NodeRoom target;
public LockRoomAction(NodeRoom target, NodeClient client) {
super(target.isLocked() ? Resources.getString("Chat.unlock_room")
: Resources.getString("Chat.lock_room"));
setEnabled(client.getMyInfo().getId().equals(target.getOwner()) &&
!target.getName().equals(client.getDefaultRoomName()));
this.target = target;
this.client = client;
}
public void actionPerformed(ActionEvent e) {
client.lockRoom(target);
}
}
} |
package edu.northwestern.bioinformatics.studycalendar.web.tools;
import edu.northwestern.bioinformatics.studycalendar.osgi.hostservices.HostBeans;
import edu.northwestern.bioinformatics.studycalendar.osgi.hostservices.internal.HostBeansImpl;
import edu.northwestern.bioinformatics.studycalendar.security.FilterSecurityInterceptorConfigurer;
import edu.northwestern.bioinformatics.studycalendar.security.StubAuthenticationSystem;
import edu.northwestern.bioinformatics.studycalendar.security.plugin.AuthenticationSystem;
import edu.northwestern.bioinformatics.studycalendar.test.PscTestingBundleContext;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.memory.InMemoryDaoImpl;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import java.io.IOException;
import java.util.Dictionary;
/**
* @author Rhett Sutphin
*/
public class WebTestingBundleContext extends PscTestingBundleContext {
public WebTestingBundleContext() {
reset();
}
public void reset() {
testingDetails.clear();
addService(AuthenticationSystem.class, new StubAuthenticationSystem());
addService(HostBeans.class, new HostBeansImpl());
addService(UserDetailsService.class, new InMemoryDaoImpl());
addService(ConfigurationAdmin.class, new MockConfigurationAdmin());
addService(FilterSecurityInterceptorConfigurer.class, new FilterSecurityInterceptorConfigurer());
}
private static class MockConfigurationAdmin implements ConfigurationAdmin {
public Configuration createFactoryConfiguration(String s) throws IOException {
return new MockConfiguration();
}
public Configuration createFactoryConfiguration(String s, String s1) throws IOException {
return new MockConfiguration();
}
public Configuration getConfiguration(String s, String s1) throws IOException {
return new MockConfiguration();
}
public Configuration getConfiguration(String s) throws IOException {
return new MockConfiguration();
}
public Configuration[] listConfigurations(String s) throws IOException, InvalidSyntaxException {
return new Configuration[] { new MockConfiguration() };
}
}
private static class MockConfiguration implements Configuration {
public String getPid() {
throw new UnsupportedOperationException("getPid not implemented");
}
public Dictionary getProperties() {
throw new UnsupportedOperationException("getProperties not implemented");
}
public void update(Dictionary dictionary) throws IOException {
// do nothing
}
public void delete() throws IOException {
// do nothing
}
public String getFactoryPid() {
throw new UnsupportedOperationException("getFactoryPid not implemented");
}
public void update() throws IOException {
// do nothing
}
public void setBundleLocation(String s) {
throw new UnsupportedOperationException("setBundleLocation not implemented");
}
public String getBundleLocation() {
throw new UnsupportedOperationException("getBundleLocation not implemented");
}
}
} |
package com.marverenic.music.player;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.KeyEvent;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.activity.NowPlayingActivity;
import com.marverenic.music.data.store.MediaStoreUtil;
import com.marverenic.music.data.store.PlayCountStore;
import com.marverenic.music.data.store.PreferencesStore;
import com.marverenic.music.data.store.ReadOnlyPreferencesStore;
import com.marverenic.music.data.store.RemotePreferenceStore;
import com.marverenic.music.data.store.SharedPreferencesStore;
import com.marverenic.music.instances.Song;
import com.marverenic.music.utils.Util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.inject.Inject;
import timber.log.Timber;
import static android.content.Intent.ACTION_HEADSET_PLUG;
import static android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY;
/**
* High level implementation for a MediaPlayer. MusicPlayer is backed by a {@link QueuedMediaPlayer}
* and provides high-level behavior definitions (for actions like {@link #skip()},
* {@link #skipPrevious()} and {@link #togglePlay()}) as well as system integration.
*
* MediaPlayer provides shuffle and repeat with {@link #setShuffle(boolean)} and
* {@link #setRepeat(int)}, respectively.
*
* MusicPlayer also provides play count logging and state reloading.
* See {@link #logPlayCount(Song, boolean)}, {@link #loadState()} and {@link #saveState()}
*
* System integration is implemented by handling Audio Focus through {@link AudioManager}, attaching
* a {@link MediaSessionCompat}, and with a {@link HeadsetListener} -- an implementation of
* {@link BroadcastReceiver} that pauses playback when headphones are disconnected.
*/
public class MusicPlayer implements AudioManager.OnAudioFocusChangeListener,
QueuedMediaPlayer.PlaybackEventListener {
private static final String TAG = "MusicPlayer";
/**
* The filename of the queue state used to load and save previous configurations.
* This file will be stored in the directory defined by
* {@link Context#getExternalFilesDir(String)}
*/
private static final String QUEUE_FILE = ".queue";
/**
* An {@link Intent} action broadcasted when a MusicPlayer has changed its state automatically
*/
public static final String UPDATE_BROADCAST = "marverenic.jockey.player.REFRESH";
/**
* An {@link Intent} action broadcasted when a MusicPlayer has information that should be
* presented to the user
* @see #INFO_EXTRA_MESSAGE
*/
public static final String INFO_BROADCAST = "marverenic.jockey.player.INFO";
/**
* An {@link Intent} extra sent with {@link #INFO_BROADCAST} intents which maps to a
* user-friendly information message
*/
public static final String INFO_EXTRA_MESSAGE = "marverenic.jockey.player.INFO:MSG";
/**
* An {@link Intent} action broadcasted when a MusicPlayer has encountered an error when
* setting the current playback source
* @see #ERROR_EXTRA_MSG
*/
public static final String ERROR_BROADCAST = "marverenic.jockey.player.ERROR";
/**
* An {@link Intent} extra sent with {@link #ERROR_BROADCAST} intents which maps to a
* user-friendly error message
*/
public static final String ERROR_EXTRA_MSG = "marverenic.jockey.player.ERROR:MSG";
/**
* Repeat value that corresponds to repeat none. Playback will continue as normal until and will
* end after the last song finishes
* @see #setRepeat(int)
*/
public static final int REPEAT_NONE = 0;
/**
* Repeat value that corresponds to repeat all. Playback will continue as normal, but the queue
* will restart from the beginning once the last song finishes
* @see #setRepeat(int)
*/
public static final int REPEAT_ALL = -1;
/**
* Repeat value that corresponds to repeat one. When the current song is finished, it will be
* repeated. The MusicPlayer will never progress to the next track until the user manually
* changes the song.
* @see #setRepeat(int)
*/
public static final int REPEAT_ONE = -2;
/**
* Defines the threshold for skip previous behavior. If the current seek position in the song is
* greater than this value, {@link #skipPrevious()} will seek to the beginning of the song.
* If the current seek position is less than this threshold, then the queue index will be
* decremented and the previous song in the queue will be played.
* This value is measured in milliseconds and is currently set to 5 seconds
* @see #skipPrevious()
*/
private static final int SKIP_PREVIOUS_THRESHOLD = 5000;
/**
* Defines the minimum duration that must be passed for a song to be considered "played" when
* logging play counts
* This value is measured in milliseconds and is currently set to 24 seconds
*/
private static final int PLAY_COUNT_THRESHOLD = 24000;
/**
* Defines the maximum duration that a song can reach to be considered "skipped" when logging
* play counts
* This value is measured in milliseconds and is currently set to 20 seconds
*/
private static final int SKIP_COUNT_THRESHOLD = 20000;
/**
* The volume scalar to set when {@link AudioManager} causes a MusicPlayer instance to duck
*/
private static final float DUCK_VOLUME = 0.5f;
private QueuedMediaPlayer mMediaPlayer;
private Context mContext;
private Handler mHandler;
private MediaSessionCompat mMediaSession;
private HeadsetListener mHeadphoneListener;
private OnPlaybackChangeListener mCallback;
private List<Song> mQueue;
private List<Song> mQueueShuffled;
private boolean mShuffle;
private int mRepeat;
private int mMultiRepeat;
/**
* Whether this MusicPlayer has focus from {@link AudioManager} to play audio
* @see #getFocus()
*/
private boolean mFocused = false;
/**
* Whether playback should continue once {@link AudioManager} returns focus to this MusicPlayer
* @see #onAudioFocusChange(int)
*/
private boolean mResumeOnFocusGain = false;
/**
* The album artwork of the current song
*/
private Bitmap mArtwork;
@Inject PlayCountStore mPlayCountStore;
private RemotePreferenceStore mRemotePreferenceStore;
private final Runnable mSleepTimerRunnable = this::onSleepTimerEnd;
/**
* Creates a new MusicPlayer with an empty queue. The backing {@link android.media.MediaPlayer}
* will create a wakelock (specified by {@link PowerManager#PARTIAL_WAKE_LOCK}), and all
* system integration will be initialized
* @param context A Context used to interact with other components of the OS and used to
* load songs. This Context will be kept for the lifetime of this Object.
*/
public MusicPlayer(Context context) {
mContext = context;
mHandler = new Handler();
JockeyApplication.getComponent(mContext).inject(this);
mRemotePreferenceStore = new RemotePreferenceStore(mContext);
// Initialize play count store
mPlayCountStore.refresh()
.subscribe(complete -> {
Timber.i("init: Initialized play count store values");
}, throwable -> {
Timber.e(throwable, "init: Failed to read play count store values");
});
// Initialize the media player
mMediaPlayer = new QueuedExoPlayer(context);
mMediaPlayer.setPlaybackEventListener(this);
mQueue = new ArrayList<>();
mQueueShuffled = new ArrayList<>();
// Attach a HeadsetListener to respond to headphone events
mHeadphoneListener = new HeadsetListener(this);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_HEADSET_PLUG);
filter.addAction(ACTION_AUDIO_BECOMING_NOISY);
context.registerReceiver(mHeadphoneListener, filter);
loadPrefs();
initMediaSession();
}
/**
* Reloads shuffle and repeat preferences from {@link SharedPreferences}
*/
private void loadPrefs() {
Timber.i("Loading SharedPreferences...");
// SharedPreferencesStore is backed by an instance of SharedPreferences. Because
// SharedPreferences isn't safe to use across processes, the only time we can get valid
// data is right after we open the SharedPreferences for the first time in this process.
// We're going to take advantage of that here so that we can load the latest preferences
// as soon as the MusicPlayer is started (which should be the same time that this process
// is started). To update these preferences, see updatePreferences(preferencesStore)
PreferencesStore preferencesStore = new SharedPreferencesStore(mContext);
mShuffle = preferencesStore.isShuffled();
setRepeat(preferencesStore.getRepeatMode());
setMultiRepeat(mRemotePreferenceStore.getMultiRepeatCount());
initEqualizer(preferencesStore);
startSleepTimer(mRemotePreferenceStore.getSleepTimerEndTime());
}
/**
* Updates shuffle and repeat preferences from a Preference Store
* @param preferencesStore The preference store to read values from
*/
public void updatePreferences(ReadOnlyPreferencesStore preferencesStore) {
Timber.i("Updating preferences...");
if (preferencesStore.isShuffled() != mShuffle) {
setShuffle(preferencesStore.isShuffled());
}
setRepeat(preferencesStore.getRepeatMode());
initEqualizer(preferencesStore);
}
/**
* Initiate a MediaSession to allow the Android system to interact with the player
*/
private void initMediaSession() {
Timber.i("Initializing MediaSession");
mMediaSession = new MediaSessionCompat(mContext, TAG, null, null);
mMediaSession.setCallback(new MediaSessionCallback(this));
mMediaSession.setSessionActivity(
PendingIntent.getActivity(
mContext, 0,
new Intent(mContext, NowPlayingActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_CANCEL_CURRENT));
mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
| MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder()
.setActions(PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
| PlaybackStateCompat.ACTION_STOP)
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f);
mMediaSession.setPlaybackState(state.build());
mMediaSession.setActive(true);
}
/**
* Reload all equalizer settings from SharedPreferences
*/
private void initEqualizer(ReadOnlyPreferencesStore preferencesStore) {
Timber.i("Initializing equalizer");
mMediaPlayer.setEqualizer(preferencesStore.getEqualizerEnabled(),
preferencesStore.getEqualizerSettings());
}
/**
* Saves the player's current state to a file with the name {@link #QUEUE_FILE} in
* the app's external files directory specified by {@link Context#getExternalFilesDir(String)}
* @throws IOException
* @see #loadState()
*/
public void saveState() throws IOException {
Timber.i("Saving player state");
// Anticipate the outcome of a command so that if we're killed right after it executes,
// we can restore to the proper state
int reloadSeekPosition = mMediaPlayer.getCurrentPosition();
int reloadQueuePosition = mMediaPlayer.getQueueIndex();
final String currentPosition = Integer.toString(reloadSeekPosition);
final String queuePosition = Integer.toString(reloadQueuePosition);
final String queueLength = Integer.toString(mQueue.size());
StringBuilder queue = new StringBuilder();
for (Song s : mQueue) {
queue.append(' ').append(s.getSongId());
}
StringBuilder queueShuffled = new StringBuilder();
for (Song s : mQueueShuffled) {
queueShuffled.append(' ').append(s.getSongId());
}
String output = currentPosition + " " + queuePosition + " "
+ queueLength + queue + queueShuffled;
File save = new File(mContext.getExternalFilesDir(null), QUEUE_FILE);
FileOutputStream stream = null;
try {
stream = new FileOutputStream(save);
stream.write(output.getBytes());
} finally {
if (stream != null) {
stream.close();
}
}
}
/**
* Reloads a saved state
* @see #saveState()
*/
public void loadState() {
Timber.i("Loading state...");
Scanner scanner = null;
try {
File save = new File(mContext.getExternalFilesDir(null), QUEUE_FILE);
scanner = new Scanner(save);
int currentPosition = scanner.nextInt();
int queuePosition = scanner.nextInt();
int queueLength = scanner.nextInt();
long[] queueIDs = new long[queueLength];
for (int i = 0; i < queueLength; i++) {
queueIDs[i] = scanner.nextInt();
}
mQueue = MediaStoreUtil.buildSongListFromIds(queueIDs, mContext);
long[] shuffleQueueIDs;
if (scanner.hasNextInt()) {
shuffleQueueIDs = new long[queueLength];
for (int i = 0; i < queueLength; i++) {
shuffleQueueIDs[i] = scanner.nextInt();
}
mQueueShuffled = MediaStoreUtil.buildSongListFromIds(shuffleQueueIDs, mContext);
} else if (mShuffle) {
shuffleQueue(queuePosition);
}
setBackingQueue(queuePosition);
mMediaPlayer.seekTo(currentPosition);
mArtwork = Util.fetchFullArt(getNowPlaying());
} catch(FileNotFoundException ignored) {
Timber.i("State does not exist. Using empty state");
// If there's no queue file, just restore to an empty state
} catch (NoSuchElementException e) {
Timber.i("Failed to parse previous state. Resetting...");
mQueue.clear();
mQueueShuffled.clear();
mMediaPlayer.reset();
} finally {
if (scanner != null) {
scanner.close();
}
}
}
public void setPlaybackChangeListener(OnPlaybackChangeListener listener) {
mCallback = listener;
}
/**
* Updates the metadata in the attached {@link MediaSessionCompat}
*/
private void updateMediaSession() {
Timber.i("Updating MediaSession");
if (getNowPlaying() != null) {
Song nowPlaying = getNowPlaying();
MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE,
nowPlaying.getSongName())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM,
nowPlaying.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION,
nowPlaying.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST,
nowPlaying.getArtistName())
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE,
nowPlaying.getArtistName())
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, getDuration())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, mArtwork);
mMediaSession.setMetadata(metadataBuilder.build());
PlaybackStateCompat.Builder state = new PlaybackStateCompat.Builder().setActions(
PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_STOP
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
if (mMediaPlayer.isPlaying()) {
state.setState(PlaybackStateCompat.STATE_PLAYING, getCurrentPosition(), 1f);
} else if (mMediaPlayer.isPaused()) {
state.setState(PlaybackStateCompat.STATE_PAUSED, getCurrentPosition(), 1f);
} else if (mMediaPlayer.isStopped()) {
state.setState(PlaybackStateCompat.STATE_STOPPED, getCurrentPosition(), 1f);
} else {
state.setState(PlaybackStateCompat.STATE_NONE, getCurrentPosition(), 1f);
}
mMediaSession.setPlaybackState(state.build());
mMediaSession.setActive(mFocused);
}
}
@Override
public void onAudioFocusChange(int focusChange) {
Timber.i("AudioFocus changed (%d)", focusChange);
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
mResumeOnFocusGain = isPlaying() || mResumeOnFocusGain;
case AudioManager.AUDIOFOCUS_LOSS:
Timber.i("Focus lost. Pausing music.");
mFocused = false;
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Timber.i("Focus lost transiently. Ducking.");
mMediaPlayer.setVolume(DUCK_VOLUME);
break;
case AudioManager.AUDIOFOCUS_GAIN:
Timber.i("Regained AudioFocus");
mMediaPlayer.setVolume(1f);
if (mResumeOnFocusGain) play();
mResumeOnFocusGain = false;
break;
default:
Timber.i("Ignoring AudioFocus state change");
break;
}
updateNowPlaying();
updateUi();
}
/**
* Notifies the attached {@link MusicPlayer.OnPlaybackChangeListener} that a playback change
* has occurred, and updates the attached {@link MediaSessionCompat}
*/
private void updateNowPlaying() {
Timber.i("updateNowPlaying() called");
updateMediaSession();
if (mCallback != null) {
mCallback.onPlaybackChange();
}
}
/**
* Called to notify the UI thread to refresh any player data when the player changes states
* on its own (Like when a song finishes)
*/
protected void updateUi() {
Timber.i("Sending broadcast to update UI process");
mContext.sendBroadcast(new Intent(UPDATE_BROADCAST), null);
}
/**
* Called to notify the UI thread that an error has occurred. The typical listener will show the
* message passed in to the user.
* @param message A user-friendly message associated with this error that may be shown in the UI
*/
protected void postError(String message) {
Timber.i("Posting error to UI process: %s", message);
mContext.sendBroadcast(
new Intent(ERROR_BROADCAST).putExtra(ERROR_EXTRA_MSG, message), null);
}
/**
* Called to notify the UI thread of a non-critical event. The typical listener will show the
* message passed in to the user
* @param message A user-friendly message associated with this event that may be shown in the UI
*/
protected void postInfo(String message) {
Timber.i("Posting info to UI process: %s", message);
mContext.sendBroadcast(
new Intent(INFO_BROADCAST).putExtra(INFO_EXTRA_MESSAGE, message), null);
}
/**
* Gain Audio focus from the system if we don't already have it
* @return whether we have gained focus (or already had it)
*/
private boolean getFocus() {
if (!mFocused) {
Timber.i("Requesting AudioFocus...");
AudioManager audioManager =
(AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
int response = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mFocused = response == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
return mFocused;
}
/**
* Generates a new random permutation of the queue, and sets it as the backing
* {@link QueuedMediaPlayer}'s queue
* @param currentIndex The index of the current song which will be moved to the top of the
* shuffled queue
*/
private void shuffleQueue(int currentIndex) {
Timber.i("Shuffling queue...");
if (mQueueShuffled == null) {
mQueueShuffled = new ArrayList<>(mQueue);
} else {
mQueueShuffled.clear();
mQueueShuffled.addAll(mQueue);
}
if (!mQueueShuffled.isEmpty()) {
Song first = mQueueShuffled.remove(currentIndex);
Collections.shuffle(mQueueShuffled);
mQueueShuffled.add(0, first);
}
}
private void unshuffleQueue() {
List<Song> unshuffled = new ArrayList<>(mQueue);
List<Song> songs = new ArrayList<>(mQueueShuffled);
Iterator<Song> unshuffledIterator = unshuffled.iterator();
while (unshuffledIterator.hasNext()) {
Song song = unshuffledIterator.next();
if (!songs.remove(song)) {
unshuffledIterator.remove();
}
}
mQueue = unshuffled;
}
/**
* Toggles playback between playing and paused states
* @see #play()
* @see #pause()
*/
public void togglePlay() {
Timber.i("Toggling playback");
if (isPlaying()) {
pause();
} else if (mMediaPlayer.isComplete()) {
mMediaPlayer.setQueueIndex(0);
play();
} else {
play();
}
}
/**
* Pauses music playback
*/
public void pause() {
Timber.i("Pausing playback");
if (isPlaying()) {
mMediaPlayer.pause();
updateNowPlaying();
}
mResumeOnFocusGain = false;
}
/**
* Starts or resumes music playback
*/
public void play() {
Timber.i("Resuming playback");
if (!isPlaying() && getFocus()) {
mMediaPlayer.play();
updateNowPlaying();
}
}
/**
* Skips to the next song in the queue and logs a play count or skip count
* If repeat all is enabled, the queue will loop from the beginning when it it is finished.
* Otherwise, calling this method when the last item in the queue is being played will stop
* playback
* @see #setRepeat(int) to set the current repeat mode
*/
public void skip() {
Timber.i("Skipping song");
if (!mMediaPlayer.isComplete()) {
logPlay();
}
setMultiRepeat(0);
if (mMediaPlayer.getQueueIndex() < mQueue.size() - 1
|| mRepeat == REPEAT_ALL) {
// If we're in the middle of the queue, or repeat all is on, start the next song
mMediaPlayer.skip();
} else {
mMediaPlayer.setQueueIndex(0);
mMediaPlayer.pause();
}
}
/**
* Records a play or skip for the current song based on the current time of the backing
* {@link MediaPlayer} as returned by {@link #getCurrentPosition()}
*/
private void logPlay() {
Timber.i("Logging play count...");
if (getNowPlaying() != null) {
if (getCurrentPosition() > PLAY_COUNT_THRESHOLD
|| getCurrentPosition() > getDuration() / 2) {
// Log a play if we're passed a certain threshold or more than 50% in a song
// (whichever is smaller)
Timber.i("Marking song as played");
logPlayCount(getNowPlaying(), false);
} else if (getCurrentPosition() < SKIP_COUNT_THRESHOLD) {
// If we're not very far into this song, log a skip
Timber.i("Marking song as skipped");
logPlayCount(getNowPlaying(), true);
} else {
Timber.i("Not writing play count. Song was neither played nor skipped.");
}
}
}
/**
* Record a play or skip for a certain song
* @param song the song to change the play count of
* @param skip Whether the song was skipped (true if skipped, false if played)
*/
private void logPlayCount(Song song, boolean skip) {
Timber.i("Logging %s count to PlayCountStore for %s...", (skip) ? "skip" : "play", song.toString());
if (skip) {
mPlayCountStore.incrementSkipCount(song);
} else {
mPlayCountStore.incrementPlayCount(song);
mPlayCountStore.setPlayDateToNow(song);
}
Timber.i("Writing PlayCountStore to disk...");
mPlayCountStore.save();
}
/**
* Skips to the previous song in the queue
* If the song's current position is more than 5 seconds or 50% of the song (whichever is
* smaller), then the song will be restarted from the beginning instead.
* If this is called when the first item in the queue is being played, it will loop to the last
* song if repeat all is enabled, otherwise the current song will always be restarted
* @see #setRepeat(int) to set the current repeat mode
*/
public void skipPrevious() {
Timber.i("skipPrevious() called");
if ((getQueuePosition() == 0 && mRepeat != REPEAT_ALL)
|| getCurrentPosition() > SKIP_PREVIOUS_THRESHOLD
|| getCurrentPosition() > getDuration() / 2) {
Timber.i("Restarting current song...");
mMediaPlayer.seekTo(0);
mMediaPlayer.play();
updateNowPlaying();
} else {
Timber.i("Starting previous song...");
mMediaPlayer.skipPrevious();
}
}
/**
* Stops music playback
*/
public void stop() {
Timber.i("stop() called");
pause();
seekTo(0);
}
/**
* Seek to a specified position in the current song
* @param mSec The time (in milliseconds) to seek to
* @see MediaPlayer#seekTo(int)
*/
public void seekTo(int mSec) {
Timber.i("Seeking to %d", mSec);
mMediaPlayer.seekTo(mSec);
}
/**
* @return The {@link Song} that is currently being played
*/
public Song getNowPlaying() {
return mMediaPlayer.getNowPlaying();
}
/**
* @return Whether music is being played or not
* @see MediaPlayer#isPlaying()
*/
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
/**
* @return Whether the current song is getting ready to be played
*/
public boolean isPreparing() {
return mMediaPlayer.isPreparing();
}
/**
* @return The current queue. If shuffle is enabled, then the shuffled queue will be returned,
* otherwise the regular queue will be returned
*/
public List<Song> getQueue() {
// If you're using this method on the UI thread, consider replacing this method with
// return new ArrayList<>(mMediaPlayer.getQueue());
// to prevent components from accidentally changing the backing queue
return mMediaPlayer.getQueue();
}
/**
* @return The current index in the queue that is being played
*/
public int getQueuePosition() {
return mMediaPlayer.getQueueIndex();
}
/**
* @return The number of items in the current queue
*/
public int getQueueSize() {
return mMediaPlayer.getQueueSize();
}
/**
* @return The current seek position of the song that is playing
* @see MediaPlayer#getCurrentPosition()
*/
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
/**
* @return The length of the current song in milliseconds
* @see MediaPlayer#getDuration()
*/
public int getDuration() {
return mMediaPlayer.getDuration();
}
public void changeSong(int position) {
Timber.i("changeSong called (position = %d)", position);
mMediaPlayer.setQueueIndex(position);
}
public void setQueue(@NonNull List<Song> queue) {
Timber.i("setQueue called (%d songs)", queue.size());
setQueue(queue, mMediaPlayer.getQueueIndex());
}
public void setQueue(@NonNull List<Song> queue, int index) {
Timber.i("setQueue called (%d songs)", queue.size());
// If you're using this method on the UI thread, consider replacing the first line in this
// method with "mQueue = new ArrayList<>(queue);"
// to prevent components from accidentally changing the backing queue
mQueue = queue;
if (mShuffle) {
Timber.i("Shuffling new queue and starting from beginning");
shuffleQueue(index);
setBackingQueue(0);
} else {
Timber.i("Setting new backing queue (starting at index %d)", index);
setBackingQueue(index);
}
seekTo(0);
}
/**
* Changes the order of the current queue without interrupting playback
* @param queue The modified queue. This List should contain all of the songs currently in the
* queue, but in a different order to prevent discrepancies between the shuffle
* and non-shuffled queue.
* @param index The index of the song that is currently playing in the modified queue
*/
public void editQueue(@NonNull List<Song> queue, int index) {
Timber.i("editQueue called (index = %d)", index);
if (mShuffle) {
mQueueShuffled = queue;
} else {
mQueue = queue;
}
setBackingQueue(index);
}
/**
* Helper method to push changes in the queue to the backing {@link QueuedMediaPlayer}
* @see #setBackingQueue(int)
*/
private void setBackingQueue() {
Timber.i("setBackingQueue() called");
setBackingQueue(mMediaPlayer.getQueueIndex());
}
/**
* Helper method to push changes in the queue to the backing {@link QueuedMediaPlayer}. This
* method will set the queue to the appropriate shuffled or ordered list and apply the
* specified index as the replacement queue position
* @param index The new queue index to send to the backing {@link QueuedMediaPlayer}.
*/
private void setBackingQueue(int index) {
Timber.i("setBackingQueue() called (index = %d)", index);
if (mShuffle) {
mMediaPlayer.setQueue(mQueueShuffled, index);
} else {
mMediaPlayer.setQueue(mQueue, index);
}
}
/**
* Sets the repeat option to control what happens when a track finishes.
* @param repeat An integer representation of the repeat option. May be one of either
* {@link #REPEAT_NONE}, {@link #REPEAT_ALL}, {@link #REPEAT_ONE}.
*/
public void setRepeat(int repeat) {
Timber.i("Changing repeat setting to %d", repeat);
mRepeat = repeat;
switch (repeat) {
case REPEAT_ALL:
mMediaPlayer.enableRepeatAll();
break;
case REPEAT_ONE:
mMediaPlayer.enableRepeatOne();
break;
case REPEAT_NONE:
default:
mMediaPlayer.enableRepeatNone();
}
}
/**
* Sets the Multi-Repeat counter to repeat a song {@code count} times before proceeding to the
* next song
* @param count The number of times to repeat the song. When multi-repeat is enabled, the
* current song will be played back-to-back for the specified number of loops.
* Once this counter decrements to 0, playback will resume as it was before and the
* previous repeat option will be restored unless it was previously Repeat All. If
* Repeat All was enabled before Multi-Repeat, the repeat setting will be reset to
* Repeat none.
*/
public void setMultiRepeat(int count) {
Timber.i("Changing Multi-Repeat counter to %d", count);
mMultiRepeat = count;
mRemotePreferenceStore.setMultiRepeatCount(count);
if (count > 1) {
mMediaPlayer.enableRepeatOne();
} else {
setRepeat(mRepeat);
}
}
public int getMultiRepeatCount() {
return mMultiRepeat;
}
public void setSleepTimer(long endTimestampInMillis) {
Timber.i("Changing sleep timer end time to %d", endTimestampInMillis);
startSleepTimer(endTimestampInMillis);
mRemotePreferenceStore.setSleepTimerEndTime(endTimestampInMillis);
}
private void startSleepTimer(long endTimestampInMillis) {
if (endTimestampInMillis <= System.currentTimeMillis()) {
Timber.i("Sleep timer end time (%1$d) is in the past (currently %2$d). Stopping timer",
endTimestampInMillis, System.currentTimeMillis());
mHandler.removeCallbacks(mSleepTimerRunnable);
} else {
long delay = endTimestampInMillis - System.currentTimeMillis();
Timber.i("Setting sleep timer for %d ms", delay);
mHandler.postDelayed(mSleepTimerRunnable, delay);
}
}
private void onSleepTimerEnd() {
Timber.i("Sleep timer ended.");
pause();
updateUi();
postInfo(mContext.getString(R.string.confirm_sleep_timer_end));
}
public long getSleepTimerEndTime() {
return mRemotePreferenceStore.getSleepTimerEndTime();
}
/**
* Sets the shuffle option and immediately applies it to the queue
* @param shuffle The new shuffle option. {@code true} will switch the current playback to a
* copy of the current queue in a randomized order. {@code false} will restore
* the queue to its original order.
*/
public void setShuffle(boolean shuffle) {
if (shuffle) {
Timber.i("Enabling shuffle...");
shuffleQueue(getQueuePosition());
mMediaPlayer.setQueue(mQueueShuffled, 0);
} else {
Timber.i("Disabling shuffle...");
unshuffleQueue();
int position = mQueue.indexOf(getNowPlaying());
mMediaPlayer.setQueue(mQueue, position);
}
mShuffle = shuffle;
updateNowPlaying();
}
/**
* Adds a {@link Song} to the queue to be played after the current song
* @param song the song to enqueue
*/
public void queueNext(Song song) {
Timber.i("queueNext(Song) called");
int index = mQueue.isEmpty() ? 0 : mMediaPlayer.getQueueIndex() + 1;
if (mShuffle) {
mQueueShuffled.add(index, song);
mQueue.add(song);
} else {
mQueue.add(index, song);
}
setBackingQueue();
}
/**
* Adds a {@link List} of {@link Song}s to the queue to be played after the current song
* @param songs The songs to enqueue
*/
public void queueNext(List<Song> songs) {
Timber.i("queueNext(List<Song>) called");
int index = mQueue.isEmpty() ? 0 : mMediaPlayer.getQueueIndex() + 1;
if (mShuffle) {
mQueueShuffled.addAll(index, songs);
mQueue.addAll(songs);
} else {
mQueue.addAll(index, songs);
}
setBackingQueue();
}
/**
* Adds a {@link Song} to the end of the queue
* @param song The song to enqueue
*/
public void queueLast(Song song) {
Timber.i("queueLast(Song) called");
if (mShuffle) {
mQueueShuffled.add(song);
mQueue.add(song);
} else {
mQueue.add(song);
}
setBackingQueue();
}
/**
* Adds a {@link List} of {@link Song}s to the end of the queue
* @param songs The songs to enqueue
*/
public void queueLast(List<Song> songs) {
Timber.i("queueLast(List<Song>)");
if (mShuffle) {
mQueueShuffled.addAll(songs);
mQueue.addAll(songs);
} else {
mQueue.addAll(songs);
}
setBackingQueue();
}
/**
* Releases all resources and bindings associated with this MusicPlayer.
* Once this is called, this MusicPlayer can no longer be used.
*/
public void release() {
Timber.i("release() called");
((AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this);
mContext.unregisterReceiver(mHeadphoneListener);
// Make sure to disable the sleep timer to purge any delayed runnables in the message queue
startSleepTimer(0);
mFocused = false;
mCallback = null;
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaSession.release();
mMediaPlayer = null;
mContext = null;
}
/**
* @return The album artwork embedded in the current song
*/
public Bitmap getArtwork() {
return mArtwork;
}
/**
* @return The state that the backing {@link QueuedMediaPlayer is in}
* @see QueuedMediaPlayer#getState()
*/
public PlayerState getState() {
return mMediaPlayer.getState();
}
protected MediaSessionCompat getMediaSession() {
return mMediaSession;
}
@Override
public void onCompletion(Song completed) {
Timber.i("onCompletion called");
logPlayCount(completed, false);
if (mMultiRepeat > 1) {
Timber.i("Multi-Repeat (%d) is enabled. Restarting current song and decrementing.",
mMultiRepeat);
setMultiRepeat(mMultiRepeat - 1);
} else if (mMediaPlayer.isComplete()) {
updateNowPlaying();
updateUi();
}
}
@Override
public void onSongStart() {
Timber.i("Started new song");
mArtwork = Util.fetchFullArt(getNowPlaying());
updateNowPlaying();
updateUi();
}
@Override
public boolean onError(Throwable error) {
Timber.i(error, "Sending error message to UI...");
if (error instanceof FileNotFoundException) {
postError(mContext.getString(
R.string.message_play_error_not_found,
getNowPlaying().getSongName()));
} else {
postError(mContext.getString(
R.string.message_play_error_io_exception,
getNowPlaying().getSongName()));
}
return false;
}
/**
* A callback for receiving information about song changes -- useful for integrating
* {@link MusicPlayer} with other components
*/
public interface OnPlaybackChangeListener {
/**
* Called when a MusicPlayer changes songs. This method will always be called, even if the
* event was caused by an external source. Implement and attach this callback to provide
* more integration with external sources which requires up-to-date song information
* (i.e. to post a notification)
*
* This method will only be called after the current song changes -- not when the
* {@link MediaPlayer} changes states.
*/
void onPlaybackChange();
}
private static class MediaSessionCallback extends MediaSessionCompat.Callback {
/**
* A period of time added after a remote button press to delay handling the event. This
* delay allows the user to press the remote button multiple times to execute different
* actions
*/
private static final int REMOTE_CLICK_SLEEP_TIME_MS = 300;
private int mClickCount;
private MusicPlayer mMusicPlayer;
private Handler mHandler;
MediaSessionCallback(MusicPlayer musicPlayer) {
mHandler = new Handler();
mMusicPlayer = musicPlayer;
}
private final Runnable mButtonHandler = () -> {
if (mClickCount == 1) {
mMusicPlayer.togglePlay();
mMusicPlayer.updateUi();
} else if (mClickCount == 2) {
onSkipToNext();
} else {
onSkipToPrevious();
}
mClickCount = 0;
};
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
KeyEvent keyEvent = mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) {
if (keyEvent.getAction() == KeyEvent.ACTION_UP && !keyEvent.isLongPress()) {
onRemoteClick();
}
return true;
} else {
return super.onMediaButtonEvent(mediaButtonEvent);
}
}
private void onRemoteClick() {
mClickCount++;
mHandler.removeCallbacks(mButtonHandler);
mHandler.postDelayed(mButtonHandler, REMOTE_CLICK_SLEEP_TIME_MS);
}
@Override
public void onPlay() {
mMusicPlayer.play();
mMusicPlayer.updateUi();
}
@Override
public void onSkipToQueueItem(long id) {
mMusicPlayer.changeSong((int) id);
mMusicPlayer.updateUi();
}
@Override
public void onPause() {
mMusicPlayer.pause();
mMusicPlayer.updateUi();
}
@Override
public void onSkipToNext() {
mMusicPlayer.skip();
mMusicPlayer.updateUi();
}
@Override
public void onSkipToPrevious() {
mMusicPlayer.skipPrevious();
mMusicPlayer.updateUi();
}
@Override
public void onStop() {
mMusicPlayer.stop();
// Don't update the UI if this object has been released
if (mMusicPlayer.mContext != null) {
mMusicPlayer.updateUi();
}
}
@Override
public void onSeekTo(long pos) {
mMusicPlayer.seekTo((int) pos);
mMusicPlayer.updateUi();
}
}
/**
* Receives headphone connect and disconnect intents so that music may be paused when headphones
* are disconnected
*/
public static class HeadsetListener extends BroadcastReceiver {
private MusicPlayer mInstance;
public HeadsetListener(MusicPlayer instance) {
mInstance = instance;
}
@Override
public void onReceive(Context context, Intent intent) {
if (!mInstance.isPlaying()) {
return;
}
boolean unplugged = ACTION_HEADSET_PLUG.equals(intent.getAction())
&& intent.getIntExtra("state", -1) == 0;
boolean becomingNoisy = ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction());
if (unplugged || becomingNoisy) {
mInstance.pause();
mInstance.updateUi();
}
}
}
} |
package com.obsidium.focusbracket;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.github.ma1co.pmcademo.app.BaseActivity;
import com.sony.scalar.hardware.CameraEx;
import com.sony.scalar.sysutil.ScalarProperties;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
public class FocusActivity extends BaseActivity implements SurfaceHolder.Callback, CameraEx.ShutterListener
{
private static final int COUNTDOWN_SECONDS = 5;
private SurfaceHolder m_surfaceHolder;
private CameraEx m_camera;
private CameraEx.AutoPictureReviewControl m_autoReviewControl;
private int m_pictureReviewTime;
private Handler m_handler = new Handler();
private FocusScaleView m_focusScaleView;
private LinearLayout m_lFocusScale;
private TextView m_tvMsg;
private TextView m_tvInstructions;
enum State { error, setMin, setMax, setNumPics, shoot }
private State m_state = State.setMin;
private int m_minFocus;
private int m_maxFocus;
private int m_curFocus;
private int m_focusBeforeDrive;
private ArrayList<Integer> m_pictureCounts;
private int m_pictureCountIndex;
private LinkedList<Integer> m_focusQueue;
private boolean m_waitingForFocus;
private int m_countdown;
private final Runnable m_countDownRunnable = new Runnable()
{
@Override
public void run()
{
if (--m_countdown > 0)
{
m_tvMsg.setText(String.format("Starting in %d...", m_countdown));
m_handler.postDelayed(this, 1000);
}
else
{
m_tvMsg.setVisibility(View.GONE);
startShooting();
}
}
};
private final Runnable m_checkFocusRunnable = new Runnable()
{
@Override
public void run()
{
if (m_waitingForFocus && m_focusBeforeDrive == m_curFocus)
focus();
}
};
// Built-in images
private static final int p_16_dd_parts_rec_focuscontrol_near = 0x01080ddd;
private static final int p_16_dd_parts_rec_focuscontrol_far = 0x010807f9;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_focus);
if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler))
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
m_surfaceHolder = surfaceView.getHolder();
m_surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
m_focusScaleView = (FocusScaleView)findViewById(R.id.vFocusScale);
m_lFocusScale = (LinearLayout)findViewById(R.id.lFocusScale);
m_tvMsg = (TextView)findViewById(R.id.tvMsg);
m_tvInstructions = (TextView)findViewById(R.id.tvInstructions);
}
@Override
protected void onResume()
{
super.onResume();
m_camera = CameraEx.open(0, null);
m_surfaceHolder.addCallback(this);
m_autoReviewControl = new CameraEx.AutoPictureReviewControl();
m_camera.setAutoPictureReviewControl(m_autoReviewControl);
//noinspection ResourceType
((ImageView)findViewById(R.id.ivRight)).setImageResource(p_16_dd_parts_rec_focuscontrol_far);
//noinspection ResourceType
((ImageView)findViewById(R.id.ivLeft)).setImageResource(p_16_dd_parts_rec_focuscontrol_near);
m_camera.setShutterListener(this);
m_camera.setFocusDriveListener(new CameraEx.FocusDriveListener()
{
@Override
public void onChanged(CameraEx.FocusPosition focusPosition, CameraEx cameraEx)
{
Logger.info("FocusDriveListener: currentPosition " + focusPosition.currentPosition);
m_handler.removeCallbacks(m_checkFocusRunnable);
m_focusScaleView.setMaxPosition(focusPosition.maxPosition);
m_focusScaleView.setCurPosition(focusPosition.currentPosition);
m_curFocus = focusPosition.currentPosition;
if (m_waitingForFocus)
{
if (m_curFocus == m_focusQueue.getFirst())
{
// Focused, take picture
Logger.info("Taking picture (FocusDriveListener)");
takePicture();
}
else
focus();
}
}
});
setDefaults();
setState(State.setMin);
}
// CameraEx.ShutterListener
@Override
public void onShutter(int i, CameraEx cameraEx)
{
// i: 0 = success, 1 = canceled, 2 = error
Logger.info("onShutter (i " + i + ")");
m_camera.cancelTakePicture();
if (i == 0)
{
m_focusQueue.removeFirst();
if (m_focusQueue.isEmpty())
{
m_tvMsg.setText("\uE013 Done!");
m_tvMsg.setVisibility(View.VISIBLE);
m_tvInstructions.setText("Press \uE04C to start over...");
m_tvInstructions.setVisibility(View.VISIBLE);
}
else
{
// Move to next focus position
startFocusing();
}
}
}
private void takePicture()
{
m_tvMsg.setVisibility(View.GONE);
m_tvInstructions.setVisibility(View.GONE);
m_waitingForFocus = false;
m_camera.burstableTakePicture();
}
private void focus()
{
final int nextFocus = m_focusQueue.getFirst();
m_focusBeforeDrive = m_curFocus;
if (m_curFocus == nextFocus)
{
Logger.info("Taking picture (focus)");
takePicture();
}
else
{
final int absDiff = Math.abs(m_curFocus - nextFocus);
final int speed;
if (absDiff > 25)
speed = 4;
else if (absDiff > 20)
speed = 3;
else if (absDiff > 15)
speed = 2;
else
speed = 1;
Logger.info("Starting focus drive (speed " + speed + ")");
m_camera.startOneShotFocusDrive(m_curFocus < nextFocus ? CameraEx.FOCUS_DRIVE_DIRECTION_FAR : CameraEx.FOCUS_DRIVE_DIRECTION_NEAR, speed);
// startOneShotFocusDrive won't always trigger our FocusDriveListener
m_handler.postDelayed(m_checkFocusRunnable, 50);
}
}
private void startFocusing()
{
m_waitingForFocus = true;
m_tvMsg.setText("Focusing...");
m_tvMsg.setVisibility(View.VISIBLE);
m_tvInstructions.setText(String.format("%d remaining", m_focusQueue.size()));
m_tvInstructions.setVisibility(View.VISIBLE);
focus();
}
private void startShooting()
{
m_tvMsg.setVisibility(View.GONE);
startFocusing();
}
private void initFocusQueue()
{
m_focusQueue = new LinkedList<Integer>();
final int focusDiff = m_maxFocus - m_minFocus;
final int pictureCount = m_pictureCounts.get(m_pictureCountIndex);
final int step = (int)((float)focusDiff / (float)(pictureCount - 1));
int focus = m_minFocus;
for (int i = 0; i < pictureCount; ++i, focus += step)
m_focusQueue.addLast(focus);
}
private void initPictureCounts()
{
m_pictureCounts = new ArrayList<Integer>();
final int focusDiff = m_maxFocus - m_minFocus;
int lastStep = 0;
for (int i = 3; i < focusDiff; ++i)
{
final int step = (int)((float)focusDiff / (float)(i - 1));
if (step > 1 && step != lastStep)
{
m_pictureCounts.add(i);
lastStep = step;
}
}
m_pictureCounts.add(focusDiff);
m_pictureCountIndex = 0;
}
private void updatePictureCountMsg()
{
m_tvMsg.setText(String.valueOf(m_pictureCounts.get(m_pictureCountIndex)));
}
private void initControlsFromState()
{
switch (m_state)
{
case setMin:
m_tvMsg.setVisibility(View.GONE);
m_lFocusScale.setVisibility(View.VISIBLE);
m_focusScaleView.setMinPosition(0);
m_tvInstructions.setVisibility(View.VISIBLE);
m_tvInstructions.setText("Set minimum focus distance, \uE04C to confirm");
break;
case setMax:
m_tvInstructions.setText("Set maximum focus distance, \uE04C to confirm");
break;
case setNumPics:
m_tvInstructions.setText("Use dial to select number of pictures, \uE04C to confirm");
m_tvMsg.setVisibility(View.VISIBLE);
m_lFocusScale.setVisibility(View.GONE);
break;
case shoot:
m_tvMsg.setVisibility(View.VISIBLE);
m_tvMsg.setText(String.format("Starting in %d...", m_countdown));
m_tvInstructions.setVisibility(View.GONE);
break;
}
}
/*
Sets camera default parameters (manual mode, single shooting, manual focus, picture review)
*/
private void setDefaults()
{
final Camera.Parameters params = m_camera.createEmptyParameters();
final CameraEx.ParametersModifier modifier = m_camera.createParametersModifier(params);
params.setSceneMode(CameraEx.ParametersModifier.SCENE_MODE_MANUAL_EXPOSURE);
modifier.setDriveMode(CameraEx.ParametersModifier.DRIVE_MODE_SINGLE);
params.setFocusMode(CameraEx.ParametersModifier.FOCUS_MODE_MANUAL);
modifier.setSelfTimer(0);
m_camera.getNormalCamera().setParameters(params);
/*
modifier.isFocusDriveSupported() returns false on ILCE-5100, focus drive is working anyway...
This is how SmartRemote checks for it:
*/
final String platformVersion = ScalarProperties.getString(ScalarProperties.PROP_VERSION_PLATFORM);
if (platformVersion != null)
{
final String[] split = platformVersion.split("\\Q.\\E");
if (split.length >= 2)
{
if (Integer.parseInt(split[1]) < 3)
{
m_state = State.error;
m_tvMsg.setVisibility(View.VISIBLE);
m_tvMsg.setText("ERROR: Focus drive not supported");
}
}
}
// Disable picture review
m_pictureReviewTime = m_autoReviewControl.getPictureReviewTime();
m_autoReviewControl.setPictureReviewTime(0);
}
private void abortShooting()
{
m_waitingForFocus = false;
m_handler.removeCallbacks(m_checkFocusRunnable);
m_handler.removeCallbacks(m_countDownRunnable);
m_focusQueue = null;
m_pictureCounts = null;
}
private void setState(State state)
{
m_state = state;
switch (m_state)
{
case setMin:
m_minFocus = 0;
break;
case setMax:
m_maxFocus = 0;
break;
case setNumPics:
initPictureCounts();
updatePictureCountMsg();
break;
case shoot:
initFocusQueue();
m_countdown = COUNTDOWN_SECONDS;
m_handler.postDelayed(m_countDownRunnable, 1000);
break;
}
initControlsFromState();
}
@Override
protected boolean onUpperDialChanged(int value)
{
if (m_state == State.setNumPics)
{
if (value < 0)
{
if (m_pictureCountIndex > 0)
--m_pictureCountIndex;
}
else
{
if (m_pictureCountIndex < m_pictureCounts.size() - 1)
++m_pictureCountIndex;
}
updatePictureCountMsg();
}
return true;
}
@Override
protected boolean onEnterKeyUp() {
return true;
}
@Override
protected boolean onEnterKeyDown()
{
// Don't use onEnterKeyUp - we sometimes get an onEnterKeyUp event when launching the app
switch (m_state)
{
case setMin:
m_minFocus = m_curFocus;
m_focusScaleView.setMinPosition(m_curFocus);
setState(State.setMax);
break;
case setMax:
if (m_curFocus > m_minFocus)
{
m_maxFocus = m_curFocus;
setState(State.setNumPics);
}
break;
case setNumPics:
setState(State.shoot);
break;
case shoot:
abortShooting();
setState(State.setMin);
break;
}
return true;
}
@Override
protected boolean onMenuKeyUp()
{
onBackPressed();
return true;
}
@Override
protected void onPause()
{
super.onPause();
abortShooting();
m_surfaceHolder.removeCallback(this);
m_autoReviewControl.setPictureReviewTime(m_pictureReviewTime);
m_camera.setAutoPictureReviewControl(null);
m_autoReviewControl = null;
m_camera.getNormalCamera().stopPreview();
m_camera.release();
m_camera = null;
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
try
{
Camera cam = m_camera.getNormalCamera();
cam.setPreviewDisplay(holder);
cam.startPreview();
}
catch (IOException e)
{
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {}
@Override
protected void setColorDepth(boolean highQuality)
{
super.setColorDepth(false);
}
} |
package com.quartzodev.adapters;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.amulyakhare.textdrawable.TextDrawable;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.quartzodev.buddybook.GlideApp;
import com.quartzodev.buddybook.R;
import com.quartzodev.data.Book;
import com.quartzodev.fragments.BookGridFragment;
import com.quartzodev.utils.TextUtils;
import com.quartzodev.views.DynamicImageView;
import java.util.ArrayList;
import java.util.List;
public class BookGridAdapter extends RecyclerView.Adapter<BookGridViewHolder> {
private final int POS_BOOK_LENT = 1;
private final int POS_BOOK_AVAILABLE = 2;
private final int POS_BOOK_CUSTOM_LENT = 3;
private final int POS_BOOK_CUSTOM_AVAILABLE = 4;
private Context mContext;
private List<Book> mBookList = new ArrayList<>();
private BookGridFragment.OnGridFragmentInteractionListener mListener;
private String mFolderId;
private int mMenuId;
/**
* Here is the key method to apply the animation
*/
private int lastPosition = -1;
public BookGridAdapter(Context mContext,
List<Book> bookList,
BookGridFragment.OnGridFragmentInteractionListener listener,
int menuId) {
this.mContext = mContext;
this.mBookList = bookList;
this.mListener = listener;
this.mMenuId = menuId;
}
@Override
public BookGridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == POS_BOOK_LENT) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_lent, parent, false);
} else if (viewType == POS_BOOK_CUSTOM_LENT) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_custom, parent, false);
} else if (viewType == POS_BOOK_CUSTOM_AVAILABLE) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book_custom_available, parent, false);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_book, parent, false);
}
return new BookGridViewHolder(view);
}
@Override
public int getItemViewType(int position) {
final Book book = new ArrayList<>(mBookList).get(position);
if(mFolderId == null){
return 0;
}
if(book.getLend() != null){
if(book.isCustom()){
return POS_BOOK_CUSTOM_LENT;
}
return POS_BOOK_LENT;
}else if (book.isCustom()) {
return POS_BOOK_CUSTOM_AVAILABLE;
}
return POS_BOOK_AVAILABLE;
}
public void setFolderId(String folderId) {
mFolderId = folderId;
}
public void swap(List<Book> bookApiList) {
if (bookApiList != null) {
bookApiList.removeAll(mBookList);
if(!bookApiList.isEmpty()) {
if(!mBookList.isEmpty()) {
for (Book book1 : bookApiList) {
for (Book book2 : mBookList) {
if(book1.getId() != null && book2.getId() != null){
if(book1.getId().equals(book2.getId())){
int position = mBookList.indexOf(book2);
mBookList.remove(position);
mBookList.add(position,book1);
break;
}
}else if(book1.getIdProvider() != null && book2.getIdProvider() != null){
if(book1.getIdProvider().equals(book2.getIdProvider())){
int position = mBookList.indexOf(book2);
mBookList.remove(position);
mBookList.add(position,book1);
break;
}
}
}
mBookList.add(0,book1);
}
}else{
mBookList.addAll(bookApiList);
}
}else{
mBookList.clear();
}
this.notifyDataSetChanged();
}
}
private void setAnimation(View viewToAnimate, int position) {
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
@Override
public void onBindViewHolder(final BookGridViewHolder holder, int position) {
try {
final Book book = new ArrayList<>(mBookList).get(position);
holder.textViewBookTitle.setText(book.getVolumeInfo().getTitle());
holder.textViewBookAuthor.setText(book.getVolumeInfo().getAuthors() == null ? "" : book.getVolumeInfo().getAuthors().get(0));
holder.toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClickListenerBookGridInteraction(mFolderId, book, (DynamicImageView) holder.imageViewThumbnail);
}
});
if (!holder.toolbar.getMenu().hasVisibleItems()) {
holder.toolbar.inflateMenu(mMenuId);
if (book.getLend() != null && holder.toolbar.getMenu().findItem(R.id.action_lend) != null) {
holder.toolbar.getMenu().findItem(R.id.action_lend)
.setTitle(mContext.getString(R.string.action_return_lend));
}
}
holder.toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int menuId = item.getItemId();
switch (menuId) {
case R.id.action_delete:
mListener.onDeleteBookClickListener(mFolderId, book);
break;
case R.id.action_move_folder:
mListener.onAddBookToFolderClickListener(mFolderId, book);
break;
case R.id.action_copy:
mListener.onCopyBookToFolderClickListener(mFolderId, book);
break;
case R.id.action_lend:
if (item.getTitle().equals(mContext.getString(R.string.action_return_lend))) {
mListener.onReturnBookClickListener(book);
} else {
mListener.onLendBookClickListener(book, item);
}
break;
}
return false;
}
});
if (book.getVolumeInfo().getImageLink() != null) {
GlideApp.with(mContext)
.load(book.getVolumeInfo().getImageLink().getThumbnail())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imageViewThumbnail);
holder.imageViewThumbnail.setContentDescription(
String.format(mContext.getString(R.string.cover_book_cd), book.getVolumeInfo()
.getTitle()));
} else if (book.isCustom()) {
TextDrawable drawable = TextDrawable.builder()
.buildRect(TextUtils.getFirstLetterTitle(book), Color.BLUE);
holder.imageViewThumbnail.setContentDescription(
String.format(mContext.getString(R.string.cover_book_cd), book.getVolumeInfo()
.getTitle()));
holder.imageViewThumbnail.setImageDrawable(drawable);
} else {
TextDrawable drawable = TextDrawable.builder()
.buildRect(TextUtils.getFirstLetterTitle(book), Color.RED);
holder.imageViewThumbnail.setImageDrawable(drawable);
}
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClickListenerBookGridInteraction(mFolderId, book, (DynamicImageView) holder.imageViewThumbnail);
}
});
// call Animation function
setAnimation(holder.itemView, position);
}catch (Exception ex){
Log.wtf("TAG",ex.getMessage());
}
}
@Override
public int getItemCount() {
return mBookList != null ? mBookList.size() : 0;
}
} |
package won.matcher.service.crawler.actor;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.apache.jena.query.Dataset;
import org.apache.jena.shared.Lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.cluster.pubsub.DistributedPubSub;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import won.matcher.service.common.event.AtomEvent;
import won.matcher.service.common.event.Cause;
import won.matcher.service.common.service.sparql.SparqlService;
import won.matcher.service.crawler.config.CrawlConfig;
import won.matcher.service.crawler.exception.CrawlWrapperException;
import won.matcher.service.crawler.msg.CrawlUriMessage;
import won.matcher.service.crawler.msg.ResourceCrawlUriMessage;
import won.matcher.service.crawler.service.CrawlSparqlService;
import won.protocol.exception.IncorrectPropertyCountException;
import won.protocol.model.AtomState;
import won.protocol.rest.DatasetResponseWithStatusCodeAndHeaders;
import won.protocol.rest.LinkedDataFetchingException;
import won.protocol.util.AtomModelWrapper;
import won.protocol.util.RdfUtils;
import won.protocol.util.linkeddata.LinkedDataSourceBase;
import won.protocol.vocabulary.WON;
@Component
@Scope("prototype")
public class WorkerCrawlerActor extends UntypedActor {
private LoggingAdapter log = Logging.getLogger(getContext().system(), this);
@Autowired
private LinkedDataSourceBase linkedDataSource;
@Autowired
private CrawlSparqlService sparqlService;
@Autowired
private CrawlConfig config;
private ActorRef pubSubMediator;
@Override
public void preStart() {
// initialize the distributed event bus to send atom events to the matchers
pubSubMediator = DistributedPubSub.get(getContext().system()).mediator();
}
/**
* Receives messages with an URI and processes them by requesting the resource,
* saving it to a triple store, extracting URIs from content and answering the
* sender.
*
* @param msg if type is {@link CrawlUriMessage} then process it
*/
@Override
public void onReceive(Object msg) throws RestClientException {
if (!(msg instanceof CrawlUriMessage)) {
unhandled(msg);
return;
}
CrawlUriMessage uriMsg = (CrawlUriMessage) msg;
if (!uriMsg.getStatus().equals(CrawlUriMessage.STATUS.PROCESS)
&& !uriMsg.getStatus().equals(CrawlUriMessage.STATUS.SAVE)) {
unhandled(msg);
return;
}
crawlUri(uriMsg);
}
private void crawlUri(CrawlUriMessage uriMsg) {
Dataset ds = null;
List<String> etags = null;
Lock lock = null;
try {
// check if resource is already downloaded
if (uriMsg instanceof ResourceCrawlUriMessage) {
ResourceCrawlUriMessage resMsg = ((ResourceCrawlUriMessage) uriMsg);
if (resMsg.getSerializedResource() != null && resMsg.getSerializationFormat() != null) {
// TODO: this should be optimized, why deserialize the resource here when we
// just want to save it in the RDF
// store? How to insert this serialized resource into the SPARQL endpoint?
ds = SparqlService.deserializeDataset(resMsg.getSerializedResource(),
resMsg.getSerializationFormat());
}
}
// download resource if not already downloaded
if (ds == null) {
// use ETag/If-None-Match Headers to make the process more efficient
HttpHeaders httpHeaders = new HttpHeaders();
if (uriMsg.getResourceETagHeaderValues() != null && !uriMsg.getResourceETagHeaderValues().isEmpty()) {
String ifNoneMatchHeaderValue = StringUtils
.collectionToDelimitedString(uriMsg.getResourceETagHeaderValues(), ", ");
httpHeaders.add("If-None-Match", ifNoneMatchHeaderValue);
}
DatasetResponseWithStatusCodeAndHeaders datasetWithHeaders = linkedDataSource
.getDatasetWithHeadersForResource(URI.create(uriMsg.getUri()), httpHeaders);
ds = datasetWithHeaders.getDataset();
etags = datasetWithHeaders.getResponseHeaders().get("ETag");
// if dataset was not modified (304) we can treat the current crawl uri as done
if (ds == null && datasetWithHeaders.getStatusCode() == 304) {
sendDoneUriMessage(uriMsg, uriMsg.getWonNodeUri(), etags);
return;
}
// if there is paging activated and the won node tells us that there is more
// data (previous link)
// to be downloaded, then we add this link to the crawling process too
String prevLink = linkedDataSource.getPreviousLinkFromDatasetWithHeaders(datasetWithHeaders);
if (prevLink != null) {
CrawlUriMessage newUriMsg = new CrawlUriMessage(uriMsg.getBaseUri(), prevLink,
uriMsg.getWonNodeUri(), CrawlUriMessage.STATUS.PROCESS, System.currentTimeMillis(),
null);
getSender().tell(newUriMsg, getSelf());
}
}
lock = ds == null ? null : ds.getLock();
lock.enterCriticalSection(true);
// Save dataset to triple store
sparqlService.updateNamedGraphsOfDataset(ds);
String wonNodeUri = extractWonNodeUri(ds, uriMsg.getUri());
if (wonNodeUri == null) {
wonNodeUri = uriMsg.getWonNodeUri();
}
// do nothing more here if the STATUS of the message was SAVE
if (uriMsg.getStatus().equals(CrawlUriMessage.STATUS.SAVE)) {
log.debug("processed crawl uri event {} with status 'SAVE'", uriMsg);
return;
}
// extract URIs from current resource and send extracted URI messages back to
// sender
log.debug("Extract URIs from message {}", uriMsg);
Set<CrawlUriMessage> newCrawlMessages = sparqlService.extractCrawlUriMessages(uriMsg.getBaseUri(),
wonNodeUri);
for (CrawlUriMessage newMsg : newCrawlMessages) {
getSender().tell(newMsg, getSelf());
}
// signal sender that this URI is processed and save meta data about crawling
// the URI.
// This needs to be done after all extracted URI messages have been sent to
// guarantee consistency
// in case of failure
sendDoneUriMessage(uriMsg, wonNodeUri, etags);
// if this URI/dataset was an atom then send an event to the distributed event
if (AtomModelWrapper.isAAtom(ds)) {
AtomModelWrapper atomModelWrapper = new AtomModelWrapper(ds, false);
AtomState state = atomModelWrapper.getAtomState();
AtomEvent.TYPE type = state.equals(AtomState.ACTIVE) ? AtomEvent.TYPE.ACTIVE : AtomEvent.TYPE.INACTIVE;
log.debug("Created atom event for atom uri {}", uriMsg.getUri());
long crawlDate = System.currentTimeMillis();
AtomEvent atomEvent = new AtomEvent(uriMsg.getUri(), wonNodeUri, type, crawlDate, ds, Cause.CRAWLED);
pubSubMediator.tell(new DistributedPubSubMediator.Publish(atomEvent.getClass().getName(), atomEvent),
getSelf());
}
} catch (RestClientException e1) {
// usually happens if the fetch of the dataset fails e.g.
// HttpServerErrorException, HttpClientErrorException
log.debug("Exception during crawling: " + e1);
throw new CrawlWrapperException(e1, uriMsg);
} catch (LinkedDataFetchingException e) {
log.debug("Exception during crawling: " + e);
Throwable cause = e.getCause();
if (cause instanceof HttpClientErrorException
&& Objects.equals(((HttpClientErrorException) cause).getStatusCode(), HttpStatus.GONE)) {
log.debug("Uri used to exist, but has been deleted, marking uri as done");
sendDoneUriMessage(uriMsg, uriMsg.getWonNodeUri(), etags);
} else {
throw new CrawlWrapperException(e, uriMsg);
}
} catch (Exception e) {
log.debug("Exception during crawling: " + e);
throw new CrawlWrapperException(e, uriMsg);
} finally {
if (lock != null) {
lock.leaveCriticalSection();
}
}
}
/**
* Extract won node uri from a won resource
*
* @param ds resource as dataset
* @param uri uri that represents resource
* @return won node uri or null if link to won node is not linked in the
* resource
*/
private String extractWonNodeUri(Dataset ds, String uri) {
try {
return RdfUtils.findOnePropertyFromResource(ds, URI.create(uri), WON.wonNode).asResource().getURI();
} catch (IncorrectPropertyCountException e) {
return null;
}
}
private void sendDoneUriMessage(CrawlUriMessage sourceUriMessage, String wonNodeUri, Collection<String> etags) {
long crawlDate = System.currentTimeMillis();
CrawlUriMessage uriDoneMsg = new CrawlUriMessage(sourceUriMessage.getUri(), sourceUriMessage.getBaseUri(),
wonNodeUri, CrawlUriMessage.STATUS.DONE, crawlDate, etags);
String ifNoneMatch = sourceUriMessage.getResourceETagHeaderValues() != null
? String.join(", ", sourceUriMessage.getResourceETagHeaderValues())
: "<None>";
String responseETags = etags != null ? String.join(", ", etags) : "<None>";
log.debug("Crawling done for URI {} with ETag Header Values {} (If-None-Match request value: {})",
uriDoneMsg.getUri(), responseETags, ifNoneMatch);
getSender().tell(uriDoneMsg, getSelf());
}
public void setSparqlService(final CrawlSparqlService sparqlService) {
this.sparqlService = sparqlService;
}
} |
package com.tehran.traffic;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import org.acra.ACRA;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.sender.HttpSender;
/**
* This is a subclass of {@link Application} used to provide shared objects for this app, such as
* the {@link Tracker}.
*/
@ReportsCrashes(
reportType = HttpSender.Type.JSON,
httpMethod = HttpSender.Method.PUT,
formUri = "https://collector.tracepot.com/1bb22253",
mode = ReportingInteractionMode.DIALOG,
resToastText = R.string.crash_toast_text, // optional, displayed as soon as the crash occurs, before collecting data which can take a few seconds
resDialogText = R.string.crash_dialog_text,
resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. When defined, adds a user text field input with this text resource as a label
resDialogEmailPrompt = R.string.crash_user_email_label, // optional. When defined, adds a user email text entry with this text resource as label. The email address will be populated from SharedPreferences and will be provided as an ACRA field if configured.
resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
)
public class AnalyticsApplication extends Application {
//Logging TAG
private static final String TAG = "AnalyticsApplication";
private Tracker mTracker;
public AnalyticsApplication() {
super();
}
@Override
public void onCreate() {
super.onCreate();
// The following line triggers the initialization of ACRA
ACRA.init(this);
}
public synchronized Tracker getTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
mTracker = analytics.newTracker(R.xml.analytics_app_tracker);
}
return mTracker;
}
} |
package com.tobi.movies;
import com.tobi.movies.backend.Backend;
import com.tobi.movies.popularstream.ApiMoviePoster;
import com.tobi.movies.popularstream.ApiMoviePosterConverter;
import com.tobi.movies.popularstream.MoviePoster;
import com.tobi.movies.popularstream.PopularStreamApiDatasource;
import com.tobi.movies.popularstream.PopularStreamRepository;
import com.tobi.movies.posterdetails.ApiMovieDetails;
import com.tobi.movies.posterdetails.ApiMovieDetailsConverter;
import com.tobi.movies.posterdetails.MovieDetails;
import com.tobi.movies.posterdetails.MovieDetailsApiDatasource;
import com.tobi.movies.posterdetails.MovieDetailsRepository;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class ApplicationDependencies implements Dependencies {
private ImageLoader imageLoader;
private Backend backend;
private PopularStreamRepository streamRepository;
private MovieDetailsRepository movieDetailsRepository;
@Override
public ImageLoader imageLoader() {
if (imageLoader == null) {
imageLoader = createImageLoader();
}
return imageLoader;
}
@Override
public PopularStreamRepository streamRepository() {
if (streamRepository == null) {
streamRepository = createStreamRepository();
}
return streamRepository;
}
@Override
public MovieDetailsRepository movieDetailsRepository() {
if (movieDetailsRepository == null) {
movieDetailsRepository = createMovieDetailsRepository();
}
return movieDetailsRepository;
}
@Override
public Scheduler createSubscriberThread() {
return Schedulers.io();
}
@Override
public Scheduler createObserverThread() {
return AndroidSchedulers.mainThread();
}
protected MovieDetailsRepository createMovieDetailsRepository() {
return new MovieDetailsRepository(
createMovieDetailsApiSource(),
createMovieDetailsConverter()
);
}
protected ImageLoader createImageLoader() {
return new ImageLoader();
}
protected Converter<ApiMoviePoster, MoviePoster> createPosterConverter() {
return new ApiMoviePosterConverter();
}
protected PopularStreamApiDatasource createStreamApiDataSource() {
return new PopularStreamApiDatasource(backend());
}
private PopularStreamRepository createStreamRepository() {
return new PopularStreamRepository(
createStreamApiDataSource(),
createSubscriberThread(),
createObserverThread(),
createPosterConverter()
);
}
protected Converter<ApiMovieDetails, MovieDetails> createMovieDetailsConverter() {
return new ApiMovieDetailsConverter();
}
protected MovieDetailsApiDatasource createMovieDetailsApiSource() {
return new MovieDetailsApiDatasource(backend());
}
protected Backend backend() {
if (backend == null) {
throw new IllegalStateException("Backend should be provided via dagger");
}
return backend;
}
@Override
public void setBackend(Backend backend) {
this.backend = backend;
}
} |
package org.jaggeryjs.modules.ws.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
public class XSLTTransformer {
public static final String WSDL2SIG_XSL_LOCATION = "xslt/wsdl2sig.xslt";
public static final String JSSTUB_XSL_LOCATION = "xslt/jsstub.xslt";
public static final String WSDL10TO20_XSL_LOCATION = "xslt/wsdl11to20.xslt";
private static Log log = LogFactory.getLog(XSLTTransformer.class);
static {
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
}
public XSLTTransformer() {
}
public static DOMSource getSigStream(InputStream wsdlInStream, Map paramMap)
throws TransformerFactoryConfigurationError, TransformerException,
ParserConfigurationException {
Source wsdlSource = new StreamSource(wsdlInStream);
InputStream sigStream =
XSLTTransformer.class.getClassLoader().getResourceAsStream(WSDL2SIG_XSL_LOCATION);
Source wsdl2sigXSLTSource = new StreamSource(sigStream);
DocumentBuilder docB = getSecuredDocumentBuilder(false);
Document docSig = docB.newDocument();
Result resultSig = new DOMResult(docSig);
transform(wsdlSource, wsdl2sigXSLTSource, resultSig, paramMap, new URIResolver() {
@Override
public Source resolve(String href, String base) throws TransformerException {
String xsd = href.substring(href.toLowerCase().indexOf("?xsd=") + 5);
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return new StreamSource(new ByteArrayInputStream(outputStream.toByteArray()));
} catch (Exception e) {
log.error("Error while printing xsd : " + xsd, e);
throw new TransformerException(e);
}
}
});
return new DOMSource(docSig);
}
public static void generateStub(Source xmlIn, Result result, Map paramMap)
throws TransformerException {
try (InputStream stubXSLTStream = XSLTTransformer.class.getClassLoader()
.getResourceAsStream(JSSTUB_XSL_LOCATION);) {
Source stubXSLSource = new StreamSource(stubXSLTStream);
transform(xmlIn, stubXSLSource, result, paramMap, new URIResolver() {
public Source resolve(String href, String base) {
InputStream is = XSLTTransformer.class.getResourceAsStream(href);
return new StreamSource(is);
}
});
} catch (IOException e) {
log.error("Error while handling inputstream: ", e);
throw new TransformerException(e);
}
}
public static InputStream getWSDL2(InputStream wsdl1InStream, Map paramMap) throws TransformerException, ParserConfigurationException {
InputStream wsdl10to20xslt =
XSLTTransformer.class.getClassLoader().getResourceAsStream(WSDL10TO20_XSL_LOCATION);
InputStream wsdlIS;
Source wsdl10Source = new StreamSource(wsdl1InStream);
DocumentBuilder docB = getSecuredDocumentBuilder(false);
Document docWSDL = docB.newDocument();
Result resultWSDL20 = new DOMResult(docWSDL);
Source wsdlXSLSource = new StreamSource(wsdl10to20xslt);
try {
transform(wsdl10Source, wsdlXSLSource, resultWSDL20, paramMap, new URIResolver() {
public Source resolve(String href, String base) {
InputStream is = XSLTTransformer.class.getResourceAsStream(href);
Source isSource = new StreamSource(is);
try {
is.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return isSource;
}
});
ByteArrayOutputStream wsdl20OutputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(docWSDL);
Result outputTarget = new StreamResult(wsdl20OutputStream);
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlSource, outputTarget);
wsdlIS = new ByteArrayInputStream(wsdl20OutputStream.toByteArray());
} catch (TransformerException e) {
log.error(e.getMessage(), e);
throw e;
} finally {
try {
wsdl10to20xslt.close();
} catch (IOException ignore) {
log.error("Unable to close the XSLT used to transform WSDL 1.1 to 2.0", ignore);
}
}
return wsdlIS;
}
public static void transform(Source xmlIn, Source xslIn, Result result, Map paramMap,
URIResolver uriResolver) throws TransformerException {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setURIResolver(uriResolver);
Transformer transformer = transformerFactory.newTransformer(xslIn);
if (paramMap != null) {
Set set = paramMap.keySet();
for (Object aSet : set) {
String key = (String) aSet;
String value = (String) paramMap.get(key);
transformer.setParameter(key, value);
}
}
transformer.transform(xmlIn, result);
} catch (TransformerException e) {
log.error(e.getMessage(), e);
throw e;
}
}
/**
* This method provides a secured document builder which will secure XXE attacks.
*
* @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
* @return DocumentBuilder
* @throws ParserConfigurationException
*/
public static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setIgnoringComments(setIgnoreComments);
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setExpandEntityReferences(false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
}
});
return documentBuilder;
}
} |
package com.xeiam.xchange.btcchina.service.polling;
import static com.xeiam.xchange.btcchina.BTCChinaUtils.getNonce;
import java.io.IOException;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.HttpStatusIOException;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.btcchina.BTCChina;
import com.xeiam.xchange.btcchina.BTCChinaUtils;
import com.xeiam.xchange.btcchina.dto.BTCChinaResponse;
import com.xeiam.xchange.btcchina.dto.trade.BTCChinaOrders;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaBuyOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaCancelOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaGetOrdersRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaSellOrderRequest;
import com.xeiam.xchange.btcchina.dto.trade.request.BTCChinaTransactionsRequest;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaBooleanResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrderResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaGetOrdersResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaIntegerResponse;
import com.xeiam.xchange.btcchina.dto.trade.response.BTCChinaTransactionsResponse;
import com.xeiam.xchange.dto.Order.OrderType;
/**
* @author ObsessiveOrange
* <p>
* Implementation of the trade service for BTCChina
* </p>
* <ul>
* <li>Provides access to trade functions</li>
* </ul>
*/
public class BTCChinaTradeServiceRaw extends BTCChinaBasePollingService<BTCChina> {
private final Logger log = LoggerFactory.getLogger(BTCChinaTradeServiceRaw.class);
/**
* Constructor
*
* @param exchangeSpecification
*/
public BTCChinaTradeServiceRaw(ExchangeSpecification exchangeSpecification) {
super(BTCChina.class, exchangeSpecification);
}
/**
* Get order status.
*
* @param id the order id.
* @return order status.
* @throws IOException indicates I/O exception.
*/
public BTCChinaGetOrderResponse getBTCChinaOrder(long id) throws IOException {
BTCChinaGetOrderRequest request = new BTCChinaGetOrderRequest(id);
BTCChinaGetOrderResponse returnObject = btcChina.getOrder(signatureCreator, getNonce(), request);
return checkResult(returnObject);
}
/**
* Get order status.
*
* @param id the order id.
* @param market BTCCNY | LTCCNY | LTCBTC
* @return order status.
* @throws IOException indicates I/O exception.
*/
public BTCChinaGetOrderResponse getBTCChinaOrder(long id, String market) throws IOException {
BTCChinaGetOrderRequest request = new BTCChinaGetOrderRequest(id, market);
BTCChinaGetOrderResponse returnObject = btcChina.getOrder(signatureCreator, getNonce(), request);
return checkResult(returnObject);
}
/**
* @return Set of BTCChina Orders
* @throws IOException
* @deprecated Use {@link #getBTCChinaOrders(Boolean, String, Integer, Integer)} instead.
*/
@Deprecated
public BTCChinaResponse<BTCChinaOrders> getBTCChinaOpenOrders() throws IOException {
return checkResult(btcChina.getOrders(signatureCreator, BTCChinaUtils.getNonce(), new BTCChinaGetOrdersRequest()));
}
/**
* @see {@link BTCChinaGetOrdersRequest#BTCChinaGetOrdersRequest(Boolean, String, Integer, Integer)}.
*/
public BTCChinaGetOrdersResponse getBTCChinaOrders(
Boolean openOnly, String market, Integer limit, Integer offset)
throws IOException {
BTCChinaGetOrdersRequest request = new BTCChinaGetOrdersRequest(
openOnly, market, limit, offset);
BTCChinaGetOrdersResponse response = btcChina.getOrders(
signatureCreator, BTCChinaUtils.getNonce(), request);
return checkResult(response);
}
/**
* @return BTCChinaIntegerResponse of new limit order status.
* @deprecated use {@link #buy(BigDecimal, BigDecimal, String)} or {@link #sell(BigDecimal, BigDecimal, String)} instead.
*/
@Deprecated
public BTCChinaIntegerResponse placeBTCChinaLimitOrder(BigDecimal price, BigDecimal amount, OrderType orderType) throws IOException {
BTCChinaIntegerResponse response = null;
if (orderType == OrderType.BID) {
response = btcChina.buyOrder2(signatureCreator, BTCChinaUtils.getNonce(), new BTCChinaBuyOrderRequest(price, amount));
}
else {
response = btcChina.sellOrder2(signatureCreator, BTCChinaUtils.getNonce(), new BTCChinaSellOrderRequest(price, amount));
}
return checkResult(response);
}
/**
* Place a buy order.
*
* @param price The price in quote currency to buy 1 base currency.
* Max 2 decimals for BTC/CNY and LTC/CNY markets.
* 4 decimals for LTC/BTC market.
* Market order is executed by setting price to 'null'.
* @param amount The amount of LTC/BTC to buy.
* Supports 4 decimal places for BTC and 3 decimal places for LTC.
* @param market [ BTCCNY | LTCCNY | LTCBTC ]
* @return order ID.
* @throws IOException
*/
public BTCChinaIntegerResponse buy(
BigDecimal price, BigDecimal amount, String market) throws IOException {
BTCChinaBuyOrderRequest request = new BTCChinaBuyOrderRequest(
price, amount, market);
final BTCChinaIntegerResponse response;
try {
response = btcChina.buyOrder2(
signatureCreator, BTCChinaUtils.getNonce(), request);
} catch (HttpStatusIOException e) {
if (e.getHttpStatusCode() == 401) {
log.error("{}, request: {}, response: {}",
e.getMessage(),
request, e.getHttpBody());
}
throw e;
}
return checkResult(response);
}
/**
* Place a sell order.
*
* @param price The price in quote currency to sell 1 base currency.
* Max 2 decimals for BTC/CNY and LTC/CNY markets.
* 4 decimals for LTC/BTC market.
* Market order is executed by setting price to 'null'.
* @param amount The amount of LTC/BTC to sell.
* Supports 4 decimal places for BTC and 3 decimal places for LTC.
* @param market [ BTCCNY | LTCCNY | LTCBTC ]
* @return order ID.
* @throws IOException
*/
public BTCChinaIntegerResponse sell(
BigDecimal price, BigDecimal amount, String market) throws IOException {
BTCChinaSellOrderRequest request = new BTCChinaSellOrderRequest(
price, amount, market);
final BTCChinaIntegerResponse response;
try {
response = btcChina.sellOrder2(
signatureCreator, BTCChinaUtils.getNonce(), request);
} catch (HttpStatusIOException e) {
if (e.getHttpStatusCode() == 401) {
log.error("{}, request: {}, response: {}",
e.getMessage(),
request, e.getHttpBody());
}
throw e;
}
return checkResult(response);
}
/**
* @return BTCChinaBooleanResponse of limit order cancellation status.
*/
public BTCChinaBooleanResponse cancelBTCChinaOrder(String orderId) throws IOException {
return checkResult(btcChina.cancelOrder(signatureCreator, BTCChinaUtils.getNonce(), new BTCChinaCancelOrderRequest(Long.parseLong(orderId))));
}
public BTCChinaTransactionsResponse getTransactions() throws IOException {
return checkResult(btcChina.getTransactions(signatureCreator, BTCChinaUtils.getNonce(), new BTCChinaTransactionsRequest()));
}
/**
* @see {@link BTCChinaTransactionsRequest#BTCChinaTransactionsRequest(String, Integer, Integer)}.
*/
public BTCChinaTransactionsResponse getTransactions(String type, Integer limit, Integer offset) throws IOException {
BTCChinaTransactionsRequest request = new BTCChinaTransactionsRequest(type, limit, offset);
BTCChinaTransactionsResponse response = btcChina.getTransactions(signatureCreator, BTCChinaUtils.getNonce(), request);
return checkResult(response);
}
} |
package demoapps.exchangegraphics;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import demoapps.exchangegraphics.data.BuySellRate;
import demoapps.exchangegraphics.data.DolarTlKurRate;
import demoapps.exchangegraphics.data.Rate;
import demoapps.exchangegraphics.data.YorumlarRate;
import demoapps.exchangegraphics.provider.BigparaRateProvider;
import demoapps.exchangegraphics.provider.DolarTlKurRateProvider;
import demoapps.exchangegraphics.provider.EnparaRateProvider;
import demoapps.exchangegraphics.provider.IRateProvider;
import demoapps.exchangegraphics.provider.YorumlarRateProvider;
public class RatesActivity extends AppCompatActivity {
@BindView(R.id.line_usd_chart)
LineChart lineChart;
@BindView(R.id.v_progress_wheel)
View vProgress;
private long startMilis;
ArrayList<IRateProvider> providers = new ArrayList<>();
// String array for alert dialog multi choice items
static final String[] data_set_names = new String[]{
"Piyasa",
"Enpara",
"Bigpara",
"DolarTlKur",
};
// Boolean array for initial selected items
boolean[] checked_data_sources = new boolean[]{
true, // Piyasa
true, // Enpara
true, // Bigpara
true, // DolarTlKur
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rates);
ButterKnife.bind(this);
startMilis = System.currentTimeMillis();
initUsdChart();
vProgress.setVisibility(View.GONE);
providers.add(new YorumlarRateProvider(new ProviderCallbackAdapter<List<YorumlarRate>>() {
@Override
public void onResult(List<YorumlarRate> rates) {
YorumlarRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (YorumlarRate) rate;
}
}
addEntry(rateUsd != null ? rateUsd.realValue : 0.0f, 0);
}
}));
providers.add(new EnparaRateProvider(new ProviderCallbackAdapter<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> rates) {
BuySellRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (BuySellRate) rate;
}
addEntry(rateUsd != null ? rateUsd.value_sell_real : 0.0f, 1);
addEntry(rateUsd != null ? rateUsd.value_buy_real : 0.0f, 2);
}
}
}));
providers.add(
new BigparaRateProvider(new ProviderCallbackAdapter<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> value) {
addEntry(value.get(0).value_sell_real, 3);
}
}));
providers.add(new DolarTlKurRateProvider(new ProviderCallbackAdapter<List<DolarTlKurRate>>() {
@Override
public void onResult(List<DolarTlKurRate> rates) {
DolarTlKurRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (DolarTlKurRate) rate;
}
}
addEntry(rateUsd != null ? rateUsd.realValue : 0.0f, 4);
}
}));
initDataSourceSelections();
refreshSources();
}
private void initDataSourceSelections() {
for (int i = 0; i < data_set_names.length; i++) {
DataSource dataSource = new DataSource(data_set_names[i]);
dataSource.setSelected(checked_data_sources[i]);
dataSource.setiRateProvider(providers.get(i));
dataSources.add(dataSource);
}
}
private void refreshSources() {
for (DataSource dataSource : dataSources) {
IRateProvider iRateProvider = dataSource.getiRateProvider();
if (dataSource.isSelected()) {
iRateProvider.start();
} else {
iRateProvider.stop();
}
}
}
final ArrayList<DataSource> dataSources = new ArrayList<>();
private void initUsdChart() {
Description description = new Description();
description.setTextSize(12f);
description.setText("Dolar-TL Grafiği");
description.setXOffset(8);
description.setYOffset(8);
description.setTextColor(ContextCompat.getColor(this, android.R.color.white));
//lineChart.setDescription(description);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_orange_light));
// add an empty data object
lineChart.setData(new LineData());
// mChart.getXAxis().setDrawLabels(false);
// mChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setLabelCount(6);
// lineChart.getAxisRight().setAxisMaximum(3.48f);
// lineChart.getAxisRight().setAxisMinimum(3.42f);
lineChart.getAxisLeft().setEnabled(false);
final IAxisValueFormatter defaultXFormatter = lineChart.getXAxis().getValueFormatter();
lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int time = (int) value;
int minutes = time / (60);
int seconds = (time) % 60;
String str = String.format("%d:%02d", minutes, seconds, Locale.ENGLISH);
return str;
}
});
final IAxisValueFormatter defaultYFormatter = new DefaultAxisValueFormatter(3);
lineChart.getAxisRight().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return defaultYFormatter.getFormattedValue(value, axis) + " TL";
}
});
lineChart.setScaleEnabled(false);
lineChart.invalidate();
LineData data = lineChart.getData();
data.addDataSet(createSet(0));
data.addDataSet(createSet(1));
data.addDataSet(createSet(2));
data.addDataSet(createSet(3));
data.addDataSet(createSet(4));
lineChart.setExtraBottomOffset(12);
lineChart.setExtraTopOffset(12);
lineChart.setPinchZoom(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_rates, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.item_sources) {
selectSources();
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectSources() {
for (int i = 0; i < checked_data_sources.length; i++) {
checked_data_sources[i] = dataSources.get(i).isSelected();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMultiChoiceItems(data_set_names, checked_data_sources, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checked_data_sources[which] = isChecked;
}
});
builder.setCancelable(true);
builder.setTitle("Select Sources");
builder.setPositiveButton("Apply", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < dataSources.size(); i++) {
dataSources.get(i).setSelected(checked_data_sources[i]);
}
refreshSources();
}
});
builder.setNegativeButton("Dismiss", null);
AlertDialog dialog = builder.create();
dialog.show();
}
private void addEntry(float value, int chartIndex) {
LineData data = lineChart.getData();
long diffSeconds = (System.currentTimeMillis() - startMilis) / 1000;
Entry entry = new Entry(diffSeconds, value);
data.addEntry(entry, chartIndex);
data.notifyDataChanged();
// let the chart know it's data has changed
lineChart.notifyDataSetChanged();
//mChart.setVisibleYRangeMaximum(15, AxisDependency.LEFT);
lineChart.setVisibleXRangeMaximum(120);
lineChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart.getXAxis().setTextColor(ContextCompat.getColor(this, android.R.color.white));
lineChart.getAxisRight().setTextColor(ContextCompat.getColor(this, android.R.color.white));
// this automatically refreshes the chart (calls invalidate())
lineChart.moveViewToX(data.getEntryCount());
// lineChart.getAxisRight().setAxisMinimum(lineChart.getYMin()-0.01f);
// lineChart.getAxisRight().setAxisMaximum(lineChart.getYMax()-0.01f);
}
private LineDataSet createSet(int chartIndex) {
String label;
switch (chartIndex) {
case 0:
label = "Piyasa";
break;
case 1:
label = "Enpara Satış";
break;
case 2:
label = "Enpara Alış";
break;
case 3:
label = "Bigpara";
break;
case 4:
label = "Dolar TL Kur";
break;
default:
label = "Unknown";
break;
}
LineDataSet set = new LineDataSet(null, label);
set.setCubicIntensity(0.1f);
set.setDrawCircleHole(false);
set.setLineWidth(1.5f);
set.setCircleRadius(2f);
set.setDrawCircles(true);
int color;
if (chartIndex == 0) {
color = Color.rgb(240, 0, 0);
} else if (chartIndex == 1) {
color = Color.rgb(0, 0, 240);
} else if (chartIndex == 3) {
color = Color.rgb(0, 240, 0);
} else if (chartIndex == 4) {
color = Color.rgb(120, 120, 40);
} else {
color = Color.rgb(60, 60, 60);
}
set.setCircleColor(color);
set.setHighLightColor(Color.rgb(0, 0, 255));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(color);
// set.setDrawFilled(true);
set.setFillAlpha((int) (256 * 0.3f));
set.setFillColor(color);
set.setValueTextColor(color);
set.setValueTextSize(16f);
set.setDrawValues(false);
return set;
}
@Override
protected void onDestroy() {
for (IRateProvider iRateProvider : providers) {
iRateProvider.stop();
}
super.onDestroy();
}
static class ProviderCallbackAdapter<T> implements IRateProvider.Callback<T> {
@Override
public void onResult(T value) {
}
@Override
public void onError() {
}
}
static class DataSource {
private IRateProvider iRateProvider;
private String name;
private boolean selected;
public DataSource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public void setiRateProvider(IRateProvider iRateProvider) {
this.iRateProvider = iRateProvider;
}
public IRateProvider getiRateProvider() {
return iRateProvider;
}
}
} |
package org.xwiki.job.internal;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import javax.inject.Provider;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.job.DefaultJobStatus;
import org.xwiki.job.DefaultRequest;
import org.xwiki.job.Request;
import org.xwiki.job.annotation.Serializable;
import org.xwiki.job.event.status.JobStatus;
import org.xwiki.job.test.SerializableStandaloneComponent;
import org.xwiki.job.test.StandaloneComponent;
import org.xwiki.logging.marker.TranslationMarker;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
/**
* Validate {@link JobStatusSerializer}.
*
* @version $Id$
*/
public class JobStatusSerializerTest
{
private JobStatusSerializer serializer;
private File testFile = new File("target/test/status.xml");
@Serializable
private static class SerializableCrossReferenceObject
{
public SerializableCrossReferenceObject field;
public SerializableCrossReferenceObject()
{
this.field = this;
}
}
@Serializable
private static class SerializableObjectTest
{
public Object field;
public SerializableObjectTest(Object field)
{
this.field = field;
}
}
@Serializable
private static class CustomSerializableObject
{
public String field;
public CustomSerializableObject(String field)
{
this.field = field;
}
@Override
public boolean equals(Object obj)
{
return Objects.equals(((CustomSerializableObject) obj).field, this.field);
}
}
@Serializable
private static class SerializableCustomObject
{
public String field;
public SerializableCustomObject(String field)
{
this.field = field;
}
@Override
public boolean equals(Object obj)
{
return Objects.equals(((SerializableCustomObject) obj).field, this.field);
}
}
@Serializable(false)
private static class NotSerializableCustomObject
{
public String field;
public NotSerializableCustomObject(String field)
{
this.field = field;
}
@Override
public boolean equals(Object obj)
{
return Objects.equals(((NotSerializableCustomObject) obj).field, this.field);
}
@Override
public String toString()
{
return this.field;
}
}
@Serializable
private static class SerializableProvider implements Provider<String>
{
@Override
public String get()
{
return null;
}
}
private static class SerializableImplementationProvider implements Provider<String>, java.io.Serializable
{
private static final long serialVersionUID = 1L;
@Override
public String get()
{
return null;
}
}
private static class TestException extends Exception
{
private Object custom;
public TestException(String message, Throwable cause, Object custom)
{
super(message, cause);
this.custom = custom;
}
public Object getCustom()
{
return this.custom;
}
}
@BeforeEach
public void before() throws ParserConfigurationException
{
this.serializer = new JobStatusSerializer();
}
private JobStatus writeRead(JobStatus status) throws IOException
{
this.serializer.write(status, this.testFile);
return this.serializer.read(this.testFile);
}
// Tests
@Test
public void serializeUnserialize() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
writeRead(status);
}
@Test
public void serializeUnserializeWhenLogMessage() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message");
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
}
@Test
public void serializeUnserializeWhenLogMarker() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error(new TranslationMarker("translation.key"), "error message");
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(new TranslationMarker("translation.key"), status.getLog().peek().getMarker());
}
@Test
public void serializeUnserializeWhenLogWithException() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message",
new TestException("exception message", new Exception("cause"), "custom"));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals("exception message", status.getLog().peek().getThrowable().getMessage());
assertEquals("cause", status.getLog().peek().getThrowable().getCause().getMessage());
assertNull(((TestException) status.getLog().peek().getThrowable()).getCustom(), "exception message");
}
@Test
public void serializeUnserializeWhenLogWithArguments() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", "arg1", "arg2");
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals("arg1", status.getLog().peek().getArgumentArray()[0]);
assertEquals("arg2", status.getLog().peek().getArgumentArray()[1]);
}
@Test
public void serializeUnserializeWhenLogWithNullArguments() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", "arg1", null, "arg3");
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals("arg1", status.getLog().peek().getArgumentArray()[0]);
assertNull(status.getLog().peek().getArgumentArray()[1]);
assertEquals("arg3", status.getLog().peek().getArgumentArray()[2]);
}
@Test
public void serializeUnserializeWhenLogWithComponentArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new DefaultJobStatusStore());
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(String.class, status.getLog().peek().getArgumentArray()[0].getClass());
}
@Test
public void serializeUnserializeWhenLogWithStandaloneComponentArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new StandaloneComponent());
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(String.class, status.getLog().peek().getArgumentArray()[0].getClass());
}
@Test
public void serializeUnserializeWhenLogWithSerializableStandaloneComponentArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableStandaloneComponent());
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(SerializableStandaloneComponent.class, status.getLog().peek().getArgumentArray()[0].getClass());
}
@Test
public void serializeUnserializeWhenLogWithCrossReference() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("message", new SerializableCrossReferenceObject());
status = writeRead(status);
assertNotNull(status.getLog());
SerializableCrossReferenceObject obj =
(SerializableCrossReferenceObject) status.getLog().peek().getArgumentArray()[0];
assertSame(obj, obj.field);
}
@Test
public void serializeUnserializeWhenLogWithComponentField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(new DefaultJobStatusStore()));
status = writeRead(status);
assertNotNull(status.getLog());
assertNull(((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field);
}
@Test
public void serializeUnserializeWhenLogWithStandaloneComponentField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(new StandaloneComponent()));
status = writeRead(status);
assertNotNull(status.getLog());
assertNull(((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field);
}
@Test
public void serializeUnserializeWhenLogWithLoggerField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(mock(Logger.class)));
status = writeRead(status);
assertNotNull(status.getLog());
assertNull(((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field);
}
@Test
public void serializeUnserializeWhenLogWithProviderField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(mock(Provider.class)));
status = writeRead(status);
assertNotNull(status.getLog());
assertNull(((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field);
}
@Test
public void serializeUnserializeWhenLogWithComponentManagerField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(mock(ComponentManager.class)));
status = writeRead(status);
assertNotNull(status.getLog());
assertNull(((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field);
}
@Test
public void serializeUnserializeWhenLogWithSerializableProviderField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(new SerializableProvider()));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(SerializableProvider.class,
((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field.getClass());
}
@Test
public void serializeUnserializeWhenLogWithSerializableImplementationProviderField() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableObjectTest(new SerializableImplementationProvider()));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(SerializableImplementationProvider.class,
((SerializableObjectTest) status.getLog().peek().getArgumentArray()[0]).field.getClass());
}
@Test
public void serializeUnserializeWhenLogWithCustomObjectArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new CustomSerializableObject("value"));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(new CustomSerializableObject("value"), status.getLog().peek().getArgumentArray()[0]);
}
@Test
public void serializeUnserializeWhenLogWithSerializableCustomObjectArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new SerializableCustomObject("value"));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals(new SerializableCustomObject("value"), status.getLog().peek().getArgumentArray()[0]);
}
@Test
public void serializeUnserializeWhenLogWithNotSerializableCustomObjectArgument() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status.getLog().error("error message", new NotSerializableCustomObject("value"));
status = writeRead(status);
assertNotNull(status.getLog());
assertEquals("error message", status.getLog().peek().getMessage());
assertEquals("value", status.getLog().peek().getArgumentArray()[0]);
}
@Test
public void serializeUnserializeProgress() throws IOException
{
JobStatus status = new DefaultJobStatus<Request>("type", new DefaultRequest(), null, null, null);
status = writeRead(status);
assertNotNull(status.getProgress());
assertEquals(0.0d, status.getProgress().getOffset(), 0.1d);
assertEquals(0.0d, status.getProgress().getCurrentLevelOffset(), 0.1d);
assertEquals("Progress with name [{}]", status.getProgress().getRootStep().getMessage().getMessage());
}
} |
package dynoapps.exchange_rates;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.transition.TransitionManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import dynoapps.exchange_rates.data.RateDataSource;
import dynoapps.exchange_rates.data.RatesHolder;
import dynoapps.exchange_rates.event.RatesEvent;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BuySellRate;
import dynoapps.exchange_rates.model.rates.IRate;
import dynoapps.exchange_rates.service.RatePollingService;
import dynoapps.exchange_rates.time.TimeIntervalManager;
import dynoapps.exchange_rates.util.RateUtils;
public class LandingActivity extends BaseActivity implements DataSourcesManager.SelectionCallback {
@BindView(R.id.drawer_layout)
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle toggle;
@BindView(R.id.v_drawer_item_usd)
View vDrawerItemUsd;
@BindView(R.id.v_card_enpara_sell_usd)
View cardEnparaSellUsd;
@BindView(R.id.v_card_enpara_usd_buy)
View cardEnparaBuyUsd;
@BindView(R.id.v_card_yorumlar_usd)
View cardYorumlarUsd;
@BindView(R.id.v_card_enpara_sell_eur)
View cardEnparaSellEur;
@BindView(R.id.v_card_enpara_buy_eur)
View cardEnparaBuyEur;
@BindView(R.id.v_card_yorumlar_eur)
View cardYorumlarEur;
@BindView(R.id.v_card_enpara_sell_parite)
View cardEnparaSellParite;
@BindView(R.id.v_card_enpara_buy_parite)
View cardEnparaBuyParite;
@BindView(R.id.v_card_yorumlar_parite)
View cardYorumlarParite;
@BindView(R.id.v_landing_side_menu_hint_close)
ImageView ivCloseHint;
@BindView(R.id.v_landing_side_menu_hint)
View vCloseHint;
private Handler mHandler;
private static final int NAVDRAWER_LAUNCH_DELAY = 250;
@Override
public void onDone() {
refreshCards();
}
private void refreshCards() {
ArrayList<RateDataSource> dataSources = DataSourcesManager.getRateDataSources();
for (RateDataSource dataSource : dataSources) {
boolean isEnabled = dataSource.isEnabled();
for (CardViewItemParent parent : parentItems) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
TransitionManager.beginDelayedTransition(parent.me);
}
boolean foundCard = false;
for (CardViewItem item : parent.items) {
if (item.source_type == dataSource.getSourceType()) {
item.card.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
foundCard = true;
}
}
if (!foundCard && isEnabled) {
if (dataSource.getSourceType() == RateDataSource.Type.TLKUR) {
addCardToParent(parent, ValueType.AVG, dataSource.getSourceType());
}
if (dataSource.getSourceType() == RateDataSource.Type.BIGPARA || dataSource.getSourceType() == RateDataSource.Type.YAPIKREDI) {
addCardToParent(parent, ValueType.BUY, dataSource.getSourceType());
addCardToParent(parent, ValueType.SELL, dataSource.getSourceType());
}
}
}
}
}
private void addCardToParent(CardViewItemParent parent, int valueType, int sourceType) {
LayoutInflater.from(this).inflate(R.layout.layout_simple_rate_card, parent.me, true);
View v = parent.me.getChildAt(parent.me.getChildCount() - 1);
CardViewItem item = new CardViewItem(v, sourceType, valueType);
String postFix = "";
if (item.valueType == ValueType.SELL) {
postFix = " " + getString(R.string.sell);
} else if (item.valueType == ValueType.BUY) {
postFix = " " + getString(R.string.buy);
}
((TextView) v.findViewById(R.id.tv_type)).setText(DataSourcesManager.getSourceName(sourceType) + postFix);
parent.items.add(item);
}
interface ValueType {
int BUY = 1;
int SELL = 2;
int AVG = 3;
}
List<CardViewItemParent> parentItems = new ArrayList<>();
static class CardViewItemParent {
ViewGroup me;
/**
* Refers to {@link IRate#getRateType()}
**/
int type;
List<CardViewItem> items = new ArrayList<>();
@Override
public String toString() {
String itemsToString = "";
for (CardViewItem item : items) {
itemsToString += "\n" + item.toString();
}
return itemsToString + "\nType : " + type;
}
}
static class CardViewItem {
CardViewItem(View card, int source_type, int valueType) {
this.card = card;
this.source_type = source_type;
this.valueType = valueType;
}
View card;
int valueType;
/**
* Refers to {@link RateDataSource#getSourceType()}
*/
int source_type;
}
private void setUpDataSourceCards() {
if (parentItems == null) parentItems = new ArrayList<>();
//
CardViewItemParent parentUsd = new CardViewItemParent();
parentUsd.me = (ViewGroup) findViewById(R.id.v_card_holder_usd);
parentUsd.type = IRate.USD;
parentUsd.items.add(new CardViewItem(cardEnparaSellUsd, RateDataSource.Type.ENPARA, ValueType.SELL));
parentUsd.items.add(new CardViewItem(cardEnparaBuyUsd, RateDataSource.Type.ENPARA, ValueType.BUY));
parentUsd.items.add(new CardViewItem(cardYorumlarUsd, RateDataSource.Type.YORUMLAR, ValueType.AVG));
parentItems.add(parentUsd);
//
CardViewItemParent parentEur = new CardViewItemParent();
parentEur.type = IRate.EUR;
parentEur.me = (ViewGroup) findViewById(R.id.v_card_holder_eur);
parentEur.items.add(new CardViewItem(cardEnparaSellEur, RateDataSource.Type.ENPARA, ValueType.SELL));
parentEur.items.add(new CardViewItem(cardEnparaBuyEur, RateDataSource.Type.ENPARA, ValueType.BUY));
parentEur.items.add(new CardViewItem(cardYorumlarEur, RateDataSource.Type.YORUMLAR, ValueType.AVG));
parentItems.add(parentEur);
//
CardViewItemParent parentParity = new CardViewItemParent();
parentParity.type = IRate.EUR_USD;
parentParity.me = (ViewGroup) findViewById(R.id.v_card_holder_parity);
parentParity.items.add(new CardViewItem(cardEnparaSellParite, RateDataSource.Type.ENPARA, ValueType.SELL));
parentParity.items.add(new CardViewItem(cardEnparaBuyParite, RateDataSource.Type.ENPARA, ValueType.BUY));
parentParity.items.add(new CardViewItem(cardYorumlarParite, RateDataSource.Type.YORUMLAR, ValueType.AVG));
parentItems.add(parentParity);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler(Looper.getMainLooper());
if (getActionBarToolbar() != null) {
getActionBarToolbar().setTitle(getTitle());
}
setupNavDrawer();
DataSourcesManager.init();
setUpDataSourceCards();
refreshCards();
SparseArray<List<BaseRate>> sparseArray = RatesHolder.getInstance().getAllRates();
if (sparseArray != null) {
for (int i = 0; i < sparseArray.size(); i++) {
List<BaseRate> rates = sparseArray.valueAt(i);
update(rates, sparseArray.keyAt(i));
}
}
if (!isMyServiceRunning(RatePollingService.class)) {
Intent intent = new Intent(this, RatePollingService.class);
bindService(intent, rateServiceConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, RatePollingService.class));
}
for (CardViewItemParent parent : parentItems) {
for (CardViewItem item : parent.items) {
String postFix = "";
if (item.valueType == ValueType.SELL) {
postFix = " " + getString(R.string.sell);
} else if (item.valueType == ValueType.BUY) {
postFix = " " + getString(R.string.buy);
}
((TextView) item.card.findViewById(R.id.tv_type)).setText(DataSourcesManager.getSourceName(item.source_type) + postFix);
}
}
boolean isHintRemoved = Prefs.isLandingHintClosed();
vCloseHint.setVisibility(isHintRemoved ? View.GONE : View.VISIBLE);
if (!isHintRemoved) {
ivCloseHint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
Prefs.saveLandingHintState(true);
vCloseHint.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
TransitionManager.beginDelayedTransition((ViewGroup) findViewById(R.id.v_main_content));
}
vCloseHint.setVisibility(View.GONE);
}
}).setDuration(400).start();
}
});
}
}
private void doLeftMenuWork(final Runnable runnable) {
closeNavDrawer();
// launch the target Activity after a short delay, to allow the close animation to play
mHandler.postDelayed(runnable, NAVDRAWER_LAUNCH_DELAY);
}
protected void closeNavDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
@Override
public int getLayoutId() {
return R.layout.activity_landing;
}
@Override
protected void onResume() {
super.onResume();
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
vDrawerItemUsd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doLeftMenuWork(new Runnable() {
@Override
public void run() {
Intent i = new Intent(LandingActivity.this, RatesActivity.class);
startActivity(i);
}
});
}
});
}
/**
* Sets up the navigation drawer as appropriate. Note that the nav drawer will be different
* depending on whether the attendee indicated that they are attending the event on-site vs.
* attending remotely.
*/
private void setupNavDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
if (mDrawerLayout == null) return;
// mDrawerLayout.getParent().requestDisallowInterceptTouchEvent(true);
findViewById(R.id.v_main_content).getParent().requestDisallowInterceptTouchEvent(true);
mDrawerLayout.setScrimColor(Color.TRANSPARENT);
// mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// invalidateOptionsMenu();
syncState();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// invalidateOptionsMenu();
syncState();
}
@Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
if (mDrawerLayout == null) {
return;
}
mDrawerLayout.addDrawerListener(toggle);
mDrawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
getActionBarToolbar().setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isNavDrawerOpen())
mDrawerLayout.openDrawer(GravityCompat.START);
else
mDrawerLayout.closeDrawer(GravityCompat.START);
}
});
}
protected boolean isNavDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
protected void onDestroy() {
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
if (isMyServiceRunning(RatePollingService.class)) {
stopService(new Intent(this, RatePollingService.class));
unbindService(rateServiceConnection);
}
super.onDestroy();
}
RatePollingService ratePollingService;
private ServiceConnection rateServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
ratePollingService = ((RatePollingService.SimpleBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName className) {
ratePollingService = null;
}
};
private void update(List<BaseRate> rates, int source_type) {
for (CardViewItemParent parent : parentItems) {
for (CardViewItem item : parent.items) {
if (item.source_type == source_type) {
BaseRate baseRate = RateUtils.getRate(rates, parent.type);
String val = "";
if (baseRate instanceof BuySellRate) {
if (item.valueType == ValueType.SELL) {
val = baseRate.getFormatted(((BuySellRate) baseRate).value_sell_real);
} else if (item.valueType == ValueType.BUY) {
val = baseRate.getFormatted(((BuySellRate) baseRate).value_buy_real);
}
} else {
val = baseRate.getFormatted(baseRate.realValue);
}
((TextView) item.card.findViewById(R.id.tv_rate_value)).setText(val);
}
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(RatesEvent ratesEvent) {
List<BaseRate> rates = ratesEvent.rates;
update(rates, ratesEvent.sourceType);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_landing, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_time_interval) {
TimeIntervalManager.selectInterval(this);
return true;
} else if (id == R.id.menu_item_sources) {
DataSourcesManager.selectSources(this);
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package in.testpress.testpress.core;
import java.util.HashMap;
import java.util.List;
import in.testpress.testpress.models.Attempt;
import in.testpress.testpress.models.AttemptQuestion;
import in.testpress.testpress.models.Exam;
import in.testpress.testpress.models.TestpressApiResponse;
import retrofit.http.Body;
import retrofit.http.EncodedPath;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.POST;
import retrofit.http.PUT;
public interface ExamService {
@GET(Constants.Http.URL_AVAILABLE_EXAMS_FRAG)
TestpressApiResponse<Exam> getAvailableExams(@Header("Authorization") String authorization);
@GET(Constants.Http.URL_UPCOMING_EXAMS_FRAG)
TestpressApiResponse<Exam> getUpcomingExams(@Header("Authorization") String authorization);
@GET(Constants.Http.URL_HISTORY_EXAMS_FRAG)
TestpressApiResponse<Exam> getHistoryExams(@Header("Authorization") String authorization);
@GET("/{questions_url}")
TestpressApiResponse<AttemptQuestion> getQuestions(@EncodedPath("questions_url") String questionsUrlFrag, @Header("Authorization") String authorization);
@POST("/{attempts_url}")
Attempt createAttempt(@EncodedPath("attempts_url") String attemptsUrlFrag, @Header("Authorization") String authorization);
@PUT("/{start_attempt_url}")
Attempt startAttempt(@EncodedPath("start_attempt_url") String startAttemptUrlFrag, @Header("Authorization") String authorization);
@PUT("/{answer_url}")
AttemptQuestion postAnswer(@EncodedPath("answer_url") String answerUrlFrag, @Header("Authorization") String authorization, @Body HashMap<String, List<Integer>> arguments);
@PUT("/{heartbeat_url}")
Attempt heartbeat(@EncodedPath("answer_url") String heartbeatUrlFrag, @Header("Authorization") String authorization);
@PUT("/{end_exam_url}")
Attempt endExam(@EncodedPath("end_exam_url") String endExamUrlFrag, @Header("Authorization") String authorization);
} |
package com.yahoo.vespa.zookeeper;
import com.yahoo.cloud.config.ZookeeperServerConfig;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.tls.AuthorizationMode;
import com.yahoo.security.tls.DefaultTlsContext;
import com.yahoo.security.tls.HostnameVerification;
import com.yahoo.security.tls.PeerAuthentication;
import com.yahoo.security.tls.TlsContext;
import com.yahoo.security.tls.policy.AuthorizedPeers;
import com.yahoo.yolean.Exceptions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static com.yahoo.cloud.config.ZookeeperServerConfig.TlsForClientServerCommunication;
import static com.yahoo.cloud.config.ZookeeperServerConfig.TlsForQuorumCommunication;
import static com.yahoo.security.KeyAlgorithm.EC;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
import static com.yahoo.vespa.zookeeper.Configurator.ZOOKEEPER_JUTE_MAX_BUFFER;
import static java.time.Instant.EPOCH;
import static java.time.temporal.ChronoUnit.DAYS;
import static org.junit.Assert.assertEquals;
/**
* Tests the zookeeper server.
*/
public class ConfiguratorTest {
private File cfgFile;
private File idFile;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Before
public void setup() throws IOException {
cfgFile = folder.newFile();
idFile = folder.newFile();
}
@Test
public void config_is_written_correctly_when_one_server() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
new Configurator(builder.build()).writeConfigToDisk(Optional.empty());
validateConfigFileSingleHost(cfgFile);
validateIdFile(idFile, "0\n");
}
@Test
public void config_is_written_correctly_when_multiple_servers() {
ZookeeperServerConfig.Builder builder = new ZookeeperServerConfig.Builder();
builder.zooKeeperConfigFile(cfgFile.getAbsolutePath());
builder.server(newServer(0, "foo", 123, 321, false));
builder.server(newServer(1, "bar", 234, 432, false));
builder.server(newServer(2, "baz", 345, 543, true));
builder.myidFile(idFile.getAbsolutePath());
builder.myid(1);
new Configurator(builder.build()).writeConfigToDisk(Optional.empty());
validateConfigFileMultipleHosts(cfgFile);
validateIdFile(idFile, "1\n");
}
@Test
public void config_is_written_correctly_with_tls_for_quorum_communication_port_unification() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
builder.tlsForQuorumCommunication(TlsForQuorumCommunication.PORT_UNIFICATION);
builder.tlsForClientServerCommunication(TlsForClientServerCommunication.PORT_UNIFICATION);
TlsContext tlsContext = createTlsContext();
new Configurator(builder.build()).writeConfigToDisk(Optional.of(tlsContext));
validateConfigFilePortUnification(cfgFile);
}
@Test
public void config_is_written_correctly_with_tls_for_quorum_communication_tls_with_port_unification() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
builder.tlsForQuorumCommunication(TlsForQuorumCommunication.TLS_WITH_PORT_UNIFICATION);
builder.tlsForClientServerCommunication(TlsForClientServerCommunication.TLS_WITH_PORT_UNIFICATION);
TlsContext tlsContext = createTlsContext();
new Configurator(builder.build()).writeConfigToDisk(Optional.of(tlsContext));
validateConfigFileTlsWithPortUnification(cfgFile);
}
@Test
public void config_is_written_correctly_with_tls_for_quorum_communication_tls_only() {
ZookeeperServerConfig.Builder builder = createConfigBuilderForSingleHost(cfgFile, idFile);
builder.tlsForQuorumCommunication(TlsForQuorumCommunication.TLS_ONLY);
builder.tlsForClientServerCommunication(TlsForClientServerCommunication.TLS_ONLY);
TlsContext tlsContext = createTlsContext();
new Configurator(builder.build()).writeConfigToDisk(Optional.of(tlsContext));
validateConfigFileTlsOnly(cfgFile);
}
@Test(expected = RuntimeException.class)
public void require_that_this_id_must_be_present_amongst_servers() {
ZookeeperServerConfig.Builder builder = new ZookeeperServerConfig.Builder();
builder.zooKeeperConfigFile(cfgFile.getAbsolutePath());
builder.server(newServer(1, "bar", 234, 432, false));
builder.server(newServer(2, "baz", 345, 543, false));
builder.myid(0);
new Configurator(builder.build()).writeConfigToDisk(Optional.empty());
}
@Test
public void jute_max_buffer_can_be_set() throws IOException {
ZookeeperServerConfig.Builder builder = new ZookeeperServerConfig.Builder();
builder.myid(0);
File idFile = folder.newFile();
File cfgFile = folder.newFile();
builder.server(new ZookeeperServerConfig.Server.Builder().id(0).hostname("testhost"));
builder.zooKeeperConfigFile(cfgFile.getAbsolutePath());
builder.myidFile(idFile.getAbsolutePath());
new Configurator(builder.build()).writeConfigToDisk(Optional.empty());
assertEquals("" + new ZookeeperServerConfig(builder).juteMaxBuffer(), System.getProperty(ZOOKEEPER_JUTE_MAX_BUFFER));
final int max_buffer = 1;
builder.juteMaxBuffer(max_buffer);
new Configurator(builder.build()).writeConfigToDisk(Optional.empty());
assertEquals("" + max_buffer, System.getProperty(ZOOKEEPER_JUTE_MAX_BUFFER));
}
private ZookeeperServerConfig.Builder createConfigBuilderForSingleHost(File cfgFile, File idFile) {
ZookeeperServerConfig.Builder builder = new ZookeeperServerConfig.Builder();
builder.zooKeeperConfigFile(cfgFile.getAbsolutePath());
builder.myidFile(idFile.getAbsolutePath());
builder.server(newServer(0, "foo", 123, 321, false));
builder.myid(0);
return builder;
}
private ZookeeperServerConfig.Server.Builder newServer(int id, String hostName, int electionPort, int quorumPort, boolean joining) {
ZookeeperServerConfig.Server.Builder builder = new ZookeeperServerConfig.Server.Builder();
builder.id(id);
builder.hostname(hostName);
builder.electionPort(electionPort);
builder.quorumPort(quorumPort);
builder.joining(joining);
return builder;
}
private void validateIdFile(File idFile, String expected) {
String actual = Exceptions.uncheck(() -> Files.readString(idFile.toPath()));
assertEquals(expected, actual);
}
private String commonConfig() {
return "tickTime=2000\n" +
"initLimit=20\n" +
"syncLimit=15\n" +
"maxClientCnxns=0\n" +
"snapCount=50000\n" +
"dataDir=" + getDefaults().underVespaHome("var/zookeeper") + "\n" +
"autopurge.purgeInterval=1\n" +
"autopurge.snapRetainCount=15\n" +
"4lw.commands.whitelist=conf,cons,crst,dirs,dump,envi,mntr,ruok,srst,srvr,stat,wchs\n" +
"admin.enableServer=false\n" +
"serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory\n" +
"quorumListenOnAllIPs=true\n" +
"standaloneEnabled=false\n" +
"reconfigEnabled=true\n" +
"skipACL=yes\n" +
"metricsProvider.className=org.apache.zookeeper.metrics.impl.NullMetricsProvider\n";
}
private void validateConfigFileSingleHost(File cfgFile) {
String expected =
commonConfig() +
"server.0=foo:321:123\n" +
"sslQuorum=false\n" +
"portUnification=false\n" +
"client.portUnification=false\n" +
"clientPort=2181\n" +
"secureClientPort=0\n";
validateConfigFile(cfgFile, expected);
}
private String tlsQuorumConfig() {
return "ssl.quorum.context.supplier.class=com.yahoo.vespa.zookeeper.VespaSslContextProvider\n" +
"ssl.quorum.ciphersuites=TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256," +
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n" +
"ssl.quorum.enabledProtocols=TLSv1.2\n" +
"ssl.quorum.clientAuth=NEED\n";
}
private String tlsClientServerConfig() {
return "ssl.context.supplier.class=com.yahoo.vespa.zookeeper.VespaSslContextProvider\n" +
"ssl.ciphersuites=TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256," +
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n" +
"ssl.enabledProtocols=TLSv1.2\n" +
"ssl.clientAuth=NEED\n";
}
private void validateConfigFileMultipleHosts(File cfgFile) {
String expected =
commonConfig() +
"server.0=foo:321:123\n" +
"server.1=bar:432:234\n" +
"server.2=baz:543:345:observer\n" +
"sslQuorum=false\n" +
"portUnification=false\n" +
"client.portUnification=false\n" +
"clientPort=2181\n" +
"secureClientPort=0\n";
validateConfigFile(cfgFile, expected);
}
private void validateConfigFilePortUnification(File cfgFile) {
String expected =
commonConfig() +
"server.0=foo:321:123\n" +
"sslQuorum=false\n" +
"portUnification=true\n" +
tlsQuorumConfig() +
"client.portUnification=true\n" +
"clientPort=2181\n" +
"secureClientPort=0\n" +
tlsClientServerConfig();
validateConfigFile(cfgFile, expected);
}
private void validateConfigFileTlsWithPortUnification(File cfgFile) {
String expected =
commonConfig() +
"server.0=foo:321:123\n" +
"sslQuorum=true\n" +
"portUnification=true\n" +
tlsQuorumConfig() +
"client.portUnification=true\n" +
"clientPort=2181\n" +
"secureClientPort=0\n" +
tlsClientServerConfig();
validateConfigFile(cfgFile, expected);
}
private void validateConfigFileTlsOnly(File cfgFile) {
String expected =
commonConfig() +
"server.0=foo:321:123\n" +
"sslQuorum=true\n" +
"portUnification=false\n" +
tlsQuorumConfig() +
"client.portUnification=false\n" +
"clientPort=0\n" +
"secureClientPort=2181\n" +
tlsClientServerConfig();
validateConfigFile(cfgFile, expected);
}
private void validateConfigFile(File cfgFile, String expected) {
String actual = Exceptions.uncheck(() -> Files.readString(cfgFile.toPath()));
assertEquals(expected, actual);
}
private TlsContext createTlsContext() {
KeyPair keyPair = KeyUtils.generateKeypair(EC);
X509Certificate certificate = X509CertificateBuilder
.fromKeypair(keyPair, new X500Principal("CN=dummy"), EPOCH, EPOCH.plus(1, DAYS), SHA256_WITH_ECDSA, BigInteger.ONE)
.build();
return new DefaultTlsContext(
List.of(certificate), keyPair.getPrivate(), List.of(certificate), new AuthorizedPeers(Set.of()),
AuthorizationMode.ENFORCE, PeerAuthentication.NEED, HostnameVerification.DISABLED);
}
} |
package fr.xtof54.jsgo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testbrowser.R;
import fr.xtof54.jsgo.EventManager.eventType;
import fr.xtof54.jsgo.ServerConnection.DetLogger;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
/**
* TODO:
* - create a dir in externalStorage - done
* - copy in there the eidogo dir - done
* - load games from DGS - done
* - create an example.html file with the sgf inline - done
* - init goban zoom from physical screen size
*
* @author xtof
*
*/
public class GoJsActivity extends FragmentActivity {
ServerConnection server=null;
int chosenServer=0, chosenLogin=0;
// String server;
enum guistate {nogame, play, markDeadStones, checkScore, message};
guistate curstate = guistate.nogame;
File eidogodir;
final boolean forcecopy=false;
HttpClient httpclient=null;
WebView wv;
ArrayList<Game> games2play = new ArrayList<Game>();
int curgidx2play=0,moveid=0;
final String netErrMsg = "Connection errors or timeout, you may retry";
static GoJsActivity main;
// private static void copyFile(InputStream in, OutputStream out) throws IOException {
// byte[] buffer = new byte[1024];
// int read;
// while((read = in.read(buffer)) != -1){
// out.write(buffer, 0, read);
private void setButtons(final String b1, final String b2, final String b3, final String b4) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Button but1 = (Button)findViewById(R.id.but1);
but1.setText(b1);
Button but2 = (Button)findViewById(R.id.but2);
but2.setText(b2);
Button but3 = (Button)findViewById(R.id.but3);
but3.setText(b3);
Button but4 = (Button)findViewById(R.id.but4);
but4.setText(b4);
}
});
}
private guistate lastGameState;
private void changeState(guistate newstate) {
if (curstate==guistate.markDeadStones && newstate!=guistate.markDeadStones)
wv.loadUrl("javascript:eidogo.autoPlayers[0].detmarkp()");
System.out.println("inchangestate "+curstate+" .. "+newstate);
switch (newstate) {
case nogame:
// we allow clicking just in case the user wants to play locally, disconnected
writeInLabel("click Getgame to download a game from DGS");
wv.loadUrl("javascript:eidogo.autoPlayers[0].detallowClicking()");
setButtons("Getgame","Zoom+","Zoom-","Msg"); break;
case play:
writeInLabel("click on the board to play");
wv.loadUrl("javascript:eidogo.autoPlayers[0].detallowClicking()");
setButtons("Send","Zoom+","Zoom-","Reset"); break;
case markDeadStones:
writeInLabel("click on the board to mark dead stones");
wv.loadUrl("javascript:eidogo.autoPlayers[0].detallowClicking()");
showMessage("Scoring phase: put one X marker on each dead group and click SCORE to check score (you can still change after)");
// just in case the board is already rendered...
// normally, detmarkx() is called right after the board is displayed,
// but here, the board is displayed long ago, so we have to call it manually
wv.loadUrl("javascript:eidogo.autoPlayers[0].detmarkx()");
setButtons("Score","Zoom+","Zoom-","Play"); break;
case checkScore:
wv.loadUrl("javascript:eidogo.autoPlayers[0].detforbidClicking()");
setButtons("Accept","Zoom+","Zoom-","Refuse"); break;
case message:
wv.loadUrl("javascript:eidogo.autoPlayers[0].detforbidClicking()");
lastGameState=curstate;
setButtons("GetMsg","Invite","SendMsg","Back2game"); break;
default:
}
curstate=newstate;
}
public String showCounting(JSONObject o) {
String sc="";
try {
sc = o.getString("score");
String bt = o.getString("black_territory").trim();
for (int i=0;i<bt.length();i+=2) {
String coords = bt.substring(i, i+2);
wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TB\",\""+coords+"\")");
}
bt = o.getString("white_dead").trim();
for (int i=0;i<bt.length();i+=2) {
String coords = bt.substring(i, i+2);
wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TB\",\""+coords+"\")");
}
String wt = o.getString("white_territory").trim();
for (int i=0;i<wt.length();i+=2) {
String coords = wt.substring(i, i+2);
wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TW\",\""+coords+"\")");
}
wt = o.getString("black_dead").trim();
for (int i=0;i<wt.length();i+=2) {
String coords = wt.substring(i, i+2);
wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TW\",\""+coords+"\")");
}
wv.loadUrl("javascript:eidogo.autoPlayers[0].refresh()");
} catch (JSONException e) {
e.printStackTrace();
showMessage("warning: error counting");
}
return sc;
}
/**
* we remove all territories and X in the goban but not in the sgf,
* because we'll need them to compute the "toggled dead stones" to estimate the score
* we then add back the X from the server onto the goban, so that the user knows which stones were
* marked dead and he can modify them. It should also make the toggle computing easier
*/
void cleanTerritory() {
wv.loadUrl("javascript:eidogo.autoPlayers[0].detsoncleanT()");
Game g = Game.gameShown;
String serverMarkedStones = g.deadstInSgf;
for (int i=0;i<serverMarkedStones.length();i+=2) {
String coord = serverMarkedStones.substring(i,i+2);
wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"MA\", \""+coord+"\")");
}
wv.loadUrl("javascript:eidogo.autoPlayers[0].refresh()");
}
void copyEidogo(final String edir, final File odir) {
AssetManager mgr = getResources().getAssets();
try {
String[] fs = mgr.list(edir);
for (String s : fs) {
try {
InputStream i = mgr.open(edir+"/"+s);
// this is a file
File f0 = new File(odir,s);
FileOutputStream f = new FileOutputStream(f0);
for (;;) {
int d = i.read();
if (d<0) break;
f.write(d);
}
f.close();
i.close();
} catch (FileNotFoundException e) {
// this is a directory and not a file
File f = new File(odir,s);
f.mkdirs();
copyEidogo(edir+"/"+s,f);
}
}
} catch (IOException e) {
e.printStackTrace();
showMessage("DISK ERROR: "+e.toString());
}
System.out.println("endof copy");
}
public void writeInLabel(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final TextView label = (TextView)findViewById(R.id.textView1);
label.setText(s);
label.invalidate();
}
});
}
void initFinished() {
System.out.println("init finished");
writeInLabel("init done. You can play !");
final Button button1 = (Button)findViewById(R.id.but1);
button1.setClickable(true);
button1.setEnabled(true);
final Button button2 = (Button)findViewById(R.id.but2);
button2.setClickable(true);
button2.setEnabled(true);
final Button button3 = (Button)findViewById(R.id.but3);
button3.setClickable(true);
button3.setEnabled(true);
button1.invalidate();
button2.invalidate();
button3.invalidate();
}
private String getMarkedStones(String sgf) {
String res = null;
int i=0;
for (;;) {
System.out.println("debug "+sgf.substring(i));
int j=sgf.indexOf("MA[",i);
if (j<0) {
return res;
} else {
i=j+2;
while (i<sgf.length()) {
if (sgf.charAt(i)!='[') break;
j=sgf.indexOf(']',i);
if (j<0) break;
String stone = sgf.substring(i+1,j);
if (res==null) res=stone;
else res+=stone;
i=j+1;
}
}
}
}
private class myWebViewClient extends WebViewClient {
@Override
public void onPageFinished(final WebView view, String url) {
view.loadUrl("javascript:eidogo.autoPlayers[0].last()");
if (curstate==guistate.markDeadStones)
view.loadUrl("javascript:eidogo.autoPlayers[0].detmarkx()");
final EventManager em = EventManager.getEventManager();
em.sendEvent(eventType.gobanReady);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("mywebclient detecting command from javascript: "+url);
int i=url.indexOf("androidcall01");
if (i>=0) {
int j=url.lastIndexOf('|')+1;
String lastMove = url.substring(j);
// this is trigerred when the user clicks the SEND button
final Game g = Game.gameShown;
if (curstate==guistate.markDeadStones) {
String sgfdata = url.substring(i+14, j);
String deadstones=getMarkedStones(sgfdata);
final EventManager em = EventManager.getEventManager();
EventManager.EventListener f = new EventManager.EventListener() {
@Override
public String getName() {return "mywebclient";}
@Override
public synchronized void reactToEvent() {
em.unregisterListener(eventType.moveSentEnd, this);
JSONObject o = server.o;
if (o==null) {
// error: do nothing
return;
}
String err = o.getString("error");
if (err!=null&&err.length()>0) {
// error: do nothing
return;
}
// show territories
String sc = showCounting(o);
showMessage("dead stones sent; score="+sc);
writeInLabel("score: "+sc);
changeState(guistate.checkScore);
}
};
em.registerListener(eventType.moveSentEnd, f);
g.sendDeadstonesToServer(deadstones, server, true);
} else {
final EventManager em = EventManager.getEventManager();
EventManager.EventListener f = new EventManager.EventListener() {
@Override
public String getName() {return "mywebclient";}
@Override
public synchronized void reactToEvent() {
em.unregisterListener(eventType.moveSentEnd, this);
JSONObject o = server.o;
if (o==null) {
// error: don't switch game
return;
}
String err = o.getString("error");
if (err!=null&&err.length()>0) {
// error: don't switch game
return;
}
// switch to next game
g.finishedWithThisGame();
if (Game.getGames().size()==0) {
showMessage("No more games locally");
changeState(guistate.nogame);
} else
downloadAndShowGame();
}
};
em.registerListener(eventType.moveSentEnd, f);
g.sendMove2server(lastMove,server);
}
return true;
} else {
// its not an android call back
// let the browser navigate normally
return false;
}
}
}
void showGame(Game g) {
g.showGame();
// detect if the other player has already agreed on dead stones
if (g.getGameStatus().equals("SCORE2")) {
System.out.println("Check score phase detected !");
final EventManager em = EventManager.getEventManager();
// this listener is trigerred when the goban has finished displayed
final EventManager.EventListener drawTerritory = new EventManager.EventListener() {
@Override
public void reactToEvent() {
em.unregisterListener(eventType.gobanReady, this);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
JSONObject o = server.o;
if (o==null) {
// error: do nothing
return;
}
String err = o.getString("error");
if (err!=null&&err.length()>0) {
// error: do nothing
return;
}
// show territories
String sc = showCounting(o);
showMessage("dead stones sent; score="+sc);
writeInLabel("score: "+sc);
changeState(guistate.checkScore);
}
@Override
public String getName() {return "drawTerritory";}
};
em.registerListener(eventType.moveSentEnd, new EventManager.EventListener() {
// this listener is triggered when the server sends back the score and dead stones
@Override
public void reactToEvent() {
em.unregisterListener(eventType.moveSentEnd, this);
curstate=guistate.markDeadStones;
// show the board game
String f=eidogodir+"/example.html";
System.out.println("debugloadurl file:
em.registerListener(eventType.gobanReady, drawTerritory);
// we then ask the goban to show the game in lark deadstone mode, but the second listener
// will be immediately trigerred once the goban is shown
wv.loadUrl("file:
}
@Override
public String getName() {return "showgamedeadstones";}
});
// send NO stones to server to get the final score
g.sendDeadstonesToServer("", server, false);
} else {
// detect if in scoring phase
// TODO: replace this by checking the game STATUS !
if (g.isTwoPasses()) {
System.out.println("scoring phase detected !");
changeState(guistate.markDeadStones);
}
}
// show the board game
String f=eidogodir+"/example.html";
System.out.println("debugloadurl file:
wv.loadUrl("file:
}
void downloadAndShowGame() {
int ngames = Game.getGames().size();
if (curgidx2play>=ngames) {
if (ngames==0) {
showMessage("No game to show");
return;
} else {
curgidx2play=0;
}
}
System.out.println("showing game "+curgidx2play);
final Game g = Game.getGames().get(curgidx2play);
g.downloadGame(server);
final EventManager em = EventManager.getEventManager();
em.registerListener(eventType.GameOK, new EventManager.EventListener() {
@Override
public String getName() {return "downloadAndShowGame";}
@Override
public synchronized void reactToEvent() {
em.unregisterListener(eventType.GameOK, this);
showGame(g);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.web1);
wv.setWebViewClient(new myWebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setSupportZoom(true);
// String myHTML = "<html><body><a href='androidcall01|123456'>Call Back to Android 01 with param 123456</a>my Content<p>my Content<p>my Content<p><a href='androidcall02|7890123'>Call Back to Android 01 with param 7890123</a></body></html>";
// wv.loadDataWithBaseURL("about:blank", myHTML, "text/html", "utf-8", "");
// wv.addJavascriptInterface(new WebAppInterface(this), "Android");
{
final Button button = (Button)findViewById(R.id.morebutts);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("press last button on state "+curstate);
showMoreButtons();
}
});
}
{
final Button button = (Button)findViewById(R.id.but1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("press button1 on state "+curstate);
switch(curstate) {
case nogame: // download games
downloadListOfGames();
break;
case play: // send the move
// ask eidogo to send last move; it will be captured by the web listener
wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()");
break;
case markDeadStones: // send a request to the server to compute the score
// ask eidogo to send sgf, which shall contain X
wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()");
break;
case checkScore: // accept the current score evaluation
acceptScore();
break;
case message: // get messages
if (!initServer()) return;
Message.downloadMessages(server,main);
break;
}
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addCategory(Intent.CATEGORY_BROWSABLE);
// intent.setDataAndType(Uri.fromFile(ff), "application/x-webarchive-xml");
// // intent.setDataAndType(Uri.fromFile(ff), "text/html");
// intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
// // intent.setClassName("Lnu.tommie.inbrowser", "com.android.browser.BrowserActivity");
// startActivity(intent);
// // to launch a browser:
// // Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///mnt/sdcard/"));
}
});
}
{
final Button button = (Button)findViewById(R.id.but2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("press button2 on state "+curstate);
switch(curstate) {
case nogame:
case play:
case markDeadStones:
case checkScore:
wv.zoomIn();
wv.invalidate();
break;
case message: // send invitation
// TODO
break;
}
}
});
}
{
final Button button = (Button)findViewById(R.id.but3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("press button3 on state "+curstate);
switch(curstate) {
case nogame:
case play:
case markDeadStones:
case checkScore:
wv.zoomOut();
wv.invalidate();
case message: // send message
Message.send();
break;
}
}
});
}
{
final Button button = (Button)findViewById(R.id.but4);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("press button4 on state "+curstate);
switch(curstate) {
case nogame: // send message (TODO)
changeState(guistate.message); break;
case play: // reset to the original download SGF
showGame(Game.gameShown);
break;
case markDeadStones: // cancels marking stones and comes back to playing
changeState(guistate.play);
break;
case checkScore: // refuse score and continues to mark stones
refuseScore();
break;
case message: // go back to last game mode
changeState(lastGameState);
break;
}
}
});
}
// copy the eidogo dir into the external sdcard
// only copy if it does not exist already
// this takes time, so do it in a thread and show a message for the user to wait
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
if (mExternalStorageAvailable&&mExternalStorageWriteable) {
File d = getExternalCacheDir();
eidogodir = new File(d, "eidogo");
if (forcecopy||!eidogodir.exists()) {
eidogodir.mkdirs();
final Button button3 = (Button)findViewById(R.id.but3);
button3.setClickable(false);
button3.setEnabled(false);
final Button button2= (Button)findViewById(R.id.but2);
button2.setClickable(false);
button2.setEnabled(false);
final Button button1= (Button)findViewById(R.id.but1);
button1.setClickable(false);
button1.setEnabled(false);
button1.invalidate();
button2.invalidate();
button3.invalidate();
new CopyEidogoTask().execute("noparms");
} else {
showMessage("eidogo already on disk");
initFinished();
}
} else {
showMessage("R/W ERROR sdcard");
}
// manage events to show/hide the waiting dialog
main = this;
final EventManager em = EventManager.getEventManager();
EventManager.EventListener waitDialogShower = new EventManager.EventListener() {
@Override
public String getName() {return "onStartShowWaitDialog";}
@Override
public synchronized void reactToEvent() {
try {
if (!isWaitingDialogShown) {
waitdialog = new WaitDialogFragment();
waitdialog.show(getSupportFragmentManager(),"waiting");
isWaitingDialogShown=true;
}
} catch (Exception e) {
e.printStackTrace();
}
numEventsReceived++;
}
};
// we put here all events that should trigger the "waiting" dialog
em.registerListener(eventType.downloadGameStarted, waitDialogShower);
em.registerListener(eventType.downloadListStarted, waitDialogShower);
em.registerListener(eventType.loginStarted, waitDialogShower);
em.registerListener(eventType.moveSentStart, waitDialogShower);
EventManager.EventListener waitDialogHider = new EventManager.EventListener() {
@Override
public String getName() {return "onStartHideWaitDialog";}
@Override
public synchronized void reactToEvent() {
try {
--numEventsReceived;
if (numEventsReceived<0) {
System.out.println("ERROR events stream...");
return;
}
if (numEventsReceived==0) {
waitdialog.dismiss();
isWaitingDialogShown=false;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
em.registerListener(eventType.downloadGameEnd, waitDialogHider);
em.registerListener(eventType.downloadListEnd, waitDialogHider);
em.registerListener(eventType.loginEnd, waitDialogHider);
em.registerListener(eventType.moveSentEnd, waitDialogHider);
// initialize guistate
changeState(guistate.nogame);
}
private void acceptScore() {
final Game g = Game.gameShown;
final EventManager em = EventManager.getEventManager();
EventManager.EventListener f = new EventManager.EventListener() {
@Override
public String getName() {return "acceptScore";}
@Override
public synchronized void reactToEvent() {
em.unregisterListener(eventType.moveSentEnd, this);
JSONObject o = server.o;
if (o==null) {
// error: don't switch game
return;
}
String err = o.getString("error");
if (err!=null&&err.length()>0) {
// error: don't switch game
return;
}
// switch to next game
g.finishedWithThisGame();
if (Game.getGames().size()==0) {
showMessage("No more games locally");
changeState(guistate.nogame);
} else
downloadAndShowGame();
}
};
em.registerListener(eventType.moveSentEnd, f);
g.acceptScore(server);
}
private void refuseScore() {
cleanTerritory();
changeState(guistate.markDeadStones);
}
static class PrefUtils {
public static final String PREFS_LOGIN_USERNAME_KEY = "__USERNAME__" ;
public static final String PREFS_LOGIN_PASSWORD_KEY = "__PASSWORD__" ;
public static final String PREFS_LOGIN_USERNAME2_KEY = "__USERNAME2__" ;
public static final String PREFS_LOGIN_PASSWORD2_KEY = "__PASSWORD2__" ;
/**
* Called to save supplied value in shared preferences against given key.
* @param context Context of caller activity
* @param key Key of value to save against
* @param value Value to save
*/
public static void saveToPrefs(Context context, String key, String value) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString(key,value);
editor.commit();
}
/**
* Called to retrieve required value from shared preferences, identified by given key.
* Default value will be returned of no value found or error occurred.
* @param context Context of caller activity
* @param key Key to find value against
* @param defaultValue Value to return if no data found against given key
* @return Return the value found against given key, default if not found or any error occurs
*/
public static String getFromPrefs(Context context, String key, String defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
return sharedPrefs.getString(key, defaultValue);
} catch (Exception e) {
e.printStackTrace();
return defaultValue;
}
}
}
/*
* This method must not be blocking, otherwise the waiting dialog window is never displayed.
*/
public Thread runInWaitingThread(final Runnable method) {
final Thread computingThread = new Thread(new Runnable() {
@Override
public void run() {
// this is blocking
method.run();
try {
// just in case, wait for the waiting dialog to be visible
for (;;) {
if (waitdialog!=null && waitdialog.getDialog()!=null) break;
Thread.sleep(500);
}
// then dismisses it
waitdialog.getDialog().cancel();
} catch (Exception e) {
e.printStackTrace();
}
// I notify potential threads that wait for computing to be finished
synchronized (waiterComputingFinished) {
waiterComputingFinished.notifyAll();
}
}
});
computingThread.start();
return computingThread;
}
private Boolean waiterComputingFinished=true;
private boolean initServer() {
System.out.println("call initserver "+server);
if (server!=null) return true;
String loginkey = PrefUtils.PREFS_LOGIN_USERNAME_KEY;
String pwdkey = PrefUtils.PREFS_LOGIN_PASSWORD_KEY;
if (chosenLogin==1) {
loginkey = PrefUtils.PREFS_LOGIN_USERNAME2_KEY;
pwdkey = PrefUtils.PREFS_LOGIN_PASSWORD2_KEY;
}
String u = PrefUtils.getFromPrefs(this, loginkey ,null);
String p = PrefUtils.getFromPrefs(this, pwdkey ,null);
System.out.println("credsdebug "+u+" "+p+" "+chosenLogin);
if (u==null||p==null) {
showMessage("Please enter your credentials first via menu Settings");
return false;
}
System.out.println("credentials passed to server "+u+" "+p);
if (server==null) {
server = new ServerConnection(chosenServer, u, p);
DetLogger l = new DetLogger() {
@Override
public void showMsg(String s) {
showMessage(s);
}
};
server.setLogget(l);
}
return true;
}
private void downloadListOfGames() {
if (!initServer()) return;
final EventManager em = EventManager.getEventManager();
EventManager.EventListener l = new EventManager.EventListener() {
@Override
public String getName() {return "downloadListOfGames";}
@Override
public void reactToEvent() {
em.unregisterListener(eventType.downloadListGamesEnd, this);
int ngames = Game.getGames().size();
System.out.println("in downloadList listener "+ngames);
if (ngames>=0)
showMessage("Nb games to play: "+ngames);
if (ngames>0) {
curgidx2play=0;
downloadAndShowGame();
// download detects if 2 passes and auto change state to markdeadstones
if (curstate!=guistate.markDeadStones) changeState(guistate.play);
} else return;
}
};
em.registerListener(eventType.downloadListGamesEnd, l);
Game.loadStatusGames(server);
}
private class CopyEidogoTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... parms) {
copyEidogo("eidogo",eidogodir);
return "init done";
}
protected void onPostExecute(String res) {
System.out.println("eidogo copy finished");
initFinished();
}
}
public static class WaitDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.waiting, null))
// Add action buttons
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
WaitDialogFragment.this.getDialog().cancel();
// TODO stop thread
}
});
return builder.create();
}
}
private WaitDialogFragment waitdialog;
private int numEventsReceived = 0;
boolean isWaitingDialogShown = false;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
ask4credentials();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
void showMessage(final String txt) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), txt, Toast.LENGTH_LONG).show();
}
});
}
private void ask4credentials() {
System.out.println("calling settings");
final Context c = this;
class LoginDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
TextView username = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.username);
TextView pwd = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.password);
String userkey = PrefUtils.PREFS_LOGIN_USERNAME_KEY;
String pwdkey = PrefUtils.PREFS_LOGIN_PASSWORD_KEY;
if (chosenLogin==1) {
System.out.println("saving creds 1");
userkey = PrefUtils.PREFS_LOGIN_USERNAME2_KEY;
pwdkey = PrefUtils.PREFS_LOGIN_PASSWORD2_KEY;
} else
System.out.println("saving creds 0");
PrefUtils.saveToPrefs(c, userkey, username.getText().toString());
PrefUtils.saveToPrefs(c, pwdkey, (String)pwd.getText().toString());
showMessage("Credentials saved");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
LoginDialogFragment dialog = new LoginDialogFragment();
dialog.show(getSupportFragmentManager(),"dgs signin");
}
private void ask4credentials2() {
System.out.println("calling debug settings");
final Context c = this;
class LoginDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
TextView username = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.username);
TextView pwd = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.password);
PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_USERNAME2_KEY, username.getText().toString());
PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_PASSWORD2_KEY, (String)pwd.getText().toString());
showMessage("Credentials2 saved");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
LoginDialogFragment dialog = new LoginDialogFragment();
dialog.show(getSupportFragmentManager(),"dgs signin");
}
private void skipGame() {
if (Game.getGames().size()<=1) {
showMessage("No more games downloaded; retry GetGames ?");
changeState(guistate.nogame);
return;
}
if (++curgidx2play>=Game.getGames().size()) curgidx2play=0;
downloadAndShowGame();
}
private void resignGame() {
String cmd = "quick_do.php?obj=game&cmd=resign&gid="+Game.gameShown.getGameID()+"&move_id="+moveid;
HttpGet httpget = new HttpGet(server+cmd);
try {
HttpResponse response = httpclient.execute(httpget);
// TODO: check if move has correctly been sent
showMessage("resign sent !");
moveid=0;
games2play.remove(curgidx2play);
downloadAndShowGame();
} catch (Exception e) {
e.printStackTrace();
showMessage(netErrMsg);
}
}
private void loadSgf() {
System.out.println("eidogodir: "+eidogodir);
String f=eidogodir+"/example.html";
wv.loadUrl("file:
}
private void showMoreButtons() {
System.out.println("showing more buttons");
class MoreButtonsDialogFragment extends DialogFragment {
private final MoreButtonsDialogFragment dialog = this;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View v = inflater.inflate(R.layout.other_buttons, null);
Button bdebug = (Button)v.findViewById(R.id.loadSgf);
bdebug.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
System.out.println("loading sgf");
loadSgf();
changeState(guistate.play);
Game.createDebugGame();
dialog.dismiss();
}
});
RadioButton bserver1 = (RadioButton)v.findViewById(R.id.dgs);
bserver1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
chosenServer=0;
if (server!=null) server.closeConnection();
server=null;
dialog.dismiss();
}
});
RadioButton bserver2 = (RadioButton)v.findViewById(R.id.devdgs);
if (chosenServer==1) bserver2.setChecked(true);
bserver2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
chosenServer=1;
if (server!=null) server.closeConnection();
server=null;
dialog.dismiss();
}
});
RadioButton blogin1 = (RadioButton)v.findViewById(R.id.log1);
blogin1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
chosenLogin=0;
if (server!=null) server.closeConnection();
server=null;
dialog.dismiss();
}
});
RadioButton blogin2 = (RadioButton)v.findViewById(R.id.log2);
if (chosenLogin==1) blogin2.setChecked(true);
blogin2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
chosenLogin=1;
if (server!=null) server.closeConnection();
server=null;
dialog.dismiss();
}
});
Button beidogo = (Button)v.findViewById(R.id.copyEidogo);
beidogo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
System.out.println("copy eidogo");
new CopyEidogoTask().execute("noparms");
dialog.dismiss();
}
});
Button bcycle = (Button)v.findViewById(R.id.cycleStates);
bcycle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
switch (curstate) {
case nogame: changeState(guistate.play); break;
case play: changeState(guistate.markDeadStones); break;
case markDeadStones: changeState(guistate.checkScore); break;
case checkScore: changeState(guistate.nogame); break;
default:
}
System.out.println("cycle state "+curstate);
}
});
Button bskip = (Button)v.findViewById(R.id.skipGame);
bskip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
System.out.println("skip game");
skipGame();
dialog.dismiss();
}
});
Button bresign= (Button)v.findViewById(R.id.resign);
bresign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View vv) {
System.out.println("resign game");
resignGame();
dialog.dismiss();
}
});
builder.setView(v);
return builder.create();
}
}
MoreButtonsDialogFragment dialog = new MoreButtonsDialogFragment();
dialog.show(getSupportFragmentManager(),"more actions");
}
} |
package manparvesh.ideatrackerplus;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.RecognizerIntent;
import android.support.annotation.ColorInt;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.BounceInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.github.ivbaranov.mfb.MaterialFavoriteButton;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.ExpandableDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.SwitchDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.shehabic.droppy.DroppyClickCallbackInterface;
import com.shehabic.droppy.DroppyMenuItem;
import com.shehabic.droppy.DroppyMenuPopup;
import com.shehabic.droppy.animations.DroppyFadeInAnimation;
import com.thebluealliance.spectrum.SpectrumDialog;
import com.woxthebox.draglistview.DragListView;
import com.yarolegovich.lovelydialog.LovelyCustomDialog;
import com.yarolegovich.lovelydialog.LovelyStandardDialog;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import manparvesh.ideatrackerplus.customviews.MyMaterialIntroView;
import manparvesh.ideatrackerplus.customviews.NonSwipeableViewPager;
import manparvesh.ideatrackerplus.customviews.ToolbarColorizeHelper;
import manparvesh.ideatrackerplus.database.DataEntry;
import manparvesh.ideatrackerplus.database.DatabaseHelper;
import manparvesh.ideatrackerplus.database.Project;
import manparvesh.ideatrackerplus.database.TinyDB;
import manparvesh.ideatrackerplus.ideamenu.FabShadowBuilder;
import manparvesh.ideatrackerplus.ideamenu.IdeaMenuItemClickListener;
import manparvesh.ideatrackerplus.ideamenu.IdeaMenuItemDragListener;
import manparvesh.ideatrackerplus.recycler.HorizontalAdapter;
import manparvesh.ideatrackerplus.recycler.RecyclerOnClickListener;
import co.mobiwise.materialintro.animation.MaterialIntroListener;
import co.mobiwise.materialintro.prefs.PreferencesManager;
import co.mobiwise.materialintro.shape.Focus;
import co.mobiwise.materialintro.shape.FocusGravity;
public class MainActivity extends AppCompatActivity implements
TextView.OnEditorActionListener,
TextWatcher,
Drawer.OnDrawerItemClickListener,
Drawer.OnDrawerListener,
OnCheckedChangeListener,
MaterialSearchBar.OnSearchActionListener,
MaterialFavoriteButton.OnFavoriteChangeListener,
View.OnClickListener,
View.OnLongClickListener {
// Database
private DatabaseHelper mDbHelper;
// Drawers items
private Drawer leftDrawer = null;
private Drawer rightDrawer = null;
private AccountHeader header = null;
private SwitchDrawerItem doneSwitch;
private SwitchDrawerItem bigTextSwitch;
private PrimaryDrawerItem mColorItem1;
private PrimaryDrawerItem mColorItem2;
private PrimaryDrawerItem mColorItem3;
private ProfileSettingDrawerItem mAddProject;
private MaterialFavoriteButton mFavoriteButton;
// UI elements
private Toolbar mToolbar;
private FloatingActionButton mFab;
private FragmentManager mFragmentManager;
private NonSwipeableViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private TabLayout tabLayout;
private MaterialSearchBar mSearchBar = null;
private static boolean searchMode;
private DroppyMenuPopup.Builder mDroppyBuilder = null;
private RelativeLayout mIdeasMenu = null;
private MyMaterialIntroView mIdeasMenuGuide;
// Dialogs
private Dialog mNewIdeaDialog;
private Dialog mProjectDialog;
// Dialogs views
private RadioGroup mRadioGroup;
private TextView mIdeaError;
private EditText mIdeaField;
private EditText mNoteField;
private TextView mProjectError;
private EditText mProjectField;
// Preferences
private TinyDB mTinyDB;
private static final String PREF_KEY = "MyPrefKey";
private int mPrimaryColor;
private int mSecondaryColor;
private int mTextColor;
private ArrayList<Object> mProjects;
private List<IProfile> mProfiles;
private int mSelectedProfileIndex;
private boolean mNoProject = false;
// Color preferences
private int defaultPrimaryColor;
private int defaultSecondaryColor;
private int defaultTextColor;
// Voice
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
// SINGLETON //
private static MainActivity sInstance;
public static synchronized MainActivity getInstance() {
return sInstance;
}
// OVERRODE METHODS //
@SuppressWarnings("ConstantConditions")
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sInstance = this;
// Databases
mTinyDB = new TinyDB(this);
mDbHelper = DatabaseHelper.getInstance(this);
// App intro
introOnFirstStart();
setUpUI();
// Fragments manager to populate the tabs
mFragmentManager = getSupportFragmentManager();
mSectionsPagerAdapter = new SectionsPagerAdapter(mFragmentManager);
// Set up the ViewPager with the sections adapter.
mViewPager = (NonSwipeableViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set up the tab layout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorHeight(8);
//TABLES
loadProjects();
// Select favorite project
selectFavoriteProject();
// Set up drawers in background tasks
setUpDrawers();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
if (leftDrawer != null) {
outState = leftDrawer.saveInstanceState(outState);
}
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (leftDrawer != null && leftDrawer.isDrawerOpen()) {
leftDrawer.closeDrawer();
} else if (searchMode) {
disableSearchMode();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search:
activateSearch();
return true;
case R.id.action_settings:
if (!mNoProject) rightDrawer.openDrawer();
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Speech reckognition
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
// Capitalize first letter
if (!matches.isEmpty()) {
StringBuilder capitalized = new StringBuilder(matches.get(0).toLowerCase());
capitalized.setCharAt(0, Character.toUpperCase(capitalized.charAt(0)));
// create idea dialog with the spoken text
newIdeaDialog(capitalized.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
// ON CREATE SET UP METHODS //
private void setUpUI() {
//Default colors
defaultPrimaryColor = ContextCompat.getColor(this, R.color.md_blue_grey_800);
defaultSecondaryColor = ContextCompat.getColor(this, R.color.md_teal_a400);
defaultTextColor = ContextCompat.getColor(this, R.color.md_white);
// Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setOnClickListener(this);
// Wire the floating button
mFab = (FloatingActionButton) findViewById(R.id.fab);
mFab.setOnClickListener(this);
mFab.setOnLongClickListener(this);
}
// Select favorite project if any, select the first project if no favorite. Show no project if no project.
private void selectFavoriteProject() {
if (!mNoProject) {
mSelectedProfileIndex = getIndexOfFavorite();
IProfile activeProfile = mProfiles.get(mSelectedProfileIndex);
String activeProfileName = activeProfile.getName().getText();
ActionBar bar;
if ((bar = getSupportActionBar()) != null) {
bar.setTitle(activeProfileName);
}
DataEntry.setTableName(activeProfileName);
switchToProjectColors();
}
}
// Set up the left and right drawers
private void setUpDrawers() {
mAddProject = new ProfileSettingDrawerItem().withName("New project").withIcon(FontAwesome.Icon.faw_plus).withIdentifier(30).withSelectable(false).withOnDrawerItemClickListener(this);
//HEADER
header = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.header)
.withProfiles(mProfiles)
.addProfiles(mAddProject)
.withProfileImagesVisible(false)
.build();
//SWITCHES
setUpSwitches();
//LEFT DRAWER
leftDrawer = new DrawerBuilder(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggleAnimated(true)
.withSelectedItem(-1)
.withAccountHeader(header)
.addDrawerItems(
new PrimaryDrawerItem().withIdentifier(1).withName(R.string.rename_pro).withIcon(FontAwesome.Icon.faw_i_cursor).withSelectable(false),
new PrimaryDrawerItem().withIdentifier(2).withName(R.string.delete_pro).withIcon(FontAwesome.Icon.faw_trash).withSelectable(false),
new DividerDrawerItem(),
new PrimaryDrawerItem().withIdentifier(4).withName(R.string.all_pro).withIcon(GoogleMaterial.Icon.gmd_inbox).withSelectable(false),
new PrimaryDrawerItem().withIdentifier(3).withName(R.string.new_pro).withIcon(FontAwesome.Icon.faw_plus).withSelectable(false),
new DividerDrawerItem(),
new ExpandableDrawerItem().withName(R.string.settings).withIcon(FontAwesome.Icon.faw_gear).withSelectable(false).withSubItems(
doneSwitch, bigTextSwitch),
new ExpandableDrawerItem().withName(R.string.help_feedback).withIcon(FontAwesome.Icon.faw_question_circle).withSelectable(false).withSubItems(
new SecondaryDrawerItem().withName(R.string.see_app_intro).withLevel(2).withIcon(GoogleMaterial.Icon.gmd_camera_rear).withIdentifier(8).withSelectable(false),
new SecondaryDrawerItem().withName(R.string.activate_tuto).withLevel(2).withIcon(GoogleMaterial.Icon.gmd_info).withIdentifier(9).withSelectable(false),
new SecondaryDrawerItem().withName(R.string.rate_app).withLevel(2).withIcon(GoogleMaterial.Icon.gmd_star).withIdentifier(11).withSelectable(false),
new SecondaryDrawerItem().withName(R.string.feedback).withLevel(2).withIcon(GoogleMaterial.Icon.gmd_bug).withIdentifier(10).withSelectable(false),
new SecondaryDrawerItem().withName(R.string.source_code).withLevel(2).withIcon(GoogleMaterial.Icon.gmd_github).withIdentifier(12).withSelectable(false))
)
.withOnDrawerItemClickListener(this)
.withOnDrawerListener(this)
.withCloseOnClick(false)
.build();
//FAVORITE BUTTON
mFavoriteButton = (MaterialFavoriteButton) header.getView().findViewById(R.id.favorite_button);
mFavoriteButton.setOnFavoriteChangeListener(
new MaterialFavoriteButton.OnFavoriteChangeListener() {
@Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
if (favorite) {
mTinyDB.putInt(getString(R.string.favorite_project), getProjectId());
} else if (mTinyDB.getInt(getString(R.string.favorite_project)) == mSelectedProfileIndex) {
mTinyDB.putInt(getString(R.string.favorite_project), -1); //no favorite
}
}
});
//COLORS BUTTONS
mColorItem1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.primary_col).withIcon(FontAwesome.Icon.faw_paint_brush).withIconColor(mPrimaryColor).withSelectable(false);
mColorItem2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.secondary_col).withIcon(FontAwesome.Icon.faw_paint_brush).withIconColor(mSecondaryColor).withSelectable(false);
mColorItem3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.text_col).withIcon(FontAwesome.Icon.faw_paint_brush).withIconColor(mTextColor).withSelectable(false);
//RIGHT DRAWER
rightDrawer = new DrawerBuilder(this)
.withActionBarDrawerToggleAnimated(true)
.withSelectedItem(-1)
.addDrawerItems(
new SectionDrawerItem().withName(R.string.color_prefs),
mColorItem1,
mColorItem2,
mColorItem3,
new PrimaryDrawerItem().withIdentifier(6).withName(R.string.reset_color_prefs).withIcon(FontAwesome.Icon.faw_tint).withSelectable(false),
new SectionDrawerItem().withName(R.string.functions),
new PrimaryDrawerItem().withIdentifier(4).withName(R.string.clear_done).withIcon(FontAwesome.Icon.faw_check_circle).withSelectable(false),
new PrimaryDrawerItem().withIdentifier(5).withName(R.string.sort_priority).withIcon(FontAwesome.Icon.faw_sort_amount_desc).withSelectable(false)
)
.withDrawerGravity(Gravity.END)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem != null && !mNoProject) {
int id = (int) drawerItem.getIdentifier();
switch (id) {
case 1:
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_prim_col)
.setColors(R.array.colors)
.setSelectedColor(mPrimaryColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mPrimaryColor = color;
changePrimaryColor();
saveProjectColors();
//change project icon
Drawable disk = ContextCompat.getDrawable(getApplicationContext(), R.drawable.disk);
disk.setColorFilter(mPrimaryColor, PorterDuff.Mode.SRC_ATOP);
IProfile p = header.getActiveProfile();
p.withIcon(disk);
header.updateProfile(p);
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
break;
case 2:
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_sec_col)
.setColors(R.array.accent_colors)
.setSelectedColor(mSecondaryColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mSecondaryColor = color;
changeSecondaryColor();
saveProjectColors();
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
break;
case 3:
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_text_col)
.setColors(R.array.textColors)
.setSelectedColor(mTextColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOutlineWidth(2)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mTextColor = color;
changeTextColor();
saveProjectColors();
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
break;
case 4:
mDbHelper.clearDoneWithSnack(mViewPager);
rightDrawer.closeDrawer();
break;
case 5:
mDbHelper.sortByAscPriority();
rightDrawer.closeDrawer();
break;
case 6:
resetColorsDialog();
break;
}
} else {
noProjectSnack();
}
return true;
}
})
.append(leftDrawer);
//CURRENT PROJECT
if (!mNoProject) {
header.setActiveProfile(mProfiles.get(mSelectedProfileIndex));
displayIdeasCount();
refreshStar();
} else { // No project
header.setProfiles(mProfiles);
header.setSelectionSecondLine(getString(R.string.no_project));
//reset color
mPrimaryColor = defaultPrimaryColor;
mSecondaryColor = defaultSecondaryColor;
mTextColor = defaultTextColor;
updateColors();
refreshStar();
}
}
// Creates the swicthes displayed in the drawer
private void setUpSwitches() {
doneSwitch = new SwitchDrawerItem().withName(R.string.show_done_msg).withLevel(2).withIdentifier(6).withOnCheckedChangeListener(this).withSelectable(false);
if (mTinyDB.getBoolean(getString(R.string.show_done_pref))) doneSwitch.withChecked(true);
else toggleDoneTab();
bigTextSwitch = new SwitchDrawerItem().withName(R.string.big_text_msg).withLevel(2).withIdentifier(20).withOnCheckedChangeListener(this).withSelectable(false);
if (mTinyDB.getBoolean(getString(R.string.big_text_pref), false)) {
bigTextSwitch.withChecked(true);
HorizontalAdapter.setBigText(true);
}
}
// DIALOG METHODS //
// Shows an idea creation dialog
public void newIdeaDialog() {
mNewIdeaDialog = new LovelyCustomDialog(this, R.style.EditTextTintTheme)
.setView(R.layout.new_idea_form)
.setTopColor(mPrimaryColor)
.setIcon(R.drawable.ic_bulb)
.setListener(R.id.doneButton, new View.OnClickListener() {
@Override
public void onClick(View v) {
sendIdeaFromDialog();
}
})
.show();
//get the view items
mRadioGroup = (RadioGroup) mNewIdeaDialog.findViewById(R.id.radioGroup);
mIdeaError = (TextView) mNewIdeaDialog.findViewById(R.id.new_error_message);
mIdeaField = (EditText) mNewIdeaDialog.findViewById(R.id.editText);
mNoteField = (EditText) mNewIdeaDialog.findViewById(R.id.editNote);
//set up listener for "ENTER" and text changed
mIdeaField.addTextChangedListener(this);
mIdeaField.setTag(1);
mIdeaField.setOnEditorActionListener(this);
mNoteField.setTag(2);
mNoteField.setOnEditorActionListener(this);
//request focus on the edit text
if (mIdeaField.requestFocus()) {
mNewIdeaDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private void sendIdeaFromDialog() {
Switch doLater = (Switch) mNewIdeaDialog.findViewById(R.id.doLater);
String text = mIdeaField.getText().toString();
if (!text.equals("")) {
boolean later = doLater.isChecked();
if (mRadioGroup.getCheckedRadioButtonId() != -1) {
View radioButton = mRadioGroup.findViewById(mRadioGroup.getCheckedRadioButtonId());
RadioButton btn = (RadioButton) mRadioGroup.getChildAt(mRadioGroup.indexOfChild(radioButton));
String selection = (String) btn.getText();
String note = mNoteField.getText().toString();
int priority = Integer.parseInt(selection);
mDbHelper.newEntry(text, note, priority, later); //add the idea to the actual database
displayIdeasCount();
DatabaseHelper.notifyAllLists();
}
mNewIdeaDialog.dismiss();
if (mTinyDB.getBoolean(getString(R.string.handle_idea_pref))) {
//move tab where idea was created
int index = 0;
if (later) index = 1;
tabLayout.setScrollPosition(index, 0f, true);
mViewPager.setCurrentItem(index);
//start the handle idea guide
handleIdeaGuide();
}
} else {
mIdeaError.setVisibility(View.VISIBLE);
}
}
// Shows and idea creation dialog
// pre-select the given priority
public void newIdeaDialog(int priority) {
newIdeaDialog();
//check the right priority radio button
RadioButton radio = (RadioButton) mNewIdeaDialog.findViewById(R.id.radioButton1);
switch (priority) {
case 1:
radio = (RadioButton) mNewIdeaDialog.findViewById(R.id.radioButton1);
break;
case 2:
radio = (RadioButton) mNewIdeaDialog.findViewById(R.id.radioButton2);
break;
case 3:
radio = (RadioButton) mNewIdeaDialog.findViewById(R.id.radioButton3);
break;
}
radio.setChecked(true);
}
// Shows an idea creation dialog
// pre-fill the idea with the given text
public void newIdeaDialog(String idea) {
newIdeaDialog();
//fill idea field with text
mIdeaField.append(idea);
}
private void newProjectDialog() {
mProjectDialog = new LovelyCustomDialog(this, R.style.EditTextTintTheme)
.setView(R.layout.project_form)
.setTopColor(mPrimaryColor)
.setIcon(R.drawable.ic_notepad)
.setListener(R.id.projectDoneButton, new View.OnClickListener() {
@Override
public void onClick(View v) {
createProjectFromDialog();
}
})
.show();
//get the views
mProjectError = (TextView) mProjectDialog.findViewById(R.id.project_error_message);
mProjectField = (EditText) mProjectDialog.findViewById(R.id.editProjectName);
//hide error when text change
mProjectField.addTextChangedListener(this);
//request focus on the edit text
if (mProjectField.requestFocus()) {
mProjectDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private void createProjectFromDialog() {
String projectName = mProjectField.getText().toString();
if (isProjectNameAvailable(projectName) && !projectName.equals("")) {
mDbHelper.newTable(projectName);
//create the profile with its colored icon
Drawable disk = ContextCompat.getDrawable(getApplicationContext(), R.drawable.disk);
disk.setColorFilter(defaultPrimaryColor, PorterDuff.Mode.SRC_ATOP);
IProfile newProfile = new ProfileDrawerItem().withName(projectName).withIcon(disk).withOnDrawerItemClickListener(this);
mProfiles.add(newProfile);
saveProject(new Project(projectName, defaultPrimaryColor, defaultSecondaryColor, defaultTextColor));
//open the profile drawer and select the new profile
header.removeProfile(mAddProject);
header.addProfile(mAddProject, mProfiles.size());
header.setActiveProfile(newProfile);
mSelectedProfileIndex = mProfiles.size() - 2;
switchToProjectColors();
mToolbar.setTitle(projectName);
displayIdeasCount();
if (mNoProject) {
mFab.setVisibility(View.VISIBLE);
mNoProject = false;
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
//If first project ever
if (mTinyDB.getBoolean(getString(R.string.first_project_pref))) {
leftDrawer.openDrawer();
header.toggleSelectionList(getApplicationContext());
firstProjectGuide();
}
refreshStar();
mProjectDialog.dismiss();
} else { //Error - project name is taken or empty, show the error
mProjectError.setVisibility(View.VISIBLE);
}
}
// Show a dialog to rename the current project
private void renameProjectDialog() {
mProjectDialog = new LovelyCustomDialog(this, R.style.EditTextTintTheme)
.setView(R.layout.project_form)
.setTopColor(mPrimaryColor)
.setIcon(R.drawable.ic_edit)
.setListener(R.id.projectDoneButton, new View.OnClickListener() {
@Override
public void onClick(View v) {
String projectName = mProjectField.getText().toString();
if (!projectName.equals("") && isProjectNameAvailable(projectName)) {
//update table's name is the list and the database
renameProject(projectName);
mDbHelper.renameTable(projectName);
//update profile's name
IProfile profile = mProfiles.get(mSelectedProfileIndex);
profile.withName(projectName);
header.updateProfile(profile);
mProfiles.remove(mSelectedProfileIndex);
mProfiles.add(mSelectedProfileIndex, profile);
mToolbar.setTitle(projectName);
mProjectDialog.dismiss();
} else { //Error - project name taken or empty, show message
mProjectError.setVisibility(View.VISIBLE);
}
}
})
.show();
//get the views
mProjectError = (TextView) mProjectDialog.findViewById(R.id.project_error_message);
mProjectField = (EditText) mProjectDialog.findViewById(R.id.editProjectName);
Button projectButton = (Button) mProjectDialog.findViewById(R.id.projectDoneButton);
TextView projectTitle = (TextView) mProjectDialog.findViewById(R.id.projectTitle);
//change title and button label
projectButton.setText(R.string.rename);
projectTitle.setText(R.string.rename_pro);
//hide error when text change
mProjectField.addTextChangedListener(this);
//request focus on the edit text
if (mProjectField.requestFocus()) {
mProjectDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
// Shows a dialog to delete the current project
private void deleteProjectDialog() {
new LovelyStandardDialog(this)
.setTopColorRes(R.color.md_red_400)
.setButtonsColorRes(R.color.md_deep_orange_500)
.setIcon(R.drawable.ic_warning)
.setTitle(getString(R.string.delete_pro_title) + ((Project) mProjects.get(mSelectedProfileIndex)).getName() + "'")
.setMessage(R.string.delete_pro_message)
.setPositiveButton(R.string.delete, new View.OnClickListener() {
@Override
public void onClick(View v) {
mProfiles.remove(mSelectedProfileIndex);
deleteProject();
mDbHelper.deleteTable();
if (mProjects.isEmpty()) {
DataEntry.setTableName("");
mToolbar.setTitle(R.string.app_name);
mFab.setVisibility(View.INVISIBLE);
header.setProfiles(mProfiles);
header.setSelectionSecondLine(getString(R.string.no_project));
mNoProject = true;
//refresh the fragment display
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
//reset color
mPrimaryColor = defaultPrimaryColor;
mSecondaryColor = defaultSecondaryColor;
mTextColor = defaultTextColor;
updateColors();
}
switchToExistingProject(mSelectedProfileIndex);
//favorite star
refreshStar();
//search mode
disableSearchMode();
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
// Shows a dialog to reset color preferences to default
private void resetColorsDialog() {
new LovelyStandardDialog(this)
.setTopColor(mPrimaryColor)
.setButtonsColorRes(R.color.md_pink_a200)
.setIcon(R.drawable.ic_drop)
.setTitle(R.string.reset_color_prefs)
.setMessage(R.string.reset_color_pref_message)
.setPositiveButton(android.R.string.yes, new View.OnClickListener() {
@Override
public void onClick(View v) {
mPrimaryColor = defaultPrimaryColor;
mSecondaryColor = defaultSecondaryColor;
mTextColor = defaultTextColor;
saveProjectColors();
updateColors();
//change project icon
Drawable disk = ContextCompat.getDrawable(getApplicationContext(), R.drawable.disk);
disk.setColorFilter(mPrimaryColor, PorterDuff.Mode.SRC_ATOP);
IProfile p = header.getActiveProfile();
p.withIcon(disk);
header.updateProfile(p);
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
// Shows an activity to record voice inputs, to put them as a new idea after
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// identifying your application to the Google service
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
// hint in the dialog
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.voice_msg));
// hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// number of results
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
// recognition language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
// TUTORIAL AND INTRO METHODS //
// Launch the app introduction only for the first start
private void introOnFirstStart() {
// Declare a new thread to do a preference check
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Create a new boolean and preference and set it to true
boolean firstStart = mTinyDB.getBoolean("firstStart");
// If the activity has never started before...
if (firstStart) {
forceIntro();
mTinyDB.putBoolean("firstStart", false);
}
}
});
t.start();
}
// Launch the app introduction
private void forceIntro() {
Intent i = new Intent(MainActivity.this, MyIntro.class);
startActivity(i);
}
// Shows the tutorial for the first project creation
private void firstProjectGuide() {
new PreferencesManager(this).reset("first_project");
new MyMaterialIntroView.Builder(this)
.enableIcon(true)
.enableDotAnimation(true)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(Focus.NORMAL)
.setDelayMillis(100)
.enableFadeAnimation(true)
.performClick(true)
.setInfoText(getString(R.string.first_project_content))
.setInfoTextSize(13)
.setTarget(header.getView())
.setUsageId("first_project") //THIS SHOULD BE UNIQUE ID
.show();
mTinyDB.putBoolean(getString(R.string.first_project_pref), false);
}
// Shows the tutorial for the first idea creation
private void firstIdeaGuide() {
new PreferencesManager(this).reset("first");
new MyMaterialIntroView.Builder(this)
.enableIcon(true)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(Focus.NORMAL)
.setTargetPadding(30)
.setDelayMillis(100)
.enableFadeAnimation(true)
.performClick(false)
.setInfoText(getString(R.string.first_idea_title))
.setInfoTextSize(13)
.setTarget(mFab)
.setUsageId("first") //THIS SHOULD BE UNIQUE ID
.show();
rightDrawer.closeDrawer();
leftDrawer.closeDrawer();
mTinyDB.putBoolean(getString(R.string.first_idea_pref), false);
}
// Shows the tutorial on how interacting with ideas
private void handleIdeaGuide() {
View firstIdea = findViewById(R.id.firstIdea);
new PreferencesManager(this).reset("handle");
new MyMaterialIntroView.Builder(this)
.enableDotAnimation(true)
.enableIcon(true)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(Focus.NORMAL)
.enableFadeAnimation(true)
.setInfoText(getString(R.string.handle_idea_content))
.setInfoTextSize(13)
.setTarget(firstIdea)
.setUsageId("handle") //THIS SHOULD BE UNIQUE ID
.show();
mTinyDB.putBoolean(getString(R.string.handle_idea_pref), false);
}
private void rightDrawerGuide() {
new PreferencesManager(this).reset("right_drawer");
new MyMaterialIntroView.Builder(MainActivity.this)
.enableIcon(true)
.enableFadeAnimation(true)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(Focus.NORMAL)
.setInfoText(getString(R.string.right_drawer_guide))
.setInfoTextSize(13)
.performClick(true)
.setTarget(mToolbar.getChildAt(2))
.setListener(new MaterialIntroListener() {
@Override
public void onUserClicked(String MyMaterialIntroViewId) {
rightDrawer.openDrawer();
}
})
.setUsageId("right_drawer") //THIS SHOULD BE UNIQUE ID
.show();
mTinyDB.putBoolean(getString(R.string.right_drawer_pref), false);
}
private MyMaterialIntroView menuIdeaGuide(View fabView) {
new PreferencesManager(this).reset("first_menu_idea");
return new MyMaterialIntroView.Builder(this)
.enableIcon(true)
.enableDotAnimation(false)
.setFocusGravity(FocusGravity.CENTER)
.setFocusType(Focus.NORMAL)
.enableFadeAnimation(false)
.setTargetPadding(530)
.setInfoText("Drag and drop to targets for different type of idea creation")
.setInfoTextSize(13)
.setTarget(fabView)
.setUsageId("first_menu_idea") //THIS SHOULD BE UNIQUE ID
.show();
}
// UI COLOR METHODS //
@SuppressWarnings("ConstantConditions")
private void changePrimaryColor() {
//disable search mode for tabLayout
disableSearchMode();
AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
mToolbar.setBackgroundColor(mPrimaryColor);
tabLayout.setBackgroundColor(mPrimaryColor);
appbar.setBackgroundColor(mPrimaryColor);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(darken(mPrimaryColor));
}
if (rightDrawer != null) {
mColorItem1.withIconColor(mPrimaryColor);
rightDrawer.updateItem(mColorItem1);
}
RecyclerOnClickListener.setPrimaryColor(mPrimaryColor);
}
private void changeSecondaryColor() {
//disable search mode for tabLayout
disableSearchMode();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setSelectedTabIndicatorColor(mSecondaryColor);
mFab.setBackgroundTintList(ColorStateList.valueOf(mSecondaryColor));
if (rightDrawer != null) {
mColorItem2.withIconColor(mSecondaryColor);
rightDrawer.updateItem(mColorItem2);
}
}
private void changeTextColor() {
//disable search mode for tabLayout
disableSearchMode();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabTextColors(slightDarken(mTextColor), mTextColor);
mToolbar.setTitleTextColor(mTextColor);
ToolbarColorizeHelper.colorizeToolbar(mToolbar, mTextColor, this);
if (rightDrawer != null) {
mColorItem3.withIconColor(mTextColor);
rightDrawer.updateItem(mColorItem3);
}
}
// Change all UI colors to match the color attributes
private void updateColors() {
changePrimaryColor();
changeSecondaryColor();
changeTextColor();
}
// Change all UI colors to match the selected project preferences
private void switchToProjectColors() {
//Disable search mode
disableSearchMode();
Project selectedProject = (Project) mProjects.get(mSelectedProfileIndex);
mPrimaryColor = selectedProject.getPrimaryColor();
mSecondaryColor = selectedProject.getSecondaryColor();
mTextColor = selectedProject.getTextColor();
updateColors();
}
// Makes a color darker
private int darken(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.85f;
color = Color.HSVToColor(hsv);
return color;
}
// Makes a color slightly darker
private int slightDarken(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.90f;
color = Color.HSVToColor(hsv);
return color;
}
// UI METHODS //
// Shows/hide the DONE tab
private void toggleDoneTab() {
int count = tabLayout.getTabCount();
for (int i = 0; i < count; i++) {
if (tabLayout.getTabAt(i).getText().equals(getString(R.string.done))) {
tabLayout.removeTabAt(i);
mSectionsPagerAdapter.setTabCount(2);
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTinyDB.putBoolean(getString(R.string.show_done_pref), false);
return;
}
}
tabLayout.addTab(tabLayout.newTab().setText("Done"));
mSectionsPagerAdapter.setTabCount(3);
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTinyDB.putBoolean(getString(R.string.show_done_pref), true);
}
// Activate search mode
private void activateSearch() {
// Searchbar
if (mSearchBar == null) {
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mSearchBar = new MaterialSearchBar(this, null);
mSearchBar.setHint(getString(R.string.search));
mSearchBar.setOnSearchActionListener(this);
((CoordinatorLayout) findViewById(R.id.main_content)).addView(mSearchBar, params);
EditText searchEdit = (EditText) mSearchBar.findViewById(com.mancj.materialsearchbar.R.id.mt_editText);
searchEdit.addTextChangedListener(this);
}
searchMode = true;
//hide tabs
AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
appbar.removeView(tabLayout);
//hide floating button
mFab.setVisibility(View.INVISIBLE);
//display search bar
mSearchBar.setVisibility(View.VISIBLE);
mSearchBar.enableSearch();
//refresh the fragment display
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
// Disable the search mode, go back to standard mode
private void disableSearchMode() {
if (searchMode) {
searchMode = false;
//display tabs again
AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
appbar.removeView(tabLayout); //make sure we're not adding the tabLayout while it's already there
appbar.addView(tabLayout);
//display floating button
mFab.setVisibility(View.VISIBLE);
//hide searchbar
mSearchBar.setVisibility(View.GONE);
//refresh the fragment display
mViewPager.setAdapter(null);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
}
// Vibrates breefly for feedback
public void feedbackVibration() {
Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(18);
}
// Animate the items for the idea creation, moving them onto circles
private void setUpIdeaMenuItems() {
final int RADIUS = (int) (mFab.getWidth() * 1.8f);
final int BIG_RADIUS = (int) (mFab.getWidth() * 3f);
final int RADII = (int) (Math.sqrt(2) * RADIUS / 2);
final int DURATION = 250;
final int DELAY = 0;
//ANIMATE ITEM P1
final FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.item_p1);
AnimationSet set1 = new AnimationSet(true);
set1.setInterpolator(new AccelerateDecelerateInterpolator());
set1.setDuration(DURATION);
set1.setFillAfter(true);
TranslateAnimation tr1 = new TranslateAnimation(0f, 0f, 0f, -RADIUS);
ScaleAnimation scale = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
set1.addAnimation(tr1);
set1.addAnimation(scale);
set1.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fab1.getLayoutParams();
params.setMargins(0, 0, 0, RADIUS);
fab1.setLayoutParams(params);
fab1.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
//ANIMATE ITEM P2
final FloatingActionButton fab2 = (FloatingActionButton) findViewById(R.id.item_p2);
AnimationSet set2 = new AnimationSet(true);
set2.setInterpolator(new AccelerateDecelerateInterpolator());
set2.setDuration(DURATION);
set2.setStartOffset(DELAY);
set2.setFillAfter(true);
TranslateAnimation tr2 = new TranslateAnimation(0f, -RADII, 0f, -RADII);
set2.addAnimation(tr2);
set2.addAnimation(scale);
set2.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fab2.getLayoutParams();
params.setMargins(0, 0, RADII, RADII);
fab2.setLayoutParams(params);
fab2.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
//ANIMATE ITEM P3
final FloatingActionButton fab3 = (FloatingActionButton) findViewById(R.id.item_p3);
AnimationSet set3 = new AnimationSet(true);
set3.setInterpolator(new AccelerateDecelerateInterpolator());
set3.setDuration(DURATION);
set3.setStartOffset(2 * DELAY);
set3.setFillAfter(true);
TranslateAnimation tr3 = new TranslateAnimation(0f, -RADIUS, 0f, 0f);
set3.addAnimation(tr3);
set3.addAnimation(scale);
set3.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fab3.getLayoutParams();
params.setMargins(0, 0, RADIUS, 0);
fab3.setLayoutParams(params);
fab3.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
//ANIMATE ITEM MIC
final FloatingActionButton fabMic = (FloatingActionButton) findViewById(R.id.item_mic);
AnimationSet setMic = new AnimationSet(true);
setMic.setInterpolator(new AccelerateDecelerateInterpolator());
setMic.setDuration(DURATION);
setMic.setStartOffset(3 * DELAY);
setMic.setFillAfter(true);
TranslateAnimation trMic = new TranslateAnimation(0f, 0f, 0f, -BIG_RADIUS);
setMic.addAnimation(trMic);
setMic.addAnimation(scale);
setMic.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) fabMic.getLayoutParams();
params.setMargins(0, 0, 0, BIG_RADIUS);
fabMic.setLayoutParams(params);
fabMic.clearAnimation();
//notify the onDragListener that the items are ready for action
IdeaMenuItemDragListener.setReady(true);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
//LAUNCH ALL ANIMATIONS
mIdeasMenu.setVisibility(View.VISIBLE);
IdeaMenuItemDragListener.setReady(false);
fab1.startAnimation(set1);
fab2.startAnimation(set2);
fab3.startAnimation(set3);
fabMic.startAnimation(setMic);
}
// Move the items for the idea creation back to the origin point
public void rebootIdeaMenuItems() {
mFab.setVisibility(View.VISIBLE);
mIdeasMenu.setVisibility(View.INVISIBLE);
FloatingActionButton fab_item;
RelativeLayout.LayoutParams params;
// Loop through all children
for (int i = 0; i < mIdeasMenu.getChildCount(); i++) {
fab_item = (FloatingActionButton) mIdeasMenu.getChildAt(i);
params = (RelativeLayout.LayoutParams) fab_item.getLayoutParams();
params.setMargins(0, 0, 0, 0);
fab_item.setLayoutParams(params);
}
// Dismiss the guide if it was there
if (mIdeasMenuGuide != null) {
mIdeasMenuGuide.dismiss();
mIdeasMenuGuide = null;
mTinyDB.putBoolean(getString(R.string.idea_menu_pref), false);
}
}
// Convert dp to px
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
// PROJECT METHODS //
// Saves a project in the TinyDB
private void saveProject(Project p) {
if (mProjects == null) {
mProjects = new ArrayList<>();
}
mProjects.add(p);
// save the project list to preference
mTinyDB.putListObject(PREF_KEY, mProjects);
}
// Saves color preferences for the current project
private void saveProjectColors() {
Project p = (Project) mProjects.get(mSelectedProfileIndex);
p.setPrimaryColor(mPrimaryColor);
p.setSecondaryColor(mSecondaryColor);
p.setTextColor(mTextColor);
mTinyDB.putListObject(PREF_KEY, mProjects);
}
private void renameProject(String newName) {
Project p = (Project) mProjects.get(mSelectedProfileIndex);
p.setName(newName);
mTinyDB.putListObject(PREF_KEY, mProjects);
}
private boolean isProjectNameAvailable(String name) {
for (Object o : mProjects) {
Project p = (Project) o;
if (p.getName().equalsIgnoreCase(name)) return false;
}
return true;
}
private void deleteProject() {
mProjects.remove(mSelectedProfileIndex);
mTinyDB.putListObject(PREF_KEY, mProjects);
}
// Fills the project and profile lists with the projects saved in the TinyDB
private void loadProjects() {
mProjects = mTinyDB.getListObject(PREF_KEY, Project.class);
if (mProjects.size() == 0) {
DataEntry.setTableName("");
mToolbar.setTitle(R.string.app_name);
mFab.setVisibility(View.INVISIBLE);
mNoProject = true;
} else { //Start counter where we stopped
int lastId = ((Project) mProjects.get(mProjects.size() - 1)).getId();
Project.setCounter(lastId + 1);
}
mProfiles = new ArrayList<>();
for (Object p : mProjects) {
Project project = (Project) p;
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.disk);
drawable.setColorFilter(project.getPrimaryColor(), PorterDuff.Mode.SRC_ATOP);
mProfiles.add(new ProfileDrawerItem().withName(project.getName())
.withIcon(drawable)
.withOnDrawerItemClickListener(this));
}
}
public void displayIdeasCount() {
int count = mDbHelper.getIdeasCount(0);
if (count == 0) {
header.setSelectionSecondLine(getString(R.string.no_ideas));
} else if (count == 1) {
header.setSelectionSecondLine(count + " " + getString(R.string.idea));
} else {
header.setSelectionSecondLine(count + " " + getString(R.string.ideas));
}
}
// Shows a snackbar message to tell the user there's no project
private void noProjectSnack() {
leftDrawer.closeDrawer();
rightDrawer.closeDrawer();
Snackbar.make(findViewById(R.id.main_content), R.string.no_project_snack_message, Snackbar.LENGTH_LONG).show();
}
// Get selected project toString
private int getProjectId() {
return ((Project) mProjects.get(mSelectedProfileIndex)).getId();
}
// Fill or empty star depending is the current project is favorite
private void refreshStar() {
if (!mNoProject) {
mFavoriteButton.setVisibility(View.VISIBLE);
if (mTinyDB.getInt(getString(R.string.favorite_project)) == getProjectId()) {
mFavoriteButton.setFavorite(true, false);
} else {
mFavoriteButton.setFavorite(false, false);
}
} else {
mFavoriteButton.setVisibility(View.INVISIBLE);
}
}
// Get index of favorite project if any
private int getIndexOfFavorite() {
int favoriteId = mTinyDB.getInt(getString(R.string.favorite_project)); //id of fav or -1 if no fav
Project p;
int index = 0;
for (Object o : mProjects) {
p = (Project) o;
if (p.getId() == favoriteId) {
return index;
}
index++;
}
return 0;
}
// Get index of project with a given name
private int getIndexOfProject(String projectName) {
Project p;
int index = 0;
for (Object o : mProjects) {
p = (Project) o;
if (p.getName().equals(projectName)) {
return index;
}
index++;
}
return 0;
}
// Get the list of the other projects, excluding the current one
private Project[] getOtherProjects() {
int size = mProjects.size() - 1;
Project[] otherProjects = new Project[size];
Object currentProject = mProjects.remove(mSelectedProfileIndex);
int index = 0;
for (Object o : mProjects) {
otherProjects[index] = (Project) o;
index++;
}
mProjects.add(mSelectedProfileIndex, currentProject);
return otherProjects;
}
// Switch to another project, project name has to be a valid project
private void switchToProject(String projectName) {
mSelectedProfileIndex = getIndexOfProject(projectName);
IProfile profileToSelect = mProfiles.get(mSelectedProfileIndex);
header.setActiveProfile(profileToSelect);
mToolbar.setTitle(projectName);
mDbHelper.switchTable(projectName);
DatabaseHelper.notifyAllLists();
displayIdeasCount();
switchToProjectColors();
//favorite star
refreshStar();
//search mode
disableSearchMode();
}
/**
* After project deletion, selects another project
*
* @param index the index of the deleted project
*/
private void switchToExistingProject(int index) {
index -= 1;
boolean inBounds = (index >= 0) && (index < mProfiles.size());
if (!mNoProject) {
if (inBounds) mSelectedProfileIndex = index;
else mSelectedProfileIndex = 0;
IProfile profileToSelect = mProfiles.get(mSelectedProfileIndex);
String tableToSelect = profileToSelect.getName().getText();
header.setActiveProfile(profileToSelect);
mToolbar.setTitle(tableToSelect);
mDbHelper.switchTable(tableToSelect);
displayIdeasCount();
switchToProjectColors();
}
}
// FRAGMENT CLASSES //
/**
* Fragment containing the listView to be displayed in each tab
*/
public static class ListFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static MainActivity mainActivity;
public static ListFragment newInstance(String tabName) {
ListFragment f = new ListFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putString("tabName", tabName);
f.setArguments(args);
return f;
}
public String getTabName() {
return getArguments().getString("tabName");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainActivity = MainActivity.getInstance();
View rootView;
// NO PROJECT
if (DataEntry.TABLE_NAME.equals("[]")) {
rootView = inflater.inflate(R.layout.no_project_layout, container, false);
LinearLayout lin = (LinearLayout) rootView.findViewById(R.id.noProject);
lin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mainActivity.newProjectDialog();
}
});
return rootView;
}
if (MainActivity.searchMode) {
rootView = inflater.inflate(R.layout.search_view, container, false);
ListView list = (ListView) rootView.findViewById(R.id.search_list);
SearchListAdapter adapter = SearchListAdapter.getInstance(getContext());
list.setAdapter(adapter);
return rootView;
}
//Inflate the list view
rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
DragListView mDragListView = (DragListView) rootView.findViewById(R.id.list);
mDragListView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Determine tab number
int tabNumber = 0;
if (getTabName().equals(getString(R.string.first_tab))) { //IDEAS
tabNumber = 1;
} else if (getTabName().equals(getString(R.string.second_tab))) {
tabNumber = 2;
} else if (getTabName().equals(getString(R.string.third_tab))) {
tabNumber = 3;
}
//Set reorder listener
final int finalTabNumber = tabNumber;
mDragListView.setDragListListener(new DragListView.DragListListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
if (fromPosition != toPosition) {
DatabaseHelper.getInstance(getContext()).resetEntriesOrderAt(finalTabNumber);
}
}
@Override
public void onItemDragging(int itemPosition, float x, float y) {
}
});
//Set adapter
ItemAdapter itemAdapter = new ItemAdapter(getContext(), tabNumber, R.layout.recycler_view_item, R.id.horizontal_recycler_view);
mDragListView.setAdapter(itemAdapter, false);
mDragListView.setCanDragHorizontally(false);
DatabaseHelper.setAdapterAtTab(tabNumber, itemAdapter);
DatabaseHelper.notifyAllLists();
return rootView;
}
}
/**
* Fragment adapter creating the right fragment for the right tab
*/
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private int tabCount = 3;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public void setTabCount(int count) {
tabCount = count;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return ListFragment.newInstance(tabLayout.getTabAt(position).getText().toString());
}
@Override
public int getCount() {
return tabCount;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.first_tab);
case 1:
return getString(R.string.second_tab);
case 2:
return getString(R.string.third_tab);
}
return null;
}
}
// INTERFACE LISTENERS METHODS //
// TextView.OnEditorActionListener method
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO
|| actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
|| actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_NULL) {
switch ((int) v.getTag()) {
case 1:
mNoteField.requestFocus();
break;
case 2:
sendIdeaFromDialog();
break;
default:
break;
}
return true;
}
return false;
}
// TextWatcher methods
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mIdeaError != null) mIdeaError.setVisibility(View.GONE);
if (mProjectError != null) mProjectError.setVisibility(View.GONE);
if (searchMode) SearchListAdapter.changeSearch(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
// Drawer.OnDrawerItemClickListener method
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem != null) {
int id = (int) drawerItem.getIdentifier();
switch (id) {
case 1: //Rename project
if (!mNoProject) {
renameProjectDialog();
} else {
noProjectSnack();
}
break;
case 2: //Delete project
if (!mNoProject) {
deleteProjectDialog();
leftDrawer.closeDrawer();
} else {
noProjectSnack();
}
break;
case 3: //New project
newProjectDialog();
break;
case 4: //My projects
if (!mNoProject) {
header.toggleSelectionList(getApplicationContext());
} else {
noProjectSnack();
}
break;
case 8: //See intro again
forceIntro();
break;
case 9: //Tutorial mode
leftDrawer.closeDrawer();
Snackbar snackbar = Snackbar.make(findViewById(R.id.main_content), R.string.tuto_mode, Snackbar.LENGTH_SHORT)
.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
mTinyDB.putBoolean(getString(R.string.handle_idea_pref), true);
mTinyDB.putBoolean(getString(R.string.first_project_pref), true);
mTinyDB.putBoolean(getString(R.string.first_idea_pref), true);
mTinyDB.putBoolean(getString(R.string.right_drawer_pref), true);
mTinyDB.putBoolean(getString(R.string.idea_menu_pref), true);
}
});
snackbar.show();
break;
case 10:
// Open browser to github issues section
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/nserguier/IdeasTracker/issues"));
startActivity(browserIntent);
break;
case 11:
// Rate
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case 12:
// Open browser to github source code
Intent browserSource = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/nserguier/IdeasTracker"));
startActivity(browserSource);
break;
case 21:
if (!mNoProject) {
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_prim_col)
.setColors(R.array.colors)
.setSelectedColor(mPrimaryColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mPrimaryColor = color;
changePrimaryColor();
saveProjectColors();
//change project icon
Drawable disk = ContextCompat.getDrawable(getApplicationContext(), R.drawable.disk);
disk.setColorFilter(mPrimaryColor, PorterDuff.Mode.SRC_ATOP);
IProfile p = header.getActiveProfile();
p.withIcon(disk);
header.updateProfile(p);
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
} else noProjectSnack();
break;
case 22:
if (!mNoProject) {
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_sec_col)
.setColors(R.array.accent_colors)
.setSelectedColor(mSecondaryColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mSecondaryColor = color;
changeSecondaryColor();
saveProjectColors();
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
} else noProjectSnack();
break;
case 23:
if (!mNoProject) {
new SpectrumDialog.Builder(getApplicationContext())
.setTitle(R.string.select_text_col)
.setColors(R.array.textColors)
.setSelectedColor(mTextColor)
.setDismissOnColorSelected(false)
.setFixedColumnCount(4)
.setOutlineWidth(2)
.setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
@Override
public void onColorSelected(boolean positiveResult, @ColorInt int color) {
if (positiveResult) {
//update selected color
mTextColor = color;
changeTextColor();
saveProjectColors();
}
}
}).build().show(mFragmentManager, "dialog_spectrum");
} else noProjectSnack();
break;
case 24:
if (!mNoProject) {
mDbHelper.clearDoneWithSnack(mViewPager);
rightDrawer.closeDrawer();
} else noProjectSnack();
break;
case 25:
if (!mNoProject) {
mDbHelper.sortByAscPriority();
rightDrawer.closeDrawer();
} else noProjectSnack();
break;
case 26:
if (!mNoProject) {
resetColorsDialog();
} else noProjectSnack();
break;
case 30: //Add project
newProjectDialog();
return false;
}
}
if (drawerItem != null && drawerItem instanceof IProfile) {
String projectName = ((IProfile) drawerItem).getName().getText(MainActivity.this);
switchToProject(projectName);
leftDrawer.closeDrawer();
}
return false;
}
// Drawer.OnDrawerListener - Listener to trigger tutorial when drawer is closed
private boolean mHandleFilter;
@Override
public void onDrawerOpened(View drawerView) {
mHandleFilter = rightDrawer.isDrawerOpen();
}
@Override
public void onDrawerClosed(View drawerView) {
if (mTinyDB.getBoolean(getString(R.string.right_drawer_pref)) && !mNoProject && !mHandleFilter) {//Left drawer closed
rightDrawerGuide();
} else if (mTinyDB.getBoolean(getString(R.string.first_idea_pref)) && !mNoProject && mHandleFilter) {
firstIdeaGuide();
}
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
// OnCheckedChangeListener - Listener for the settings switches in the left drawer
@Override
public void onCheckedChanged(IDrawerItem drawerItem, CompoundButton buttonView, boolean isChecked) {
int id = (int) drawerItem.getIdentifier();
switch (id) {
case 6:
toggleDoneTab();
break;
case 20:
if (isChecked) {
HorizontalAdapter.setBigText(true);
mTinyDB.putBoolean(getString(R.string.big_text_pref), true);
DatabaseHelper.notifyAllLists();
} else {
HorizontalAdapter.setBigText(false);
mTinyDB.putBoolean(getString(R.string.big_text_pref), false);
DatabaseHelper.notifyAllLists();
}
}
}
// MaterialSearchBar.OnSearchActionListener - Listeners and watcher for the search tab
@Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled) {
disableSearchMode();
}
}
@Override
public void onSearchConfirmed(final CharSequence text) {
SearchListAdapter.changeSearch(text.toString());
}
@Override
public void onButtonClicked(int buttonCode) {
}
//MaterialFavoriteButton.OnFavoriteChangeListener
@Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
if (favorite) {
mTinyDB.putInt(getString(R.string.favorite_project), getProjectId());
} else if (mTinyDB.getInt(getString(R.string.favorite_project)) == mSelectedProfileIndex) {
mTinyDB.putInt(getString(R.string.favorite_project), -1); //no favorite
}
}
// View.OnClickListener - Listener for the toolbar project name and the FAB
@Override
public void onClick(View v) {
if (v instanceof FloatingActionButton) { // FAB click- new idea
newIdeaDialog();
} else { // Toolbar click - display othe rproject list
// Drop down menu - droppy
if (mDroppyBuilder == null) {
mDroppyBuilder = new DroppyMenuPopup.Builder(MainActivity.this, mToolbar);
mDroppyBuilder.triggerOnAnchorClick(false);
}
final Project[] otherProjects = getOtherProjects();
mDroppyBuilder = new DroppyMenuPopup.Builder(MainActivity.this, mToolbar);
mDroppyBuilder.triggerOnAnchorClick(false);
if (otherProjects.length > 0) {
for (Project p : otherProjects) {
mDroppyBuilder.addMenuItem(new DroppyMenuItem(p.getName()));
}
mDroppyBuilder.setOnClick(new DroppyClickCallbackInterface() {
@Override
public void call(View v, int id) {
switchToProject(otherProjects[id].getName());
}
});
mDroppyBuilder.setPopupAnimation(new DroppyFadeInAnimation())
.setXOffset(150);
DroppyMenuPopup droppyMenu = mDroppyBuilder.build();
droppyMenu.show();
}
}
}
// View.OnLongClickListener - Listener for fab to trigger menu idea creation
@Override
public boolean onLongClick(View v) {
//inflate idea menu layout
if (mIdeasMenu == null) {
mIdeasMenu = (RelativeLayout) getLayoutInflater().inflate(R.layout.idea_menu, null);
CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams(
CoordinatorLayout.LayoutParams.MATCH_PARENT,
CoordinatorLayout.LayoutParams.MATCH_PARENT
);
int marginPx = dpToPx(16);
params.setMargins(marginPx, marginPx, marginPx, marginPx);
((CoordinatorLayout) findViewById(R.id.main_content)).addView(mIdeasMenu, params);
//Set up click listeners on items in case the drag fails
findViewById(R.id.item_p1).setOnClickListener(new IdeaMenuItemClickListener(1));
findViewById(R.id.item_p2).setOnClickListener(new IdeaMenuItemClickListener(2));
findViewById(R.id.item_p3).setOnClickListener(new IdeaMenuItemClickListener(3));
findViewById(R.id.item_mic).setOnClickListener(new IdeaMenuItemClickListener(4));
}
//animation for the fab
final Animation.AnimationListener fabAnimListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//Set up drag listeners on items
findViewById(R.id.item_p1).setOnDragListener(new IdeaMenuItemDragListener(1));
findViewById(R.id.item_p2).setOnDragListener(new IdeaMenuItemDragListener(2));
findViewById(R.id.item_p3).setOnDragListener(new IdeaMenuItemDragListener(3));
findViewById(R.id.item_mic).setOnDragListener(new IdeaMenuItemDragListener(4));
//Move items on a circle
setUpIdeaMenuItems();
//Shadow to drop
FabShadowBuilder shadowBuilder = new FabShadowBuilder(mFab);
mFab.startDrag(ClipData.newPlainText("", ""), shadowBuilder, mFab, 0);
mFab.setVisibility(View.INVISIBLE);
//Guide on first use
if (mTinyDB.getBoolean(getString(R.string.idea_menu_pref))) {
mIdeasMenuGuide = menuIdeaGuide(mFab);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
feedbackVibration();
Animation anim = new ScaleAnimation(
1f, 1.2f, // Start and end values for the X axis scaling
1f, 1.2f, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling
anim.setDuration(350);
anim.setInterpolator(new BounceInterpolator());
anim.setAnimationListener(fabAnimListener);
v.startAnimation(anim);
return true;
}
} |
package org.odddev.fantlab.auth.reg;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import org.odddev.fantlab.R;
import org.odddev.fantlab.auth.AuthActivity;
import org.odddev.fantlab.auth.AuthRouter;
import org.odddev.fantlab.core.layers.presenter.PresenterManager;
import org.odddev.fantlab.core.utils.DateUtils;
import org.odddev.fantlab.databinding.RegFragmentBinding;
import java.util.Calendar;
/**
* @author kenrube
* @date 18.09.16
*/
public class RegFragment extends Fragment implements IRegView, DatePickerDialog.OnDateSetListener {
private static final int PRESENTER_ID = RegFragment.class.getSimpleName().hashCode();
private static final int MIN_AGE = 5;
private static final int DEFAULT_AGE = 20;
private static final int MAX_AGE = 100;
private static final int JANUARY_FIRST_DAY = 1;
private static final int DECEMBER_LAST_DAY = 31;
private static final int DAY_LAST_HOUR = 23;
private static final int HOUR_LAST_MINUTE = 59;
private static final int MINUTE_LAST_SECOND = 59;
private RegPresenter mPresenter;
private RegFragmentBinding mBinding;
private AuthRouter mRouter;
private RegParams mRegParams;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPresenter = PresenterManager.getPresenter(PRESENTER_ID, RegPresenter::new);
mRouter = new AuthRouter((AuthActivity) getActivity());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
mBinding = RegFragmentBinding.inflate(inflater, container, false);
return mBinding.getRoot();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mBinding.setActionsHandler(this);
mRegParams = new RegParams(getContext());
mBinding.setRegParams(mRegParams);
setDefaultBirthDate();
}
@Override
public void onStart() {
super.onStart();
mPresenter.attachView(this);
}
@Override
public void onStop() {
mPresenter.detachView(this);
super.onStop();
}
public void register() {
if (mRegParams.isValid()) {
mPresenter.register(mRegParams);
}
}
private void setDefaultBirthDate() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
showBirthDate(day, month + 1, year - DEFAULT_AGE);
}
private void showBirthDate(int day, int month, int year) {
mBinding.birthdate.setText(DateUtils.valuesToDateString(day, month, year));
}
public void pickDate() {
Calendar calendar = DateUtils.dateStringToCalendar(mBinding.birthdate.getText().toString());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getContext(), this, year, month, day);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
calendar.set(year - MAX_AGE, Calendar.JANUARY, JANUARY_FIRST_DAY);
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
calendar.set(
year - MIN_AGE,
Calendar.DECEMBER,
DECEMBER_LAST_DAY,
DAY_LAST_HOUR,
HOUR_LAST_MINUTE,
MINUTE_LAST_SECOND);
dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
dialog.show();
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mRegParams.setBirthDay(dayOfMonth);
mRegParams.setBirthMonth(monthOfYear + 1);
mRegParams.setBirthYear(year);
showBirthDate(dayOfMonth, monthOfYear + 1, year);
}
@Override
public void showRegResult(boolean registered) {
if (registered) {
mRouter.routeToHome(true);
} else {
showError(getString(R.string.error_reg));
}
}
@Override
public void showError(String error) {
Snackbar.make(mBinding.getRoot(), error, Snackbar.LENGTH_LONG).show();
}
} |
package radiancetops.com.resistora;
import android.hardware.Camera;
import android.util.Log;
import java.io.*;
public class ImageHandler implements Camera.PreviewCallback {
private int width, height, stripheight;
private double[] H, S, L;
private int[] rgb;
private double[] Ha, Sa, La, diff;
private int[] idxs;
public ImageHandler(int width, int height, int stripheight) {
super();
this.width = width;
this.height = height;
this.stripheight = stripheight;
this.H = new double[width * stripheight];
this.S = new double[width * stripheight];
this.L = new double[width * stripheight];
this.Ha = new double[width];
this.Sa = new double[width];
this.La = new double[width];
this.diff = new double[width];
this.idxs = new int[4];
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// Decode the image data to HSL
decodeNV21(data, width, height);
// Average data
avgImg();
// Find the maxima
}
private void avgImg() {
for(int i = 0; i < width; i++) {
for (int j = 0; j < stripheight; j++) {
Ha[i] += H[i + j * width];
Sa[i] += H[i + j * width];
La[i] += H[i + j * width];
}
Ha[i] /= stripheight;
Sa[i] /= stripheight;
La[i] /= stripheight;
diff[i] = Sa[i] - La[i];
}
}
private void findMaxima() {
}
public void writeCSV () {
try {
PrintWriter pw = new PrintWriter(new FileWriter("data.csv"));
for (int i = 0; i < width; i++) {
pw.println(Ha[i] + ","+ Sa[i]+ "," + La[i]);
}
pw.close();
} catch (IOException e) {}
}
private void decodeNV21(byte[] data, int width, int height) {
final int frameSize = width * height;
int a = 0;
for (int i = height / 2 - stripheight / 2; i < height / 2 + stripheight / 2; ++i) {
for (int j = 0; j < width; ++j) {
int y = (0xff & ((int) data[i * width + j]));
int v = (0xff & ((int) data[frameSize + (i >> 1) * width + (j & ~1) + 0]));
int u = (0xff & ((int) data[frameSize + (i >> 1) * width + (j & ~1) + 1]));
int rgb = this.rgb[a] = YUVtoRGB(y, u, v);
int r = 0xff & (rgb >> 16);
int g = 0xff & (rgb >> 8);
int b = 0xff & (rgb >> 0);
int max = Math.max(r, Math.max(g, b)), min = Math.min(r, Math.min(g, b));
L[a] = ((max + min) / 2) / 255.;
if(max == min){
H[a] = S[a] = 0; // achromatic
} else {
int d = max - min;
S[a] = L[a] > 0.5 ? d / (double) (510 - max - min) : d / (double) (max + min);
if (max == r) {
H[a] = (g - b) / (double) d + (g < b ? 6 : 0);
} else if (max == g) {
H[a] = (b - r) / (double) d + 1;
} else {
H[a] = (r - g) / (double) d + 4;
}
H[a] /= 6;
}
a++;
}
}
}
private int YUVtoRGB(int y, int u, int v) {
y = y < 16 ? 16 : y;
int a0 = 1192 * (y - 16);
int a1 = 1634 * (v - 128);
int a2 = 832 * (v - 128);
int a3 = 400 * (u - 128);
int a4 = 2066 * (u - 128);
int r = (a0 + a1) >> 10;
int g = (a0 - a2 - a3) >> 10;
int b = (a0 + a4) >> 10;
r = r < 0 ? 0 : (r > 255 ? 255 : r);
g = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
return 0xff000000 | (r << 16) | (g << 8) | b;
}
} |
package galileo.dataset;
import java.io.IOException;
import galileo.serialization.ByteSerializable;
import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;
/**
* Encapsulates a point in space with latitude, longitude coordinates.
*/
public class Coordinates implements ByteSerializable {
private float lat;
private float lon;
/**
* Create Coordinates at the specified latitude and longitude.
*
* @param lat
* Latitude for this coordinate pair, in degrees.
* @param lon
* Longitude for this coordinate pair, in degrees.
*/
public Coordinates(float lat, float lon) {
if(lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180){
this.lat = lat;
this.lon = lon;
} else if(lat >= -180 && lat <=180 && lon >= -90 && lon <= 90){
this.lat = lon;
this.lon = lat;
} else {
throw new IllegalArgumentException("Illegal location. Valid range is Latitude [-90, 90] and Longitude[-180, 180].");
}
}
/**
* Get the latitude of this coordinate pair.
*
* @return latitude, in degrees.
*/
public float getLatitude() {
return lat;
}
/**
* Get the longitude of this coordinate pair.
*
* @return longitude, in degrees
*/
public float getLongitude() {
return lon;
}
/**
* Print this coordinate pair's String representation:
* (lat, lon).
*
* @return String representation of the Coordinates
*/
@Override
public String toString() {
return "(" + lat + ", " + lon + ")";
}
public Coordinates(SerializationInputStream in)
throws IOException {
this.lat = in.readFloat();
this.lon = in.readFloat();
}
@Override
public void serialize(SerializationOutputStream out)
throws IOException {
out.writeFloat(lat);
out.writeFloat(lon);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.