answer
stringlengths 17
10.2M
|
|---|
package pl.datamatica.traccar.api.providers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.slf4j.Logger;
import pl.datamatica.traccar.api.auth.AuthenticationException;
import pl.datamatica.traccar.api.dtos.MessageKeys;
import pl.datamatica.traccar.api.dtos.in.AddUserDto;
import pl.datamatica.traccar.api.dtos.in.BleDeviceDto;
import pl.datamatica.traccar.api.dtos.in.EditUserDto;
import pl.datamatica.traccar.api.dtos.in.EditUserSettingsDto;
import pl.datamatica.traccar.api.providers.ProviderException.Type;
import pl.datamatica.traccar.model.ApplicationSettings;
import pl.datamatica.traccar.model.AuditLog;
import pl.datamatica.traccar.model.AuditLogType;
import pl.datamatica.traccar.model.BleDevice;
import pl.datamatica.traccar.model.Device;
import pl.datamatica.traccar.model.DeviceEventType;
import pl.datamatica.traccar.model.PositionIconType;
import pl.datamatica.traccar.model.GeoFence;
import pl.datamatica.traccar.model.Group;
import pl.datamatica.traccar.model.RulesVersion;
import pl.datamatica.traccar.model.User;
import pl.datamatica.traccar.model.UserPermission;
import pl.datamatica.traccar.model.UserSettings;
import pl.datamatica.traccar.model.UserSettings.SpeedUnit;
public class UserProvider extends ProviderBase {
private User requestUser;
private ApplicationSettings appSettings;
private RulesProvider rulesProvider;
private Logger logger;
public UserProvider(EntityManager entityManager, ApplicationSettings appSettings,
RulesProvider rulesProvider) {
super(entityManager);
this.appSettings = appSettings;
logger = DbLog.getLogger();
this.rulesProvider = rulesProvider;
}
public User authenticateUser(String email, String password) throws AuthenticationException {
if(email == null || email.isEmpty())
throw new AuthenticationException(MessageKeys.ERR_AUTH_NO_SUCH_USER);
if(password == null || password.isEmpty())
throw new AuthenticationException(MessageKeys.ERR_AUTH_NO_PASSWORD);
User user = getUserByLogin(email);
if(user == null)
throw new AuthenticationException(MessageKeys.ERR_AUTH_NO_SUCH_USER);
if(user.getPasswordHashMethod().doHash(password, appSettings.getSalt()).equals(user.getPassword())) {
requestUser = user;
return user;
}
throw new AuthenticationException(MessageKeys.ERR_AUTH_NO_SUCH_USER);
}
public User authenticateUser(long id) throws ProviderException,
AuthenticationException {
requestUser = get(User.class, id, u -> true);
return requestUser;
}
public User getRequestUser() {
return requestUser;
}
public Stream<User> getAllAvailableUsers() {
if(requestUser.hasPermission(UserPermission.ALL_USERS))
return getAllUsers();
return Stream.concat(requestUser.getAllManagedUsers().stream(), Stream.of(requestUser));
}
public Stream<User> getAllManagedUsers() {
if(requestUser.hasPermission(UserPermission.ALL_USERS))
return getAllUsers();
return Stream.concat(requestUser.getAllManagedUsers().stream(),
Stream.of(requestUser));
}
public User getUser(long id) throws ProviderException {
return get(User.class, id, this::isVisible);
}
public User createUser(AddUserDto dto) throws ProviderException {
checkUserManagementPermissions(requestUser);
User user = prepareNewUser(dto.getLogin(), dto.getPassword());
editUser(user, dto);
user.setManagedBy(requestUser);
em.persist(user);
return user;
}
public User registerUser(String email, String password, boolean checkMarketing)
throws ProviderException {
User user = prepareNewUser(email, password);
user.setEmail(email);
user.setManager(true);
user.setMarketingCheck(checkMarketing);
user.setEmailValid(false);
user.setBlocked(true);
user.setEmailValidationToken(generateToken("emailValidationToken"));
em.persist(user);
logger.info("{} created his account", user.getLogin());
return user;
}
private User prepareNewUser(String login, String password) throws ProviderException {
User existing = getUserByLogin(login);
if(existing != null)
throw new ProviderException(Type.USER_ALREADY_EXISTS);
String hashedPassword = appSettings.getDefaultHashImplementation().doHash(password, appSettings.getSalt());
User user = new User(login, hashedPassword);
user.setPasswordHashMethod(appSettings.getDefaultHashImplementation());
user.setUserSettings(new UserSettings());
user.setUserGroup(appSettings.getDefaultGroup());
for(RulesVersion rv : rulesProvider.getActiveRules())
if(rv.getType() == RulesVersion.Type.MARKETING && !user.getMarketingCheck()) {
user.addRulesRejection(rv);
} else {
user.addRulesAcceptance(rv);
}
user.setLastRequestTime(new Date());
user.setRegistrationTime(new Date());
generateAuditLogForCreateRemoveUser(user.getLogin(), false);
return user;
}
public void updateUser(long id, EditUserDto dto) throws ProviderException {
if (requestUser.getId() != id)
checkUserManagementPermissions(requestUser);
User u = getUser(id);
editUser(u, dto);
if(!EditUserDto.PASSWORD_PLACEHOLDER.equals(dto.getPassword())) {
u.setPassword(u.getPasswordHashMethod()
.doHash(dto.getPassword(), appSettings.getSalt()));
addSingleEditUserAuditLog(u.getLogin(), "password", null);
}
em.persist(u);
logger.info("{} updated user {}", requestUser.getLogin(), u.getLogin());
}
// REMOVING USER - START //
public void removeUser(long id) throws Exception {
if (requestUser.getId() == id)
throw new ProviderRemovingException(Type.DELETING_ITSELF);
if (requestUser.getManagedBy() != null && requestUser.getManagedBy().getId() == id)
throw new ProviderRemovingException(Type.ACCESS_DENIED);
User user;
try {
checkUserManagementPermissions(requestUser);
user = getUser(id);
} catch (ProviderException pe) {
if (pe.getType() == Type.ACCESS_DENIED)
throw new ProviderRemovingException(Type.ACCESS_DENIED);
if (pe.getType() == Type.NOT_FOUND)
throw new ProviderRemovingException(Type.NOT_FOUND);
throw pe;
}
forceRemoveUser(user);
}
public void forceRemoveUser(User user) throws Exception {
String removedLogin = user.getLogin();
removeUserSettings(user);
removeUserResources(user);
if (user.getGeoFences() != null && user.getGeoFences().size() > 0) {
Query queryDelGeo = em.createQuery("DELETE FROM GeoFence WHERE owner_id = ?");
queryDelGeo.setParameter(1, user.getId());
queryDelGeo.executeUpdate();
}
Long userSettingsId = user.getUserSettings() != null ? user.getUserSettings().getId() : null;
Query query = em.createQuery("DELETE FROM User WHERE id = ?");
query.setParameter(1, user.getId());
query.executeUpdate();
if (user.getUserSettings() != null) {
query = em.createQuery("DELETE FROM UserSettings WHERE id = ?");
query.setParameter(1, userSettingsId.longValue());
query.executeUpdate();
}
generateAuditLogForCreateRemoveUser(removedLogin, true);
logger.info("{} removed {} account", requestUser.getLogin(), removedLogin);
em.flush();
}
private void removeUserSettings(User user) throws Exception {
Query query;
query = em.createQuery("DELETE FROM NotificationSettings WHERE user = ?");
query.setParameter(1, user);
query.executeUpdate();
//Remove user data from table users_notifications
user.setNotificationEvents(Collections.EMPTY_SET);
//Remove user data from table users_mobilenotifications
user.setMobileNotificationSettings(Collections.EMPTY_MAP);
em.persist(user);
query = em.createQuery("DELETE FROM UIStateEntry WHERE user = ?");
query.setParameter(1, user);
query.executeUpdate();
query = em.createQuery("DELETE FROM UserDeviceStatus uds WHERE uds.id.user = ?");
query.setParameter(1, user);
query.executeUpdate();
query = em.createQuery("DELETE FROM UserSession us WHERE us.userId = ?");
query.setParameter(1, user.getId());
query.executeUpdate();
}
private void removeUserResources(User user) throws Exception {
DeviceGroupProvider deviceGroupProvider = new DeviceGroupProvider(em, user);
GeoFenceProvider geoProvider = new GeoFenceProvider(em);
geoProvider.setRequestUser(user);
//users
user.setManagedUsers(Collections.EMPTY_SET);
em.persist(user);
Query query = em.createQuery("SELECT u FROM User u WHERE u.managedBy = :manager");
query.setParameter("manager", user);
for (User us : (List<User>) query.getResultList()) {
us.setManagedBy(requestUser);
logger.info("{} became manager of {}", requestUser.getLogin(), us.getLogin());
}
// devices
user.setDevices(Collections.EMPTY_SET);
em.persist(user);
query = em.createQuery("SELECT d FROM Device d WHERE d.owner = :owner");
query.setParameter("owner", user);
for (Device dev : (List<Device>) query.getResultList()) {
dev.setOwner(requestUser);
logger.info("{} became owner of {}(id={})", requestUser.getLogin(),
dev.getName(), dev.getId());
}
em.flush();
// tracks
query = em.createQuery("DELETE FROM Route r WHERE r.owner = :owner");
query.setParameter("owner", user);
query.executeUpdate();
// geofences
query = em.createQuery("SELECT g FROM GeoFence g WHERE :user in elements(g.users)");
query.setParameter("user", user);
for (GeoFence geo : (List<GeoFence>) query.getResultList()) {
if (geo.getOwner() == user) {
geo.setUsers(new HashSet<>());
em.remove(geo);
}
else {
Set<User> us = geo.getUsers();
us.remove(user);
geo.setUsers(us);
}
}
// groups
for (Group gr : user.getGroups()) {
Set<User> us = gr.getUsers();
if (us == null)
continue;
if (us.size() == 1) {
deviceGroupProvider.deleteGroup(gr.getId());
}
else {
us.remove(user);
gr.setUsers(us);
}
}
// RulesAcceptances
query = em.createQuery("DELETE FROM RulesAcceptance a WHERE a.id.user = :user");
query.setParameter("user", user);
query.executeUpdate();
//BleDevices
query = em.createQuery("DELETE FROM BleDevice bd where bd.owner = :user");
query.setParameter("user", user);
query.executeUpdate();
//UserEvent
query = em.createQuery("DELETE FROM UserEvent ue where ue.user = :user");
query.setParameter("user", user);
query.executeUpdate();
}
// REMOVING USER - END //
private void editUser(User user, EditUserDto dto) throws ProviderException {
if(!requestUser.hasPermission(UserPermission.ALL_USERS) && user.equals(requestUser.getManagedBy()))
throw new ProviderException(Type.ACCESS_DENIED);
generateAuditLogEditUser(user, dto);
user.setAdmin(false);
user.setCompanyName(dto.getCompanyName());
user.setEmail(dto.getEmail());
user.setFirstName(dto.getFirstName());
user.setLastName(dto.getLastName());
user.setManager(true);
if(requestUser.hasPermission(UserPermission.ALL_USERS) || !user.equals(requestUser)) {
user.setMaxNumOfDevices(dto.getMaxNumOfDevices());
user.setExpirationDate(dto.getExpirationDate());
}
Set<DeviceEventType> notificationEvents = new HashSet<>();
for(String ev : dto.getNotificationEvents()) {
notificationEvents.add(DeviceEventType.valueOf(ev));
}
user.setNotificationEvents(notificationEvents);
user.setPhoneNumber(dto.getPhoneNumber());
if (requestUser.getId() != user.getId()) {
user.setReadOnly(false);
user.setArchive(true);
user.setBlocked(dto.isBlocked());
}
}
private void checkUserManagementPermissions(User user) throws ProviderException {
if (!user.hasPermission(UserPermission.USER_MANAGEMENT))
throw new ProviderException(ProviderException.Type.ACCESS_DENIED);
}
private String generateToken(String colName) {
TypedQuery<Long> tq = em.createQuery("select x.id from User x "
+ "where x."+colName+" = :token", Long.class);
tq.setMaxResults(1);
while(true) {
UUID token = UUID.randomUUID();
tq.setParameter("token", token.toString());
if(tq.getResultList().isEmpty())
return token.toString();
}
}
public void activateUser(String token) throws ProviderException {
User user = getUserByToken("emailValidationToken", token);
if(user == null)
throw new ProviderException(Type.NOT_FOUND);
user.setBlocked(false);
user.setEmailValid(true);
user.setEmailValidationToken(null);
em.persist(user);
logger.info("{} activated his account", user.getLogin());
}
public String requestPasswordReset(String login) throws ProviderException {
User u = getUserByLogin(login);
if (u == null)
throw new ProviderException(Type.NOT_FOUND);
u.setPassResetToken(generateToken("passResetToken"));
em.persist(u);
return u.getPassResetToken();
}
public User resetPassword(String token) throws ProviderException {
User user = getUserByToken("passResetToken", token);
if(user == null)
throw new ProviderException(Type.NOT_FOUND);
user.setPassResetToken(null);
StringBuilder pass = new StringBuilder();
Random r = new Random();
for(int i=0;i<14;++i)
pass.appendCodePoint(r.nextInt(94)+33);
user.setPassword(user.getPasswordHashMethod()
.doHash(pass.toString(), appSettings.getSalt()));
user.setPasswordRaw(pass.toString());
em.persist(user);
return user;
}
public User getUserByLogin(String login) {
try {
TypedQuery<User> tq = em.createQuery("Select x from User x where x.login = :login", User.class);
tq.setParameter("login", login);
return tq.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
private User getUserByToken(String tokenType, String token) {
try {
TypedQuery<User> tq = em.createQuery("Select x from User x "
+ "where x."+tokenType+" = :token", User.class);
tq.setParameter("token", token);
return tq.getSingleResult();
} catch(NoResultException e) {
return null;
}
}
private Stream<User> getAllUsers() {
TypedQuery<User> tq = em.createQuery("Select x from User x", User.class);
return tq.getResultList().stream();
}
private boolean isVisible(User other) {
if(requestUser == null)
return false;
if(requestUser.hasPermission(UserPermission.ALL_USERS))
return true;
return getAllAvailableUsers().anyMatch(u -> u.equals(other));
}
public void updateUserSettings(long id, EditUserSettingsDto dto) throws ProviderException {
if(id != requestUser.getId())
throw new ProviderException(Type.ACCESS_DENIED);
UserSettings us = requestUser.getUserSettings();
if(dto.getArchiveMarkerType() != null && ! dto.getArchiveMarkerType().isEmpty())
us.setArchiveMarkerType(PositionIconType.valueOf(dto.getArchiveMarkerType()));
else
us.setArchiveMarkerType(null);
us.setCenterLatitude(dto.getCenterLatitude());
us.setCenterLongitude(dto.getCenterLongitude());
us.setFollowedDeviceZoomLevel(dto.getFollowedDeviceZoomLevel());
us.setHideDuplicates(dto.isHideDuplicates());
us.setHideInvalidLocations(dto.isHideInvalidLocations());
us.setHideZeroCoordinates(dto.isHideZeroCoordinates());
us.setMapType(UserSettings.MapType.valueOf(dto.getMapType()));
us.setMaximizeOverviewMap(dto.isMaximizeOverviewMap());
us.setMinDistance(dto.getMinDistance());
us.setOverlays(dto.getOverlays());
us.setSpeedForFilter(dto.getSpeedForFilter());
us.setSpeedModifier(dto.getSpeedModifier());
if(dto.getSpeedUnit() != null && !dto.getSpeedUnit().isEmpty())
us.setSpeedUnit(SpeedUnit.valueOf(dto.getSpeedUnit()));
us.setTimePrintInterval(dto.getTimePrintInterval());
us.setTimeZoneId(dto.getTimeZoneId());
us.setTraceInterval(dto.getTraceInterval());
us.setZoomLevel(dto.getZoomLevel());
}
public UserSettings getUserSettings(long id) throws ProviderException {
if(id != requestUser.getId())
throw new ProviderException(Type.ACCESS_DENIED);
return requestUser.getUserSettings();
}
public void updateUserBleDevices(long id, List<BleDeviceDto> dtos) throws ProviderException {
if(id != requestUser.getId())
throw new ProviderException(Type.ACCESS_DENIED);
if(!dtos.isEmpty()) {
requestUser.setWasBleUser(true);
requestUser.setHadAnyDevice(true);
}
Query q = em.createQuery("DELETE FROM BleDevice bd where bd.owner = :user");
q.setParameter("user", requestUser);
q.executeUpdate();
List<BleDevice> bled = new ArrayList<>();
for(BleDeviceDto dto : dtos) {
BleDevice bd = new BleDevice();
bd.setModelName(dto.getModelName());
bd.setCreationTimestamp(dto.getCreationTimestamp());
bd.setPhoneModel(dto.getPhoneModel().toLowerCase());
bd.setPhoneSystem(dto.getPhoneSystem().toLowerCase());
bd.setOwner(requestUser);
em.persist(bd);
bled.add(bd);
}
requestUser.updateBleDevices(bled);
em.persist(requestUser);
}
// AuditLog methods
private void generateAuditLogForCreateRemoveUser(String userLogin, boolean remove) {
AuditLog al = new AuditLog.Builder()
.agentLogin(requestUser != null ? requestUser.getLogin() : "REGISTRATION")
.type(remove ? AuditLogType.REMOVED_USER : AuditLogType.CREATED_USER)
.targetUserLogin(userLogin)
.build();
em.persist(al);
}
private void generateAuditLogEditUser(User user, EditUserDto dto) {
if (!Objects.equals(user.getEmail(), dto.getEmail()))
addSingleEditUserAuditLog(user.getLogin(), "email", dto.getEmail());
if (!Objects.equals(user.getFirstName(), dto.getFirstName()))
addSingleEditUserAuditLog(user.getLogin(), "firstName", dto.getFirstName());
if (!Objects.equals(user.getLastName(), dto.getLastName()))
addSingleEditUserAuditLog(user.getLogin(), "lastName", dto.getLastName());
if (!Objects.equals(user.getMaxNumOfDevices(), dto.getMaxNumOfDevices())) {
String maxDevStr = dto.getMaxNumOfDevices() == null ?
"null" : dto.getMaxNumOfDevices().toString();
addSingleEditUserAuditLog(user.getLogin(), "maxNumOfDevices", maxDevStr);
}
if (!Objects.equals(user.getExpirationDate(), dto.getExpirationDate())) {
String dateStr = dto.getExpirationDate() == null ?
"null" : dto.getExpirationDate().toString();
addSingleEditUserAuditLog(user.getLogin(), "expirationDate", dateStr);
}
if (!Objects.equals(user.isBlocked(), dto.isBlocked()))
addSingleEditUserAuditLog(user.getLogin(), "blocked", dto.isBlocked() ? "true" : "false");
}
private void addSingleEditUserAuditLog(String userLogin, String fieldName, String fieldNewValue) {
AuditLog al = new AuditLog.Builder()
.agentLogin(requestUser.getLogin())
.type(AuditLogType.CHANGED_USER)
.targetUserLogin(userLogin)
.fieldName(fieldName)
.fieldNewValue(fieldNewValue)
.build();
em.persist(al);
}
}
|
package de.lmu.ifi.dbs.utilities.optionhandling;
import com.sun.org.apache.xerces.internal.dom.ParentNode;
import de.lmu.ifi.dbs.properties.Properties;
import de.lmu.ifi.dbs.properties.PropertyName;
import de.lmu.ifi.dbs.utilities.UnableToComplyException;
/**
* Parameter class for a parameter specifying a class name.
*
* @author Steffi Wanka
*
*/
public class ClassParameter<C> extends Parameter<String, String> {
/**
* the restriction class for this class parameter.
*/
private Class<C> restrictionClass;
/**
* Constructs a class parameter with the given name, description, and
* restriction class.
*
* @param name
* the parameter name
* @param description
* the parameter description
* @param restrictionClass
* the restriction class of this class parameter
*/
public ClassParameter(String name, String description, Class<C> restrictionClass) {
super(name, description);
this.restrictionClass = restrictionClass;
}
@Override
public void setValue(String value) throws ParameterException {
if (isValid(value)) {
setCorrectValue(value);
}
}
/**
* Returns the class names allowed according to the restriction class of
* this class parameter.
*
* @return class names allowed according to the restriction class defined.
*/
public String[] getRestrictionClasses() {
if (restrictionClass != null) {
return Properties.KDD_FRAMEWORK_PROPERTIES.getProperty(PropertyName.getOrCreatePropertyName(restrictionClass));
}
return new String[] {};
}
/**
* Checks if the given parameter value is valid for this ClassParameter. If
* not a parameter exception is thrown.
*
*/
@Override
public boolean isValid(String value) throws ParameterException {
if (value == null) {
throw new WrongParameterValueException("Parameter Error.\nNo value for parameter \"" + getName() + "\" " + "given.");
}
try {
try {
if (restrictionClass.isAssignableFrom(Class.forName(value))) {
return true;
}
}
catch (ClassNotFoundException e) {
restrictionClass.isAssignableFrom(Class.forName(restrictionClass.getPackage().getName() + "." + value));
return true;
}
}
catch (ClassNotFoundException e) {
throw new WrongParameterValueException(this.name, value, "", e);
}
throw new WrongParameterValueException(this.name, value, "subclass of " + restrictionClass.getName());
}
/**
* Returns the restriction class of this class parameter.
*
* @return the restriction class of this class parameter.
*/
public Class<C> getRestrictionClass() {
return restrictionClass;
}
private void setCorrectValue(String value) throws ParameterException {
try {
try {
if (restrictionClass.isAssignableFrom(Class.forName(value))) {
this.value = value;
}
}
catch (ClassNotFoundException e) {
restrictionClass.isAssignableFrom(Class.forName(restrictionClass.getPackage().getName() + "." + value));
this.value = restrictionClass.getPackage().getName() + "." + value;
}
}
catch (ClassNotFoundException e) {
throw new WrongParameterValueException(this.name, value, "subclass of " + restrictionClass.getName());
}
}
}
|
package se.kth.rest.application.config;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
/**
*
* @author Ermias
*/
@javax.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(MultiPartFeature.class);
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(se.kth.hopsworks.filters.RequestAuthFilter.class);
resources.add(se.kth.hopsworks.rest.ActivityService.class);
resources.add(se.kth.hopsworks.rest.AppExceptionMapper.class);
resources.add(se.kth.hopsworks.rest.AuthExceptionMapper.class);
resources.add(se.kth.hopsworks.rest.AuthService.class);
resources.add(se.kth.hopsworks.rest.DataSetService.class);
resources.add(se.kth.hopsworks.rest.ProjectMembers.class);
resources.add(se.kth.hopsworks.rest.ProjectService.class);
resources.add(se.kth.hopsworks.rest.ThrowableExceptionMapper.class);
resources.add(se.kth.hopsworks.rest.TransactionExceptionMapper.class);
resources.add(se.kth.hopsworks.rest.UserService.class);
}
}
|
package dr.app.beagle.evomodel.utilities;
import dr.app.beagle.evomodel.treelikelihood.MarkovJumpsBeagleTreeLikelihood;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.tree.TreeTrait;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.Loggable;
import dr.inference.markovjumps.StateHistory;
import dr.util.Citable;
import dr.util.Citation;
import dr.util.CommonCitations;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
/**
* A class to conveniently log a complete state history of a continuous-time Markov chain along a tree
* simulated using the Uniformization Method
* <p/>
* This work is supported by NSF grant 0856099
* <p/>
* Minin VN and Suchard MA (2008) Counting labeled transitions in continous-time Markov models of evolution.
* Journal of Mathematical Biology, 56, 391-412.
* <p/>
* Rodrigue N, Philippe H and Lartillot N (2006) Uniformization for sampling realizations of Markov processes:
* applications to Bayesian implementations of codon substitution models. Bioinformatics, 24, 56-62.
* <p/>
* Hobolth A and Stone E (2009) Simulation from endpoint-conditioned, continuous-time Markov chains on a finite
* state space, with applications to molecular evolution. Annals of Applied Statistics, 3, 1204-1231.
*
* @author Marc A. Suchard
* @author Philippe Lemey
* @author Andrew Rambaut
*/
public class CompleteHistoryLogger implements Loggable, Citable {
public static final String TOTAL_COUNT_NAME = "totalChangeCount";
public static final String COMPLETE_HISTORY_NAME = "completeHistory";
public CompleteHistoryLogger(MarkovJumpsBeagleTreeLikelihood treeLikelihood) {
this.tree = treeLikelihood.getTreeModel();
this.patternCount = treeLikelihood.getPatternCount();
treeTraitHistory = new TreeTrait[patternCount];
for (int site = 0; site < patternCount; ++site) {
String traitName = (patternCount == 1) ? MarkovJumpsBeagleTreeLikelihood.HISTORY : MarkovJumpsBeagleTreeLikelihood.HISTORY + "_" + (site + 1);
treeTraitHistory[site] = treeLikelihood.getTreeTrait(traitName);
if (treeTraitHistory[site] == null) {
throw new RuntimeException("Tree '" + treeLikelihood.getId() + "' does not have a complete history trait at site " + (site + 1));
}
}
treeTraitCount = treeLikelihood.getTreeTrait(MarkovJumpsBeagleTreeLikelihood.TOTAL_COUNTS);
if (treeTraitCount == null) {
throw new RuntimeException("No sum");
}
Logger.getLogger("dr.app.beagle").info("\tConstructing a complete history logger; please cite:\n"
+ Citable.Utils.getCitationString(this));
}
public LogColumn[] getColumns() {
LogColumn[] columns = new LogColumn[1 + patternCount];
columns[0] = new LogColumn.Abstract(TOTAL_COUNT_NAME) {
@Override
protected String getFormattedValue() {
return treeTraitCount.getTraitString(tree, null);
}
};
for (int site = 0; site < patternCount; ++site) {
String name = (patternCount == 0) ? COMPLETE_HISTORY_NAME : COMPLETE_HISTORY_NAME + "_" + (site + 1);
final int anonSite = site;
columns[1 + site] = new LogColumn.Abstract(name) {
@Override
protected String getFormattedValue() {
boolean empty = true;
StringBuilder bf = new StringBuilder("{");
int count = 0;
for (int i = 0; i < tree.getNodeCount(); ++i) {
NodeRef node = tree.getNode(i);
if (!tree.isRoot(node)) {
NodeRef parent = tree.getParent(node);
double parentTime = tree.getNodeHeight(parent);
double childTime = tree.getNodeHeight(node);
double minTime = Math.min(parentTime, childTime);
double maxTime = Math.max(parentTime, childTime);
String trait = treeTraitHistory[anonSite].getTraitString(tree, node);
if (trait.compareTo("{}") != 0) {
trait = trait.substring(1, trait.length() - 1);
StringTokenizer st = new StringTokenizer(trait, ",");
while (st.hasMoreTokens()) {
if (!empty) {
bf.append(",");
}
String event = st.nextToken();
event = event.substring(1, event.length() - 1);
StringTokenizer value = new StringTokenizer(event, ":");
String source = value.nextToken();
String dest = value.nextToken();
double thisTime = Double.parseDouble(value.nextToken());
if (thisTime < 0.0) {
throw new RuntimeException("negative time");
}
if (thisTime > maxTime || thisTime < minTime) {
throw new RuntimeException("Invalid simulation time");
}
StateHistory.addEventToStringBuilder(bf, source, dest,
thisTime);
count++;
empty = false;
}
}
}
}
bf.append("}").append(" ").append(count);
return bf.toString();
}
};
}
return columns;
}
/**
* @return a list of citations associated with this object
*/
public List<Citation> getCitations() {
List<Citation> citations = new ArrayList<Citation>();
citations.add(CommonCitations.LEMEY_2012);
citations.add(CommonCitations.SHAPIRO_2012);
citations.add(CommonCitations.BLOOM_2012);
return citations;
}
final private Tree tree;
final private TreeTrait[] treeTraitHistory;
final private TreeTrait treeTraitCount;
final private int patternCount;
}
|
package tigase.server.xmppclient;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import tigase.conf.ConfigurationException;
import tigase.net.IOService;
import tigase.net.SocketThread;
import tigase.server.Command;
import tigase.server.ConnectionManager;
import tigase.server.Iq;
import tigase.server.Message;
import tigase.server.Packet;
import tigase.server.Presence;
import tigase.server.ReceiverTimeoutHandler;
import tigase.util.DNSResolver;
import tigase.util.RoutingsContainer;
import tigase.util.TigaseStringprepException;
import tigase.vhosts.VHostItem;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPIOService;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.impl.C2SDeliveryErrorProcessor;
/**
* Class ClientConnectionManager Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class ClientConnectionManager
extends ConnectionManager<XMPPIOService<Object>> {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(ClientConnectionManager.class
.getName());
private static final String ROUTING_ENTRY_PROP_KEY = ".+";
private static final String ROUTING_MODE_PROP_KEY = "multi-mode";
private static final String ROUTINGS_PROP_KEY = "routings";
private static final long SOCKET_CLOSE_WAIT_PROP_DEF = 1;
private static final String SOCKET_CLOSE_WAIT_PROP_KEY = "socket-close-wait";
private static final String TLS_WANT_CLIENT_AUTH_ENABLED_KEY =
"tls-want-client-auth-enabled";
private static final String XMLNS = "jabber:client";
private static final boolean TLS_WANT_CLIENT_AUTH_ENABLED_DEF = false;
private static final boolean ROUTING_MODE_PROP_VAL = true;
/** Field description */
protected RoutingsContainer routings = null;
/** Field description */
protected SeeOtherHostIfc see_other_host_strategy = null;
//private final Map<String, XMPPProcessorIfc> processors = new ConcurrentHashMap<String,
// XMPPProcessorIfc>();
private XMPPIOProcessor[] processors = new XMPPIOProcessor[0];
private final ReceiverTimeoutHandler stoppedHandler = newStoppedHandler();
private final ReceiverTimeoutHandler startedHandler = newStartedHandler();
private long socket_close_wait_time =
SOCKET_CLOSE_WAIT_PROP_DEF;
/**
* This is mostly for testing purpose. We want to investigate massive (10k
* per node) connections drops at the same time during tests with Tsung. I
* suspect this might be due to problems with one of the tsung VMs working
* in the cluster generating load. If I am right then all disconnects should
* come from only one or just a few machines. If I am not right disconnects
* should be distributed evenly among all Tsung IPs.
*/
private IPMonitor ipMonitor = new IPMonitor();
private final ClientTrustManagerFactory clientTrustManagerFactory =
new ClientTrustManagerFactory();
private boolean tlsWantClientAuthEnabled = TLS_WANT_CLIENT_AUTH_ENABLED_DEF;
/**
* This method can be overwritten in extending classes to get a different
* packets distribution to different threads. For PubSub, probably better
* packets distribution to different threads would be based on the sender
* address rather then destination address.
*
* @param packet
*
* @return a value of <code>int</code>
*/
@Override
public int hashCodeForPacket(Packet packet) {
if ((packet.getPacketFrom() != null) && getComponentId().getBareJID().equals(packet
.getPacketFrom().getBareJID())) {
return packet.getPacketFrom().hashCode();
} else {
return packet.getTo().hashCode();
}
}
/**
* Method description
*
* @param packet
*/
@Override
public void processPacket(final Packet packet) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing packet: {0}", packet.toStringSecure());
}
if (packet.isCommand() && (packet.getCommand() != Command.OTHER)) {
processCommand(packet);
} else {
if (!writePacketToSocket(packet)) {
// Connection closed or broken, send message back to the SM
// if this is not IQ result...
// Ignore also all presence packets with available, unavailble
if ((packet.getType() != StanzaType.result) && (packet.getType() != StanzaType
.available) && (packet.getType() != StanzaType.unavailable) && (packet
.getType() != StanzaType.error) &&!((packet.getElemName() == "presence") &&
(packet.getType() == null))) {
try {
Packet error = Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"The user connection is no longer active.", true);
addOutPacket(error);
} catch (PacketErrorTypeException e) {
if (log.isLoggable(Level.FINEST)) {
log.finest(
"Ups, already error packet. Dropping it to prevent infinite loop.");
}
}
}
// In case the SessionManager lost synchronization for any
// reason, let's
// notify it that the user connection no longer exists.
// But in case of mass-disconnects we might have lot's of
// presences
// floating around, so just skip sending stream_close for all
// the
// offline presences
if ((packet.getType() != StanzaType.unavailable) && (packet.getPacketFrom() !=
null)) {
if (packet.getStanzaTo() != null) {
Packet command = Command.STREAM_CLOSED_UPDATE.getPacket(packet.getStanzaTo(),
packet.getPacketFrom(), StanzaType.set, UUID.randomUUID().toString());
command.setPacketFrom(packet.getPacketTo());
command.setPacketTo(packet.getPacketFrom());
// Note! we don't want to receive response to this
// request,
// thus STREAM_CLOSED_UPDATE instead of STREAM_CLOSED
addOutPacket(command);
// addOutPacketWithTimeout(command, stoppedHandler, 15l,
// TimeUnit.SECONDS);
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,
"Sending a command to close the remote session for non-existen {0} connection: {1}",
new Object[] { getName(),
command.toStringSecure() });
}
} else {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.FINE,
"Stream close update without an user JID, skipping for packet: {0}",
new Object[] { packet });
}
}
}
}
} // end of else
}
/**
* Method description
*
* @param serv
*
* @return a value of <code>Queue<Packet></code>
*/
@Override
public Queue<Packet> processSocketData(XMPPIOService<Object> serv) {
// String id = getUniqueId(serv);
JID id = serv.getConnectionId();
// String hostname =
// (String)serv.getSessionData().get(serv.HOSTNAME_KEY);
Packet p = null;
while ((p = serv.getReceivedPackets().poll()) != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing socket data: {0} from connection: {1}",
new Object[] { p.toStringSecure(),
id });
}
// Sometimes xmlns is not set for the packet. Usually it does not
// cause any problems but when the packet is sent over the s2s, ext
// or cluster connection it may be quite problematic.
// Let's force jabber:client xmlns for all packets received from c2s
// connection
// Ups, some packets like starttls or sasl-auth have own XMLNS,
// overwriting it here is not really a good idea. We have to check
// first
// if the xmlns is not set and then force it to jabber:client
if (p.getAttributeStaticStr(Packet.XMLNS_ATT) == null) {
p.setXMLNS(XMLNS);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "XMLNS set for packet: {0} from connection: {1}",
new Object[] { p.toStringSecure(),
id });
}
}
// If client is sending packet with 'from' attribute set then packets
// are being duplicated in clustered environment, so best it would be
// to remove 'from' attribute as it will be set later during processing
// by SessionManager
if (p.getStanzaFrom() != null) {
p.initVars(null, p.getStanzaTo());
}
// p.setPacketFrom(getFromAddress(id));
p.setPacketFrom(id);
JID receiver = serv.getDataReceiver();
if (receiver != null) {
p.setPacketTo(serv.getDataReceiver());
addOutPacket(p);
} else {
// Hm, receiver is not set yet..., ignoring
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,
"Hm, receiver is not set yet stream open was not send by a client or server misconfiguration..., ignoring: {0}, connection: {1}",
new Object[] { p.toStringSecure(),
serv });
}
}
// TODO: Implement sending 'req' attributes by the server too
} // end of while ()
return null;
}
/**
* Processes undelivered packets
* @param packet
* @param errorMessage
* @return true - if packet was processed
*/
@Override
public boolean processUndeliveredPacket(Packet packet, String errorMessage) {
try {
// is there a point in trying to redeliver stanza of type error?
if (packet.getType() == StanzaType.error)
return false;
// we should not send errors for presences as Presence module does not
// allow to send presence with type error from users and presences
// with type error resulting from presences sent to barejid are
// messing up a lot on client side. moreover presences with type
// unavailable will be send by Presence plugin from SessionManager
// when session will be closed just after sending this errors
if (packet.getElemName() == Presence.ELEM_NAME) {
return false;
}
if (packet.getElemName() == Message.ELEM_NAME) {
// we should mark this message packet so that SM will know that it is
// resent from here due to connection failure
Packet result = C2SDeliveryErrorProcessor.makeDeliveryError(packet);
processOutPacket(result);
return true;
}
processOutPacket(Authorization.RECIPIENT_UNAVAILABLE
.getResponseMessage(packet, errorMessage, true));
} catch (PacketErrorTypeException ex) {
log.log(Level.FINER, "exception prepareing request for returning error, data = {0}",
packet);
}
return true;
}
/**
* Method description
*
* @param port_props
*/
@Override
public void reconnectionFailed(Map<String, Object> port_props) {}
/**
* Method description
*
*
* @param service
*/
@Override
public void serviceStarted(XMPPIOService<Object> service) {
super.serviceStarted(service);
String id = getUniqueId(service);
JID connectionId = getFromAddress(id);
service.setConnectionId(connectionId);
service.setProcessors(processors);
}
/**
* Method description
*
* @param service
*
* @return a value of <code>boolean</code>
*/
@Override
public boolean serviceStopped(XMPPIOService<Object> service) {
boolean result = super.serviceStopped(service);
if (result) {
Queue<Packet> undeliveredPackets = service.getWaitingPackets();
Packet p = null;
while ((p = undeliveredPackets.poll()) != null) {
processUndeliveredPacket(p, null);
}
}
xmppStreamClosed(service);
return result;
}
/**
* Method description
*/
@Override
public void start() {
super.start();
ipMonitor = new IPMonitor();
ipMonitor.start();
}
/**
* Method description
*/
@Override
public void stop() {
super.stop();
ipMonitor.stopThread();
}
/**
* Method description
*
*
* @param serv
*/
@Override
public void tlsHandshakeCompleted(XMPPIOService<Object> serv) {
if ((serv.getPeersJIDsFromCert() != null) && clientTrustManagerFactory.isActive()) {
Packet clientAuthCommand = Command.CLIENT_AUTH.getPacket(serv.getConnectionId(),
serv.getDataReceiver(), StanzaType.set, this.newPacketId("c2s-"), Command
.DataType.submit);
final String id = (String) serv.getSessionData().get(IOService.SESSION_ID_KEY);
Command.addFieldValue(clientAuthCommand, "session-id", id);
Command.addFieldValue(clientAuthCommand, "peer-certificate", "true");
Command.addFieldMultiValue(clientAuthCommand, "jids", serv.getPeersJIDsFromCert());
addOutPacket(clientAuthCommand);
}
}
/**
* Method description
*
* @param serv
*/
@Override
public void xmppStreamClosed(XMPPIOService<Object> serv) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Stream closed: {0}", serv.getConnectionId());
}
// It might be a Bosh service in which case it is ignored here.
// The method may be called more than one time for a single
// connection but we want to send a notification just once
if ((serv.getXMLNS() == XMLNS) && (serv.getSessionData().get("stream-closed") ==
null)) {
serv.getSessionData().put("stream-closed", "stream-closed");
ipMonitor.addDisconnect(serv.getRemoteAddress());
if (serv.getDataReceiver() != null) {
Packet command = Command.STREAM_CLOSED.getPacket(serv.getConnectionId(), serv
.getDataReceiver(), StanzaType.set, UUID.randomUUID().toString());
String userJid = serv.getUserJid();
if (userJid != null) {
Command.addFieldValue(command, "user-jid", userJid);
}
// In case of mass-disconnects, adjust the timeout properly
addOutPacketWithTimeout(command, stoppedHandler, 120l, TimeUnit.SECONDS);
log.log(Level.FINE, "Service stopped, sending packet: {0}", command);
//// For testing only.
// System.out.println("Service stopped: " +
// service.getUniqueId());
// Thread.dumpStack();
//// For testing only.
// System.out.println("Service stopped: " +
// service.getUniqueId());
// Thread.dumpStack();
} else {
log.fine("Service stopped, before stream:stream received");
}
serv.stop();
}
}
/**
* Method description
*
* @param serv
* @param attribs
*
* @return a value of <code>String</code>
*/
@Override
public String xmppStreamOpened(XMPPIOService<Object> serv, Map<String,
String> attribs) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Stream opened: {0}", attribs);
}
String lang = attribs.get("xml:lang");
final String hostname = attribs.get("to");
final String from = attribs.get("from");
BareJID fromJID = null;
if (from != null) {
try {
fromJID = BareJID.bareJIDInstance(from);
} catch (TigaseStringprepException ex) {
log.log(Level.CONFIG, "From JID violates RFC6122 (XMPP:Address Format): ", ex);
return "<?xml version='1.0'?><stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + getDefVHostItem() + "'" +
" version='1.0' xml:lang='en'>" + "<stream:error>" +
"<improper-addressing xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>" +
"</stream:error>" + "</stream:stream>";
} // end of: try-catch
} // end of: if (from != null) {
if (lang == null) {
lang = "en";
}
if (hostname == null) {
return "<?xml version='1.0'?><stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + getDefVHostItem() + "'" +
" version='1.0' xml:lang='en'>" + "<stream:error>" +
"<improper-addressing xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>" +
"</stream:error>" + "</stream:stream>";
} // end of if (hostname == null)
if (!isLocalDomain(hostname)) {
return "<?xml version='1.0'?><stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + getDefVHostItem() + "'" +
" version='1.0' xml:lang='en'>" + "<stream:error>" +
"<host-unknown xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>" +
"</stream:error>" + "</stream:stream>";
} // end of if (!hostnames.contains(hostname))
if (!isAllowed(serv, hostname)) {
return "<?xml version='1.0'?><stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + hostname + "'" +
" version='1.0' xml:lang='en'>" + "<stream:error>" +
"<policy-violation xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>" +
"</stream:error>" + "</stream:stream>";
}
if ((fromJID != null) && (see_other_host_strategy != null) && see_other_host_strategy
.isEnabled(SeeOtherHostIfc.Phase.OPEN)) {
BareJID see_other_host = see_other_host_strategy.findHostForJID(fromJID,
getDefHostName());
if ((see_other_host != null) &&!see_other_host.equals(getDefHostName())) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Sending redirect for {0} to host {1}, connection {2}.",
new Object[] { fromJID,
see_other_host, serv });
}
return "<stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + getDefVHostItem() + "'" +
" version='1.0' xml:lang='en'>" + see_other_host_strategy.getStreamError(
"urn:ietf:params:xml:ns:xmpp-streams", see_other_host).toString() +
"</stream:stream>";
}
} // of if (from != null )
String id = (String) serv.getSessionData().get(IOService.SESSION_ID_KEY);
if (id == null) {
id = UUID.randomUUID().toString();
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "No Session ID, generating a new one: {0}", id);
}
serv.getSessionData().put(IOService.SESSION_ID_KEY, id);
serv.setXMLNS(XMLNS);
serv.getSessionData().put(IOService.HOSTNAME_KEY, hostname);
serv.setDataReceiver(JID.jidInstanceNS(routings.computeRouting(hostname)));
String streamOpenData = "<?xml version='1.0'?><stream:stream" + " xmlns='" +
XMLNS + "'" + " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" +
hostname + "'" + " id='" + id + "'" + " version='1.0' xml:lang='en'>";
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Writing raw data to the socket: {0}", streamOpenData);
}
writeRawData(serv, streamOpenData);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "DONE");
}
Packet streamOpen = Command.STREAM_OPENED.getPacket(serv.getConnectionId(), serv
.getDataReceiver(), StanzaType.set, this.newPacketId("c2s-"), Command.DataType
.submit);
Command.addFieldValue(streamOpen, "session-id", id);
Command.addFieldValue(streamOpen, "hostname", hostname);
Command.addFieldValue(streamOpen, "xml:lang", lang);
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Sending a system command to SM: {0}", streamOpen);
}
addOutPacketWithTimeout(streamOpen, startedHandler, 45l, TimeUnit.SECONDS);
log.log(Level.FINER, "DOEN 2");
} else {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Session ID is: {0}", id);
}
writeRawData(serv, "<?xml version='1.0'?><stream:stream" + " xmlns='" + XMLNS +
"'" + " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" +
hostname + "'" + " id='" + id + "'" + " version='1.0' xml:lang='en'>");
addOutPacket(Command.GETFEATURES.getPacket(serv.getConnectionId(), serv
.getDataReceiver(), StanzaType.get, UUID.randomUUID().toString(), null));
}
return null;
}
/**
* Method description
*
* @param params
*
* @return a value of <code>Map<String,Object></code>
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
Boolean r_mode = (Boolean) params.get(getName() + "/" +
ROUTINGS_PROP_KEY + "/" + ROUTING_MODE_PROP_KEY);
String see_other_host_class = (String) params.get(SeeOtherHostIfc
.CM_SEE_OTHER_HOST_CLASS_PROPERTY);
see_other_host_strategy = getSeeOtherHostInstance(see_other_host_class);
props.put(SeeOtherHostIfc.CM_SEE_OTHER_HOST_CLASS_PROP_KEY, see_other_host_class);
if (see_other_host_strategy != null) {
see_other_host_strategy.getDefaults(props, params);
}
if (r_mode == null) {
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_MODE_PROP_KEY, ROUTING_MODE_PROP_VAL);
// If the server is configured as connection manager only node then
// route packets to SM on remote host where is default routing
// for external component.
// Otherwise default routing is to SM on localhost
if (params.get("config-type").equals(GEN_CONFIG_CS) && (params.get(GEN_EXT_COMP) !=
null)) {
String[] comp_params = ((String) params.get(GEN_EXT_COMP)).split(",");
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_ENTRY_PROP_KEY, DEF_SM_NAME + "@" +
comp_params[1]);
} else {
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_ENTRY_PROP_KEY, DEF_SM_NAME + "@" +
DNSResolver.getDefaultHostname());
}
}
props.put(SOCKET_CLOSE_WAIT_PROP_KEY, SOCKET_CLOSE_WAIT_PROP_DEF);
props.put(TLS_WANT_CLIENT_AUTH_ENABLED_KEY, TLS_WANT_CLIENT_AUTH_ENABLED_DEF);
return props;
}
/**
* Method description
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoCategoryType() {
return "c2s";
}
/**
* Method description
*
*
* @return a value of <code>String</code>
*/
@Override
public String getDiscoDescription() {
return "Client connection manager";
}
/**
* Method description
*
*
* @param see_other_host_class
*
*
* @return a value of <code>SeeOtherHostIfc</code>
*/
public SeeOtherHostIfc getSeeOtherHostInstance(String see_other_host_class) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Configuring see_other_host strategy for: " + see_other_host_class);
}
if (see_other_host_class == null) {
see_other_host_class = SeeOtherHostIfc.CM_SEE_OTHER_HOST_CLASS_PROP_DEF_VAL;
}
if (see_other_host_class.equals("none")) {
return null;
}
try {
see_other_host_strategy = (SeeOtherHostIfc) Class.forName(see_other_host_class)
.newInstance();
} catch (Exception e) {
log.log(Level.SEVERE, "Can not instantiate see_other_host strategy for class: " +
see_other_host_class, e);
}
return see_other_host_strategy;
}
/**
* Method description
*
* @param props
* @throws tigase.conf.ConfigurationException
*/
@Override
public void setProperties(Map<String, Object> props) throws ConfigurationException {
super.setProperties(props);
clientTrustManagerFactory.setProperties(props);
if (props.get(SOCKET_CLOSE_WAIT_PROP_KEY) != null) {
socket_close_wait_time = (Long) props.get(SOCKET_CLOSE_WAIT_PROP_KEY);
}
processors = XMPPIOProcessorsFactory.updateIOProcessors(this, processors, props);
if (props.size() == 1) {
// If props.size() == 1, it means this is a single property update
// and this component does not support single property change for
// the rest
// of it's settings
return;
}
String see_other_host_class = (String) props.get(SeeOtherHostIfc
.CM_SEE_OTHER_HOST_CLASS_PROP_KEY);
see_other_host_strategy = getSeeOtherHostInstance(see_other_host_class);
if (see_other_host_strategy != null) {
see_other_host_strategy.setProperties(props);
}
boolean routing_mode = (Boolean) props.get(ROUTINGS_PROP_KEY + "/" +
ROUTING_MODE_PROP_KEY);
routings = new RoutingsContainer(routing_mode);
int idx = (ROUTINGS_PROP_KEY + "/").length();
for (Map.Entry<String, Object> entry : props.entrySet()) {
if (entry.getKey().startsWith(ROUTINGS_PROP_KEY + "/") &&!entry.getKey().equals(
ROUTINGS_PROP_KEY + "/" + ROUTING_MODE_PROP_KEY)) {
routings.addRouting(entry.getKey().substring(idx), (String) entry.getValue());
} // end of if (entry.getKey().startsWith(ROUTINGS_PROP_KEY + "/"))
} // end of for ()
if (props.containsKey(TLS_WANT_CLIENT_AUTH_ENABLED_KEY)) {
tlsWantClientAuthEnabled = (Boolean) props.get(TLS_WANT_CLIENT_AUTH_ENABLED_KEY);
}
}
/**
* Method description
*
*
* @param packet
* @param newAddress
* @param command_sessionId
* @param serv
*
* @return a value of <code>JID</code>
*/
protected JID changeDataReceiver(Packet packet, JID newAddress,
String command_sessionId, XMPPIOService<Object> serv) {
if (serv != null) {
String serv_sessionId = (String) serv.getSessionData().get(IOService
.SESSION_ID_KEY);
if (serv_sessionId.equals(command_sessionId)) {
JID old_receiver = serv.getDataReceiver();
serv.setDataReceiver(newAddress);
return old_receiver;
} else {
log.log(Level.WARNING,
"Incorrect session ID, ignoring data redirect for: {0}, expected: {1}, received: {2}",
new Object[] { newAddress,
serv_sessionId, command_sessionId });
}
}
return null;
}
protected boolean isAllowed(XMPPIOService<Object> serv, String hostname) {
VHostItem vhost = this.vHostManager.getVHostItem(hostname);
if (vhost != null) {
int[] allowedPorts = vhost.getC2SPortsAllowed();
if (allowedPorts != null && Arrays.binarySearch(allowedPorts, serv.getLocalPort()) < 0) {
return false;
}
}
return true;
}
/**
* Method description
*
*
*
* @return a value of <code>ReceiverTimeoutHandler</code>
*/
protected ReceiverTimeoutHandler newStartedHandler() {
return new StartedHandler();
}
/**
* Method description
*
*
*
* @return a value of <code>ReceiverTimeoutHandler</code>
*/
protected ReceiverTimeoutHandler newStoppedHandler() {
return new StoppedHandler();
}
/**
* Method description
*
*
* @param packet
*/
protected void processCommand(Packet packet) {
XMPPIOService<Object> serv = getXMPPIOService(packet);
Iq iqc = (Iq) packet;
switch (iqc.getCommand()) {
case GETFEATURES :
if (iqc.getType() == StanzaType.result) {
List<Element> features = getFeatures(serv);
Element elem_features = new Element("stream:features");
elem_features.addChildren(features);
elem_features.addChildren(Command.getData(iqc));
Packet result = Packet.packetInstance(elem_features, null, null);
// Is it actually needed?? Yes, it is needed, IOService is
// looked up based on this.
result.setPacketTo(iqc.getTo());
writePacketToSocket(result);
} // end of if (packet.getType() == StanzaType.get)
break;
case USER_LOGIN :
String jid = Command.getFieldValue(iqc, "user-jid");
if (jid != null) {
if (serv != null) {
BareJID fromJID = null;
try {
fromJID = BareJID.bareJIDInstance(jid);
} catch (TigaseStringprepException ex) {
log.log(Level.SEVERE, null, ex);
}
if ((fromJID != null) && ((see_other_host_strategy != null) &&
see_other_host_strategy.isEnabled(SeeOtherHostIfc.Phase.LOGIN))) {
BareJID see_other_host = see_other_host_strategy.findHostForJID(fromJID,
getDefHostName());
if ((see_other_host != null) &&!see_other_host.equals(getDefHostName())) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,
"Sending redirect for {0} to host {1}, connection {2}.",
new Object[] { fromJID,
see_other_host, serv });
}
String redirectMessage = "<stream:stream" + " xmlns='" + XMLNS + "'" +
" xmlns:stream='http://etherx.jabber.org/streams'" +
" id='tigase-error-tigase'" + " from='" + getDefVHostItem() + "'" +
" version='1.0' xml:lang='en'>" + see_other_host_strategy
.getStreamError("urn:ietf:params:xml:ns:xmpp-streams", see_other_host)
.toString() + "</stream:stream>";
try {
SocketThread.removeSocketService(serv);
serv.writeRawData(redirectMessage);
serv.processWaitingPackets();
Thread.sleep(socket_close_wait_time);
serv.stop();
} catch (Exception e) {}
}
} else {
serv.setUserJid(jid);
}
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Missing XMPPIOService for USER_LOGIN command: {0}", iqc);
}
}
} else {
log.log(Level.WARNING, "Missing user-jid for USER_LOGIN command: {0}", iqc);
}
break;
case STARTZLIB :
if (serv != null) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Starting zlib compression: {0}", serv);
}
try {
Element compressed = Command.getData(iqc, "compressed", null);
Packet p_compressed = Packet.packetInstance(compressed, null, null);
// SocketThread readThread = SocketThread.getInstance();
SocketThread.removeSocketService(serv);
// writePacketToSocket(serv, p_proceed);
serv.addPacketToSend(p_compressed);
serv.processWaitingPackets();
serv.startZLib(Deflater.BEST_COMPRESSION);
// serv.call();
SocketThread.addSocketService(serv);
} catch (IOException ex) {
log.log(Level.INFO, "Problem enabling zlib compression on the connection: ",
ex);
}
} else {
log.log(Level.WARNING, "Can't find sevice for STARTZLIB command: {0}", iqc);
}
break;
case STARTTLS :
if (serv != null) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Starting TLS for connection: {0}", serv);
}
try {
// Note:
// If you send <proceed> packet to client you must expect
// instant response from the client with TLS handshaking
// data before you will call startTLS() on server side.
// So the initial handshaking data might be lost as they
// will be processed in another thread reading data from the
// socket.
// That's why below code first removes service from reading
// threads pool and then sends <proceed> packet and starts
// TLS.
Element proceed = Command.getData(iqc, "proceed", null);
Packet p_proceed = Packet.packetInstance(proceed, null, null);
// SocketThread readThread = SocketThread.getInstance();
SocketThread.removeSocketService(serv);
// writePacketToSocket(serv, p_proceed);
serv.addPacketToSend(p_proceed);
serv.processWaitingPackets();
TrustManager[] x = clientTrustManagerFactory.getManager(serv);
serv.setX509TrustManagers(x);
serv.startTLS(false, isTlsWantClientAuthEnabled());
SocketThread.addSocketService(serv);
} catch (Exception e) {
log.log(Level.WARNING, "Error starting TLS: {0}", e);
serv.forceStop();
} // end of try-catch
} else {
log.log(Level.WARNING, "Can't find sevice for STARTTLS command: {0}", iqc);
} // end of else
break;
case REDIRECT :
String command_sessionId = Command.getFieldValue(iqc, "session-id");
JID newAddress = iqc.getFrom();
JID old_receiver = changeDataReceiver(iqc, newAddress, command_sessionId, serv);
if (old_receiver != null) {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Redirecting data for sessionId: {0}, to: {1}",
new Object[] { command_sessionId,
newAddress });
}
Packet response = null;
response = iqc.commandResult(null);
Command.addFieldValue(response, "session-id", command_sessionId);
Command.addFieldValue(response, "action", "activate");
response.getElement().setAttribute("to", newAddress.toString());
addOutPacket(response);
} else {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST,
"Connection for REDIRECT command does not exist, ignoring " + "packet: " +
"{0}", iqc.toStringSecure());
}
}
break;
case STREAM_CLOSED :
break;
case GETDISCO :
break;
case CLOSE :
if (serv != null) {
String streamClose = "</stream:stream>";
List<Element> err_el = packet.getElement().getChildrenStaticStr(Iq
.IQ_COMMAND_PATH);
boolean moreToSend = false;
if ((err_el != null) && (err_el.size() > 0)) {
streamClose = "<stream:error>" + err_el.get(0).toString() + "</stream:error>" +
streamClose;
moreToSend = true;
}
try {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Sending stream close to the client: {0}", streamClose);
}
serv.writeRawData(streamClose);
if (moreToSend) {
// This is kind of a workaround. serv.stop() is supposed
// to wait
// until all data are sent to the client, however, even
// then there
// is still a chance, that the connection is closed
// before data
// reached the client
Thread.sleep(socket_close_wait_time);
}
} catch (Exception e) {}
serv.stop();
} else {
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE,
"Attempt to stop non-existen service for packet: {0}, Service already stopped?",
iqc);
}
} // end of if (serv != null) else
break;
case CHECK_USER_CONNECTION :
if (serv != null) {
// It's ok, the session has been found, respond with OK.
addOutPacket(iqc.okResult((String) null, 0));
} else {
// Session is no longer active, respond with an error.
try {
addOutPacket(Authorization.ITEM_NOT_FOUND.getResponseMessage(iqc,
"Connection gone.", false));
} catch (PacketErrorTypeException e) {
// Hm, error already, ignoring...
log.log(Level.INFO, "Error packet is not really expected here: {0}", iqc
.toStringSecure());
}
}
break;
case STREAM_MOVED :
if (processors != null) {
for (XMPPIOProcessor processor : processors) {
// handled |= processor.processCommand(packet);
processor.processCommand(serv, packet);
}
}
break;
default :
writePacketToSocket(iqc);
break;
} // end of switch (pc.getCommand())
}
/**
* Method description
*
*
*
* @return a value of <code>int[]</code>
*/
@Override
protected int[] getDefPlainPorts() {
return new int[] { 5222 };
}
/**
* Method description
*
*
*
* @return a value of <code>int[]</code>
*/
@Override
protected int[] getDefSSLPorts() {
return new int[] { 5223 };
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time for
* inactive connection. Let's assume user should send something at least
* once every 24 hours....
*
* @return a <code>long</code> value
*/
@Override
protected long getMaxInactiveTime() {
return 24 * HOUR;
}
/**
* Method description
*
*
* @param def
*
*
* @return a value of <code>Integer</code>
*/
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
/**
* Method description
*
*
*
* @return a value of <code>XMPPIOService<Object></code>
*/
@Override
protected XMPPIOService<Object> getXMPPIOServiceInstance() {
return new XMPPIOService<Object>();
}
/**
* Method description
*
*
* @return a value of <code>boolean</code>
*/
@Override
protected boolean isTlsWantClientAuthEnabled() {
return clientTrustManagerFactory.isSaslExternalAvailable();
}
private List<Element> getFeatures(XMPPIOService service) {
List<Element> results = new LinkedList<Element>();
for (XMPPIOProcessor proc : processors) {
Element[] features = proc.supStreamFeatures(service);
if (features != null) {
results.addAll(Arrays.asList(features));
} // end of if (features != null)
} // end of for ()
return results;
}
private JID getFromAddress(String id) {
return JID.jidInstanceNS(getName(), getDefHostName().getDomain(), id);
}
private XMPPResourceConnection getXMPPSession(Packet p) {
XMPPIOService<Object> serv = getXMPPIOService(p);
return (serv == null)
? null
: (XMPPResourceConnection) serv.getSessionData().get("xmpp-session");
}
private class StartedHandler
implements ReceiverTimeoutHandler {
/**
* Method description
*
* @param packet
* @param response
*/
@Override
public void responseReceived(Packet packet, Packet response) {
// We are now ready to ask for features....
addOutPacket(Command.GETFEATURES.getPacket(packet.getFrom(), packet.getTo(),
StanzaType.get, UUID.randomUUID().toString(), null));
}
/**
* Method description
*
* @param packet
*/
@Override
public void timeOutExpired(Packet packet) {
// If we still haven't received confirmation from the SM then
// the packet either has been lost or the server is overloaded
// In either case we disconnect the connection.
log.log(Level.INFO, "No response within time limit received for a packet: {0}",
packet.toStringSecure());
XMPPIOService<Object> serv = getXMPPIOService(packet.getFrom().toString());
if (serv != null) {
serv.stop();
} else {
log.log(Level.FINE,
"Attempt to stop non-existen service for packet: {0}, Service already stopped?",
packet);
} // end of if (serv != null) else
}
}
private class StoppedHandler
implements ReceiverTimeoutHandler {
/**
* Method description
*
* @param packet
* @param response
*/
@Override
public void responseReceived(Packet packet, Packet response) {
// Great, nothing to worry about.
if (log.isLoggable(Level.FINEST)) {
log.finest("Response for stop received...");
}
}
/**
* Method description
*
* @param packet
*/
@Override
public void timeOutExpired(Packet packet) {
// Ups, doesn't look good, the server is either oveloaded or lost
// a packet.
log.log(Level.INFO, "No response within time limit received for a packet: {0}",
packet.toStringSecure());
addOutPacketWithTimeout(packet, stoppedHandler, 60l, TimeUnit.SECONDS);
}
}
}
//~ Formatted in Tigase Code Convention on 13/09/21
|
package zmaster587.advancedRocketry.tile.cables;
import zmaster587.advancedRocketry.cable.HandlerCableNetwork;
import zmaster587.advancedRocketry.cable.NetworkRegistry;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public class TilePipe extends TileEntity {
int networkID;
boolean initialized, destroyed;
boolean connectedSides[];
public TilePipe() {
initialized = false;
destroyed = false;
connectedSides = new boolean[6];
}
public void initialize(int id) {
networkID = id;
initialized = true;
getNetworkHandler().getNetwork(id).addPipeToNetwork(this);
}
@Override
public void invalidate() {
super.invalidate();
removePipeFromSystem();
}
@Override
public void onChunkUnload() {
super.onChunkUnload();
removePipeFromSystem();
}
public void removePipeFromSystem() {
if(!isInitialized())
return;
for(EnumFacing dir : EnumFacing.VALUES) {
TileEntity tile = worldObj.getTileEntity(this.getPos().offset(dir));
if(tile != null)
getNetworkHandler().removeFromAllTypes(this, tile);
}
getNetworkHandler().getNetwork(networkID).removePipeFromNetwork(this);
//Recreate the network until a clean way to tranverse nets in unloaded chunk can be found
getNetworkHandler().removeNetworkByID(networkID);
}
@Override
public void markDirty() {
super.markDirty();
if(!worldObj.isRemote) {
worldObj.notifyBlockUpdate(pos, worldObj.getBlockState(pos), worldObj.getBlockState(pos), 3);
}
}
public void onPlaced() {
for(EnumFacing dir : EnumFacing.values()) {
TileEntity tile = worldObj.getTileEntity(getPos().offset(dir));
if(tile != null) {
if(tile instanceof TilePipe && tile.getClass() == this.getClass()) {
TilePipe pipe = (TilePipe)tile;
if(this.destroyed)
continue;
if(initialized && pipe.isInitialized() && pipe.getNetworkID() != networkID)
getNetworkHandler().mergeNetworks(networkID, pipe.getNetworkID());
else if(!initialized && pipe.isInitialized()) {
initialize(pipe.getNetworkID());
}
}
}
}
if(!initialized) {
initialize(getNetworkHandler().getNewNetworkID());
}
linkSystems();
}
public void linkSystems() {
for(EnumFacing dir : EnumFacing.values()) {
TileEntity tile = worldObj.getTileEntity(getPos().offset(dir));
if(tile != null &&tile.getClass() == this.getClass()) {
attemptLink(dir, tile);
}
}
}
protected void attemptLink(EnumFacing dir, TileEntity tile) {
//If the pipe can inject or extract, add to the cache
//if(!(tile instanceof IFluidHandler))
//return;
if(canExtract(dir, tile) && (worldObj.isBlockIndirectlyGettingPowered(pos) > 0 || worldObj.getStrongPower(pos) > 0)) {
if(worldObj.isRemote)
connectedSides[dir.ordinal()]=true;
else {
getNetworkHandler().removeFromAllTypes(this, tile);
getNetworkHandler().addSource(this,tile,dir);
}
}
if(canInject(dir, tile) && worldObj.isBlockIndirectlyGettingPowered(pos) == 0 && worldObj.getStrongPower(pos) == 0) {
if(worldObj.isRemote)
connectedSides[dir.ordinal()]=true;
else {
getNetworkHandler().removeFromAllTypes(this, tile);
getNetworkHandler().addSink(this, tile,dir);
}
}
}
public int getNetworkID() { return networkID; }
public boolean isInitialized() { return initialized && getNetworkHandler().doesNetworkExist(networkID); }
public void onNeighborTileChange(BlockPos pos) {
//if(worldObj.isRemote)
//return;
TileEntity tile = worldObj.getTileEntity(pos);
if(!worldObj.isRemote && !getNetworkHandler().doesNetworkExist(networkID)) {
initialized = false;
}
if(tile != null && tile.getClass() == this.getClass()) {
//If two networks touch, merge them
if(tile instanceof TilePipe) {
TilePipe pipe = ((TilePipe) tile);
if(worldObj.isRemote) {
EnumFacing dir = null;
for(EnumFacing dir2 : EnumFacing.values()) {
if(getPos().offset(dir2).compareTo(pos) == 0)
dir = dir2;
}
if(dir != null)
connectedSides[dir.ordinal()] = true;
}
else {
if(this.destroyed)
return;
if(pipe.isInitialized()) {
if(!initialized) {
initialize(pipe.getNetworkID());
linkSystems();
markDirty();
} else if(pipe.getNetworkID() != networkID)
mergeNetworks(pipe.getNetworkID(), networkID);
}
else if(isInitialized()) {
pipe.initialize(networkID);
}
else {
onPlaced();
markDirty();
}
}
}
else {
if(!worldObj.isRemote && !initialized) {
networkID = getNetworkHandler().getNewNetworkID();
initialized = true;
}
EnumFacing dir = null;
for(EnumFacing dir2 : EnumFacing.values()) {
if(getPos().offset(dir2).compareTo(pos) == 0)
dir = dir2;
}
//If the pipe can inject or extract, add to the cache
if(dir != null)
attemptLink(dir, tile);
}
}
else if(worldObj.isRemote) {
EnumFacing dir = null;
for(EnumFacing dir2 : EnumFacing.values()) {
if(getPos().offset(dir2).compareTo(pos) == 0)
dir = dir2;
}
if(dir != null)
connectedSides[dir.ordinal()] = false;
}
}
public HandlerCableNetwork getNetworkHandler() {
return NetworkRegistry.liquidNetwork;
}
public boolean canConnect(int side) {
return connectedSides[side];
}
public boolean canExtract(EnumFacing dir, TileEntity e) {
return false;
}
public boolean canInject(EnumFacing dir, TileEntity e) {
return false;
}
public void mergeNetworks(int a, int b) {
networkID = getNetworkHandler().mergeNetworks(a, b);
this.markDirty();
}
@Override
public String toString() {
return "ID: " + networkID + " " + getNetworkHandler().toString(networkID);
}
public void setDestroyed() {
destroyed = true;
}
public void setInvalid() {
initialized = false;
//markDirty();
}
}
|
package dr.evomodel.beagle.treelikelihood;
import beagle.Beagle;
import beagle.BeagleFactory;
import dr.evolution.alignment.PatternList;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.TaxonList;
import dr.evomodel.beagle.parsers.TreeLikelihoodParser;
import dr.evomodel.beagle.sitemodel.BranchSiteModel;
import dr.evomodel.beagle.sitemodel.SiteRateModel;
import dr.evomodel.beagle.substmodel.EigenDecomposition;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DefaultBranchRateModel;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Model;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Marc Suchard
* @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $
*/
public class BeagleTreeLikelihood extends AbstractTreeLikelihood {
/**
* Constructor.
*/
public BeagleTreeLikelihood(PatternList patternList,
TreeModel treeModel,
BranchSiteModel branchSiteModel,
SiteRateModel siteRateModel,
BranchRateModel branchRateModel,
boolean useAmbiguities,
int deviceNumber,
boolean preferSinglePrecision
) {
super(TreeLikelihoodParser.TREE_LIKELIHOOD, patternList, treeModel);
try {
final Logger logger = Logger.getLogger("dr.evomodel");
logger.info("Using BEAGLE TreeLikelihood");
this.siteRateModel = siteRateModel;
addModel(this.siteRateModel);
this.branchSiteModel = branchSiteModel;
addModel(branchSiteModel);
if (branchRateModel != null) {
this.branchRateModel = branchRateModel;
logger.info("Branch rate model used: " + branchRateModel.getModelName());
} else {
this.branchRateModel = new DefaultBranchRateModel();
}
addModel(this.branchRateModel);
this.categoryCount = this.siteRateModel.getCategoryCount();
int extNodeCount = treeModel.getExternalNodeCount();
Map<String, Object> configuration = new HashMap<String, Object>();
configuration.put(BeagleFactory.STATE_COUNT, stateCount);
configuration.put(BeagleFactory.PREFER_SINGLE_PRECISION, preferSinglePrecision);
configuration.put(BeagleFactory.DEVICE_NUMBER, deviceNumber);
beagle = BeagleFactory.loadBeagleInstance(configuration);
// override use preference on useAmbiguities based on actual ability of the likelihood core
if (!beagle.canHandleTipPartials()) {
useAmbiguities = false;
}
if (!beagle.canHandleTipStates()){
useAmbiguities = true;
}
// dynamicRescaling = likelihoodCore.canHandleDynamicRescaling();
beagle.initialize(
nodeCount,
extNodeCount,
patternCount,
categoryCount,
1 // matrixCount
);
for (int i = 0; i < extNodeCount; i++) {
// Find the id of tip i in the patternList
String id = treeModel.getTaxonId(i);
int index = patternList.getTaxonIndex(id);
if (index == -1) {
throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
", is not found in patternList, " + patternList.getId());
} else {
if (useAmbiguities) {
setPartials(beagle, patternList, index, i);
} else {
setStates(beagle, patternList, index, i);
}
}
}
updateSubstitutionModel = true;
updateSiteModel = true;
} catch (TaxonList.MissingTaxonException mte) {
throw new RuntimeException(mte.toString());
}
hasInitialized = true;
}
/**
* Sets the partials from a sequence in an alignment.
*/
protected final void setPartials(Beagle beagle,
PatternList patternList,
int sequenceIndex,
int nodeIndex) {
double[] partials = new double[patternCount * stateCount];
boolean[] stateSet;
int v = 0;
for (int i = 0; i < patternCount; i++) {
int state = patternList.getPatternState(sequenceIndex, i);
stateSet = dataType.getStateSet(state);
for (int j = 0; j < stateCount; j++) {
if (stateSet[j]) {
partials[v] = 1.0;
} else {
partials[v] = 0.0;
}
v++;
}
}
beagle.setTipPartials(nodeIndex, partials);
}
/**
* Sets the partials from a sequence in an alignment.
*/
protected final void setStates(Beagle beagle,
PatternList patternList,
int sequenceIndex,
int nodeIndex) {
int i;
int[] states = new int[patternCount];
for (i = 0; i < patternCount; i++) {
states[i] = patternList.getPatternState(sequenceIndex, i);
}
beagle.setTipStates(nodeIndex, states);
}
// ModelListener IMPLEMENTATION
/**
* Handles model changed events from the submodels.
*/
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (model == treeModel) {
if (object instanceof TreeModel.TreeChangedEvent) {
if (((TreeModel.TreeChangedEvent) object).isNodeChanged()) {
// If a node event occurs the node and its two child nodes
// are flagged for updating (this will result in everything
// above being updated as well. Node events occur when a node
// is added to a branch, removed from a branch or its height or
// rate changes.
updateNodeAndChildren(((TreeModel.TreeChangedEvent) object).getNode());
} else if (((TreeModel.TreeChangedEvent) object).isTreeChanged()) {
// Full tree events result in a complete updating of the tree likelihood
// Currently this event type is not used.
System.err.println("Full tree update event - these events currently aren't used\n" +
"so either this is in error or a new feature is using them so remove this message.");
updateAllNodes();
} else {
// Other event types are ignored (probably trait changes).
//System.err.println("Another tree event has occured (possibly a trait change).");
}
}
} else if (model == branchRateModel) {
if (index == -1) {
updateAllNodes();
} else {
updateNode(treeModel.getNode(index));
}
} else if (model == branchSiteModel) {
updateSubstitutionModel = true;
updateAllNodes();
} else if (model == siteRateModel) {
updateSubstitutionModel = true;
updateSiteModel = true;
updateAllNodes();
} else {
throw new RuntimeException("Unknown componentChangedEvent");
}
super.handleModelChangedEvent(model, object, index);
}
// Model IMPLEMENTATION
/**
* Stores the additional state other than model components
*/
protected void storeState() {
beagle.storeState();
super.storeState();
}
/**
* Restore the additional stored state
*/
protected void restoreState() {
beagle.restoreState();
super.restoreState();
}
// Likelihood IMPLEMENTATION
/**
* Calculate the log likelihood of the current state.
*
* @return the log likelihood.
*/
protected double calculateLogLikelihood() {
if (patternLogLikelihoods == null) {
patternLogLikelihoods = new double[patternCount];
}
if (branchUpdateIndices == null) {
branchUpdateIndices = new int[nodeCount];
branchLengths = new double[nodeCount];
}
if (operations == null) {
operations = new int[nodeCount * 3];
dependencies = new int[nodeCount];
}
branchUpdateCount = 0;
operationCount = 0;
final NodeRef root = treeModel.getRoot();
traverse(treeModel, root, null);
if (updateSubstitutionModel) {
// we are currently assuming a homogenous model...
EigenDecomposition ed = branchSiteModel.getEigenDecomposition(0, 0);
beagle.setStateFrequencies(branchSiteModel.getStateFrequencies(0));
beagle.setEigenDecomposition(
0, // we are only dealing with a single matrix over all categories
ed.getEigenVectors(),
ed.getInverseEigenVectors(),
ed.getEigenValues());
}
if (updateSiteModel) {
beagle.setCategoryRates(this.siteRateModel.getCategoryRates());
beagle.setCategoryProportions(this.siteRateModel.getCategoryProportions());
}
beagle.calculateProbabilityTransitionMatrices(branchUpdateIndices, branchLengths, branchUpdateCount);
beagle.calculatePartials(operations,dependencies, operationCount,false);
nodeEvaluationCount += operationCount;
beagle.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods);
double logL = 0.0;
for (int i = 0; i < patternCount; i++) {
logL += patternLogLikelihoods[i] * patternWeights[i];
}
// Attempt dynamic rescaling if over/under-flow
if (logL == Double.NaN || logL == Double.POSITIVE_INFINITY ) {
System.err.println("Potential under/over-flow; going to attempt a partials rescaling.");
updateAllNodes();
branchUpdateCount = 0;
operationCount = 0;
traverse(treeModel, root, null);
beagle.calculatePartials(operations,dependencies, operationCount,true);
beagle.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods);
logL = 0.0;
for (int i = 0; i < patternCount; i++) {
logL += patternLogLikelihoods[i] * patternWeights[i];
}
}
/**
* Traverse the tree calculating partial likelihoods.
*/
private boolean traverse(Tree tree, NodeRef node, int[] operatorNumber) {
boolean update = false;
int nodeNum = node.getNumber();
NodeRef parent = tree.getParent(node);
if (operatorNumber != null) {
operatorNumber[0] = -1;
}
// First update the transition probability matrix(ices) for this branch
if (parent != null && updateNode[nodeNum]) {
final double branchRate = branchRateModel.getBranchRate(tree, node);
// Get the operational time of the branch
final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
if (branchTime < 0.0) {
throw new RuntimeException("Negative branch length: " + branchTime);
}
branchUpdateIndices[branchUpdateCount] = nodeNum;
branchLengths[branchUpdateCount] = branchTime;
branchUpdateCount++;
update = true;
}
// If the node is internal, update the partial likelihoods.
if (!tree.isExternal(node)) {
// Traverse down the two child nodes
NodeRef child1 = tree.getChild(node, 0);
final int[] op1 = new int[] { -1 };
final boolean update1 = traverse(tree, child1, op1);
NodeRef child2 = tree.getChild(node, 1);
final int[] op2 = new int[] { -1 };
final boolean update2 = traverse(tree, child2, op2);
// If either child node was updated then update this node too
if (update1 || update2) {
int x = operationCount * 3;
operations[x] = child1.getNumber(); // source node 1
operations[x + 1] = child2.getNumber(); // source node 2
operations[x + 2] = nodeNum; // destination node
if (op1[0] >= 0) {
dependencies[op1[0]] = operationCount;
}
if (op2[0] >= 0) {
dependencies[op2[0]] = operationCount;
}
if (operatorNumber != null) {
operatorNumber[0] = operationCount;
} else {
dependencies[operationCount] = -1;
}
operationCount ++;
update = true;
}
}
return update;
}
// INSTANCE VARIABLES
// protected int[][] eigenIndicators;
// protected int[][] eigenIndicators;
/**
* the branch-site model for these sites
*/
protected final BranchSiteModel branchSiteModel;
/**
* the site model for these sites
*/
protected final SiteRateModel siteRateModel;
/**
* the branch rate model
*/
protected final BranchRateModel branchRateModel;
/**
* the pattern likelihoods
*/
protected double[] patternLogLikelihoods = null;
/**
* the number of rate categories
*/
protected int categoryCount;
/**
* an array used to transfer tip partials
*/
protected double[] tipPartials;
/**
* the BEAGLE library instance
*/
protected Beagle beagle;
/**
* Flag to specify that the substitution model has changed
*/
protected boolean updateSubstitutionModel;
/**
* Flag to specify that the site model has changed
*/
protected boolean updateSiteModel;
private int nodeEvaluationCount = 0;
public int getNodeEvaluationCount() {
return nodeEvaluationCount;
}
// private boolean dynamicRescaling = false;
}
|
package dr.inference.markovjumps;
import dr.app.beagle.evomodel.substmodel.DefaultEigenSystem;
import dr.app.beagle.evomodel.substmodel.EigenDecomposition;
import dr.app.beagle.evomodel.substmodel.EigenSystem;
import dr.math.Binomial;
import dr.math.GammaFunction;
import dr.math.distributions.GammaDistribution;
import dr.math.distributions.GeneralizedIntegerGammaDistribution;
import dr.math.matrixAlgebra.Vector;
// This class only works for 2-state models with equal rates, starting and ending in state 0
public class TwoStateOccupancyMarkovReward implements MarkovReward {
private static final boolean DEBUG = true;
private static final boolean DEBUG2 = false;
public TwoStateOccupancyMarkovReward(double[] Q) {
this(Q, 1E-10);
}
public TwoStateOccupancyMarkovReward(double[] Q, double epsilon) {
this.Q = Q;
this.maxTime = 0;
this.epsilon = epsilon;
this.maxK = 10; // TODO How to determine?
eigenSystem = new DefaultEigenSystem(2);
// if (Q[idx(0, 0)] != Q[idx(1, 1)]) {
}
private int idx(int i, int j) {
return i * 2 + j; // row-major
}
private double[] jumpProbabilities = null;
// private double getAki(double lambda1, double lambda2, int k, int i) {
//// double logA = Binomial.logChoose(k + i - 1, i) +
//// k * Math.log(lambda1) + (k - 1) * Math.log(lambda2)
//// int sign = 1;
//// return sign * Math.exp(logA);
// return Binomial.choose(k + i - 1, i) * Math.pow(-1, i) * Math.pow(lambda1, k)
// * Math.pow(lambda2, k - 1) / Math.pow(lambda2 - lambda1, k + i);
// private double getBki(double lambda1, double lambda2, int k, int i) {
// return Binomial.choose(k + i - 1, i) * Math.pow(-1, i) * Math.pow(lambda1, k)
// * Math.pow(lambda2, k - 1) / Math.pow(lambda1 - lambda2, k + i);
// private double getCki(double lambda1, double lambda2, int k, int i) {
// return Binomial.choose(k + i - 1, i) * Math.pow(-1, i) * Math.pow(lambda1, k)
// * Math.pow(lambda2, k) / Math.pow(lambda2 - lambda1, k + i);
// private double getDki(double lambda1, double lambda2, int k, int i) {
// return Binomial.choose(k + i, i) * Math.pow(-1, i) * Math.pow(lambda1, k)
// * Math.pow(lambda2, k) / Math.pow(lambda1 - lambda2, k + i + 1);
private void computeCDForJumpProbabilities(double lambda1, double lambda2, double[][] C, double[][] D) {
if (lambda1 == lambda2) return;
for (int k = 0; k < maxK / 2; ++k) {
final double l1l2k = Math.pow(lambda1 * lambda2, k);
for (int i = 0; i <= k + 1; ++i) {
final double sign = Math.pow(-1, i);
if (k == 0 && i == 0) {
C[k][i] = 1.0;
} else {
C[k][i] = sign * l1l2k * Binomial.choose(k + i - 1, i)
/ Math.pow(lambda2 - lambda1, k + i);
}
D[k][i] = sign * l1l2k * Binomial.choose(k + i, i)
/ Math.pow(lambda1 - lambda2, k + i + 1);
// C[k][i] = C1(lambda1, lambda2, k, i);
// D[k][i] = D1(lambda1, lambda2, k, i);
}
}
}
// private static double C1(double lambda1, double lambda2, int k, int index) {
// if (k == 0 && index == 0) return 1.0;
// return Math.pow(-1, index) * Math.pow(lambda1 * lambda2, k) * Binomial.choose(k + index - 1, index) /
// Math.pow(lambda2 - lambda1, k + index);
// private static double D1(double lambda1, double lambda2, int k, int index) {
// return Math.pow(-1, index) * Math.pow(lambda1 * lambda2, k) * Binomial.choose(k + index, index) /
// Math.pow(lambda1 - lambda2, k + index + 1);
private void computeJumpProbabilities(double lambda1, double lambda2, double time,
final double[][] C, final double[][] D, double[] jumpProbabilities) {
// jumpProbabilities = new double[maxK];
final double expLambda1Time = Math.exp(-lambda1 * time);
final double expLambda2Time = Math.exp(-lambda2 * time);
if (lambda1 == lambda2) {
for (int m = 1; m < maxK / 2 + 1; ++m) {
final int k = 2 * m;
jumpProbabilities[k] = expLambda1Time * Math.pow(lambda1 * time, k)
/ Math.exp(GammaFunction.lnGamma(k + 1));
}
} else {
for (int k = 1; k < maxK / 2; ++k) {
double sum = 0.0;
double multiplicativeFactor = 1.0;
for (int i = 1; i <= k + 1; ++i) {
if (i > 1) {
multiplicativeFactor *= time / (i - 1);
}
sum += C[k][k - i + 1]
* multiplicativeFactor
* expLambda1Time;
if (i <= k) {
sum += D[k][k - i]
* multiplicativeFactor
* expLambda2Time;
}
}
jumpProbabilities[2 * k] = sum;
}
}
}
public double[][] getC() { return C; }
public double[][] getD() { return D; }
public double[] getJumpProbabilities() { return jumpProbabilities; }
public double computeCdf(double x, double time, int i, int j) {
throw new RuntimeException("Not yet implemented");
}
public double computePdf(double x, double time, int i, int j) {
if (i != 0 || j != 0) throw new RuntimeException("Not yet implemented");
final double lambda0 = -Q[idx(0,0)];
final double lambda1 = -Q[idx(1,1)];
final boolean symmetric = (lambda0 == lambda1);
if (!symmetric && C == null) {
C = new double[(maxK / 2) + 1][(maxK / 2) + 1];
D = new double[(maxK / 2) + 1][(maxK / 2) + 1];
computeCDForJumpProbabilities(lambda0, lambda1, C, D);
}
if (jumpProbabilities == null) {
jumpProbabilities = new double[maxK + 1];
// computeJumpProbabilities(lambda0, lambda1, time, C, D, jumpProbabilities); // Error: probs are function of time
}
computeJumpProbabilities(lambda0, lambda1, time, C, D, jumpProbabilities); // are function of time.
// TODO Could cache computeJumpProbabilities(key = time) in HashMap
if (symmetric) {
// Single rate (symmetric)
final double scale = 1.0 / lambda0;
double sum = 0.0;
// if time - x > 0, then there must have been at least k = 2 jumps
for (int m = 1; m <= maxK / 2; ++m) {
final int k = 2 * m;
sum += jumpProbabilities[k] *
Math.exp(
+ GammaDistribution.logPdf(x, m, scale)
+ GammaDistribution.logPdf(time - x, m + 1, scale)
- GammaDistribution.logPdf(time, k + 1, scale)
);
}
return sum;
} else {
// Two rate model
double sum = 0.0;
for (int m = 1; m <= maxK / 2; ++m) {
final int k = 2 * m;
sum += jumpProbabilities[k] *
GammaDistribution.pdf(x, m, 1.0 / lambda1) *
GammaDistribution.pdf(time - x, m + 1, 1.0 / lambda0) /
GeneralizedIntegerGammaDistribution.pdf(time, m, m + 1, lambda1, lambda0); // TODO Cache
}
// TODO Remove code duplication in if (symmetric) { } else { }
return sum;
}
}
public double[] computePdf(double x, double time) {
throw new RuntimeException("Not yet implemented");
}
private double[][] squareMatrix(final double[] mat) {
final int dim = 2;
double[][] rtn = new double[dim][dim];
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j) {
rtn[i][j] = mat[idx(i, j)];
}
}
return rtn;
}
private int determineNumberOfSteps(double time, double lambda) {
// final double tolerance = (1.0 - epsilon) / Math.exp(-lambda * time);
// final double logTolerance = Math.log(1.0 - epsilon);
int i = -1;
// double sum = 0.0;
// int factorialI = 1;
// while (sum < tolerance) {
// sum += Math.pow(lambda * time, i) / factorialI;
// factorialI *= (i + 1); // + 1 because used on next iterate
// int firstN = i;
// LogTricks.logSum()
// i = -1;
final double tolerance2 =
// -epsilon;
(1.0 - epsilon);
double sum2 = 0.0;
// double sum2 = Double.NEGATIVE_INFINITY;
while (Math.abs(sum2 - tolerance2) > epsilon && sum2 < 1.0) {
// while (sum2 < tolerance2) {
i++;
double logDensity = -lambda * time + i * (Math.log(lambda) + Math.log(time)) - GammaFunction.lnGamma(i + 1);
sum2 += Math.exp(logDensity);
// sum2 = LogTricks.logSum(sum2, logDensity);
if (DEBUG2) {
System.err.println(sum2 + " " + tolerance2 + " " + Math.abs(sum2 - tolerance2) + " " + epsilon * 0.01);
// if (i > 500) System.exit(-1);
}
}
// System.err.println("First: " + firstN);
// System.err.println("Second:" + i);
// System.exit(-1);
return i;
}
// private static int getKMax(int n) {
// if (n % 2 == 0) {
// return n / 2;
// } else {
// return (n + 1) / 2;
// private static void hypgeoF11_k_2k(final double x, double[] result, double[] work) {
// final int len = result.length;
// if (len == 1 || x <= 0.0) return;
// final int nmax = len - 1;
// final int kmax = getKMax(nmax);
// final double y = x / 2.0;
// final double lx = Math.log(0.25 * x);
// // TODO finish
// private static void pclt(double t, double lambda1, double lambda2, double[] result) {
// final int len = result.length;
// final int nmax = len - 1;
// final int kmax = getKMax(nmax);
// double[] work = new double[kmax + 1];
// final double x = t * (lambda2 - lambda1);
// final double abs_x = Math.abs(x);
// final double log_l1 = Math.log(lambda1), log_l2 = Math.log(lambda2), log_t = Math.log(t);
// final double max_rate = Math.max(lambda1, lambda2);
// double log_gamma = 0.0;
// hypgeoF11_k_2k(abs_x, result, work);
// // TODO finish
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Q: " + new Vector(Q) + "\n");
// sb.append("r: " + new Vector(r) + "\n");
// sb.append("lambda: " + lambda + "\n");
// sb.append("N: " + getNfromC() + "\n");
// sb.append("maxTime: " + maxTime + "\n");
// sb.append("cprob at maxTime: " + new Vector(computeConditionalProbabilities(maxTime)) + "\n");
return sb.toString();
}
private EigenDecomposition getEigenDecomposition() {
if (eigenDecomposition == null) {
eigenDecomposition = eigenSystem.decomposeMatrix(squareMatrix(Q));
}
return eigenDecomposition;
}
private EigenDecomposition eigenDecomposition;
public double[] computeConditionalProbabilities(double distance) {
double[] matrix = new double[4];
eigenSystem.computeExponential(getEigenDecomposition(), distance, matrix);
return matrix;
}
public double computeConditionalProbability(double distance, int i, int j) {
return eigenSystem.computeExponential(getEigenDecomposition(), distance, i, j);
}
private final double[] Q;
private final int maxK;
private final double epsilon;
private final EigenSystem eigenSystem;
private double maxTime;
private double[][] C = null;
private double[][] D = null;
}
|
package me.prettyprint.hom;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import me.prettyprint.cassandra.service.ThriftCfDef;
import me.prettyprint.cassandra.service.ThriftKsDef;
import me.prettyprint.cassandra.testutils.EmbeddedServerHelper;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.factory.HFactory;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.contrib.utils.service.CassandraServiceDataCleaner;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.KsDef;
import org.apache.thrift.transport.TTransportException;
import org.junit.BeforeClass;
public class CassandraTestBase {
protected static boolean cassandraStarted = false;
protected static Keyspace keyspace;
protected static Cluster cluster;
protected static EmbeddedServerHelper embedded;
public static void startCassandraInstance(String pathToDataDir) throws TTransportException, IOException,
InterruptedException, SecurityException, IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
if (cassandraStarted) {
return;
}
try {
FileUtils.deleteRecursive(new File(pathToDataDir));
}
catch (AssertionError e) {
// eat
}
catch (IOException e) {
// eat
}
embedded = new EmbeddedServerHelper();
try {
embedded.setup();
} catch (ConfigurationException ce) {
throw new RuntimeException(ce);
}
cassandraStarted = true;
}
public static void createKeyspace(Cluster cluster, String name, String strategy, int replicationFactor,
List<CfDef> cfDefList) {
try {
KsDef ksDef = new KsDef(name, strategy, cfDefList);
ksDef.setReplication_factor(replicationFactor);
cluster.addKeyspace(new ThriftKsDef(ksDef));
return;
}
catch (Throwable e) {
System.out.println("exception while creating keyspace, " + name + " - probably already exists : "
+ e.getMessage());
}
for (CfDef cfDef : cfDefList) {
try {
cluster.addColumnFamily(new ThriftCfDef(cfDef));
}
catch (Throwable e) {
System.out.println("exception while creating CF, " + cfDef.getName() + " - probably already exists : "
+ e.getMessage());
}
}
}
@BeforeClass
public static void setupKeyspace() throws TTransportException,
SecurityException, IllegalArgumentException, IOException,
InterruptedException, NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
startCassandraInstance("tmp/var/lib/cassandra");
ArrayList<CfDef> cfDefList = new ArrayList<CfDef>(2);
cfDefList.add(new CfDef("TestKeyspace", "TestBeanColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "CustomIdColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "SimpleTestBeanColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "SimpleRelationshipBeanColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "NoAnonymousColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "ComplexColumnFamily").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cfDefList.add(new CfDef("TestKeyspace", "Furniture").setComparator_type(BytesType.class.getSimpleName())
.setKey_cache_size(0).setRow_cache_size(0).setGc_grace_seconds(86400));
cluster = HFactory.getOrCreateCluster("TestPool", "localhost:9161");
createKeyspace(cluster, "TestKeyspace", "org.apache.cassandra.locator.SimpleStrategy", 1, cfDefList);
keyspace = HFactory.createKeyspace("TestKeyspace", cluster);
}
}
|
package org.vrjuggler.tweek.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.vrjuggler.tweek.beans.BeanRegistry;
import org.vrjuggler.tweek.beans.TweekBean;
import org.vrjuggler.tweek.services.EnvironmentService;
import org.vrjuggler.tweek.services.GlobalPreferencesService;
import org.vrjuggler.tweek.net.corba.CorbaService;
/**
* A modal dialog box used to make a connection with a remote ORB. The Tweek
* CORBA Service created as a result of the connection is made available to
* external code.
*
* @since 1.0
*/
public class ConnectionDialog extends JDialog
{
public ConnectionDialog (Frame owner, String title)
{
super(owner, title);
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
mNSHostField.getDocument().addDocumentListener(new AddressFieldValidator());
mNSPortField.getDocument().addDocumentListener(new AddressFieldValidator());
this.mSubjectMgrList.addListSelectionListener(new SubjectMgrListSelectionListener());
// Set defaults for the Naming Service host and the port number.
GlobalPreferencesService prefs =
(GlobalPreferencesService) BeanRegistry.instance().getBean("GlobalPreferences");
mNSHostField.setText(prefs.getDefaultCorbaHost());
mNSPortField.setText(String.valueOf(prefs.getDefaultCorbaPort()));
// Add an input validator for the port number field.
mNSPortField.setInputVerifier(new InputVerifier()
{
public boolean verify(JComponent input)
{
JTextField tf = (JTextField) input;
return validatePortNumber(tf.getText());
}
});
this.setModal(true);
this.setLocationRelativeTo(owner);
}
public void display ()
{
this.pack();
this.setVisible(true);
}
public int getStatus ()
{
return status;
}
public String getNameServiceHost ()
{
return nameServiceHost;
}
public int getNameServicePort ()
{
return nameServicePort;
}
public String getNamingSubcontext ()
{
return namingSubcontext;
}
public CorbaService getCorbaService()
{
return corbaService;
}
public static final int OK_OPTION = JOptionPane.OK_OPTION;
public static final int CANCEL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int CLOSED_OPTION = JOptionPane.CLOSED_OPTION;
protected void processWindowEvent (WindowEvent e)
{
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING)
{
status = CLOSED_OPTION;
}
}
private void jbInit() throws Exception
{
mNSConnectBorder = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Naming Service Connection");
mSubjectMgrBorder = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Subject Manager Choice");
mNSConnectPanel.setLayout(mNSConnectLayout);
mNSConnectPanel.setBorder(mNSConnectBorder);
mNSConnectPanel.setMinimumSize(new Dimension(450, 150));
mNSConnectPanel.setPreferredSize(new Dimension(450, 155));
mNSHostLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNSHostLabel.setText("Naming Service Host");
mNSHostField.setMinimumSize(new Dimension(80, 17));
mNSHostField.setPreferredSize(new Dimension(180, 17));
mNSHostField.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
validateNetworkAddress(e);
}
});
mNSPortField.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
validateNetworkAddress(e);
}
});
mSubjectMgrPanel.setBorder(mSubjectMgrBorder);
mSubjectMgrPanel.setMinimumSize(new Dimension(450, 200));
mSubjectMgrPanel.setPreferredSize(new Dimension(450, 200));
mSubjectMgrPanel.setLayout(mSubjectMgrLayout);
mSubjectMgrSplitPane.setDividerSize(7);
mNSConnectButton.setEnabled(false);
mNSConnectButton.setMaximumSize(new Dimension(60, 18));
mNSConnectButton.setMinimumSize(new Dimension(60, 18));
mNSConnectButton.setText("Connect");
mNSConnectButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
namingServiceConnectAction(e);
}
});
mOkayButton.setEnabled(false);
mSubjectMgrList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mButtonPanel.setMinimumSize(new Dimension(450, 33));
mButtonPanel.setPreferredSize(new Dimension(450, 33));
mSubjectMgrListPane.setMinimumSize(new Dimension(100, 90));
mSubjectMgrListPane.setPreferredSize(new Dimension(180, 90));
mSubjectMgrInfo.setMinimumSize(new Dimension(100, 90));
mSubjectMgrInfo.setPreferredSize(new Dimension(180, 90));
mNSPortLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNamingContextLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNSConnectPanel.add(mNSHostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 47, 18));
mNSConnectPanel.add(mNSHostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 14, 6));
mNSPortLabel.setText("Naming Service Port");
mNSPortField.setMinimumSize(new Dimension(50, 17));
mNSPortField.setPreferredSize(new Dimension(50, 17));
mNSConnectPanel.add(mNSPortLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 51, 18));
mNSConnectPanel.add(mNSPortField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 10, 6));
mNamingContextLabel.setText("Naming Subcontext");
mNamingContextField.setMinimumSize(new Dimension(80, 17));
mNamingContextField.setPreferredSize(new Dimension(150, 17));
mOkayButton.setText("OK");
mOkayButton.setMnemonic('O');
mOkayButton.setSelected(true);
mOkayButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
okButtonAction(e);
}
});
mCancelButton.setText("Cancel");
mCancelButton.setMnemonic('C');
mCancelButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
cancelButtonAction(e);
}
});
this.getContentPane().add(mNSConnectPanel, BorderLayout.NORTH);
mNSConnectPanel.add(mNamingContextLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 56, 18));
mNSConnectPanel.add(mNamingContextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 44, 6));
mNSConnectPanel.add(mNSConnectButton, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 45, 5));
this.getContentPane().add(mButtonPanel, BorderLayout.SOUTH);
mButtonPanel.add(mOkayButton, null);
mButtonPanel.add(mCancelButton, null);
this.getContentPane().add(mSubjectMgrPanel, BorderLayout.CENTER);
mSubjectMgrPanel.add(mSubjectMgrSplitPane, BorderLayout.CENTER);
mSubjectMgrSplitPane.add(mSubjectMgrListPane, JSplitPane.LEFT);
mSubjectMgrSplitPane.add(mSubjectMgrInfo, JSplitPane.RIGHT);
}
/**
* Handles the event generated by the user clicking the "Connect" button in
* the Naming Service connection panel.
*/
private void namingServiceConnectAction(ActionEvent e)
{
// Commit the information provided by the user in the data entry fields.
commitConnectInfo();
// Create a new CORBA service using the information provided by the user.
CorbaService new_orb = new CorbaService(this.getNameServiceHost(),
this.getNameServicePort(),
this.getNamingSubcontext());
TweekBean service = BeanRegistry.instance().getBean("Environment");
try
{
// If we have the Tweek Environment Service, and we should, initialize
// the new CORBA service with the command line arguments passed when
// the Tweek GUI was started.
if ( null != service )
{
EnvironmentService env_service = (EnvironmentService) service;
new_orb.init(env_service.getCommandLineArgs());
}
else
{
new_orb.init(null);
}
// XXX: Is this the best time to do this? We want to be sure that
// anyone who calls getCorbaService() gets a valid reference back. If
// something goes wrong later with the Subject Manager choice, this
// should be set to null.
corbaService = new_orb;
// XXX: Should we allow the user to make multiple connections from a
// single dialog box? Probably not...
mNSConnectButton.setEnabled(false);
// Create a new list model for the fresh list of Subject Managers.
DefaultListModel mgr_list_model = new DefaultListModel();
// Get the list of Subject Managers. There had better be at least one!
java.util.Iterator i = new_orb.getSubjectManagerList().iterator();
tweek.SubjectManager cur_mgr;
while ( i.hasNext() )
{
cur_mgr = (tweek.SubjectManager) i.next();
mgr_list_model.addElement(new SubjectManagerWrapper(cur_mgr));
}
mSubjectMgrList.setModel(mgr_list_model);
}
// Something went wrong with the CORBA service initialization.
catch (org.omg.CORBA.SystemException sys_ex)
{
// Disable the Naming Service connection button just to be safe.
mNSConnectButton.setEnabled(false);
JOptionPane.showMessageDialog(null, "CORBA System Exception: '" +
sys_ex.getMessage() + "'",
"CORBA System Exception",
JOptionPane.ERROR_MESSAGE);
// DEBUG
sys_ex.printStackTrace();
}
}
/**
* Commits the user-specified information from the text fields to this
* object's properties. After calling this method, those properties can be
* considered up to date and usable.
*/
private void commitConnectInfo()
{
nameServiceHost = mNSHostField.getText();
nameServicePort = Integer.parseInt(mNSPortField.getText());
namingSubcontext = mNamingContextField.getText();
}
private void okButtonAction (ActionEvent e)
{
status = OK_OPTION;
commit();
setVisible(false);
}
/**
* Sets the close status to CANCEL_OPTION and closes this dialog box. If
* an ORB is running, it is shut down.
*/
private void cancelButtonAction (ActionEvent e)
{
// If we have an ORB running, we have to shut it down.
if ( null != corbaService )
{
corbaService.shutdown(true);
corbaService = null;
}
status = CANCEL_OPTION;
setVisible(false);
}
private void commit()
{
if ( null != mSubjectManager )
{
corbaService.setSubjectManager(mSubjectManager);
}
}
/**
* Validates that the network address (hostname and port number) entered
* by the user. If the network address is valid, then the Naming Service
* connection button is enabled. Otherwise, it is disabled.
*/
private void validateNetworkAddress(ActionEvent e)
{
if ( ! mNSHostField.getText().equals("") &&
validatePortNumber(mNSPortField.getText()) )
{
mNSConnectButton.setEnabled(true);
}
else
{
mNSConnectButton.setEnabled(false);
}
}
/**
* Verifies that the given string is a valid port number.
*/
private boolean validatePortNumber(String port)
{
boolean valid = false;
try
{
int port_num = Integer.parseInt(port);
if ( port_num > 0 && port_num < 65536 )
{
valid = true;
}
}
catch (Exception e)
{
System.err.println("Invalid port number: " + port);
}
return valid;
}
/**
* An implementation of DocumentListener used to validate the network
* address entered for the CORBA Naming Service.
*/
private class AddressFieldValidator implements DocumentListener
{
public void insertUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
public void removeUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
public void changedUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
}
/**
* An implementation of ListSelectionListener for use with the list of
* known Tweek Subject Manager references. When a Subject Manager is
* selected in the list, the table mSubjectMgrInfo is updated to display
* information queried from that Subject Manager.
*/
private class SubjectMgrListSelectionListener
implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent e)
{
// Pull the tweek.SubjectManager reference from the list.
int index = mSubjectMgrList.getSelectedIndex();
// No selection.
if ( -1 == index )
{
mOkayButton.setEnabled(false);
}
// New selection.
else
{
mOkayButton.setEnabled(true);
SubjectManagerWrapper mgr_wrapper =
(SubjectManagerWrapper) mSubjectMgrList.getModel().getElementAt(index);
mSubjectManager = mgr_wrapper.getSubjectManager();
// Fill in the table model for the selected Subject Manager.
Object[] column_names = new Object[]{"Property", "Value"};
DefaultTableModel table_model = new DefaultTableModel();
table_model.setColumnIdentifiers(column_names);
try
{
table_model.addRow(new Object[]{"Hostname",
mSubjectManager.getHostName()});
table_model.addRow(new Object[]{"Application",
mSubjectManager.getApplicationName()});
table_model.addRow(new Object[]{"User",
mSubjectManager.getUserName()});
mSubjectMgrInfo.setModel(table_model);
}
catch (org.omg.CORBA.COMM_FAILURE commEx)
{
String msg = "Invalid Subject Manager Selected";
// If the exception has an error message, append it.
if ( ! commEx.getMessage().equals("") )
{
msg += ": '" + commEx.getMessage() + "'";
}
JOptionPane.showMessageDialog(null, msg,
"CORBA Communication Exception",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// Attributes that may be queried by the class that instantiated us.
private int status;
private String nameServiceHost = null;
private int nameServicePort = 2809;
private String namingSubcontext = null;
private CorbaService corbaService = null;
// Internal-use properties.
private tweek.SubjectManager mSubjectManager = null;
// GUI elements for the Naming Service connection panel.
private TitledBorder mNSConnectBorder;
private JPanel mNSConnectPanel = new JPanel();
private GridBagLayout mNSConnectLayout = new GridBagLayout();
private JLabel mNSHostLabel = new JLabel();
private JTextField mNSHostField = new JTextField();
private JLabel mNSPortLabel = new JLabel();
private JTextField mNSPortField = new JTextField();
private JLabel mNamingContextLabel = new JLabel();
private JTextField mNamingContextField = new JTextField();
// GUI elements for the Subject Manager panel.
private TitledBorder mSubjectMgrBorder;
private JPanel mSubjectMgrPanel = new JPanel();
private BorderLayout mSubjectMgrLayout = new BorderLayout();
private JSplitPane mSubjectMgrSplitPane = new JSplitPane();
private JList mSubjectMgrList = new JList();
private JScrollPane mSubjectMgrListPane = new JScrollPane(mSubjectMgrList);
private JTable mSubjectMgrInfo = new JTable();
private JButton mNSConnectButton = new JButton();
// GUI elements for the OK/Cancel button panel.
private JPanel mButtonPanel = new JPanel();
private JButton mOkayButton = new JButton();
private JButton mCancelButton = new JButton();
}
|
package org.rhq.metrics.restServlet;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.rhq.metrics.RHQMetrics;
import org.rhq.metrics.core.MetricsService;
/**
* @author John Sanda
*/
@ApplicationScoped
public class MetricsServiceProducer {
private static final Logger LOG = LoggerFactory.getLogger(MetricsServiceProducer.class);
private MetricsService metricsService;
@Produces
public MetricsService getMetricsService() {
if (metricsService == null) {
String backend = System.getProperty("rhq-metrics.backend");
RHQMetrics.Builder metricsServiceBuilder = new RHQMetrics.Builder();
if (backend != null) {
switch (backend) {
case "cass":
LOG.info("Using Cassandra backend implementation");
metricsServiceBuilder.withCassandraDataStore();
break;
case "mem":
default:
LOG.info("Using memory backend implementation");
metricsServiceBuilder.withInMemoryDataStore();
}
} else {
metricsServiceBuilder.withInMemoryDataStore();
}
metricsService = metricsServiceBuilder.build();
ServiceKeeper.getInstance().service = metricsService;
}
return metricsService;
}
}
|
package org.vrjuggler.tweek.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.vrjuggler.tweek.beans.BeanRegistry;
import org.vrjuggler.tweek.beans.TweekBean;
import org.vrjuggler.tweek.services.EnvironmentService;
import org.vrjuggler.tweek.services.GlobalPreferencesService;
import org.vrjuggler.tweek.net.corba.CorbaService;
/**
* A modal dialog box used to make a connection with a remote ORB. The Tweek
* CORBA Service created as a result of the connection is made available to
* external code.
*
* @since 1.0
*/
public class ConnectionDialog extends JDialog
{
public ConnectionDialog (Frame owner, String title)
{
super(owner, title);
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
mNSHostField.getDocument().addDocumentListener(new AddressFieldValidator());
mNSPortField.getDocument().addDocumentListener(new AddressFieldValidator());
this.mSubjectMgrList.addListSelectionListener(new SubjectMgrListSelectionListener());
// Set defaults for the Naming Service host and the port number.
GlobalPreferencesService prefs =
(GlobalPreferencesService) BeanRegistry.instance().getBean("GlobalPreferences");
mNSHostField.setText(prefs.getDefaultCorbaHost());
mNSPortField.setText(String.valueOf(prefs.getDefaultCorbaPort()));
// Add an input validator for the port number field.
mNSPortField.setInputVerifier(new InputVerifier()
{
public boolean verify(JComponent input)
{
JTextField tf = (JTextField) input;
return validatePortNumber(tf.getText());
}
});
this.setModal(true);
this.setLocationRelativeTo(owner);
}
public void display ()
{
this.pack();
this.setVisible(true);
}
public int getStatus ()
{
return status;
}
public String getNameServiceHost ()
{
return nameServiceHost;
}
public int getNameServicePort ()
{
return nameServicePort;
}
public String getNamingSubcontext ()
{
return namingSubcontext;
}
public CorbaService getCorbaService()
{
return corbaService;
}
public static final int OK_OPTION = JOptionPane.OK_OPTION;
public static final int CANCEL_OPTION = JOptionPane.CANCEL_OPTION;
public static final int CLOSED_OPTION = JOptionPane.CLOSED_OPTION;
protected void processWindowEvent (WindowEvent e)
{
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING)
{
status = CLOSED_OPTION;
}
}
private void jbInit() throws Exception
{
mNSConnectBorder = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Naming Service Connection");
mSubjectMgrBorder = new TitledBorder(new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(142, 142, 142)),"Subject Manager Choice");
mNSConnectPanel.setLayout(mNSConnectLayout);
mNSConnectPanel.setBorder(mNSConnectBorder);
mNSConnectPanel.setMinimumSize(new Dimension(450, 150));
mNSConnectPanel.setPreferredSize(new Dimension(450, 155));
mNSHostLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNSHostLabel.setText("Naming Service Host");
mNSHostField.setMinimumSize(new Dimension(80, 17));
mNSHostField.setPreferredSize(new Dimension(180, 17));
mNSHostField.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
validateNetworkAddress(e);
}
});
mNSPortField.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
validateNetworkAddress(e);
}
});
mSubjectMgrPanel.setBorder(mSubjectMgrBorder);
mSubjectMgrPanel.setMinimumSize(new Dimension(450, 200));
mSubjectMgrPanel.setPreferredSize(new Dimension(450, 200));
mSubjectMgrPanel.setLayout(mSubjectMgrLayout);
mSubjectMgrSplitPane.setDividerSize(7);
mNSConnectButton.setEnabled(false);
mNSConnectButton.setMaximumSize(new Dimension(60, 18));
mNSConnectButton.setMinimumSize(new Dimension(60, 18));
mNSConnectButton.setText("Connect");
mNSConnectButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e)
{
namingServiceConnectAction(e);
}
});
mOkayButton.setEnabled(false);
mSubjectMgrList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mButtonPanel.setMinimumSize(new Dimension(450, 33));
mButtonPanel.setPreferredSize(new Dimension(450, 33));
mSubjectMgrListPane.setMinimumSize(new Dimension(100, 90));
mSubjectMgrListPane.setPreferredSize(new Dimension(180, 90));
mSubjectMgrInfo.setMinimumSize(new Dimension(100, 90));
mSubjectMgrInfo.setPreferredSize(new Dimension(180, 90));
mNSPortLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNamingContextLabel.setHorizontalAlignment(SwingConstants.TRAILING);
mNSConnectPanel.add(mNSHostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 47, 18));
mNSConnectPanel.add(mNSHostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 14, 6));
mNSPortLabel.setText("Naming Service Port");
mNSPortField.setMinimumSize(new Dimension(50, 17));
mNSPortField.setPreferredSize(new Dimension(50, 17));
mNSConnectPanel.add(mNSPortLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 51, 18));
mNSConnectPanel.add(mNSPortField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 10, 6));
mNamingContextLabel.setText("Naming Subcontext");
mNamingContextField.setMinimumSize(new Dimension(80, 17));
mNamingContextField.setPreferredSize(new Dimension(150, 17));
mOkayButton.setText("OK");
mOkayButton.setMnemonic('O');
mOkayButton.setSelected(true);
mOkayButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
okButtonAction(e);
}
});
mCancelButton.setText("Cancel");
mCancelButton.setMnemonic('C');
mCancelButton.addActionListener(new ActionListener()
{
public void actionPerformed (ActionEvent e)
{
cancelButtonAction(e);
}
});
this.getContentPane().add(mNSConnectPanel, BorderLayout.NORTH);
mNSConnectPanel.add(mNamingContextLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 2), 56, 18));
mNSConnectPanel.add(mNamingContextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 44, 6));
mNSConnectPanel.add(mNSConnectButton, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 0, 0), 45, 5));
this.getContentPane().add(mButtonPanel, BorderLayout.SOUTH);
mButtonPanel.add(mOkayButton, null);
mButtonPanel.add(mCancelButton, null);
this.getContentPane().add(mSubjectMgrPanel, BorderLayout.CENTER);
mSubjectMgrPanel.add(mSubjectMgrSplitPane, BorderLayout.CENTER);
mSubjectMgrSplitPane.add(mSubjectMgrListPane, JSplitPane.LEFT);
mSubjectMgrSplitPane.add(mSubjectMgrInfo, JSplitPane.RIGHT);
}
/**
* Handles the event generated by the user clicking the "Connect" button in
* the Naming Service connection panel.
*/
private void namingServiceConnectAction(ActionEvent e)
{
// Commit the information provided by the user in the data entry fields.
commitConnectInfo();
// Create a new CORBA service using the information provided by the user.
CorbaService new_orb = new CorbaService(this.getNameServiceHost(),
this.getNameServicePort(),
this.getNamingSubcontext());
TweekBean service = BeanRegistry.instance().getBean("Environment");
try
{
// If we have the Tweek Environment Service, and we should, initialize
// the new CORBA service with the command line arguments passed when
// the Tweek GUI was started.
if ( null != service )
{
EnvironmentService env_service = (EnvironmentService) service;
new_orb.init(env_service.getCommandLineArgs());
}
else
{
new_orb.init(null);
}
// XXX: Is this the best time to do this? We want to be sure that
// anyone who calls getCorbaService() gets a valid reference back. If
// something goes wrong later with the Subject Manager choice, this
// should be set to null.
corbaService = new_orb;
// XXX: Should we allow the user to make multiple connections from a
// single dialog box? Probably not...
mNSConnectButton.setEnabled(false);
// Create a new list model for the fresh list of Subject Managers.
DefaultListModel mgr_list_model = new DefaultListModel();
// Get the list of Subject Managers. There had better be at least one!
java.util.Iterator i = new_orb.getSubjectManagerList().iterator();
tweek.SubjectManager cur_mgr;
while ( i.hasNext() )
{
cur_mgr = (tweek.SubjectManager) i.next();
mgr_list_model.addElement(new SubjectManagerWrapper(cur_mgr));
}
mSubjectMgrList.setModel(mgr_list_model);
}
// Something went wrong with the CORBA service initialization.
catch (org.omg.CORBA.SystemException sys_ex)
{
// Disable the Naming Service connection button just to be safe.
mNSConnectButton.setEnabled(false);
JOptionPane.showMessageDialog(null, "CORBA System Exception: '" +
sys_ex.getMessage() + "'",
"CORBA System Exception",
JOptionPane.ERROR_MESSAGE);
// DEBUG
sys_ex.printStackTrace();
}
}
/**
* Commits the user-specified information from the text fields to this
* object's properties. After calling this method, those properties can be
* considered up to date and usable.
*/
private void commitConnectInfo()
{
nameServiceHost = mNSHostField.getText();
nameServicePort = Integer.parseInt(mNSPortField.getText());
namingSubcontext = mNamingContextField.getText();
}
private void okButtonAction (ActionEvent e)
{
status = OK_OPTION;
commit();
setVisible(false);
}
/**
* Sets the close status to CANCEL_OPTION and closes this dialog box. If
* an ORB is running, it is shut down.
*/
private void cancelButtonAction (ActionEvent e)
{
// If we have an ORB running, we have to shut it down.
if ( null != corbaService )
{
corbaService.shutdown(true);
corbaService = null;
}
status = CANCEL_OPTION;
setVisible(false);
}
private void commit()
{
if ( null != mSubjectManager )
{
corbaService.setSubjectManager(mSubjectManager);
}
}
/**
* Validates that the network address (hostname and port number) entered
* by the user. If the network address is valid, then the Naming Service
* connection button is enabled. Otherwise, it is disabled.
*/
private void validateNetworkAddress(ActionEvent e)
{
if ( ! mNSHostField.getText().equals("") &&
validatePortNumber(mNSPortField.getText()) )
{
mNSConnectButton.setEnabled(true);
}
else
{
mNSConnectButton.setEnabled(false);
}
}
/**
* Verifies that the given string is a valid port number.
*/
private boolean validatePortNumber(String port)
{
boolean valid = false;
try
{
int port_num = Integer.parseInt(port);
if ( port_num > 0 && port_num < 65536 )
{
valid = true;
}
}
catch (Exception e)
{
System.err.println("Invalid port number: " + port);
}
return valid;
}
/**
* An implementation of DocumentListener used to validate the network
* address entered for the CORBA Naming Service.
*/
private class AddressFieldValidator implements DocumentListener
{
public void insertUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
public void removeUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
public void changedUpdate(DocumentEvent e)
{
validateNetworkAddress(null);
}
}
/**
* An implementation of ListSelectionListener for use with the list of
* known Tweek Subject Manager references. When a Subject Manager is
* selected in the list, the table mSubjectMgrInfo is updated to display
* information queried from that Subject Manager.
*/
private class SubjectMgrListSelectionListener
implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent e)
{
// Pull the tweek.SubjectManager reference from the list.
int index = mSubjectMgrList.getSelectedIndex();
// No selection.
if ( -1 == index )
{
mOkayButton.setEnabled(false);
}
// New selection.
else
{
SubjectManagerWrapper mgr_wrapper =
(SubjectManagerWrapper) mSubjectMgrList.getModel().getElementAt(index);
mSubjectManager = mgr_wrapper.getSubjectManager();
// Fill in the table model for the selected Subject Manager.
Object[] column_names = new Object[]{"Property", "Value"};
DefaultTableModel table_model = new DefaultTableModel();
table_model.setColumnIdentifiers(column_names);
try
{
table_model.addRow(new Object[]{"Hostname",
mSubjectManager.getHostName()});
table_model.addRow(new Object[]{"Application",
mSubjectManager.getApplicationName()});
table_model.addRow(new Object[]{"User",
mSubjectManager.getUserName()});
mSubjectMgrInfo.setModel(table_model);
mOkayButton.setEnabled(true);
}
catch (org.omg.CORBA.COMM_FAILURE commEx)
{
mOkayButton.setEnabled(false);
String msg = "Invalid Subject Manager Selected";
// If the exception has an error message, append it.
if ( ! commEx.getMessage().equals("") )
{
msg += ": '" + commEx.getMessage() + "'";
}
JOptionPane.showMessageDialog(null, msg,
"CORBA Communication Exception",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
// Attributes that may be queried by the class that instantiated us.
private int status;
private String nameServiceHost = null;
private int nameServicePort = 2809;
private String namingSubcontext = null;
private CorbaService corbaService = null;
// Internal-use properties.
private tweek.SubjectManager mSubjectManager = null;
// GUI elements for the Naming Service connection panel.
private TitledBorder mNSConnectBorder;
private JPanel mNSConnectPanel = new JPanel();
private GridBagLayout mNSConnectLayout = new GridBagLayout();
private JLabel mNSHostLabel = new JLabel();
private JTextField mNSHostField = new JTextField();
private JLabel mNSPortLabel = new JLabel();
private JTextField mNSPortField = new JTextField();
private JLabel mNamingContextLabel = new JLabel();
private JTextField mNamingContextField = new JTextField();
// GUI elements for the Subject Manager panel.
private TitledBorder mSubjectMgrBorder;
private JPanel mSubjectMgrPanel = new JPanel();
private BorderLayout mSubjectMgrLayout = new BorderLayout();
private JSplitPane mSubjectMgrSplitPane = new JSplitPane();
private JList mSubjectMgrList = new JList();
private JScrollPane mSubjectMgrListPane = new JScrollPane(mSubjectMgrList);
private JTable mSubjectMgrInfo = new JTable();
private JButton mNSConnectButton = new JButton();
// GUI elements for the OK/Cancel button panel.
private JPanel mButtonPanel = new JPanel();
private JButton mOkayButton = new JButton();
private JButton mCancelButton = new JButton();
}
|
package com.s3auth.hosts;
import com.amazonaws.services.s3.model.BucketWebsiteConfiguration;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.jcabi.log.Logger;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.LinkedList;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang.StringUtils;
/**
* Default implementation of {@link Host}.
*
* <p>The class is immutable and thread-safe.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 0.0.1
*/
final class DefaultHost implements Host {
/**
* The S3 bucket.
*/
private final transient Bucket bucket;
/**
* Htpasswd file abstraction.
*/
private final transient Htpasswd htpasswd;
/**
* Public ctor.
* @param bckt The S3 bucket to use
*/
public DefaultHost(@NotNull final Bucket bckt) {
this.bucket = bckt;
this.htpasswd = new Htpasswd(this);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("%s with %s", this.bucket, this.htpasswd);
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
// nothing to do
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public Resource fetch(@NotNull final URI uri) throws IOException {
Resource resource = null;
final Collection<String> errors = new LinkedList<String>();
for (DefaultHost.ObjectName name : this.names(uri)) {
try {
resource = new DefaultResource(
this.bucket.client().getObject(
new GetObjectRequest(
this.bucket.name(),
name.get()
)
)
);
break;
} catch (com.amazonaws.AmazonClientException ex) {
errors.add(
String.format(
"'%s': %s",
name,
ex.getMessage()
)
);
}
}
if (resource == null) {
throw new IOException(
Logger.format(
"failed to fetch %s from '%s' (key=%s): %[list]s",
uri,
this.bucket.name(),
this.bucket.key(),
errors
)
);
}
Logger.info(
this,
"#fetch('%s'): found at %s as %s",
uri,
this.bucket.name(),
resource
);
return resource;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isHidden(@NotNull final URI uri) {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean authorized(@NotNull final String user,
@NotNull final String password) throws IOException {
boolean auth;
if (user.equals(this.bucket.key())
&& password.equals(this.bucket.secret())) {
auth = true;
} else {
auth = this.htpasswd.authorized(user, password);
}
Logger.info(
this,
"#authorized('%s', '%s'): %B",
user,
password,
auth
);
return auth;
}
/**
* Name of an S3 Object, context dependent.
*/
private interface ObjectName {
/**
* Returns a name of S3 object.
* @return The name
*/
String get();
}
/**
* Convert URI to all possible S3 object names (in order of importance).
* @param uri The URI
* @return Object names
*/
private Collection<DefaultHost.ObjectName> names(final URI uri) {
final String name = StringUtils.strip(uri.getPath(), "/");
final Collection<DefaultHost.ObjectName> names =
new LinkedList<DefaultHost.ObjectName>();
if (!name.isEmpty()) {
names.add(
new DefaultHost.ObjectName() {
@Override
public String get() {
return name;
}
@Override
public String toString() {
return name;
}
}
);
}
names.add(new DefaultHost.NameWithSuffix(name));
return names;
}
/**
* Object name with a suffix from a bucket.
*/
private final class NameWithSuffix implements DefaultHost.ObjectName {
/**
* Original name.
*/
private final transient String origin;
/**
* Public ctor.
* @param name The original name
*/
public NameWithSuffix(final String name) {
this.origin = name;
}
/**
* {@inheritDoc}
*/
@Override
public String get() {
String suffix = null;
try {
final BucketWebsiteConfiguration conf =
DefaultHost.this.bucket.client()
.getBucketWebsiteConfiguration(
DefaultHost.this.bucket.name()
);
if (conf != null) {
suffix = conf.getIndexDocumentSuffix();
}
} catch (com.amazonaws.AmazonClientException ex) {
suffix = "";
}
if (suffix == null || suffix.isEmpty()) {
suffix = "index.html";
}
final StringBuilder text = new StringBuilder(this.origin);
if (text.length() > 0) {
text.append('/');
}
text.append(suffix);
Logger.debug(this, "#get('%s'): %s", this.origin, text);
return text.toString();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("%s+suffix", this.origin);
}
}
}
|
package org.eclipse.egit.core.op;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.egit.core.Activator;
import org.eclipse.egit.core.CoreText;
import org.eclipse.egit.core.EclipseGitProgressTransformer;
import org.eclipse.egit.core.internal.util.ProjectUtil;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeResult;
import org.eclipse.jgit.api.MergeResult.MergeStatus;
import org.eclipse.jgit.api.PullCommand;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.api.errors.DetachedHeadException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidConfigurationException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.errors.TransportException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;
/**
* Wraps the JGit API {@link PullCommand} into an operation
*/
public class PullOperation implements IEGitOperation {
private final Repository[] repositories;
private final Map<Repository, Object> results = new HashMap<Repository, Object>();
private final int timeout;
/**
* @param repositories
* the repository
* @param timeout
* in seconds
*/
public PullOperation(Set<Repository> repositories, int timeout) {
this.timeout = timeout;
this.repositories = repositories.toArray(new Repository[repositories
.size()]);
}
public void execute(IProgressMonitor m) throws CoreException {
if (!results.isEmpty())
throw new CoreException(new Status(IStatus.ERROR, Activator
.getPluginId(), CoreText.OperationAlreadyExecuted));
IProgressMonitor monitor;
if (m == null)
monitor = new NullProgressMonitor();
else
monitor = m;
monitor.beginTask(NLS.bind(CoreText.PullOperation_TaskName, Integer
.valueOf(repositories.length)), repositories.length * 2);
IWorkspaceRunnable action = new IWorkspaceRunnable() {
public void run(IProgressMonitor mymonitor) throws CoreException {
for (int i = 0; i < repositories.length; i++) {
Repository repository = repositories[i];
if (mymonitor.isCanceled())
throw new CoreException(Status.CANCEL_STATUS);
IProject[] validProjects = ProjectUtil.getValidOpenProjects(repository);
PullCommand pull = new Git(repository).pull();
PullResult pullResult = null;
try {
pull.setProgressMonitor(new EclipseGitProgressTransformer(
new SubProgressMonitor(mymonitor, 1)));
pull.setTimeout(timeout);
pullResult = pull.call();
results.put(repository, pullResult);
} catch (DetachedHeadException e) {
results.put(repository, Activator.error(
CoreText.PullOperation_DetachedHeadMessage, e));
} catch (InvalidConfigurationException e) {
IStatus error = Activator
.error(CoreText.PullOperation_PullNotConfiguredMessage,
e);
results.put(repository, error);
} catch (GitAPIException e) {
results.put(repository,
Activator.error(e.getMessage(), e));
} catch (JGitInternalException e) {
Throwable cause = e.getCause();
if (cause == null || !(cause instanceof TransportException))
cause = e;
results.put(repository,
Activator.error(cause.getMessage(), cause));
} finally {
mymonitor.worked(1);
if (refreshNeeded(pullResult)) {
ProjectUtil.refreshValidProjects(validProjects,
new SubProgressMonitor(mymonitor, 1));
mymonitor.worked(1);
}
}
}
}
};
// lock workspace to protect working tree changes
ResourcesPlugin.getWorkspace().run(action, monitor);
}
private boolean refreshNeeded(PullResult pullResult) {
if (pullResult == null)
return true;
MergeResult mergeResult = pullResult.getMergeResult();
if (mergeResult == null)
return true;
if (mergeResult.getMergeStatus() == MergeStatus.ALREADY_UP_TO_DATE)
return false;
return true;
}
/**
* @return the results, or an empty Map if this has not been executed
*/
public Map<Repository, Object> getResults() {
return this.results;
}
public ISchedulingRule getSchedulingRule() {
return ResourcesPlugin.getWorkspace().getRoot();
}
}
|
package com.google.code.morphia;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.code.morphia.annotations.CappedAt;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Index;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Indexes;
import com.google.code.morphia.annotations.NotSaved;
import com.google.code.morphia.annotations.PostPersist;
import com.google.code.morphia.annotations.Reference;
import com.google.code.morphia.annotations.Serialized;
import com.google.code.morphia.annotations.Version;
import com.google.code.morphia.logging.Logr;
import com.google.code.morphia.logging.MorphiaLoggerFactory;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.MappingException;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.google.code.morphia.mapping.lazy.DatastoreHolder;
import com.google.code.morphia.mapping.lazy.proxy.ProxyHelper;
import com.google.code.morphia.query.DefaultQueryFactory;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryException;
import com.google.code.morphia.query.QueryFactory;
import com.google.code.morphia.query.QueryImpl;
import com.google.code.morphia.query.UpdateException;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateOpsImpl;
import com.google.code.morphia.query.UpdateResults;
import com.google.code.morphia.utils.Assert;
import com.google.code.morphia.utils.IndexDirection;
import com.google.code.morphia.utils.IndexFieldDef;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBDecoderFactory;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import com.mongodb.DefaultDBDecoder;
import com.mongodb.MapReduceCommand;
import com.mongodb.MapReduceCommand.OutputType;
import com.mongodb.MapReduceOutput;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
/**
* A generic (type-safe) wrapper around mongodb collections
*
* @author Scott Hernandez
*/
@SuppressWarnings({"unchecked"})
public class DatastoreImpl implements AdvancedDatastore {
private static final Logr LOG = MorphiaLoggerFactory.get(DatastoreImpl.class);
protected final Mapper mapper;
protected final Mongo mongo;
protected final DB db;
protected WriteConcern defConcern = WriteConcern.SAFE;
protected DBDecoderFactory decoderFactory;
private volatile QueryFactory queryFactory = new DefaultQueryFactory();
public DatastoreImpl(final Mapper mapper, final Mongo mongo, final String dbName) {
this.mapper = mapper;
this.mongo = mongo;
db = mongo.getDB(dbName);
// VERY discussable
DatastoreHolder.getInstance().set(this);
}
public DatastoreImpl(final Morphia morphia, final Mongo mongo) {
this(morphia, mongo, null);
}
/**
* @deprecated Authentication is already handled by the Mongo instance
*/
public DatastoreImpl(final Morphia morphia, final Mongo mongo, final String dbName, final String username, final char[] password) {
this(morphia.getMapper(), mongo, dbName);
}
public DatastoreImpl(final Morphia morphia, final Mongo mongo, final String dbName) {
this(morphia.getMapper(), mongo, dbName);
}
public DatastoreImpl copy(final String database) {
return new DatastoreImpl(mapper, mongo, database);
}
public <T, V> DBRef createRef(final Class<T> clazz, final V id) {
if (id == null) {
throw new MappingException("Could not get id for " + clazz.getName());
}
return new DBRef(getDB(), getCollection(clazz).getName(), id);
}
public <T> DBRef createRef(final T entity) {
final T wrapped = ProxyHelper.unwrap(entity);
final Object id = mapper.getId(wrapped);
if (id == null) {
throw new MappingException("Could not get id for " + wrapped.getClass().getName());
}
return createRef(wrapped.getClass(), id);
}
@Deprecated
protected Object getId(final Object entity) {
return mapper.getId(entity);
}
@Deprecated // use mapper instead.
public <T> Key<T> getKey(final T entity) {
return mapper.getKey(entity);
}
public <T> WriteResult delete(final String kind, final T id) {
final DBCollection dbColl = getCollection(kind);
final WriteResult wr = dbColl.remove(BasicDBObjectBuilder.start().add(Mapper.ID_KEY, id).get());
throwOnError(null, wr);
return wr;
}
public <T, V> WriteResult delete(final String kind, final Class<T> clazz, final V id) {
return delete(find(kind, clazz).filter(Mapper.ID_KEY, id));
}
public <T, V> WriteResult delete(final String kind, final Class<T> clazz, final V id, final WriteConcern wc) {
return delete(find(kind, clazz).filter(Mapper.ID_KEY, id), wc);
}
public <T, V> WriteResult delete(final Class<T> clazz, final V id) {
return delete(clazz, id, getWriteConcern(clazz));
}
public <T, V> WriteResult delete(final Class<T> clazz, final V id, final WriteConcern wc) {
return delete(createQuery(clazz).filter(Mapper.ID_KEY, id), wc);
}
public <T, V> WriteResult delete(final Class<T> clazz, final Iterable<V> ids) {
final Query<T> q = find(clazz).disableValidation().filter(Mapper.ID_KEY + " in", ids);
return delete(q);
}
public <T> WriteResult delete(final T entity) {
return delete(entity, getWriteConcern(entity));
}
public <T> WriteResult delete(final T entity, final WriteConcern wc) {
final T wrapped = ProxyHelper.unwrap(entity);
if (wrapped instanceof Class<?>) {
throw new MappingException("Did you mean to delete all documents? -- delete(ds.createQuery(???.class))");
}
try {
final Object id = mapper.getId(wrapped);
return delete(wrapped.getClass(), id, wc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> WriteResult delete(final Query<T> query) {
return delete(query, getWriteConcern(query.getEntityClass()));
}
public <T> WriteResult delete(final Query<T> query, final WriteConcern wc) {
final QueryImpl<T> q = (QueryImpl<T>) query;
DBCollection dbColl = q.getCollection();
//TODO remove this after testing.
if (dbColl == null) {
dbColl = getCollection(q.getEntityClass());
}
final WriteResult wr;
if (q.getSortObject() != null || q.getOffset() != 0 || q.getLimit() > 0) {
throw new QueryException("Delete does not allow sort/offset/limit query options.");
}
if (q.getQueryObject() != null) {
if (wc == null) {
wr = dbColl.remove(q.getQueryObject());
} else {
wr = dbColl.remove(q.getQueryObject(), wc);
}
} else if (wc == null) {
wr = dbColl.remove(new BasicDBObject());
} else {
wr = dbColl.remove(new BasicDBObject(), wc);
}
throwOnError(wc, wr);
return wr;
}
public <T> void ensureIndex(final Class<T> type, final String fields) {
ensureIndex(type, null, fields, false, false);
}
/**
* @deprecated IndexFieldDef is deprecated
*/
public <T> void ensureIndex(final Class<T> clazz, final String name, final IndexFieldDef[] definitions, final boolean unique,
final boolean dropDupsOnCreate) {
ensureIndex(clazz, name, definitions, unique, dropDupsOnCreate, false);
}
public <T> void ensureIndex(final Class<T> clazz, final String name, final String fields, final boolean unique,
final boolean dropDupsOnCreate) {
ensureIndex(clazz, name, QueryImpl.parseFieldsString(fields, clazz, mapper, true), unique, dropDupsOnCreate, false, false, -1);
}
public <T> void ensureIndex(final Class<T> clazz, final String name, final String fields, final boolean unique,
final boolean dropDupsOnCreate, final boolean background) {
ensureIndex(clazz, name, QueryImpl.parseFieldsString(fields, clazz, mapper, true), unique, dropDupsOnCreate, background, false, -1);
}
protected <T> void ensureIndex(final Class<T> clazz, final String name, final BasicDBObject fields, final boolean unique,
final boolean dropDupsOnCreate, final boolean background, final boolean sparse, final int expireAfterSeconds) {
final BasicDBObjectBuilder keyOpts = new BasicDBObjectBuilder();
if (name != null && name.length() != 0) {
keyOpts.add("name", name);
}
if (unique) {
keyOpts.add("unique", true);
if (dropDupsOnCreate) {
keyOpts.add("dropDups", true);
}
}
if (background) {
keyOpts.add("background", true);
}
if (sparse) {
keyOpts.add("sparse", true);
}
if (expireAfterSeconds > -1) {
keyOpts.add("expireAfterSeconds", expireAfterSeconds);
}
final DBCollection dbColl = getCollection(clazz);
final BasicDBObject opts = (BasicDBObject) keyOpts.get();
if (opts.isEmpty()) {
LOG.debug("Ensuring index for " + dbColl.getName() + " with keys:" + fields);
dbColl.ensureIndex(fields);
} else {
LOG.debug("Ensuring index for " + dbColl.getName() + " with keys:" + fields + " and opts:" + opts);
dbColl.ensureIndex(fields, opts);
}
}
/**
* @deprecated IndexFieldDef is deprecated
*/
@SuppressWarnings({"rawtypes"})
public void ensureIndex(final Class clazz, final String name, final IndexFieldDef[] definitions, final boolean unique,
final boolean dropDupsOnCreate, final boolean background) {
final BasicDBObjectBuilder keys = BasicDBObjectBuilder.start();
for (final IndexFieldDef def : definitions) {
final String fieldName = def.getField();
final IndexDirection dir = def.getDirection();
keys.add(fieldName, dir.toIndexValue());
}
ensureIndex(clazz, name, (BasicDBObject) keys.get(), unique, dropDupsOnCreate, background, false, -1);
}
public <T> void ensureIndex(final Class<T> type, final String name, final IndexDirection dir) {
ensureIndex(type, new IndexFieldDef(name, dir));
}
public <T> void ensureIndex(final Class<T> type, final IndexFieldDef... fields) {
ensureIndex(type, null, fields, false, false);
}
public <T> void ensureIndex(final Class<T> type, final boolean background, final IndexFieldDef... fields) {
ensureIndex(type, null, fields, false, false, background);
}
protected void ensureIndexes(final MappedClass mc, final boolean background) {
ensureIndexes(mc, background, new ArrayList<MappedClass>(), new ArrayList<MappedField>());
}
protected void ensureIndexes(final MappedClass mc, final boolean background, final List<MappedClass> parentMCs,
final List<MappedField> parentMFs) {
if (parentMCs.contains(mc)) {
return;
}
if (mc.getEmbeddedAnnotation() != null && parentMCs.isEmpty()) {
return;
}
processClassAnnotations(mc, background);
processEmbeddedAnnotations(mc, background, parentMCs, parentMFs);
}
/**
* Ensure indexes from field annotations, and embedded entities
*/
private void processEmbeddedAnnotations(final MappedClass mc, final boolean background, final List<MappedClass> parentMCs,
final List<MappedField> parentMFs) {
for (final MappedField mf : mc.getPersistenceFields()) {
if (mf.hasAnnotation(Indexed.class)) {
final Indexed index = mf.getAnnotation(Indexed.class);
final StringBuilder field = new StringBuilder();
final Class<?> indexedClass = (parentMCs.isEmpty() ? mc : parentMCs.get(0)).getClazz();
if (!parentMCs.isEmpty()) {
for (final MappedField pmf : parentMFs) {
field.append(pmf.getNameToStore()).append(".");
}
}
field.append(mf.getNameToStore());
ensureIndex(indexedClass, index.name(), new BasicDBObject(field.toString(), index.value().toIndexValue()), index.unique(),
index.dropDups(), index.background() ? index.background() : background, index.sparse(), index.expireAfterSeconds());
}
if (!mf.isTypeMongoCompatible() && !mf.hasAnnotation(Reference.class) && !mf.hasAnnotation(Serialized.class)) {
final List<MappedClass> newParentClasses = new ArrayList<MappedClass>(parentMCs);
final List<MappedField> newParents = new ArrayList<MappedField>(parentMFs);
newParentClasses.add(mc);
newParents.add(mf);
ensureIndexes(mapper.getMappedClass(mf.isSingleValue() ? mf.getType() : mf.getSubClass()), background, newParentClasses,
newParents);
}
}
}
private void processClassAnnotations(final MappedClass mc, final boolean background) {
//Ensure indexes from class annotation
final List<Annotation> indexes = mc.getAnnotations(Indexes.class);
if (indexes != null) {
for (final Annotation ann : indexes) {
final Indexes idx = (Indexes) ann;
if (idx != null && idx.value() != null && idx.value().length > 0) {
for (final Index index : idx.value()) {
final BasicDBObject fields = QueryImpl.parseFieldsString(index.value(), mc.getClazz(), mapper, !index.disableValidation());
ensureIndex(mc.getClazz(), index.name(), fields, index.unique(), index.dropDups(),
index.background() ? index.background() : background, index.sparse(), index.expireAfterSeconds());
}
}
}
}
}
public <T> void ensureIndexes(final Class<T> clazz) {
ensureIndexes(clazz, false);
}
public <T> void ensureIndexes(final Class<T> clazz, final boolean background) {
final MappedClass mc = mapper.getMappedClass(clazz);
ensureIndexes(mc, background);
}
public void ensureIndexes() {
ensureIndexes(false);
}
public void ensureIndexes(final boolean background) {
// loops over mappedClasses and call ensureIndex for each @Entity object
// (for now)
for (final MappedClass mc : mapper.getMappedClasses()) {
ensureIndexes(mc, background);
}
}
public void ensureCaps() {
for (final MappedClass mc : mapper.getMappedClasses()) {
if (mc.getEntityAnnotation() != null && mc.getEntityAnnotation().cap().value() > 0) {
final CappedAt cap = mc.getEntityAnnotation().cap();
final String collName = mapper.getCollectionName(mc.getClazz());
final BasicDBObjectBuilder dbCapOpts = BasicDBObjectBuilder.start("capped", true);
if (cap.value() > 0) {
dbCapOpts.add("size", cap.value());
}
if (cap.count() > 0) {
dbCapOpts.add("max", cap.count());
}
final DB database = getDB();
if (database.getCollectionNames().contains(collName)) {
final DBObject dbResult = database.command(BasicDBObjectBuilder.start("collstats", collName).get());
if (dbResult.containsField("capped")) {
// TODO: check the cap options.
LOG.warning("DBCollection already exists is capped already; doing nothing. " + dbResult);
} else {
LOG.warning("DBCollection already exists with same name(" + collName + ") and is not capped; not creating capped version!");
}
} else {
getDB().createCollection(collName, dbCapOpts.get());
LOG.debug("Created capped DBCollection (" + collName + ") with opts " + dbCapOpts);
}
}
}
}
/**
* Creates and returns a {@link Query} using the underlying {@link QueryFactory}.
*
* @see QueryFactory#createQuery(Datastore, DBCollection, Class)
*/
private <T> Query<T> newQuery(final Class<T> type, final DBCollection collection) {
return getQueryFactory().createQuery(this, collection, type);
}
/**
* Creates and returns a {@link Query} using the underlying {@link QueryFactory}.
*
* @see QueryFactory#createQuery(Datastore, DBCollection, Class, DBObject)
*/
private <T> Query<T> newQuery(final Class<T> type, final DBCollection collection, final DBObject query) {
return getQueryFactory().createQuery(this, collection, type, query);
}
public <T> Query<T> queryByExample(final T ex) {
return queryByExample(getCollection(ex), ex);
}
public <T> Query<T> queryByExample(final String kind, final T ex) {
return queryByExample(db.getCollection(kind), ex);
}
private <T> Query<T> queryByExample(final DBCollection coll, final T example) {
//TODO: think about remove className from baseQuery param below.
final Class<T> type = (Class<T>)example.getClass();
final DBObject query = entityToDBObj(example, new HashMap<Object, DBObject>());
return createQuery(type, query);
}
public <T> Query<T> createQuery(final Class<T> type) {
return newQuery(type, getCollection(type));
}
public <T> Query<T> createQuery(final String kind, final Class<T> type) {
return newQuery(type, db.getCollection(kind));
}
public <T> Query<T> createQuery(final Class<T> type, final DBObject q) {
return newQuery(type, getCollection(type), q);
}
public <T> Query<T> createQuery(final String kind, final Class<T> type, final DBObject q) {
return newQuery(type, getCollection(kind), q);
}
public <T> Query<T> find(final String kind, final Class<T> clazz) {
return createQuery(kind, clazz);
}
public <T> Query<T> find(final Class<T> clazz) {
return createQuery(clazz);
}
public <T, V> Query<T> find(final Class<T> clazz, final String property, final V value) {
final Query<T> query = createQuery(clazz);
return query.filter(property, value);
}
public <T, V> Query<T> find(final String kind, final Class<T> clazz, final String property, final V value, final int offset,
final int size) {
return find(kind, clazz, property, value, offset, size, true);
}
public <T, V> Query<T> find(final String kind, final Class<T> clazz, final String property, final V value, final int offset,
final int size, final boolean validate) {
final Query<T> query = find(kind, clazz);
if (!validate) {
query.disableValidation();
}
query.offset(offset);
query.limit(size);
return query.filter(property, value).enableValidation();
}
public <T, V> Query<T> find(final Class<T> clazz, final String property, final V value, final int offset, final int size) {
final Query<T> query = createQuery(clazz);
query.offset(offset);
query.limit(size);
return query.filter(property, value);
}
public <T> T get(final Class<T> clazz, final DBRef ref) {
return (T) mapper.fromDBObject(clazz, ref.fetch(), createCache());
}
public <T, V> Query<T> get(final Class<T> clazz, final Iterable<V> ids) {
return find(clazz).disableValidation().filter(Mapper.ID_KEY + " in", ids).enableValidation();
}
/**
* Queries the server to check for each DBRef
*/
public <T> List<Key<T>> getKeysByRefs(final List<DBRef> refs) {
final List<Key<T>> tempKeys = new ArrayList<Key<T>>(refs.size());
final Map<String, List<DBRef>> kindMap = new HashMap<String, List<DBRef>>();
for (final DBRef ref : refs) {
if (kindMap.containsKey(ref.getRef())) {
kindMap.get(ref.getRef()).add(ref);
} else {
kindMap.put(ref.getRef(), new ArrayList<DBRef>(Collections.singletonList(ref)));
}
}
for (final String kind : kindMap.keySet()) {
final List<Object> objIds = new ArrayList<Object>();
final List<DBRef> kindRefs = kindMap.get(kind);
for (final DBRef key : kindRefs) {
objIds.add(key.getId());
}
final List<Key<T>> kindResults = this.<T>find(kind, null).disableValidation().filter("_id in", objIds).asKeyList();
tempKeys.addAll(kindResults);
}
//put them back in order, minus the missing ones.
final List<Key<T>> keys = new ArrayList<Key<T>>(refs.size());
for (final DBRef ref : refs) {
final Key<T> testKey = mapper.refToKey(ref);
if (tempKeys.contains(testKey)) {
keys.add(testKey);
}
}
return keys;
}
public <T> List<T> getByKeys(final Iterable<Key<T>> keys) {
return getByKeys(null, keys);
}
@SuppressWarnings("rawtypes")
public <T> List<T> getByKeys(final Class<T> clazz, final Iterable<Key<T>> keys) {
final Map<String, List<Key>> kindMap = new HashMap<String, List<Key>>();
final List<T> entities = new ArrayList<T>();
// String clazzKind = (clazz==null) ? null :
// getMapper().getCollectionName(clazz);
for (final Key<?> key : keys) {
mapper.updateKind(key);
// if (clazzKind != null && !key.getKind().equals(clazzKind))
// clazz + "!=" + key.getKindClass() +
// ") for key and method parameter clazz");
if (kindMap.containsKey(key.getKind())) {
kindMap.get(key.getKind()).add(key);
} else {
kindMap.put(key.getKind(), new ArrayList<Key>(Collections.singletonList((Key) key)));
}
}
for (final String kind : kindMap.keySet()) {
final List<Object> objIds = new ArrayList<Object>();
final List<Key> kindKeys = kindMap.get(kind);
for (final Key key : kindKeys) {
objIds.add(key.getId());
}
final List kindResults = find(kind, null).disableValidation().filter("_id in", objIds).asList();
entities.addAll(kindResults);
}
//TODO: order them based on the incoming Keys.
return entities;
}
public <T, V> T get(final String kind, final Class<T> clazz, final V id) {
final List<T> results = find(kind, clazz, Mapper.ID_KEY, id, 0, 1).asList();
if (results == null || results.isEmpty()) {
return null;
}
return results.get(0);
}
public <T, V> T get(final Class<T> clazz, final V id) {
return find(getCollection(clazz).getName(), clazz, Mapper.ID_KEY, id, 0, 1, true).get();
}
public <T> T getByKey(final Class<T> clazz, final Key<T> key) {
final String kind = mapper.getCollectionName(clazz);
final String keyKind = mapper.updateKind(key);
if (!kind.equals(keyKind)) {
throw new RuntimeException("collection names don't match for key and class: " + kind + " != " + keyKind);
}
return get(clazz, key.getId());
}
public <T> T get(final T entity) {
final T unwrapped = ProxyHelper.unwrap(entity);
final Object id = mapper.getId(unwrapped);
if (id == null) {
throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
}
return (T) get(unwrapped.getClass(), id);
}
public Key<?> exists(final Object entityOrKey) {
final Object unwrapped = ProxyHelper.unwrap(entityOrKey);
final Key<?> key = mapper.getKey(unwrapped);
final Object id = key.getId();
if (id == null) {
throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
}
String collName = key.getKind();
if (collName == null) {
collName = getCollection(key.getKindClass()).getName();
}
return find(collName, key.getKindClass()).filter(Mapper.ID_KEY, key.getId()).getKey();
}
@SuppressWarnings("rawtypes")
public DBCollection getCollection(final Class clazz) {
final String collName = mapper.getCollectionName(clazz);
return getDB().getCollection(collName);
}
public DBCollection getCollection(final Object obj) {
if (obj == null) {
return null;
}
return getCollection(obj.getClass());
}
protected DBCollection getCollection(final String kind) {
if (kind == null) {
return null;
}
return getDB().getCollection(kind);
}
public <T> long getCount(final T entity) {
return getCollection(ProxyHelper.unwrap(entity)).count();
}
public <T> long getCount(final Class<T> clazz) {
return getCollection(clazz).count();
}
public long getCount(final String kind) {
return getCollection(kind).count();
}
public <T> long getCount(final Query<T> query) {
return query.countAll();
}
public Mongo getMongo() {
return mongo;
}
public DB getDB() {
return db;
}
public Mapper getMapper() {
return mapper;
}
public <T> Iterable<Key<T>> insert(final Iterable<T> entities) {
//TODO: try not to create two iterators...
final Object first = entities.iterator().next();
return insert(entities, getWriteConcern(first));
}
public <T> Iterable<Key<T>> insert(final String kind, final Iterable<T> entities, final WriteConcern wc) {
final DBCollection dbColl = db.getCollection(kind);
return insert(dbColl, entities, wc);
}
public <T> Iterable<Key<T>> insert(final String kind, final Iterable<T> entities) {
return insert(kind, entities, getWriteConcern(entities.iterator().next()));
}
public <T> Iterable<Key<T>> insert(final Iterable<T> entities, final WriteConcern wc) {
//TODO: Do this without creating another iterator
final DBCollection dbColl = getCollection(entities.iterator().next());
return insert(dbColl, entities, wc);
}
private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {
final List<DBObject> list = entities instanceof List
? new ArrayList<DBObject>(((List<T>) entities).size())
: new ArrayList<DBObject>();
final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
for (final T ent : entities) {
final MappedClass mc = mapper.getMappedClass(ent);
if (mc.getAnnotation(NotSaved.class) != null) {
throw new MappingException(
"Entity type: " + mc.getClazz().getName() + " is marked as NotSaved which means you should not try to save it!");
}
list.add(entityToDBObj(ent, involvedObjects));
}
final WriteResult wr = null;
final DBObject[] dbObjects = new DBObject[list.size()];
dbColl.insert(list.toArray(dbObjects), wc);
throwOnError(wc, wr);
final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
final Iterator<T> entitiesIT = entities.iterator();
final Iterator<DBObject> dbObjectsIT = list.iterator();
while (entitiesIT.hasNext()) {
final T entity = entitiesIT.next();
final DBObject dbObj = dbObjectsIT.next();
savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
}
return savedKeys;
}
public <T> Iterable<Key<T>> insert(final T... entities) {
return insert(Arrays.asList(entities), getWriteConcern(entities[0]));
}
public <T> Key<T> insert(final T entity) {
return insert(entity, getWriteConcern(entity));
}
public <T> Key<T> insert(final T entity, final WriteConcern wc) {
final T unwrapped = ProxyHelper.unwrap(entity);
final DBCollection dbColl = getCollection(unwrapped);
return insert(dbColl, unwrapped, wc);
}
public <T> Key<T> insert(final String kind, final T entity) {
final T unwrapped = ProxyHelper.unwrap(entity);
final DBCollection dbColl = getCollection(kind);
return insert(dbColl, unwrapped, getWriteConcern(unwrapped));
}
public <T> Key<T> insert(final String kind, final T entity, final WriteConcern wc) {
final T unwrapped = ProxyHelper.unwrap(entity);
final DBCollection dbColl = getCollection(kind);
return insert(dbColl, unwrapped, wc);
}
protected <T> Key<T> insert(final DBCollection dbColl, final T entity, final WriteConcern wc) {
final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
final DBObject dbObj = entityToDBObj(entity, involvedObjects);
final WriteResult wr;
if (wc == null) {
wr = dbColl.insert(dbObj);
} else {
wr = dbColl.insert(dbObj, wc);
}
throwOnError(wc, wr);
return postSaveGetKey(entity, dbObj, dbColl, involvedObjects);
}
protected DBObject entityToDBObj(final Object entity, final Map<Object, DBObject> involvedObjects) {
return mapper.toDBObject(ProxyHelper.unwrap(entity), involvedObjects);
}
/**
* call postSaveOperations and returns Key for entity
*/
protected <T> Key<T> postSaveGetKey(final T entity, final DBObject dbObj, final DBCollection dbColl,
final Map<Object, DBObject> involvedObjects) {
if (dbObj.get(Mapper.ID_KEY) == null) {
throw new MappingException("Missing _id after save!");
}
postSaveOperations(entity, dbObj, involvedObjects);
final Key<T> key = new Key<T>(dbColl.getName(), mapper.getId(entity));
key.setKindClass((Class<? extends T>) entity.getClass());
return key;
}
public <T> Iterable<Key<T>> save(final Iterable<T> entities) {
Object first = null;
try {
first = entities.iterator().next();
} catch (Exception e) {
//do nothing
}
return save(entities, getWriteConcern(first));
}
public <T> Iterable<Key<T>> save(final Iterable<T> entities, final WriteConcern wc) {
final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
for (final T ent : entities) {
savedKeys.add(save(ent, wc));
}
return savedKeys;
}
public <T> Iterable<Key<T>> save(final T... entities) {
final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
for (final T ent : entities) {
savedKeys.add(save(ent));
}
return savedKeys;
}
protected <T> Key<T> save(final DBCollection dbColl, final T entity, final WriteConcern wc) {
if (entity == null) {
throw new UpdateException("Can not persist a null entity");
}
final MappedClass mc = mapper.getMappedClass(entity);
if (mc.getAnnotation(NotSaved.class) != null) {
throw new MappingException(
"Entity type: " + mc.getClazz().getName() + " is marked as NotSaved which means you should not try to save it!");
}
WriteResult wr;
//involvedObjects is used not only as a cache but also as a list of what needs to be called for life-cycle methods at the end.
final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
final DBObject dbObj = entityToDBObj(entity, involvedObjects);
//try to do an update if there is a @Version field
final Object idValue = dbObj.get(Mapper.ID_KEY);
wr = tryVersionedUpdate(dbColl, entity, dbObj, idValue, wc, db, mc);
if (wr == null) {
if (wc == null) {
wr = dbColl.save(dbObj);
} else {
wr = dbColl.save(dbObj, wc);
}
}
throwOnError(wc, wr);
return postSaveGetKey(entity, dbObj, dbColl, involvedObjects);
}
protected <T> WriteResult tryVersionedUpdate(final DBCollection dbColl, final T entity, final DBObject dbObj, final Object idValue,
final WriteConcern wc, final DB database, final MappedClass mc) {
WriteResult wr = null;
if (mc.getFieldsAnnotatedWith(Version.class).isEmpty()) {
return wr;
}
final MappedField mfVersion = mc.getFieldsAnnotatedWith(Version.class).get(0);
final String versionKeyName = mfVersion.getNameToStore();
final Long oldVersion = (Long) mfVersion.getFieldValue(entity);
final long newVersion = VersionHelper.nextValue(oldVersion);
dbObj.put(versionKeyName, newVersion);
if (oldVersion != null && oldVersion > 0) {
final UpdateResults<T> res = update(find(dbColl.getName(), (Class<T>) entity.getClass()).filter(Mapper.ID_KEY, idValue).filter(
versionKeyName, oldVersion), dbObj, false, false, wc);
wr = res.getWriteResult();
if (res.getUpdatedCount() != 1) {
throw new ConcurrentModificationException(
"Entity of class " + entity.getClass().getName() + " (id='" + idValue + "',version='" + oldVersion
+ "') was concurrently updated.");
}
} else if (wc == null) {
wr = dbColl.save(dbObj);
} else {
wr = dbColl.save(dbObj, wc);
}
//update the version.
mfVersion.setFieldValue(entity, newVersion);
return wr;
}
protected void throwOnError(final WriteConcern wc, final WriteResult wr) {
if (wc == null && wr.getLastConcern() == null) {
final CommandResult cr = wr.getLastError();
if (cr != null && cr.getErrorMessage() != null && cr.getErrorMessage().length() != 0) {
cr.throwOnError();
}
}
}
public <T> Key<T> save(final T entity) {
return save(entity, getWriteConcern(entity));
}
public <T> Key<T> save(final String kind, final T entity) {
final T unwrapped = ProxyHelper.unwrap(entity);
return save(kind, entity, getWriteConcern(unwrapped));
}
public <T> Key<T> save(final String kind, final T entity, final WriteConcern wc) {
return save(getCollection(kind), ProxyHelper.unwrap(entity), wc);
}
public <T> Key<T> save(final T entity, final WriteConcern wc) {
final T unwrapped = ProxyHelper.unwrap(entity);
final DBCollection dbColl = getCollection(unwrapped);
return save(dbColl, unwrapped, wc);
}
public <T> UpdateOperations<T> createUpdateOperations(final Class<T> clazz) {
return new UpdateOpsImpl<T>(clazz, getMapper());
}
public <T> UpdateOperations<T> createUpdateOperations(final Class<T> kind, final DBObject ops) {
final UpdateOpsImpl<T> upOps = (UpdateOpsImpl<T>) createUpdateOperations(kind);
upOps.setOps(ops);
return upOps;
}
public <T> UpdateResults<T> update(final Query<T> query, final UpdateOperations<T> ops, final boolean createIfMissing) {
return update(query, ops, createIfMissing, getWriteConcern(query.getEntityClass()));
}
public <T> UpdateResults<T> update(final Query<T> query, final UpdateOperations<T> ops, final boolean createIfMissing,
final WriteConcern wc) {
return update(query, ops, createIfMissing, true, wc);
}
public <T> UpdateResults<T> update(final T ent, final UpdateOperations<T> ops) {
if (ent instanceof Query) {
return update((Query<T>) ent, ops);
}
final MappedClass mc = mapper.getMappedClass(ent);
final Query<T> q = (Query<T>) createQuery(mc.getClazz());
q.disableValidation().filter(Mapper.ID_KEY, mapper.getId(ent));
if (!mc.getFieldsAnnotatedWith(Version.class).isEmpty()) {
final MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0);
final Long oldVer = (Long) versionMF.getFieldValue(ent);
q.filter(versionMF.getNameToStore(), oldVer);
ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer));
}
return update(q, ops);
}
public <T> UpdateResults<T> update(final Key<T> key, final UpdateOperations<T> ops) {
Class<T> clazz = (Class<T>) key.getKindClass();
if (clazz == null) {
clazz = (Class<T>) mapper.getClassFromKind(key.getKind());
}
return updateFirst(createQuery(clazz).disableValidation().filter(Mapper.ID_KEY, key.getId()), ops);
}
public <T> UpdateResults<T> update(final Query<T> query, final UpdateOperations<T> ops) {
return update(query, ops, false, true);
}
public <T> UpdateResults<T> updateFirst(final Query<T> query, final UpdateOperations<T> ops) {
return update(query, ops, false, false);
}
public <T> UpdateResults<T> updateFirst(final Query<T> query, final UpdateOperations<T> ops, final boolean createIfMissing) {
return update(query, ops, createIfMissing, getWriteConcern(query.getEntityClass()));
}
public <T> UpdateResults<T> updateFirst(final Query<T> query, final UpdateOperations<T> ops, final boolean createIfMissing,
final WriteConcern wc) {
return update(query, ops, createIfMissing, false, wc);
}
public <T> UpdateResults<T> updateFirst(final Query<T> query, final T entity, final boolean createIfMissing) {
final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
final DBObject dbObj = mapper.toDBObject(entity, involvedObjects);
final UpdateResults<T> res = update(query, dbObj, createIfMissing, false, getWriteConcern(entity));
//update _id field
final CommandResult gle = res.getWriteResult().getCachedLastError();
if (gle != null && res.getInsertedCount() > 0) {
dbObj.put(Mapper.ID_KEY, res.getNewId());
}
postSaveOperations(entity, dbObj, involvedObjects);
return res;
}
public <T> Key<T> merge(final T entity) {
return merge(entity, getWriteConcern(entity));
}
public <T> Key<T> merge(final T entity, final WriteConcern wc) {
T unwrapped = entity;
final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
final DBObject dbObj = mapper.toDBObject(unwrapped, involvedObjects);
final Key<T> key = mapper.getKey(unwrapped);
unwrapped = ProxyHelper.unwrap(unwrapped);
final Object id = mapper.getId(unwrapped);
if (id == null) {
throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
}
//remove (immutable) _id field for update.
final Object idValue = dbObj.get(Mapper.ID_KEY);
dbObj.removeField(Mapper.ID_KEY);
WriteResult wr;
final MappedClass mc = mapper.getMappedClass(unwrapped);
final DBCollection dbColl = getCollection(unwrapped);
//try to do an update if there is a @Version field
wr = tryVersionedUpdate(dbColl, unwrapped, dbObj, idValue, wc, db, mc);
if (wr == null) {
final Query<T> query = (Query<T>) createQuery(unwrapped.getClass()).filter(Mapper.ID_KEY, id);
wr = update(query, new BasicDBObject("$set", dbObj), false, false, wc).getWriteResult();
}
final UpdateResults<T> res = new UpdateResults<T>(wr);
throwOnError(wc, wr);
//check for updated count if we have a gle
final CommandResult gle = wr.getCachedLastError();
if (gle != null && res.getUpdatedCount() == 0) {
throw new UpdateException("Not updated: " + gle);
}
postSaveOperations(unwrapped, dbObj, involvedObjects);
return key;
}
private <T> void postSaveOperations(final Object entity, final DBObject dbObj, final Map<Object, DBObject> involvedObjects) {
mapper.updateKeyInfo(entity, dbObj, createCache());
//call PostPersist on all involved entities (including the entity)
for (final Map.Entry<Object, DBObject> e : involvedObjects.entrySet()) {
final Object ent = e.getKey();
final DBObject dbO = e.getValue();
final MappedClass mc = mapper.getMappedClass(ent);
mc.callLifecycleMethods(PostPersist.class, ent, dbO, mapper);
}
}
@SuppressWarnings("rawtypes")
private <T> UpdateResults<T> update(final Query<T> query, final UpdateOperations ops, final boolean createIfMissing, final boolean multi,
final WriteConcern wc) {
final DBObject u = ((UpdateOpsImpl) ops).getOps();
if (((UpdateOpsImpl) ops).isIsolated()) {
final Query<T> q = query.clone();
q.disableValidation().filter("$atomic", true);
return update(q, u, createIfMissing, multi, wc);
}
return update(query, u, createIfMissing, multi, wc);
}
@SuppressWarnings("rawtypes")
private <T> UpdateResults<T> update(final Query<T> query, final UpdateOperations ops, final boolean createIfMissing,
final boolean multi) {
return update(query, ops, createIfMissing, multi, getWriteConcern(query.getEntityClass()));
}
private <T> UpdateResults<T> update(final Query<T> query, final DBObject u, final boolean createIfMissing, final boolean multi,
final WriteConcern wc) {
final QueryImpl<T> qi = (QueryImpl<T>) query;
DBCollection dbColl = qi.getCollection();
//TODO remove this after testing.
if (dbColl == null) {
dbColl = getCollection(qi.getEntityClass());
}
if (qi.getSortObject() != null && qi.getSortObject().keySet() != null && !qi.getSortObject().keySet().isEmpty()) {
throw new QueryException("sorting is not allowed for updates.");
}
if (qi.getOffset() > 0) {
throw new QueryException("a query offset is not allowed for updates.");
}
if (qi.getLimit() > 0) {
throw new QueryException("a query limit is not allowed for updates.");
}
DBObject q = qi.getQueryObject();
if (q == null) {
q = new BasicDBObject();
}
if (LOG.isTraceEnabled()) {
LOG.trace("Executing update(" + dbColl.getName() + ") for query: " + q + ", ops: " + u + ", multi: " + multi + ", upsert: "
+ createIfMissing);
}
final WriteResult wr;
if (wc == null) {
wr = dbColl.update(q, u, createIfMissing, multi);
} else {
wr = dbColl.update(q, u, createIfMissing, multi, wc);
}
throwOnError(wc, wr);
return new UpdateResults<T>(wr);
}
public <T> T findAndDelete(final Query<T> query) {
DBCollection dbColl = ((QueryImpl<T>) query).getCollection();
//TODO remove this after testing.
if (dbColl == null) {
dbColl = getCollection(query.getEntityClass());
}
final QueryImpl<T> qi = ((QueryImpl<T>) query);
final EntityCache cache = createCache();
if (LOG.isTraceEnabled()) {
LOG.trace("Executing findAndModify(" + dbColl.getName() + ") with delete ...");
}
final DBObject result = dbColl.findAndModify(qi.getQueryObject(), qi.getFieldsObject(), qi.getSortObject(), true, null, false, false);
if (result != null) {
return (T) mapper.fromDBObject(qi.getEntityClass(), result, cache);
}
return null;
}
public <T> T findAndModify(final Query<T> q, final UpdateOperations<T> ops) {
return findAndModify(q, ops, false);
}
public <T> T findAndModify(final Query<T> query, final UpdateOperations<T> ops, final boolean oldVersion) {
return findAndModify(query, ops, oldVersion, false);
}
public <T> T findAndModify(final Query<T> query, final UpdateOperations<T> ops, final boolean oldVersion, final boolean createIfMissing) {
final QueryImpl<T> qi = (QueryImpl<T>) query;
DBCollection dbColl = qi.getCollection();
//TODO remove this after testing.
if (dbColl == null) {
dbColl = getCollection(qi.getEntityClass());
}
if (LOG.isTraceEnabled()) {
LOG.info("Executing findAndModify(" + dbColl.getName() + ") with update ");
}
DBObject res = null;
try {
res = dbColl.findAndModify(qi.getQueryObject(), qi.getFieldsObject(), qi.getSortObject(), false, ((UpdateOpsImpl<T>) ops).getOps(),
!oldVersion, createIfMissing);
} catch (MongoException e) {
if (e.getMessage() == null || !e.getMessage().contains("matching")) {
throw e;
}
}
if (res == null) {
return null;
} else {
return (T) mapper.fromDBObject(qi.getEntityClass(), res, createCache());
}
}
@SuppressWarnings("rawtypes")
public <T> MapreduceResults<T> mapReduce(final MapreduceType type, final Query q, final Class<T> outputType,
final MapReduceCommand baseCommand) {
Assert.parametersNotNull("map", baseCommand.getMap());
Assert.parameterNotEmpty(baseCommand.getMap(), "map");
Assert.parametersNotNull("reduce", baseCommand.getReduce());
Assert.parameterNotEmpty(baseCommand.getMap(), "reduce");
final QueryImpl<T> qi = (QueryImpl<T>) q;
if (qi.getOffset() != 0 || qi.getFieldsObject() != null) {
throw new QueryException("mapReduce does not allow the offset/retrievedFields query options.");
}
final OutputType outType;
switch (type) {
case REDUCE:
outType = OutputType.REDUCE;
break;
case MERGE:
outType = OutputType.MERGE;
break;
case INLINE:
outType = OutputType.INLINE;
break;
default:
outType = OutputType.REPLACE;
break;
}
final DBCollection dbColl = qi.getCollection();
final MapReduceCommand cmd = new MapReduceCommand(dbColl, baseCommand.getMap(), baseCommand.getReduce(), baseCommand.getOutputTarget(),
outType, qi.getQueryObject());
cmd.setFinalize(baseCommand.getFinalize());
cmd.setScope(baseCommand.getScope());
if (qi.getLimit() > 0) {
cmd.setLimit(qi.getLimit());
}
if (qi.getSortObject() != null) {
cmd.setSort(qi.getSortObject());
}
if (LOG.isTraceEnabled()) {
LOG.info("Executing " + cmd.toString());
}
final MapReduceOutput mpo = dbColl.mapReduce(baseCommand);
final EntityCache cache = createCache();
final MapreduceResults results = (MapreduceResults) mapper.fromDBObject(MapreduceResults.class, mpo.getCommandResult(), cache);
results.setType(type);
if (MapreduceType.INLINE.equals(type)) {
results.setInlineRequiredOptions(outputType, getMapper(), cache);
} else {
results.setQuery(newQuery(outputType, db.getCollection(results.getOutputCollectionName())));
}
return results;
}
@SuppressWarnings("rawtypes")
public <T> MapreduceResults<T> mapReduce(final MapreduceType type, final Query query, final String map, final String reduce,
final String finalize, final Map<String, Object> scopeFields, final Class<T> outputType) {
final QueryImpl<T> qi = (QueryImpl<T>) query;
final DBCollection dbColl = qi.getCollection();
final String outColl = mapper.getCollectionName(outputType);
final OutputType outType;
switch (type) {
case REDUCE:
outType = OutputType.REDUCE;
break;
case MERGE:
outType = OutputType.MERGE;
break;
case INLINE:
outType = OutputType.INLINE;
break;
default:
outType = OutputType.REPLACE;
break;
}
final MapReduceCommand cmd = new MapReduceCommand(dbColl, map, reduce, outColl, outType, qi.getQueryObject());
if (qi.getLimit() > 0) {
cmd.setLimit(qi.getLimit());
}
if (qi.getSortObject() != null) {
cmd.setSort(qi.getSortObject());
}
if (finalize != null && finalize.length() != 0) {
cmd.setFinalize(finalize);
}
if (scopeFields != null && !scopeFields.isEmpty()) {
cmd.setScope(scopeFields);
}
return mapReduce(type, query, outputType, cmd);
}
/**
* Converts a list of keys to refs
*/
public static <T> List<DBRef> keysAsRefs(final List<Key<T>> keys, final Mapper mapper) {
final List<DBRef> refs = new ArrayList<DBRef>(keys.size());
for (final Key<T> key : keys) {
refs.add(mapper.keyToRef(key));
}
return refs;
}
/**
* Converts a list of refs to keys
*/
public static <T> List<Key<T>> refsToKeys(final Mapper mapper, final List<DBRef> refs, final Class<T> c) {
final List<Key<T>> keys = new ArrayList<Key<T>>(refs.size());
for (final DBRef ref : refs) {
keys.add((Key<T>) mapper.refToKey(ref));
}
return keys;
}
private EntityCache createCache() {
return mapper.createEntityCache();
}
/**
* Gets the write concern for entity or returns the default write concern for this datastore
*/
public WriteConcern getWriteConcern(final Object clazzOrEntity) {
WriteConcern wc = defConcern;
if (clazzOrEntity != null) {
final Entity entityAnn = getMapper().getMappedClass(clazzOrEntity).getEntityAnnotation();
if (entityAnn != null && entityAnn.concern() != null && entityAnn.concern().length() != 0) {
wc = WriteConcern.valueOf(entityAnn.concern());
}
}
return wc;
}
public WriteConcern getDefaultWriteConcern() {
return defConcern;
}
public void setDefaultWriteConcern(final WriteConcern wc) {
defConcern = wc;
}
public DBDecoderFactory setDecoderFact(final DBDecoderFactory fact) {
decoderFactory = fact;
return decoderFactory;
}
public DBDecoderFactory getDecoderFact() {
return decoderFactory != null ? decoderFactory : DefaultDBDecoder.FACTORY;
}
public void setQueryFactory(final QueryFactory queryFactory) {
this.queryFactory = queryFactory;
}
public QueryFactory getQueryFactory() {
return queryFactory;
}
}
|
package com.planetmayo.debrief.satc.util;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Point;
public class MathUtils
{
private static final double TWO_PI = 2 * Math.PI;
/**
* return angle from [0; 2*Math.PI)
* @param angle
* @return
*/
public static double normalizeAngle(double angle)
{
double minus = angle < 0 ? 2 : -2;
while (angle < 0 || angle >= TWO_PI)
{
angle += minus * Math.PI;
}
return angle;
}
/**
* returns angle from [-Math.PI; Math.PI]
* @param angle
* @return
*/
public static double normalizeAngle2(double angle)
{
double res = angle;
while (res > Math.PI)
res -= TWO_PI;
while (res < -Math.PI)
res += TWO_PI;
return res;
}
public static double angleDiff(double angle1, double angle2, boolean normalized)
{
if (! normalized)
{
angle1 = normalizeAngle(angle1);
angle2 = normalizeAngle(angle2);
}
return Math.min(
Math.abs(angle1 - angle2),
Math.min(
Math.abs(angle1 - angle2 + TWO_PI),
Math.abs(angle1 - angle2 - TWO_PI)
));
}
public static Point calculateBezierDerivative(double t, Point start, Point end, Point[] control) {
if (control == null || control.length == 0)
{
return GeoSupport.createPoint(end.getX() - start.getX(), end.getY() - start.getY());
}
else if (control.length == 1)
{
double x = 2 * t * (start.getX() - 2 * control[0].getX() + end.getX()) + 2 * (control[0].getX() - start.getX());
double y = 2 * t * (start.getY() - 2 * control[0].getY() + end.getY()) + 2 * (control[0].getY() - start.getY());
return GeoSupport.createPoint(x, y);
}
else
{
double p0x = start.getX(), p1x = control[0].getX(), p2x = control[1].getX(), p3x = end.getX();
double p0y = start.getY(), p1y = control[0].getY(), p2y = control[1].getY(), p3y = end.getY();
double t2 = t * t;
double x = 3 * (t2 * (p3x - 3 * p2x + 3 * p1x - p0x) + 2 * t * (p2x - 2 * p1x + p0x) + (p1x - p0x));
double y = 3 * (t2 * (p3y - 3 * p2y + 3 * p1y - p0y) + 2 * t * (p2y - 2 * p1y + p0y) + (p1y - p0y));
return GeoSupport.createPoint(x, y);
}
}
public static Point calculateBezier(double t, Point start, Point end, Point[] control)
{
double invT = 1 - t;
double invT2 = invT * invT;
double invT3 = invT2 * invT;
double t2 = t * t;
double t3 = t2 * t;
if (control == null || control.length == 0)
{
double x = invT * start.getX() + t * end.getX();
double y = invT * start.getY() + t * end.getY();
return GeoSupport.createPoint(x, y);
}
else if (control.length == 1)
{
double x = invT2 * start.getX() + 2 * t * invT * control[0].getX() + t2 * end.getX();
double y = invT2 * start.getY() + 2 * t * invT * control[0].getY() + t2 * end.getY();
return GeoSupport.createPoint(x, y);
}
else
{
double x = invT3 * start.getX() + 3 * t * invT2 * control[0].getX() + 3 * t2 * invT * control[1].getX() + t3 * end.getX();
double y = invT3 * start.getY() + 3 * t * invT2 * control[0].getY() + 3 * t2 * invT * control[1].getY() + t3 * end.getY();
return GeoSupport.createPoint(x, y);
}
}
/**
* defines straight route in y(x) = k * x + b shape and returns [k, b].
* @param start and end point
* @return [k, b]
*/
public static double[] findStraightLineCoef(Point startPoint, Point endPoint)
{
double k = (startPoint.getY() - endPoint.getY()) / (startPoint.getX() - endPoint.getX());
double b = startPoint.getY() - k * startPoint.getX();
return new double[] {k, b};
}
/**
*
* @param line1 - first straight line coeffs: y(x) = line1[0] * x + line1[1]
* @param line2 - second straight line coeffs: y(x) = line2[0] * x + line2[1]
* @return intersection point between two line1 and line2
*/
public static Point findIntersection(double[] line1, double[] line2)
{
if (Math.abs(line1[0] - line2[0]) < 0.0001)
{
return null;
}
double x = (line1[1] - line2[1]) / (line2[0] - line1[0]);
double y = line1[0] * x + line1[1];
return GeoSupport.getFactory().createPoint(new Coordinate(x, y));
}
public static Point findIntersection(Coordinate a, Coordinate b, Coordinate c, Coordinate d)
{
double dx1 = b.x - a.x,
dy1 = b.y - a.y,
dx2 = d.x - c.x,
dy2 = d.y - c.y;
double c1 = ((a.x + a.y) - (c.x + c.y)) / (dx2 + dy2);
double c2 = (dx1 + dy1) / (dx2 + dy2);
double t1;
if (Math.abs(dx2) > Math.abs(dy2))
{
t1 = (a.x - c.x - dx2 * c1) / (dx2 * c2 - dx1);
}
else
{
t1 = (a.y - c.y - dy2 * c1) / (dy2 * c2 - dy1);
}
Coordinate res = new Coordinate(a.x + dx1 * t1, a.y + dy1 * t1);
return GeoSupport.getFactory().createPoint(res);
}
public static double calcAbsoluteValue(Point vector)
{
return Math.hypot(vector.getX(), vector.getY());
}
public static double calcAngle(Point vector)
{
double value = calcAbsoluteValue(vector);
double angle = Math.acos(vector.getX() / value);
if (vector.getY() < 0)
{
angle = TWO_PI - angle;
}
return angle;
}
}
|
package outland.feature;
import com.codahale.metrics.MetricRegistry;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import outland.feature.proto.Feature;
import outland.feature.proto.State;
/**
* A client which can be used to check feature state and access the feature management APIs.
* Clients must be created via a {@link FeatureClient.Builder}.
*
*/
public class FeatureClient {
private static final Logger logger = LoggerFactory.getLogger(FeatureClient.class.getSimpleName());
private final ServerConfiguration serverConfiguration;
private final FeatureStore featureStore;
private final AuthorizationProvider authorizationProvider;
private final ResourceProvider resourceProvider;
private final Resources resources;
private final ContentSupport contentSupport;
private final URI baseURI;
private final String defaultGroup;
private final String namespace;
private final boolean localStoreEnabled;
private final MetricRegistry metricRegistry;
public FeatureClient(Builder builder) {
this.serverConfiguration = builder.serverConfiguration;
this.baseURI = serverConfiguration.baseURI();
this.defaultGroup = serverConfiguration.defaultGroup();
this.namespace = serverConfiguration.namespace();
this.localStoreEnabled = serverConfiguration.localStoreEnabled();
this.authorizationProvider = builder.authorizationProvider;
this.resourceProvider = builder.resourceProvider;
this.contentSupport = builder.contentSupport;
this.metricRegistry = builder.metricRegistry;
this.resources = new Resources(
this.resourceProvider,
this.authorizationProvider,
this.defaultGroup,
this.baseURI
);
FeatureStoreLocal localFeatureStore = builder.localFeatureStore;
/*
create the cache via the client as the cache needs a client reference to pull from the server.
If the featureStore is present on the builder it means we've set a cache for testing
*/
if (builder.featureStore == null) {
final FeatureStoreReal featureStore = new FeatureStoreReal(this, localFeatureStore);
builder.featureStore = new FeatureStoreMetered(featureStore, builder.metricsContext);
featureStore.open();
}
this.featureStore = builder.featureStore;
}
/**
* Get a builder that can construct a new client. Clients can't be created directly.
*
* @return a new builder
*/
public static Builder newBuilder() {
return new Builder();
}
/**
* Check and see if a feature is enabled.
* <p>
* This is a convenience call for {@link #enabledFor(String, String)} where the group
* argument is taken from {@link #defaultGroup()}
* </p>
* <p>
* The client stores feature state locally in a cache, and will periodically refresh
* the cache record for a key by checking the remote API it's configured to use.
* </p>
* <p>
* The feature is considered enabled if the underlying {@link Feature} has a state equal
* to {@link State#on}. The call will return false for the following scenarios:
* <ol>
* <li>If the underlying {@link Feature} has a state equal to {@link State#off}.</li>
* <li>The {@link Feature} is enabled, but is a boolean option type and the boolean option
* evaluated to false. </li>
* <li>If the feature does not exist.</li>
* <li>If there was an internal error. </li>
* </ol>
* </p>
* <p>
* <b>Note</b> the last point - the client is designed generally to not throw exceptions
* at the call site, preferring instead to return false and act as if the feature was
* disabled or non-existent. Generally this means you should strongly prefer to write code
* that fires when the feature is on, rather than on the basis the feature is off. If you
* want to throw an exception for a missing feature, use {@link #enabledThrowing}.
* </p>
*
* @param featureKey the feature key defined for the feature
* @return true if the feature is enabled. Returns false if the feature is not enabled, not known,
* or there was an internal error.
* @throws FeatureException if the supplied featureKey is null, or, the default group has not
* been configured.
*/
public boolean enabled(String featureKey) {
throwIfNoDefaultNamespace();
FeatureException.throwIfNull(featureKey, "Please supply a feature key");
//noinspection ConstantConditions
return enabledInner(defaultGroup, featureKey);
}
/**
* Check and see if a feature is enabled.
* <p>
* This is a convenience call for {@link #enabledForThrowing(String, String)}
* where the group argument is taken from {@link #defaultGroup()}.
* </p>
* <p>
* This is same as {@link #enabled(String)} except it will throw a {@link FeatureException}
* if the feature does not exist or there is an internal exception.
* </p>
*
* @param featureKey the feature key defined for the feature
* @return true if the feature is enabled ({@link State#on}). Returns false if the feature
* is not enabled ({@link State#off}).
* @throws FeatureException if the supplied featureKey is null, the default group has not been
* configured, the feature does not exist or there was an internal error.
*/
public boolean enabledThrowing(String featureKey)
throws FeatureException {
throwIfNoDefaultNamespace();
FeatureException.throwIfNull(featureKey, "Please supply a feature key");
//noinspection ConstantConditions
return enabledThrowingInner(defaultGroup, featureKey);
}
/**
* Check and see if a feature is enabled.
* <p>
* The client stores feature state locally in a cache, and will periodically refresh
* the cache record for a key by checking the remote API it's configured to use.
* </p>
* <p>
* The feature is considered enabled if the underlying {@link Feature} has a state equal
* to {@link State#on}. The call will return false for the following scenarios:
* <ol>
* <li>If the underlying {@link Feature} has a state equal to {@link State#off}.</li>
* <li>The {@link Feature} is enabled, but is a boolean option type and the boolean option
* evaluated to false. </li>
* <li>If the feature does not exist.</li>
* <li>If there was an internal error. </li>
* </ol>
* </p>
* <p>
* <b>Note</b> the last point - the client is designed generally to not throw exceptions
* at the call site, preferring instead to return false and act as if the feature was
* disabled or non-existent. Generally this means you should strongly prefer to write code
* that fires when the feature is on, rather than on the basis the feature is off. If you
* want to throw an exception for a missing feature, use {@link #enabledThrowing}.
* </p>
*
* @param group the group the feature belongs to.
* @param featureKey the feature key defined for the feature
* @return true if the feature is enabled. Returns false if the feature is not enabled, not known,
* or there was an internal error.
* @throws FeatureException if the supplied featureKey is null, or, the default group has not
* been configured.
*/
public boolean enabledFor(String group, String featureKey) {
FeatureException.throwIfNull(group, "Please supply a defaultGroup");
FeatureException.throwIfNull(featureKey, "Please supply a featureKey");
return enabledInner(group, featureKey);
}
/**
* Check and see if a feature is enabled.
* <p>
* This is same as {@link #enabledForThrowing(String, String)} except it will throw a
* {@link FeatureException} if the feature does not exist or there is an internal exception.
* </p>
*
* @param group the group the feature belongs to.
* @param featureKey the feature key defined for the feature
* @return true if the feature is enabled ({@link State#on}). Returns false if the feature
* is not enabled ({@link State#off}).
* @throws FeatureException if the supplied featureKey is null, the default group has not been
* configured, the feature does not exist or there was an internal error.
*/
public boolean enabledForThrowing(String group, String featureKey) {
FeatureException.throwIfNull(group, "Please supply a defaultGroup");
FeatureException.throwIfNull(featureKey, "Please supply a featureKey");
return enabledThrowingInner(group, featureKey);
}
/**
* Entry point for the feature management APIs.
*
* @return a way to access feature management APIs.
*/
public Resources resources() {
return resources;
}
/**
* Stop the feature client.
* <p>
* This allows the client to clean up and release any cache related resources such as local
* storage.
* </p>
* <p>
* Note. The {@link Builder#build()} method places this method in a shutdown hook.
* </p>
* <p>
* <code>
* Runtime.getRuntime().addShutdownHook(new Thread(client::close));
* </code>
* </p>
*
* @throws FeatureException or a subclass.
*/
@SuppressWarnings("WeakerAccess") public void close() throws FeatureException {
logger.info("op=close, action=releasing_storage_resources");
featureStore.close();
}
@VisibleForTesting
ServerConfiguration serverConfiguration() {
return serverConfiguration;
}
@VisibleForTesting
AuthorizationProvider authorizationProvider() {
return authorizationProvider;
}
@VisibleForTesting
ResourceProvider resourceProvider() {
return resourceProvider;
}
@VisibleForTesting
ContentSupport contentSupport() {
return contentSupport;
}
@VisibleForTesting
MetricRegistry metricRegistry() {
return metricRegistry;
}
@VisibleForTesting
URI baseURI() {
return baseURI;
}
String defaultGroup() {
return defaultGroup;
}
@VisibleForTesting
boolean localStoreEnabled() {
return localStoreEnabled;
}
private void throwIfNoDefaultNamespace() {
if (defaultGroup == null) {
throw new FeatureException(Problem.configProblem("enabled_check_with_no_group",
"A feature flag check with no group cannot be called without configuring "
+ "a default group first. "
+ "Please set the default group or use the group plus feature key variant."));
}
}
private boolean enabledInner(String group, String featureKey) {
final FeatureRecord record = featureStore.find(group, featureKey);
if (record == null) {
return false;
}
return record.evaluate(this.namespace);
}
private boolean enabledThrowingInner(String group, String featureKey) {
final FeatureRecord record = featureStore.find(group, featureKey);
if (record == null) {
return throwNotFound(group, featureKey);
}
return record.evaluate(this.namespace);
}
private boolean throwNotFound(String group, String featureKey) {
throw new FeatureException(
Problem.noSuchFeature("feature_not_found",
String.format(
"feature %s for defaultGroup %s was not found and raising an error was requested",
featureKey, group)));
}
/**
* Prepares and creates a {@link FeatureClient}.
*/
public static class Builder {
private ServerConfiguration serverConfiguration;
private AuthorizationProvider authorizationProvider;
private ResourceProvider resourceProvider;
private FeatureStore featureStore;
private FeatureStoreLocal localFeatureStore;
private ContentSupport contentSupport;
private MetricRegistry metricRegistry;
private MetricsContext metricsContext;
private String metricsContextName;
Builder() {
}
/**
* Build a new {@link FeatureClient}.
* <p>
* This is the only way to create a client. There's no restriction on the number of clients
* you can create per JVM process.
* </p>
* <p>
* This method adds the returned {@link FeatureClient#close()} method
* to a shutdown hook, ie calling this method effectively does the following:
* </p>
* <p>
* <code>
* Runtime.getRuntime().addShutdownHook(new Thread(client::close));
* </code>
* </p>
*
* @return a new FeatureClient.
* @throws FeatureException if the client is considered misconfigured or missing configuration.
*/
public FeatureClient build() {
if (serverConfiguration == null) {
throw new FeatureException(Problem.localProblem(
"Please supply a configuration", ""));
}
if (metricsContextName == null) {
metricsContextName = "outland.feature";
}
if (metricRegistry == null) {
metricRegistry = new MetricRegistry();
}
metricsContext = new MetricsContext(metricsContextName, metricRegistry);
if (authorizationProvider == null) {
authorizationProvider = new EmptyAuthorizationProvider();
}
if (contentSupport == null) {
contentSupport = new ContentSupport();
}
if (serverConfiguration != null) {
serverConfiguration.validate();
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(serverConfiguration.connectTimeout(), TimeUnit.MILLISECONDS)
.readTimeout(serverConfiguration.readTimeout(), TimeUnit.MILLISECONDS);
if (serverConfiguration.certificatePath() != null) {
new CertificateLoader(
serverConfiguration.certificatePath()).applySslSocketFactory(builder);
}
if (serverConfiguration.httpLoggingEnabled()) {
builder = builder.addNetworkInterceptor(
new HttpLoggingInterceptor(new okhttp3.logging.HttpLoggingInterceptor.Logger() {
final Logger httpLogger = LoggerFactory.getLogger("FeatureClientHttpLog");
@Override public void log(String message) {
httpLogger.info(message);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY));
logger.info("http tracing enabled");
}
resourceProvider =
new OkHttpResourceProvider(builder.build(), contentSupport, metricRegistry);
}
if (serverConfiguration.localStoreEnabled() && localFeatureStore == null) {
localFeatureStore = new FeatureStoreRocksDb(metricsContext);
} else {
localFeatureStore = new FeatureStoreLocalNone();
}
final FeatureClient featureClient = new FeatureClient(this);
Runtime.getRuntime().addShutdownHook(new Thread(featureClient::close));
return featureClient;
}
/**
* Supply the {@link ServerConfiguration}.
*
* @param serverConfiguration the server configuration
* @return this
*/
public Builder serverConfiguration(ServerConfiguration serverConfiguration) {
this.serverConfiguration = serverConfiguration;
return this;
}
/**
* Supply the {@link AuthorizationProvider}.
*
* @param authorizationProvider the provider
* @return this
*/
public Builder authorizationProvider(AuthorizationProvider authorizationProvider) {
this.authorizationProvider = authorizationProvider;
return this;
}
/**
* Supply the {@link MetricRegistry}.
*
* @param metricRegistry the registry
* @return this
*/
public Builder metricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
return this;
}
/**
* Supply the prefix used for metrics.
*
* <p>
* You can set this to make the metrics for your client's cluster or service distinct.
* </p>
*
* @param metricsContextName the metrics prefix
* @return this
*/
public Builder metricsContextName(String metricsContextName) {
this.metricsContextName = metricsContextName;
return this;
}
@VisibleForTesting
Builder featureStore(FeatureStore featureStore) {
this.featureStore = featureStore;
return this;
}
@VisibleForTesting
Builder localFeatureStore(FeatureStoreLocal localFeatureStore) {
this.localFeatureStore = localFeatureStore;
return this;
}
}
}
|
package org.jetbrains.plugins.scala.lang.formatting.settings;
import com.intellij.application.options.CodeStyleAbstractPanel;
import com.intellij.ide.DataManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.UnnamedConfigurable;
import com.intellij.openapi.options.ex.ConfigurableWrapper;
import com.intellij.openapi.options.ex.Settings;
import com.intellij.profile.codeInspection.ui.ErrorsConfigurable;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.ui.EnumComboBoxModel;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.ui.TitledSeparator;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.scala.ScalaFileType;
import org.jetbrains.plugins.scala.highlighter.ScalaEditorHighlighter;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
/**
* Pavel Fatin
*/
public class TypeAnnotationsPanel extends CodeStyleAbstractPanel {
public static final String CONFIGURABLE_ID = "com.intellij.profile.codeInspection.ui.ProjectInspectionToolsConfigurableProvider";
private JPanel contentPanel;
private JComboBox myPublicPropertyComboBox;
private JComboBox myProtectedPropertyComboBox;
private JComboBox myPrivatePropertyComboBox;
private JComboBox myPublicMethodComboBox;
private JComboBox myProtectedMethodComboBox;
private JComboBox myPrivateMethodComboBox;
private JComboBox myOverridingPropertyComboBox;
private JComboBox myOverridingMethodComboBox;
private JComboBox myLocalPropertyComboBox;
private JComboBox myLocalMethodComboBox;
private JComboBox mySimplePropertyComboBox;
private JComboBox mySimpleMethodComboBox;
private JPanel myLinkContainer;
protected TypeAnnotationsPanel(@NotNull CodeStyleSettings settings) {
super(settings);
myLocalPropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myPublicPropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myProtectedPropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myPrivatePropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myOverridingPropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationPolicy>(TypeAnnotationPolicy.class));
mySimplePropertyComboBox.setModel(new EnumComboBoxModel<TypeAnnotationPolicy>(TypeAnnotationPolicy.class));
myLocalMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myPublicMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myProtectedMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myPrivateMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationRequirement>(TypeAnnotationRequirement.class));
myOverridingMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationPolicy>(TypeAnnotationPolicy.class));
mySimpleMethodComboBox.setModel(new EnumComboBoxModel<TypeAnnotationPolicy>(TypeAnnotationPolicy.class));
HyperlinkLabel link = new HyperlinkLabel("Configure type annotation inspection");
link.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(final HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
final Settings optionsEditor =
Settings.KEY.getData(DataManager.getInstance().getDataContextFromFocus().getResultSync());
if (optionsEditor != null) {
UnnamedConfigurable configurable =
optionsEditor.find(CONFIGURABLE_ID);
if (configurable instanceof ConfigurableWrapper) {
configurable = ((ConfigurableWrapper) configurable).getConfigurable();
}
if (configurable != null && configurable instanceof ErrorsConfigurable) {
final ErrorsConfigurable errorsConfigurable = (ErrorsConfigurable) configurable;
optionsEditor.select((Configurable) configurable).doWhenDone(new Runnable() {
public void run() {
errorsConfigurable.selectInspectionTool("TypeAnnotation");
}
});
}
}
}
}
});
myLinkContainer.setLayout(new BorderLayout());
myLinkContainer.add(link);
resetImpl(settings);
}
@Override
protected String getTabTitle() {
return "Type Annotations";
}
@Override
protected int getRightMargin() {
return 0;
}
@Nullable
@Override
protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) {
return new ScalaEditorHighlighter(null, null, scheme);
}
@NotNull
@Override
protected FileType getFileType() {
return ScalaFileType.SCALA_FILE_TYPE;
}
@Nullable
@Override
protected String getPreviewText() {
return "";
}
@Override
public void apply(CodeStyleSettings settings) {
ScalaCodeStyleSettings scalaSettings = settings.getCustomSettings(ScalaCodeStyleSettings.class);
scalaSettings.LOCAL_PROPERTY_TYPE_ANNOTATION = myLocalPropertyComboBox.getSelectedIndex();
scalaSettings.PUBLIC_PROPERTY_TYPE_ANNOTATION = myPublicPropertyComboBox.getSelectedIndex();
scalaSettings.PROTECTED_PROPERTY_TYPE_ANNOTATION = myProtectedPropertyComboBox.getSelectedIndex();
scalaSettings.PRIVATE_PROPERTY_TYPE_ANNOTATION = myPrivatePropertyComboBox.getSelectedIndex();
scalaSettings.OVERRIDING_PROPERTY_TYPE_ANNOTATION = myOverridingPropertyComboBox.getSelectedIndex();
scalaSettings.SIMPLE_PROPERTY_TYPE_ANNOTATION = mySimplePropertyComboBox.getSelectedIndex();
scalaSettings.LOCAL_METHOD_TYPE_ANNOTATION = myLocalMethodComboBox.getSelectedIndex();
scalaSettings.PUBLIC_METHOD_TYPE_ANNOTATION = myPublicMethodComboBox.getSelectedIndex();
scalaSettings.PROTECTED_METHOD_TYPE_ANNOTATION = myProtectedMethodComboBox.getSelectedIndex();
scalaSettings.PRIVATE_METHOD_TYPE_ANNOTATION = myPrivateMethodComboBox.getSelectedIndex();
scalaSettings.OVERRIDING_METHOD_TYPE_ANNOTATION = myOverridingMethodComboBox.getSelectedIndex();
scalaSettings.SIMPLE_METHOD_TYPE_ANNOTATION = mySimpleMethodComboBox.getSelectedIndex();
}
@Override
public boolean isModified(CodeStyleSettings settings) {
ScalaCodeStyleSettings scalaSettings = settings.getCustomSettings(ScalaCodeStyleSettings.class);
return (scalaSettings.LOCAL_PROPERTY_TYPE_ANNOTATION != myLocalPropertyComboBox.getSelectedIndex() ||
scalaSettings.PUBLIC_PROPERTY_TYPE_ANNOTATION != myPublicPropertyComboBox.getSelectedIndex() ||
scalaSettings.PROTECTED_PROPERTY_TYPE_ANNOTATION != myProtectedPropertyComboBox.getSelectedIndex() ||
scalaSettings.PRIVATE_PROPERTY_TYPE_ANNOTATION != myPrivatePropertyComboBox.getSelectedIndex() ||
scalaSettings.OVERRIDING_PROPERTY_TYPE_ANNOTATION != myOverridingPropertyComboBox.getSelectedIndex() ||
scalaSettings.SIMPLE_PROPERTY_TYPE_ANNOTATION != mySimplePropertyComboBox.getSelectedIndex() ||
scalaSettings.LOCAL_METHOD_TYPE_ANNOTATION != myLocalMethodComboBox.getSelectedIndex() ||
scalaSettings.PUBLIC_METHOD_TYPE_ANNOTATION != myPublicMethodComboBox.getSelectedIndex() ||
scalaSettings.PROTECTED_METHOD_TYPE_ANNOTATION != myProtectedMethodComboBox.getSelectedIndex() ||
scalaSettings.PRIVATE_METHOD_TYPE_ANNOTATION != myPrivateMethodComboBox.getSelectedIndex() ||
scalaSettings.OVERRIDING_METHOD_TYPE_ANNOTATION != myOverridingMethodComboBox.getSelectedIndex() ||
scalaSettings.SIMPLE_METHOD_TYPE_ANNOTATION != mySimpleMethodComboBox.getSelectedIndex());
}
@Nullable
@Override
public JComponent getPanel() {
return contentPanel;
}
@Override
protected void resetImpl(CodeStyleSettings settings) {
ScalaCodeStyleSettings scalaSettings = settings.getCustomSettings(ScalaCodeStyleSettings.class);
myLocalPropertyComboBox.setSelectedIndex(scalaSettings.LOCAL_PROPERTY_TYPE_ANNOTATION);
myPublicPropertyComboBox.setSelectedIndex(scalaSettings.PUBLIC_PROPERTY_TYPE_ANNOTATION);
myProtectedPropertyComboBox.setSelectedIndex(scalaSettings.PROTECTED_PROPERTY_TYPE_ANNOTATION);
myPrivatePropertyComboBox.setSelectedIndex(scalaSettings.PRIVATE_PROPERTY_TYPE_ANNOTATION);
myOverridingPropertyComboBox.setSelectedIndex(scalaSettings.OVERRIDING_PROPERTY_TYPE_ANNOTATION);
mySimplePropertyComboBox.setSelectedIndex(scalaSettings.SIMPLE_PROPERTY_TYPE_ANNOTATION);
myLocalMethodComboBox.setSelectedIndex(scalaSettings.LOCAL_METHOD_TYPE_ANNOTATION);
myPublicMethodComboBox.setSelectedIndex(scalaSettings.PUBLIC_METHOD_TYPE_ANNOTATION);
myProtectedMethodComboBox.setSelectedIndex(scalaSettings.PROTECTED_METHOD_TYPE_ANNOTATION);
myPrivateMethodComboBox.setSelectedIndex(scalaSettings.PRIVATE_METHOD_TYPE_ANNOTATION);
myOverridingMethodComboBox.setSelectedIndex(scalaSettings.OVERRIDING_METHOD_TYPE_ANNOTATION);
mySimpleMethodComboBox.setSelectedIndex(scalaSettings.SIMPLE_METHOD_TYPE_ANNOTATION);
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(17, 4, new Insets(0, 0, 0, 0), -1, -1));
final Spacer spacer1 = new Spacer();
contentPanel.add(spacer1, new GridConstraints(16, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
contentPanel.add(spacer2, new GridConstraints(16, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Value");
contentPanel.add(label1, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Method");
contentPanel.add(label2, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final TitledSeparator titledSeparator1 = new TitledSeparator();
titledSeparator1.setText("Instance Type Annotations");
contentPanel.add(titledSeparator1, new GridConstraints(0, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
myPublicPropertyComboBox = new JComboBox();
contentPanel.add(myPublicPropertyComboBox, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Public:");
contentPanel.add(label3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Protected:");
contentPanel.add(label4, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Private:");
contentPanel.add(label5, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myProtectedPropertyComboBox = new JComboBox();
contentPanel.add(myProtectedPropertyComboBox, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myPrivatePropertyComboBox = new JComboBox();
contentPanel.add(myPrivatePropertyComboBox, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myPublicMethodComboBox = new JComboBox();
contentPanel.add(myPublicMethodComboBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myProtectedMethodComboBox = new JComboBox();
contentPanel.add(myProtectedMethodComboBox, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myPrivateMethodComboBox = new JComboBox();
contentPanel.add(myPrivateMethodComboBox, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final TitledSeparator titledSeparator2 = new TitledSeparator();
titledSeparator2.setText("Special Cases");
contentPanel.add(titledSeparator2, new GridConstraints(10, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label6 = new JLabel();
label6.setText("Value");
contentPanel.add(label6, new GridConstraints(11, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label7 = new JLabel();
label7.setText("Method");
contentPanel.add(label7, new GridConstraints(11, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myOverridingPropertyComboBox = new JComboBox();
contentPanel.add(myOverridingPropertyComboBox, new GridConstraints(12, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myOverridingMethodComboBox = new JComboBox();
contentPanel.add(myOverridingMethodComboBox, new GridConstraints(12, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final TitledSeparator titledSeparator3 = new TitledSeparator();
titledSeparator3.setText("Local Type Annotations");
contentPanel.add(titledSeparator3, new GridConstraints(6, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label8 = new JLabel();
label8.setText("Value");
contentPanel.add(label8, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label9 = new JLabel();
label9.setText("Method");
contentPanel.add(label9, new GridConstraints(7, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myLocalPropertyComboBox = new JComboBox();
contentPanel.add(myLocalPropertyComboBox, new GridConstraints(8, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
myLocalMethodComboBox = new JComboBox();
contentPanel.add(myLocalMethodComboBox, new GridConstraints(8, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label10 = new JLabel();
label10.setText("Overriding:");
contentPanel.add(label10, new GridConstraints(12, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label11 = new JLabel();
label11.setText("Local:");
contentPanel.add(label11, new GridConstraints(8, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label12 = new JLabel();
label12.setText("Simple:");
contentPanel.add(label12, new GridConstraints(13, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
mySimplePropertyComboBox = new JComboBox();
contentPanel.add(mySimplePropertyComboBox, new GridConstraints(13, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
mySimpleMethodComboBox = new JComboBox();
contentPanel.add(mySimpleMethodComboBox, new GridConstraints(13, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label13 = new JLabel();
label13.setText("<html><body>\n<br>\n<strong>Legend:</strong>\n<ul>\n<li>Add - insert in generated code.</li>\n<li>Check - warn when not present.</li>\n</ul>\n</body></html>");
contentPanel.add(label13, new GridConstraints(14, 0, 1, 3, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
contentPanel.add(spacer3, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, 1, GridConstraints.SIZEPOLICY_FIXED, new Dimension(-1, 10), null, new Dimension(-1, 10), 0, false));
final Spacer spacer4 = new Spacer();
contentPanel.add(spacer4, new GridConstraints(9, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, 1, GridConstraints.SIZEPOLICY_FIXED, new Dimension(-1, 10), null, new Dimension(-1, 10), 0, false));
myLinkContainer = new JPanel();
myLinkContainer.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(myLinkContainer, new GridConstraints(15, 0, 1, 3, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
}
|
package de.avalax.fitbuddy.progressBar;
import android.view.Display;
import android.view.MotionEvent;
import android.view.WindowManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
public class ProgressBarOnGestureListenerTest {
private static final int SWIPE_MIN_DISTANCE = 60;
private static final int SWIPE_THRESHOLD_VELOCITY = 100;
private int onFlingEventMoved;
private WindowManager windowManager;
private ProgressBarOnGestureListener progressBarOnGestureListener;
private Display defaultDisplay;
@Before
public void setUp() {
windowManager = mock(WindowManager.class);
defaultDisplay = mock(Display.class);
when(windowManager.getDefaultDisplay()).thenReturn(defaultDisplay);
progressBarOnGestureListener = new ProgressBarOnGestureListener(windowManager, SWIPE_MIN_DISTANCE, SWIPE_THRESHOLD_VELOCITY) {
@Override
public void onFlingEvent(int moved) {
onFlingEventMoved = moved;
}
};
}
@Test
public void testOnFling_shouldReturnTrueWhenSwipingUp() throws Exception {
MotionEvent startMotionEvent = getMotionEvent(SWIPE_MIN_DISTANCE + 1);
MotionEvent endMotionEvent = getMotionEvent(0);
boolean hasFling = progressBarOnGestureListener.onFling(startMotionEvent, endMotionEvent, 0, SWIPE_THRESHOLD_VELOCITY + 1);
assertThat(hasFling, equalTo(true));
}
@Test
public void testOnFling_shouldReturnFalseWhenMinDistanceNotReachedOnSwipingUp() throws Exception {
MotionEvent startMotionEvent = getMotionEvent(SWIPE_MIN_DISTANCE);
MotionEvent endMotionEvent = getMotionEvent(0);
boolean hasFling = progressBarOnGestureListener.onFling(startMotionEvent, endMotionEvent, 0, SWIPE_THRESHOLD_VELOCITY + 1);
assertThat(hasFling, equalTo(false));
}
@Test
public void testOnFling_shouldReturnTrueWhenSwipingDown() throws Exception {
MotionEvent startMotionEvent = getMotionEvent(0);
MotionEvent endMotionEvent = getMotionEvent(SWIPE_MIN_DISTANCE + 1);
boolean hasFling = progressBarOnGestureListener.onFling(startMotionEvent, endMotionEvent, 0, SWIPE_THRESHOLD_VELOCITY + 1);
assertThat(hasFling, equalTo(true));
}
@Test
public void testOnFling_shouldReturnFalseWhenMinDistanceNotReachedOnSwipingDown() throws Exception {
MotionEvent startMotionEvent = getMotionEvent(0);
MotionEvent endMotionEvent = getMotionEvent(SWIPE_MIN_DISTANCE);
boolean hasFling = progressBarOnGestureListener.onFling(startMotionEvent, endMotionEvent, 0, SWIPE_THRESHOLD_VELOCITY + 1);
assertThat(hasFling, equalTo(false));
}
@Test
public void testOnFling_shouldReturnFalseWhenMinVelocityNotReachedOnSwiping() throws Exception {
MotionEvent startMotionEvent = getMotionEvent(SWIPE_MIN_DISTANCE + 1);
MotionEvent endMotionEvent = getMotionEvent(0);
boolean hasFling = progressBarOnGestureListener.onFling(startMotionEvent, endMotionEvent, 0, SWIPE_THRESHOLD_VELOCITY);
assertThat(hasFling, equalTo(false));
}
//TODO: issue
private MotionEvent getMotionEvent(float y) {
MotionEvent e1 = mock(MotionEvent.class);
when(e1.getY()).thenReturn(y);
return e1;
}
}
|
package org.jboss.forge.addons;
import java.util.Collections;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addons.facets.ForgeContainerAPIFacet;
import org.jboss.forge.arquillian.Addon;
import org.jboss.forge.arquillian.Dependencies;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.container.Forge;
import org.jboss.forge.container.addons.AddonId;
import org.jboss.forge.container.repositories.AddonDependencyEntry;
import org.jboss.forge.container.versions.SingleVersion;
import org.jboss.forge.dependencies.Dependency;
import org.jboss.forge.dependencies.builder.DependencyBuilder;
import org.jboss.forge.maven.projects.MavenFacet;
import org.jboss.forge.projects.Project;
import org.jboss.forge.projects.ProjectFactory;
import org.jboss.forge.projects.facets.DependencyFacet;
import org.jboss.forge.projects.facets.MetadataFacet;
import org.jboss.forge.resource.DirectoryResource;
import org.jboss.forge.resource.ResourceFactory;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class AddonProjectConfiguratorTest
{
@Deployment
@Dependencies({
@Addon(name = "org.jboss.forge:addons", version = "2.0.0-SNAPSHOT")
})
public static ForgeArchive getDeployment()
{
return ShrinkWrap.create(ForgeArchive.class).
addBeansXML().
addPackages(true, AddonProjectConfigurator.class.getPackage()).
addAsAddonDependencies(
AddonDependencyEntry.create(AddonId.from("org.jboss.forge:addons", "2.0.0-SNAPSHOT"))
);
}
@Inject
private AddonProjectConfigurator addonProjectFactory;
@Inject
private ProjectFactory projectFactory;
@Inject
private ResourceFactory resourceFactory;
@Inject
private Forge forge;
@Test
public void testCreateAddonProject()
{
DirectoryResource addonDir = resourceFactory.create(forge.getRepositories().get(0).getRootDirectory()).reify(
DirectoryResource.class);
DirectoryResource projectDir = addonDir.createTempResource();
Project project = projectFactory.createProject(projectDir);
MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
metadataFacet.setProjectName("testproject");
metadataFacet.setProjectVersion("1.0.0-SNAPSHOT");
metadataFacet.setTopLevelPackage("com.acme.testproject");
SingleVersion forgeVersion = new SingleVersion("2.0.0.Alpha3");
addonProjectFactory.setupAddonProject(project, forgeVersion, Collections.<AddonId> emptyList());
DirectoryResource projectRoot = project.getProjectRoot();
Assert.assertTrue("ADDON module is missing", projectRoot.getChild("addon").exists());
Assert.assertTrue("API module is missing", projectRoot.getChild("api").exists());
Assert.assertTrue("IMPL module is missing", projectRoot.getChild("impl").exists());
Assert.assertTrue("SPI module is missing", projectRoot.getChild("spi").exists());
Assert.assertTrue("TESTS module is missing", projectRoot.getChild("tests").exists());
Project addonProject = projectFactory.findProject(projectRoot.getChildDirectory("addon"));
Project apiProject = projectFactory.findProject(projectRoot.getChildDirectory("api"));
Project implProject = projectFactory.findProject(projectRoot.getChildDirectory("impl"));
Project spiProject = projectFactory.findProject(projectRoot.getChildDirectory("spi"));
Project testsProject = projectFactory.findProject(projectRoot.getChildDirectory("tests"));
Dependency addonDependency = DependencyBuilder.create(
addonProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
Dependency apiDependency = apiProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency implDependency = implProject.getFacet(MetadataFacet.class).getOutputDependency();
Dependency spiDependency = DependencyBuilder.create(
spiProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
/*
* Verify parent project
*/
Assert.assertNull(project.getFacet(MavenFacet.class).getPOM().getParent());
Assert.assertTrue(project.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(project.getFacet(DependencyFacet.class).hasDirectManagedDependency(
DependencyBuilder.create(addonProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon")));
Assert.assertTrue(project.getFacet(DependencyFacet.class).hasDirectManagedDependency(apiDependency));
Assert.assertTrue(project.getFacet(DependencyFacet.class).hasDirectManagedDependency(
implProject.getFacet(MetadataFacet.class).getOutputDependency()));
Assert.assertTrue(project.getFacet(DependencyFacet.class).hasDirectManagedDependency(spiDependency));
/*
* Verify impl/ sub-module
*/
Assert.assertEquals("../pom.xml", implProject.getFacet(MavenFacet.class).getPOM().getParent().getRelativePath());
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasDirectDependency(apiDependency));
Assert.assertFalse(implProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(apiDependency));
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(apiDependency));
Assert.assertEquals("provided", implProject.getFacet(DependencyFacet.class).getDirectDependency(apiDependency)
.getScopeType());
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasDirectDependency(spiDependency));
Assert.assertFalse(implProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(spiDependency));
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(spiDependency));
Assert.assertEquals("provided", implProject.getFacet(DependencyFacet.class).getDirectDependency(spiDependency)
.getScopeType());
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasDirectDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertFalse(implProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(implProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
/*
* Verify api/ sub-module
*/
Assert.assertEquals("../pom.xml", apiProject.getFacet(MavenFacet.class).getPOM().getParent().getRelativePath());
Assert.assertTrue(apiProject.getFacet(DependencyFacet.class).hasDirectDependency(spiDependency));
Assert.assertFalse(apiProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(spiDependency));
Assert.assertTrue(apiProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(spiDependency));
Assert.assertEquals("provided", apiProject.getFacet(DependencyFacet.class).getDirectDependency(spiDependency)
.getScopeType());
Assert.assertTrue(apiProject.getFacet(DependencyFacet.class).hasDirectDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertFalse(apiProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(apiProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
/*
* Verify spi/ sub-module
*/
Assert.assertEquals("../pom.xml", spiProject.getFacet(MavenFacet.class).getPOM().getParent().getRelativePath());
Assert.assertTrue(spiProject.getFacet(DependencyFacet.class).hasDirectDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertFalse(spiProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(spiProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
/*
* Verify addon/ sub-module
*/
Assert.assertEquals("../pom.xml", addonProject.getFacet(MavenFacet.class).getPOM().getParent().getRelativePath());
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasDirectDependency(apiDependency));
Assert.assertFalse(addonProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(apiDependency));
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(apiDependency));
Assert.assertNull(addonProject.getFacet(DependencyFacet.class).getDirectDependency(apiDependency)
.getScopeType());
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasDirectDependency(implDependency));
Assert.assertFalse(addonProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(implDependency));
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(implDependency));
Assert.assertEquals("runtime", addonProject.getFacet(DependencyFacet.class).getDirectDependency(implDependency)
.getScopeType());
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasDirectDependency(spiDependency));
Assert.assertFalse(addonProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(spiDependency));
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(spiDependency));
Assert.assertNull(addonProject.getFacet(DependencyFacet.class).getDirectDependency(spiDependency)
.getScopeType());
Assert.assertEquals("compile",
addonProject.getFacet(DependencyFacet.class).getEffectiveDependency(spiDependency)
.getScopeType());
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasDirectDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertFalse(addonProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(addonProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
/*
* Verify tests/ sub-module
*/
Assert.assertEquals("../pom.xml", testsProject.getFacet(MavenFacet.class).getPOM().getParent().getRelativePath());
Assert.assertTrue(testsProject.getFacet(DependencyFacet.class).hasDirectDependency(addonDependency));
Assert.assertFalse(testsProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(addonDependency));
Assert.assertTrue(testsProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(addonDependency));
Assert.assertNull(testsProject.getFacet(DependencyFacet.class).getDirectDependency(addonDependency)
.getScopeType());
Assert.assertNotNull("ADDON module is not present in the TESTS module",
testsProject.getFacet(DependencyFacet.class).getEffectiveDependency(addonDependency));
Assert.assertEquals("compile",
testsProject.getFacet(DependencyFacet.class).getEffectiveDependency(addonDependency)
.getScopeType());
Assert.assertFalse(testsProject.getFacet(DependencyFacet.class).hasDirectDependency(spiDependency));
Assert.assertFalse(testsProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(spiDependency));
Assert.assertTrue(testsProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(spiDependency));
Assert.assertTrue(testsProject.getFacet(DependencyFacet.class).hasDirectDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertFalse(testsProject.getFacet(DependencyFacet.class).hasDirectManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
Assert.assertTrue(testsProject.getFacet(DependencyFacet.class).hasEffectiveManagedDependency(
ForgeContainerAPIFacet.FORGE_API_DEPENDENCY));
}
@Test
@Ignore("FORGE-894")
public void testDependencyResolution()
{
DirectoryResource addonDir = resourceFactory.create(forge.getRepositories().get(0).getRootDirectory()).reify(
DirectoryResource.class);
DirectoryResource projectDir = addonDir.createTempResource();
Project project = projectFactory.createProject(projectDir);
MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
metadataFacet.setProjectName("testproject");
metadataFacet.setProjectVersion("1.0.0-SNAPSHOT");
metadataFacet.setTopLevelPackage("com.acme.testproject");
SingleVersion forgeVersion = new SingleVersion("2.0.0.Alpha3");
addonProjectFactory.setupAddonProject(project, forgeVersion, Collections.<AddonId> emptyList());
DirectoryResource projectRoot = project.getProjectRoot();
Assert.assertTrue("SPI module is missing", projectRoot.getChild("spi").exists());
Assert.assertTrue("TESTS module is missing", projectRoot.getChild("tests").exists());
Project spiProject = projectFactory.findProject(projectRoot.getChildDirectory("spi"));
Project testsProject = projectFactory.findProject(projectRoot.getChildDirectory("tests"));
Dependency spiDependency = DependencyBuilder.create(
spiProject.getFacet(MetadataFacet.class).getOutputDependency())
.setClassifier("forge-addon");
Assert.assertNotNull("SPI module is not present in the TESTS module", testsProject
.getFacet(DependencyFacet.class).getEffectiveDependency(spiDependency));
Assert.assertEquals("compile",
testsProject.getFacet(DependencyFacet.class).getEffectiveDependency(spiDependency)
.getScopeType());
}
}
|
package ru.stqa.pft.addressbook;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.io.File;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import static org.openqa.selenium.OutputType.*;
public class groupCreationTests {
FirefoxDriver wd;
@BeforeMethod
public void setUp() throws Exception {
wd = new FirefoxDriver();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
wd.get("http://localhost/addressbook/group.php");
wd.findElement(By.name("user")).click();
wd.findElement(By.name("user")).clear();
wd.findElement(By.name("user")).sendKeys("admin");
wd.findElement(By.name("pass")).click();
wd.findElement(By.name("pass")).clear();
wd.findElement(By.name("pass")).sendKeys("secret");
wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click();
}
@Test
public void testGroupCreation() {
wd.findElement(By.linkText("groups")).click();
wd.findElement(By.name("new")).click();
wd.findElement(By.name("group_name")).click();
wd.findElement(By.name("group_name")).clear();
wd.findElement(By.name("group_name")).sendKeys("test1");
wd.findElement(By.name("group_header")).click();
wd.findElement(By.name("group_header")).clear();
wd.findElement(By.name("group_header")).sendKeys("test2");
wd.findElement(By.name("group_footer")).click();
wd.findElement(By.name("group_footer")).clear();
wd.findElement(By.name("group_footer")).sendKeys("test3");
wd.findElement(By.name("submit")).click();
wd.findElement(By.linkText("groups")).click();
}
@AfterMethod
public void tearDown() {
wd.quit();
}
public static boolean isAlertPresent(FirefoxDriver wd) {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
|
package com.birdbraintechnologies.birdblox.Bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import com.birdbraintechnologies.birdblox.Robots.RobotType;
import com.birdbraintechnologies.birdblox.Util.NamingHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.birdbraintechnologies.birdblox.MainWebView.bbxEncode;
import static com.birdbraintechnologies.birdblox.MainWebView.mainWebViewContext;
import static com.birdbraintechnologies.birdblox.MainWebView.runJavascript;
import static com.birdbraintechnologies.birdblox.httpservice.RequestHandlers.RobotRequestHandler.connectToRobot;
import static com.birdbraintechnologies.birdblox.httpservice.RequestHandlers.RobotRequestHandler.fluttersToConnect;
import static com.birdbraintechnologies.birdblox.httpservice.RequestHandlers.RobotRequestHandler.hummingbirdsToConnect;
import static com.birdbraintechnologies.birdblox.httpservice.RequestHandlers.RobotRequestHandler.lastScanType;
/**
* Helper class for basic Bluetooth connectivity
*
* @author Terence Sun (tsun1215)
*/
public class BluetoothHelper {
private static final String TAG = "BluetoothHelper";
private static final int SCAN_DURATION = 5000; /* Length of time to perform a scan, in milliseconds */
public static boolean currentlyScanning;
private BluetoothAdapter btAdapter;
private Handler handler;
private boolean btScanning;
private Context context;
public static HashMap<String, BluetoothDevice> deviceList;
private BluetoothLeScanner scanner;
private static HashMap<String, Integer> deviceRSSI = new HashMap<>();
/* Callback for populating the device list */
private ScanCallback populateDevices = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
synchronized (deviceList) {
deviceList.put(result.getDevice().getAddress(), result.getDevice());
List<BluetoothDevice> BLEDeviceList = (new ArrayList<>(deviceList.values()));
if (lastScanType.equals("hummingbird") && hummingbirdsToConnect != null) {
if (hummingbirdsToConnect.contains(result.getDevice().getAddress())) {
connectToRobot(RobotType.Hummingbird, result.getDevice().getAddress());
}
} else if (lastScanType.equals("flutter") && fluttersToConnect != null) {
if (fluttersToConnect.contains(result.getDevice().getAddress())) {
connectToRobot(RobotType.Flutter, result.getDevice().getAddress());
}
}
deviceRSSI.put(result.getDevice().getAddress(),result.getRssi());
JSONArray robots = new JSONArray();
for (BluetoothDevice device : BLEDeviceList) {
String name = NamingHandler.GenerateName(mainWebViewContext.getApplicationContext(), device.getAddress());
String prefix = "";
System.out.println("name:"+device.getName().substring(0,2));
switch (device.getName().substring(0,2)) {
case "HM":
prefix = "Duo";
break;
case "HB":
prefix = "Duo";
break;
case "FN":
prefix = "Finch";
break;
case "BB":
prefix = "Bit";
break;
case "MB":
prefix = "micro:bit";
break;
}
JSONObject robot = new JSONObject();
try {
robot.put("id", device.getAddress());
robot.put("device", prefix);
robot.put("name", name);
robot.put("RSSI", deviceRSSI.get(device.getAddress()));
} catch (JSONException e) {
Log.e("JSON", "JSONException while discovering " + lastScanType);
}
robots.put(robot);
}
System.out.println("robot"+robots.toString());
runJavascript("CallbackManager.robot.discovered('" + lastScanType + "', '" + bbxEncode(robots.toString()) + "');");
}
}
};
/**
* Initializes a Bluetooth helper
*
* @param context Context that Bluetooth is being used by
*/
public BluetoothHelper(Context context) {
this.context = context;
this.btScanning = false;
this.handler = new Handler();
deviceList = new HashMap<>();
// Acquire Bluetooth service
final BluetoothManager btManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
this.btAdapter = btManager.getAdapter();
// Ask to enable Bluetooth if disabled
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(enableBtIntent);
}
}
/**
* Scans for Bluetooth devices that matches the filter.
*
* @param scanFilters List of Bluetooth.le.ScanFilter to filter by
*/
public void scanDevices(List<ScanFilter> scanFilters) {
Log.d("BLEScan", "About to start scan");
if (currentlyScanning) {
Log.d("BLEScan", "Scan already running.");
return;
}
if (scanner == null) {
// Start scanning for devices
scanner = btAdapter.getBluetoothLeScanner();
// Schedule thread to stop scanning after SCAN_DURATION
handler.postDelayed(new Runnable() {
@Override
public void run() {
btScanning = false;
if (scanner != null) {
scanner.stopScan(populateDevices);
Log.d("BLEScan", "Stopped scan.");
scanner = null;
}
currentlyScanning = false;
runJavascript("CallbackManager.robot.discoverTimeOut('" + lastScanType + "');");
}
}, SCAN_DURATION);
btScanning = true;
// Build scan settings (scan as fast as possible)
ScanSettings scanSettings = (new ScanSettings.Builder())
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
currentlyScanning = true;
scanner.startScan(scanFilters, scanSettings, populateDevices);
} else {
currentlyScanning = true;
}
}
/**
* Connects to a device and returns the resulting connection
*
* @param addr MAC Address of the device to connect to
* @param settings Settings to define the UART connection's TX and RX lines
* @return Result connection, null if the given MAC Address doesn't match any scanned device
*/
public UARTConnection connectToDeviceUART(String addr, UARTSettings settings) {
BluetoothDevice device;
synchronized (deviceList) {
device = deviceList.get(addr);
}
if (device == null) {
Log.e(TAG, "Unable to connect to device: " + addr);
return null;
}
UARTConnection conn = new UARTConnection(context, device, settings);
return conn;
}
/**
* Connects to a device and returns the resulting connection
*
* @param addr MAC Address of the device to connect to
* @param settings Settings to define the UART connection's TX and RX lines
* @return Result connection, null if the given MAC Address doesn't match any scanned device
*/
synchronized public MelodySmartConnection connectToDeviceMelodySmart(String addr, UARTSettings settings) {
BluetoothDevice device = deviceList.get(addr);
if (device == null) {
Log.e(TAG, "Unable to connect to device: " + addr);
return null;
}
MelodySmartConnection conn = new MelodySmartConnection(context, device, settings);
return conn;
}
public void stopScan() {
if (scanner != null) {
scanner.stopScan(populateDevices);
scanner = null;
Log.d("BLEScan", "Stopped scan.");
}
if (deviceList != null) {
deviceList.clear();
}
currentlyScanning = false;
}
}
|
package org.intermine.bio.dataconversion;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.dataconversion.FileConverter;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.PropertiesUtil;
import org.intermine.util.SAXParser;
import org.intermine.util.StringUtil;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemHelper;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* DataConverter to parse UniProt data into items
* @author Richard Smith
*/
public class UniprotConverter extends FileConverter
{
//TODO: This should come from props files!!!!
protected static final String PROP_FILE = "uniprot_config.properties";
private static final Logger LOG = Logger.getLogger(UniprotConverter.class);
private Map<String, String> pubMaster = new HashMap<String, String>();
private Map<String, Item> orgMaster = new HashMap<String, Item>();
private Map<String, Item> dbMaster = new HashMap<String, Item>();
private Map<String, Item> dsMaster = new HashMap<String, Item>();
private Map<String, Item> ontoMaster = new HashMap<String, Item>();
private Map<String, String> geneMaster = new LinkedHashMap<String, String>();
private Map<String, String> interproMaster = new HashMap<String, String>();
private Set<String> geneIdentifiers = new LinkedHashSet<String>();
// map of taxonId to object which determine which data to use for which organism
private Map<String, UniProtGeneDataMap> geneDataMaps =
new HashMap<String, UniProtGeneDataMap>();
// datasources that designate gene names e.g. WormBase, Ensembl
private Set<String> geneSources = new HashSet<String>();
private Map<String, Item> keyMaster = new HashMap<String, Item>();
private boolean createInterpro = false;
private Set<String> taxonIds = null;
private Set<String> doneTaxonIds = new HashSet<String>();
private boolean useSplitFiles = false;
private static final Set<String> FEATURE_TYPES = new HashSet<String>();
static {
FEATURE_TYPES.add("initiator methionine"); // VDAC_DROME
FEATURE_TYPES.add("signal peptide"); // AMYA_DROME
FEATURE_TYPES.add("propeptide"); // ACES_DROME
FEATURE_TYPES.add("short sequence motif"); // A4_DROME
FEATURE_TYPES.add("transit peptide"); // MMSA_DROME
FEATURE_TYPES.add("chain"); // ADCY2_DROME
FEATURE_TYPES.add("peptide"); // CCAP_DROME
FEATURE_TYPES.add("topological domain"); // 5HT2A_DROME
FEATURE_TYPES.add("transmembrane region"); // 5HT2A_DROME
FEATURE_TYPES.add("active site"); // AMYA_DROME
FEATURE_TYPES.add("metal ion-binding site"); // ADCY2_DROME
FEATURE_TYPES.add("binding site"); // MMSA_DROME
FEATURE_TYPES.add("site"); // VDAC_DROME
FEATURE_TYPES.add("modified residue"); // AMYA_DROME
FEATURE_TYPES.add("lipid moiety-binding region"); // ACES_DROME
FEATURE_TYPES.add("glycosylation site"); // 5HT2A_DROME
FEATURE_TYPES.add("splice variant"); // zen
FEATURE_TYPES.add("sequence variant"); // AMYA_DROME
FEATURE_TYPES.add("unsure residue"); // none
}
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param model the Model
*/
public UniprotConverter(ItemWriter writer, Model model) {
super(writer, model);
}
/**
* {@inheritDoc}
*/
@Override
public void process(Reader reader) throws Exception {
boolean doProcess = true;
if (useSplitFiles) {
doProcess = false;
String fileName = getCurrentFile().getName();
String taxonId = fileName.substring(0, fileName.indexOf("_"));
if (taxonIds.contains(taxonId)) {
doProcess = true;
doneTaxonIds.add(taxonId);
} else {
System .out.println("Not reading from " + fileName
+ " - not in list of organisms.");
LOG.error("Not reading from " + fileName + " - not in list of organisms.");
}
}
if (doProcess) {
readConfig();
UniprotHandler handler = new UniprotHandler(getItemWriter());
try {
SAXParser.parse(new InputSource(reader), handler);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws Exception {
if (useSplitFiles) {
if (!doneTaxonIds.containsAll(taxonIds)) {
throw new Exception("Did not process all required taxonIds. Required = " + taxonIds
+ ", done = " + doneTaxonIds);
}
}
}
private void readConfig() {
Properties props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream(PROP_FILE));
} catch (IOException e) {
throw new RuntimeException("Problem loading properties '" + PROP_FILE + "'", e);
}
Enumeration<?> propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String code = (String) propNames.nextElement();
code = code.substring(0, code.indexOf("."));
Properties codeProps = PropertiesUtil.stripStart(code,
PropertiesUtil.getPropertiesStartingWith(code, props));
String taxonId = codeProps.getProperty("taxonid");
if (taxonId == null) {
throw new IllegalArgumentException("Unable to find 'taxonid' property for "
+ "code: " + code + " in file: " + PROP_FILE);
}
taxonId = taxonId.trim();
/* which variable to use as the uniqueGeneIdentifier */
String attribute = codeProps.getProperty("attribute");
if (attribute == null) {
throw new IllegalArgumentException("Unable to find 'attribute' property for "
+ "code: " + code + " in file: " + PROP_FILE);
}
attribute = attribute.trim();
UniProtGeneDataMap geneDataMap = new UniProtGeneDataMap(attribute);
/* Sources appear as source for gene name synonym and
* are used for links out from the webapp. */
String source = codeProps.getProperty("source");
if (source != null) {
source = source.trim();
geneDataMap.setSource(source);
geneSources.add(source);
}
/* which variable to use as the genePrimaryIdentifier */
String primaryIdentifierSrcType = codeProps.getProperty("primaryIdentifierSrcType");
if (primaryIdentifierSrcType != null) {
primaryIdentifierSrcType = primaryIdentifierSrcType.trim();
String primaryIdentifierSrc = codeProps.getProperty("primaryIdentifierSrc");
if (primaryIdentifierSrc == null) {
throw new IllegalArgumentException("Unable to find 'primaryIdentifierSrc' "
+ "property for code: " + code + " in file: "
+ PROP_FILE);
}
primaryIdentifierSrc = primaryIdentifierSrc.trim();
geneDataMap.setPrimaryIdentifier(primaryIdentifierSrcType, primaryIdentifierSrc);
if (primaryIdentifierSrcType.equals("datasource")) {
geneSources.add(primaryIdentifierSrc);
}
}
/* which variable to use as the geneIdentifier */
String identifierSrcType = codeProps.getProperty("identifierSrcType");
if (identifierSrcType != null) {
identifierSrcType = identifierSrcType.trim();
String identifierSrc = codeProps.getProperty("identifierSrc");
if (identifierSrc == null) {
throw new IllegalArgumentException("Unable to find 'identifierSrc' property for"
+ " code: " + code + " in file: " + PROP_FILE);
}
identifierSrc = identifierSrc.trim();
geneDataMap.setIdentifier(identifierSrcType, identifierSrc);
if (identifierSrcType.equals("datasource")) {
geneSources.add(identifierSrc);
}
}
geneDataMaps.put(taxonId, geneDataMap);
}
}
/**
* Toggle whether or not to import interpro data
* @param createinterpro String whether or not to import interpro data (true/false)
*/
public void setCreateinterpro(String createinterpro) {
if (createinterpro.equals("true")) {
this.createInterpro = true;
} else {
this.createInterpro = false;
}
}
/**
* Sets the list of taxonIds that should be imported if using split input files.
*
* @param taxonIds a space-separated list of taxonIds
*/
public void setUniprotOrganisms(String taxonIds) {
this.taxonIds = new HashSet<String>(Arrays.asList(StringUtil.split(taxonIds, " ")));
LOG.info("Setting list of organisms to " + this.taxonIds);
}
/**
* Sets the parameter that determines whether the files in the split directory will be read, or
* the files in the root directory will be used.
* @param useSplitFiles if true the files in /split will be loaded and if false the files in
* the root directory will be loaded
*/
public void setUseSplitFiles(String useSplitFiles) {
if (useSplitFiles.equals("true")) {
this.useSplitFiles = true;
} else {
this.useSplitFiles = false;
}
}
private class UniprotHandler extends DefaultHandler
{
// the below are reset for each protein
private Item protein;
private Item sequence;
private Item comment;
private Item feature;
private Item interpro; // protein feature
private Map<String, Item> synonyms;
private Map<String, Item> genes;
private StringBuffer descr;
private String taxonId;
private String dbName;
private String evidence;
private boolean hasPrimary;
private ReferenceList pubCollection;
private ReferenceList commentCollection;
private ReferenceList keywordCollection;
private ReferenceList featureCollection;
private ReferenceList geneCollection;
private ReferenceList interproCollection;
// maps genes for this protein to that gene's lists of names, identifiers, etc
private Map<String, Map<String, String>> geneTOgeneNameTypeToName;
private Map<String, Map<String, String>> geneTOgeneDesignations;
// reset for each gene
private Map<String, String> geneNameTypeToName; // ORF, primary, etc value for gene name
private Set<String> geneNames; // list of names for this gene
private Map<String, String> geneDesignations; // gene names from each database
private String possibleGeneIdSource; // ie FlyBase, Ensemble, etc.
private String possibleGeneId; // temp holder for gene identifier
// until "gene designation" is verified on next line
// master lists - only one is created
private Item datasource;
private Item dataset;
private ItemWriter writer;
private Stack<String> stack = new Stack<String>();
private String attName = null;
private StringBuffer attValue = null;
private ArrayList<Item> delayedItems = new ArrayList<Item>();
private boolean isProtein = false;
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
*/
public UniprotHandler(ItemWriter writer) {
this.writer = writer;
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
attName = null;
try {
// <entry>
if (qName.equals("entry")) {
// TODO only store for swiss prot or trembl?
if (attrs.getValue("dataset") != null) {
isProtein = true;
// create, clear all lists for each new protein
initProtein();
// will be tremble or swiss-prot
dataset = getDataSet(attrs.getValue("dataset"));
} else {
isProtein = false;
}
}
if (isProtein) {
// <entry><protein>
if (qName.equals("protein")) {
String isFragment = "false";
// check for <protein type="fragment*">
if (attrs.getValue("type") != null) {
String type = attrs.getValue("type");
if (type.startsWith("fragment")) {
isFragment = "true";
}
}
protein.setAttribute("isFragment", isFragment);
// <entry><protein><name>
} else if (qName.equals("name") && stack.peek().equals("protein")) {
attName = "name";
evidence = attrs.getValue("evidence");
// <entry><name>
} else if (qName.equals("name") && stack.peek().equals("entry")) {
attName = "primaryIdentifier";
// <entry><accession>
} else if (qName.equals("accession")) {
attName = "value";
// <entry><sequence>
} else if (qName.equals("sequence")) {
String strLength = attrs.getValue("length");
String strMass = attrs.getValue("mass");
if (strLength != null) {
sequence = createItem("Sequence");
sequence.setAttribute("length", strLength);
protein.setAttribute("length", strLength);
attName = "residues";
}
if (strMass != null) {
protein.setAttribute("molecularWeight", strMass);
}
// <entry><feature>
} else if (qName.equals("feature")
&& attrs.getValue("type") != null
&& FEATURE_TYPES.contains(attrs.getValue("type"))) {
String strType = attrs.getValue("type");
String strName = attrs.getValue("description");
String strStatus = null;
feature = createItem("UniProtFeature");
feature.addReference(new Reference("protein", protein.getIdentifier()));
if (featureCollection.getRefIds().isEmpty()) {
protein.addCollection(featureCollection);
}
featureCollection.addRefId(feature.getIdentifier());
feature.setAttribute("type", strType);
Item keyword = getKeyword(strType);
feature.addReference(new Reference("feature", keyword.getIdentifier()));
if (attrs.getValue("status") != null) {
strStatus = attrs.getValue("status");
if (strName != null) {
strName += " (" + strStatus + ")";
} else {
strName = strStatus;
}
}
if (!StringUtils.isEmpty(strName)) {
feature.setAttribute("description", strName);
}
// <entry><feature><location><start||end>
} else if ((qName.equals("begin") || qName.equals("end")
|| qName.equals("position"))
&& stack.peek().equals("location")
&& attrs.getValue("position") != null
&& feature != null) {
if (qName.equals("begin") || qName.equals("end")) {
feature.setAttribute(qName, attrs.getValue("position"));
} else {
feature.setAttribute("begin", attrs.getValue("position"));
feature.setAttribute("end", attrs.getValue("position"));
}
// <entry><dbreference type="InterPro" >
} else if (createInterpro
&& qName.equals("dbReference")
&& attrs.getValue("type").equals("InterPro")) {
String interproId = attrs.getValue("id").toString();
String interproItemId = null;
if (interproMaster.get(interproId) == null) {
interpro = createItem("ProteinDomain");
interpro.setAttribute("primaryIdentifier", interproId);
interproItemId = interpro.getIdentifier();
interproMaster.put(interproId, interproItemId);
} else {
interproItemId = interproMaster.get(interproId);
}
if (interproCollection.getRefIds().isEmpty()) {
protein.addCollection(interproCollection);
}
interproCollection.addRefId(interproItemId);
} else if (createInterpro
&& qName.equals("property")
&& attrs.getValue("type").equals("entry name")
&& stack.peek().equals("dbReference")) {
if (interpro != null) {
interpro.setAttribute("shortName", attrs.getValue("value").toString());
writer.store(ItemHelper.convert(interpro));
interpro = null;
}
// <entry><organism><dbreference>
} else if (qName.equals("dbReference") && stack.peek().equals("organism")) {
taxonId = attrs.getValue("id");
Item organism;
if (orgMaster.get(taxonId) == null) {
organism = createItem("Organism");
orgMaster.put(attrs.getValue("id"), organism);
organism.setAttribute("taxonId", taxonId);
writer.store(ItemHelper.convert(organism));
} else {
organism = orgMaster.get(taxonId);
}
protein.setReference("organism", organism.getIdentifier());
// get relevant database for this organism
// dbName = (String) taxIdToDb.get(taxonId);
UniProtGeneDataMap geneDataMap = geneDataMaps.get(taxonId);
boolean noDatabase = false;
if (geneDataMap != null) {
dbName = geneDataMap.getSource();
if (dbName == null) {
noDatabase = true;
}
} else {
// there was no data in the config file
geneDataMap = new UniProtGeneDataMap("UniProt");
noDatabase = true;
}
if (noDatabase) {
geneDataMap.setSource("UniProt");
String message = "No gene source database defined for organism: "
+ taxonId + ", using UniProt.[" + geneDataMap.toString() + "]";
LOG.warn(message);
dbName = "UniProt";
}
// <entry><reference><citation><dbreference>
} else if (hasPrimary && qName.equals("dbReference")
&& stack.peek().equals("citation")
&& attrs.getValue("type").equals("PubMed")) {
String pubId;
if (pubMaster.get(attrs.getValue("id")) == null) {
Item pub = createItem("Publication");
pub.setAttribute("pubMedId", attrs.getValue("id"));
pubMaster.put(attrs.getValue("id"), pub.getIdentifier());
pubId = pub.getIdentifier();
writer.store(ItemHelper.convert(pub));
} else {
pubId = pubMaster.get(attrs.getValue("id"));
}
// if this is the first publication for this protein, add collection
if (pubCollection.getRefIds().isEmpty()) {
protein.addCollection(pubCollection);
}
pubCollection.addRefId(pubId);
// <entry><comment>
} else if (qName.equals("comment") && attrs.getValue("type") != null) {
comment = createItem("Comment");
comment.setAttribute("type", attrs.getValue("type"));
// <entry><comment><text>
} else if (qName.equals("text") && stack.peek().equals("comment")) {
attName = "text";
// <entry><keyword>
} else if (qName.equals("keyword")) {
attName = "keyword";
// <entry><gene>
} else if (qName.equals("gene")) {
initGene();
// <entry><gene><name>
} else if (qName.equals("name") && stack.peek().equals("gene")) {
// will be primary, ORF, synonym or ordered locus
attName = attrs.getValue("type");
// <dbreference type="EC">
} else if (qName.equals("dbReference") && attrs.getValue("type").equals("EC")) {
String ecNumber = attrs.getValue("id");
if (ecNumber != null) {
protein.setAttribute("ecNumber", ecNumber);
}
// <dbreference type="FlyBase/UniProt/etc.." id="*" key="12345">
} else if (qName.equals("dbReference")
&& geneSources.contains(attrs.getValue("type"))) {
// could be identifier but check next tag to see if this is a gene designation
possibleGeneId = attrs.getValue("id");
possibleGeneIdSource = attrs.getValue("type");
// <dbreference><property type="gene designation" value="*">
} else if (qName.equals("property") && stack.peek().equals("dbReference")
&& attrs.getValue("type").equals("gene designation")
&& geneNames.contains(attrs.getValue("value"))) {
/* for everyone but homo sapiens & honeybees */
if (possibleGeneIdSource != null && possibleGeneId != null) {
geneDesignations.put(possibleGeneIdSource, new String(possibleGeneId));
}
// <dbreference type="RefSeq">
} else if (qName.equals("dbReference") && attrs.getValue("type").equals("RefSeq")) {
String refSeqId = attrs.getValue("id");
if (refSeqId != null) {
refSeqId.trim();
Item syn = createSynonym(protein.getIdentifier(), "identifier",
refSeqId.trim(), datasource.getIdentifier());
if (syn != null) {
writer.store(ItemHelper.convert(syn));
}
}
// <dbreference><property type="organism name" value="Homo sapiens"/>
} else if (qName.equals("property") && stack.peek().equals("dbReference")
&& attrs.getValue("type").equals("organism name")
&& (attrs.getValue("value").equals("Homo sapiens")
|| attrs.getValue("value").equals("Apis mellifera"))) {
if ((possibleGeneIdSource != null) && (possibleGeneId != null)) {
// we probably don't have a <gene> reference
initGene();
Item gene = createItem("Gene");
genes.put(gene.getIdentifier(), gene);
// associate gene with lists
geneTOgeneNameTypeToName.put(gene.getIdentifier(), geneNameTypeToName);
geneTOgeneDesignations.put(gene.getIdentifier(), geneDesignations);
geneDesignations.put(possibleGeneIdSource, new String(possibleGeneId));
}
}
}
// <uniprot>
if (qName.equals("uniprot")) {
initData();
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
super.startElement(uri, localName, qName, attrs);
stack.push(qName);
attValue = new StringBuffer();
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char[] ch, int start, int length) {
if (attName != null) {
// DefaultHandler may call this method more than once for a single
// attribute content -> hold text & create attribute in endElement
while (length > 0) {
boolean whitespace = false;
switch(ch[start]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) {
break;
}
++start;
--length;
}
if (length > 0) {
StringBuffer s = new StringBuffer();
s.append(ch, start, length);
attValue.append(s);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
try {
stack.pop();
if (isProtein) {
// <entry>
if (qName.equals("entry")) {
// only store the protein if it has a primary accession value
if (hasPrimary) {
protein.setAttribute("description", descr.toString());
ReferenceList evidenceColl =
new ReferenceList("evidence", new ArrayList<String>());
protein.addCollection(evidenceColl);
evidenceColl.addRefId(dataset.getIdentifier());
// now that we know the taxonID, we can store the genes
if (hasPrimary && !genes.isEmpty()) {
Iterator<Item> i = genes.values().iterator();
while (i.hasNext()) {
Item gene = i.next();
finaliseGene(gene, protein.getReference("organism").getRefId());
}
}
// <entry><name> is a synonym
String proteinPrimaryIdentifier =
protein.getAttribute("primaryIdentifier").getValue();
Item syn = createSynonym(protein.getIdentifier(), "identifier",
proteinPrimaryIdentifier,
datasource.getIdentifier());
writer.store(ItemHelper.convert(protein));
if (syn != null) {
writer.store(ItemHelper.convert(syn));
}
} else {
LOG.info("Entry " + protein.getAttribute("name")
+ " does not have any accessions");
}
for (Item item : delayedItems) {
writer.store(ItemHelper.convert(item));
}
delayedItems.clear();
// <entry><sequence>
} else if (hasPrimary && qName.equals("sequence")) {
if (attName != null) {
sequence.setAttribute(attName, attValue.toString().replaceAll("\n", ""));
protein.addReference(new Reference("sequence", sequence.getIdentifier()));
writer.store(ItemHelper.convert(sequence));
} else {
LOG.info("Sequence for " + protein.getAttribute("name").getValue()
+ " does not have a length");
}
// <entry><protein><name>
} else if (hasPrimary && qName.equals("name") && stack.peek().equals("protein")) {
String proteinName = attValue.toString();
if (!protein.hasAttribute("name")) {
protein.setAttribute(attName, proteinName);
descr.append(proteinName);
} else {
descr.append(" (" + proteinName + ")");
}
// all names are synonyms
if (evidence != null) {
proteinName += " (Evidence " + evidence + ")";
}
Item syn = createSynonym(protein.getIdentifier(), "name", proteinName,
datasource.getIdentifier());
if (syn != null) {
delayedItems.add(syn);
}
// <entry><comment><text>
} else if (hasPrimary && qName.equals("text") && attName != null) {
if (comment.hasAttribute("type") && attValue.toString() != null) {
comment.setAttribute(attName, attValue.toString());
comment.setReference("source", dataset.getIdentifier());
if (commentCollection.getRefIds().isEmpty()) {
protein.addCollection(commentCollection);
}
commentCollection.addRefId(comment.getIdentifier());
writer.store(ItemHelper.convert(comment));
}
// <entry><gene><name>
} else if (qName.equals("name") && stack.peek().equals("gene")) {
String type = attName;
String name = attValue.toString();
// See #1199 - remove organism prefixes ("AgaP_" or "Dmel_")
name = name.replaceAll("^[A-Z][a-z][a-z][A-Za-z]_", "");
geneNames.add(new String(name));
// genes can have more than one synonym, so use name as key for map
if (!type.equals("synonym")) {
geneNameTypeToName.put(type, name);
} else {
geneNameTypeToName.put(name, name);
}
// <entry><gene>
} else if (qName.equals("gene")) {
Item gene = createItem("Gene");
genes.put(gene.getIdentifier(), gene);
// associate gene with lists
geneTOgeneNameTypeToName.put(gene.getIdentifier(), geneNameTypeToName);
geneTOgeneDesignations.put(gene.getIdentifier(), geneDesignations);
// <entry><keyword>
} else if (qName.equals("keyword")) {
if (attName != null) {
Item keyword = getKeyword(attValue.toString());
if (keywordCollection.getRefIds().isEmpty()) {
protein.addCollection(keywordCollection);
}
keywordCollection.addRefId(keyword.getIdentifier());
}
// <entry><feature>
} else if (qName.equals("feature") && feature != null) {
delayedItems.add(feature);
feature = null;
// <entry><name>
} else if (qName.equals("name")) {
if (attName != null) {
protein.setAttribute(attName, attValue.toString());
}
// <entry><accession>
} else if (qName.equals("accession") && !attValue.toString().equals("")) {
Item syn = createSynonym(protein.getIdentifier(), "accession",
attValue.toString(), datasource.getIdentifier());
if (syn != null) {
// if this is the first accession value, its the primary accession
if (protein.getAttribute("primaryAccession") == null) {
protein.setAttribute("primaryAccession", attValue.toString());
hasPrimary = true;
}
if (hasPrimary) {
delayedItems.add(syn);
}
}
}
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
private void initData()
throws SAXException {
try {
datasource = getDataSource("UniProt");
setOnto("UniProtKeyword");
} catch (Exception e) {
throw new SAXException(e);
}
}
// if synonym new, create and put in synonyms map for this <entry>
private Item createSynonym(String subjectId, String type, String value, String dbId) {
String key = subjectId + type + value + dbId;
if (!synonyms.containsKey(key)) {
Item syn = createItem("Synonym");
syn.addReference(new Reference("subject", subjectId));
syn.setAttribute("type", type);
syn.setAttribute("value", value);
syn.addReference(new Reference("source", dbId));
synonyms.put(key, syn);
return syn;
} else {
return null;
}
}
// clears all protein-related lists/values
// called when new protein is created
private void initProtein() {
protein = createItem("Protein");
featureCollection = new ReferenceList("features", new ArrayList<String>());
keywordCollection = new ReferenceList("keywords", new ArrayList<String>());
commentCollection = new ReferenceList("comments", new ArrayList<String>());
pubCollection = new ReferenceList("publications", new ArrayList<String>());
interproCollection = new ReferenceList("proteinDomains", new ArrayList<String>());
geneCollection = null;
genes = new LinkedHashMap<String, Item>();
synonyms = new LinkedHashMap<String, Item>();
descr = new StringBuffer();
taxonId = null;
dbName = null;
comment = null;
feature = null;
sequence = null;
hasPrimary = false;
// maps gene to that gene's lists
geneTOgeneNameTypeToName = new HashMap<String, Map<String, String>>();
geneTOgeneDesignations = new HashMap<String, Map<String, String>>();
}
private void initGene() {
// list of possible names for this gene
geneNames = new LinkedHashSet<String>();
// ORF, primary, etc name value for gene
geneNameTypeToName = new LinkedHashMap<String, String>();
// gene names from each database
geneDesignations = new LinkedHashMap<String, String>();
}
private Item getDataSource(String title)
throws SAXException {
Item database = dbMaster.get(title);
try {
if (database == null) {
database = createItem("DataSource");
database.setAttribute("name", title);
dbMaster.put(title, database);
writer.store(ItemHelper.convert(database));
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
return database;
}
private Item getKeyword(String title)
throws SAXException {
Item keyword = keyMaster.get(title);
try {
if (keyword == null) {
keyword = createItem("OntologyTerm");
keyword.setAttribute("name", title);
Item ontology = ontoMaster.get("UniProtKeyword");
keyword.addReference(new Reference("ontology", ontology.getIdentifier()));
keyMaster.put(title, keyword);
writer.store(ItemHelper.convert(keyword));
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
return keyword;
}
private Item getDataSet(String title)
throws SAXException {
Item ds = dsMaster.get(title);
try {
if (ds == null) {
ds = createItem("DataSet");
ds.setAttribute("title", title + " data set");
ds.setReference("dataSource", datasource);
dsMaster.put(title, ds);
ReferenceList evidenceColl =
new ReferenceList("evidence", new ArrayList<String>());
protein.addCollection(evidenceColl);
evidenceColl.addRefId(ds.getIdentifier());
writer.store(ItemHelper.convert(ds));
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
return ds;
}
private Item setOnto(String title)
throws SAXException {
Item ontology = ontoMaster.get(title);
try {
if (ontology == null) {
ontology = createItem("Ontology");
ontology.setAttribute("title", title);
ontoMaster.put(title, ontology);
writer.store(ItemHelper.convert(ontology));
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
return ontology;
}
private void finaliseGene(Item gene, String orgId)
throws SAXException {
try {
// Gene.identifier = <entry><gene><name type="ORF">
String geneSecondaryIdentifier = null;
// Gene.name = <entry><gene><name type="primary">
String primaryGeneName = null;
// get list for this gene
Map<String, String> nameTypeToName =
geneTOgeneNameTypeToName.get(gene.getIdentifier());
Map<String, String> designations =
geneTOgeneDesignations.get(gene.getIdentifier());
// loop through each name for this gene
String notCG = null;
Iterator<String> i = nameTypeToName.keySet().iterator();
while (i.hasNext()) {
String type = i.next();
String name = nameTypeToName.get(type);
if (type.equals("primary")) {
primaryGeneName = name;
} else if (type.equals("ORF")) {
if (taxonId.equals("7227") && !name.startsWith("CG")) {
notCG = name;
} else {
geneSecondaryIdentifier = name;
}
}
}
// Some UniProt entries have CGxxx as Dmel_CGxxx - need to strip prefix
// so that they match identifiers from other sources. Some genes have
// embl identifiers and no FlyBase id, ignore these.
if (geneSecondaryIdentifier == null && notCG != null) {
if (notCG.startsWith("Dmel_")) {
geneSecondaryIdentifier = notCG.substring(5);
} else {
LOG.info("Found a Drosophila gene without a CG identifer: " + notCG);
}
}
// define a gene identifier we always expect to find that is unique to this gene
// is different for each organism
String uniqueGeneIdentifier = null;
// genePrimaryIdentifier = <entry><dbReference><type="FlyBase/WormBase/..">
// where designation = primary gene name
String genePrimaryIdentifier = null;
// use map to find out where to get ids
UniProtGeneDataMap geneDataMap = geneDataMaps.get(taxonId);
if (geneDataMap != null) {
/* set vars if they come from datasource or name */
genePrimaryIdentifier = setGeneVars(designations, nameTypeToName, null,
geneDataMap.getPrimaryIdentifierSrcType(),
geneDataMap.getPrimaryIdentifierSrc(),
genePrimaryIdentifier);
geneSecondaryIdentifier = setGeneVars(designations, nameTypeToName, null,
geneDataMap.getIdentifierSrcType(),
geneDataMap.getIdentifierSrc(),
geneSecondaryIdentifier);
/* set vars if they come from another variable */
Map<String, String> variableLookup = new LinkedHashMap<String, String>();
variableLookup.put("geneIdentifier", geneSecondaryIdentifier);
variableLookup.put("genePrimaryIdentifier", genePrimaryIdentifier);
variableLookup.put("primaryGeneName", primaryGeneName);
genePrimaryIdentifier = setGeneVars(null, null, variableLookup,
geneDataMap.getPrimaryIdentifierSrcType(),
geneDataMap.getPrimaryIdentifierSrc(),
genePrimaryIdentifier);
geneSecondaryIdentifier = setGeneVars(null, null, variableLookup,
geneDataMap.getIdentifierSrcType(),
geneDataMap.getIdentifierSrc(),
geneSecondaryIdentifier);
/* organism specific */
if (taxonId.equals("10116")) { // Rattus norvegicus
if (genePrimaryIdentifier != null
&& !genePrimaryIdentifier.startsWith("RGD:")) {
genePrimaryIdentifier = "RGD:" + genePrimaryIdentifier;
}
} else if (taxonId.equals("3702")) { // Arabidopsis thaliana
if (genePrimaryIdentifier != null) {
genePrimaryIdentifier = genePrimaryIdentifier.toUpperCase();
}
}
variableLookup = new LinkedHashMap<String, String>();
variableLookup.put("geneIdentifier", geneSecondaryIdentifier);
variableLookup.put("genePrimaryIdentifier", genePrimaryIdentifier);
variableLookup.put("primaryGeneName", primaryGeneName);
/* set unique identifier */
uniqueGeneIdentifier = variableLookup.get(geneDataMap.getAttribute());
variableLookup = null;
}
// uniprot data source has primary key of Gene.primaryIdentifier
// only create gene if a value was found
if (uniqueGeneIdentifier != null) {
String geneItemId = geneMaster.get(uniqueGeneIdentifier);
// UniProt sometimes has same identifier paired with two primaryIdentifiers
// causes problems merging other data sources. Simple check to prevent
// creating a gene with a duplicate identifier.
// log problem genes
boolean isDuplicateIdentifier = false;
if ((geneItemId == null) && geneIdentifiers.contains(geneSecondaryIdentifier)) {
LOG.warn("already created a gene for identifier: " + geneSecondaryIdentifier
+ " with different primaryIdentifier, discarding this one");
isDuplicateIdentifier = true;
}
if ((geneItemId == null) && !isDuplicateIdentifier) {
if (genePrimaryIdentifier != null) {
if (genePrimaryIdentifier.equals("")) {
LOG.info("genePrimaryIdentifier was empty string");
} else {
gene.setAttribute("primaryIdentifier", genePrimaryIdentifier);
Item syn = createSynonym(gene.getIdentifier(), "identifier",
genePrimaryIdentifier,
getDataSource(dbName).getIdentifier());
if (syn != null) {
delayedItems.add(syn);
}
}
}
if (geneSecondaryIdentifier != null) {
gene.setAttribute("secondaryIdentifier", geneSecondaryIdentifier);
// don't create duplicate synonym
if (!geneSecondaryIdentifier.equals(genePrimaryIdentifier)
&& !geneSecondaryIdentifier.equals("")) {
Item syn = createSynonym(gene.getIdentifier(), "identifier",
geneSecondaryIdentifier,
getDataSource(dbName).getIdentifier());
if (syn != null) {
delayedItems.add(syn);
}
}
// keep a track of non-null gene identifiers
geneIdentifiers.add(geneSecondaryIdentifier);
}
// Problem with gene names for drosophila - ignore
if (primaryGeneName != null && !primaryGeneName.equals("")
&& !taxonId.equals("7227")) {
gene.setAttribute("symbol", primaryGeneName);
}
if (geneCollection == null) {
geneCollection = new ReferenceList("genes", new ArrayList<String>());
protein.addCollection(geneCollection);
}
geneMaster.put(uniqueGeneIdentifier, gene.getIdentifier());
geneCollection.addRefId(gene.getIdentifier());
gene.setReference("organism", orgId);
writer.store(ItemHelper.convert(gene));
i = nameTypeToName.keySet().iterator();
while (i.hasNext()) {
String synonymDescr = "";
String type = i.next();
String name = nameTypeToName.get(type);
if (type.equals("ordered locus")) {
synonymDescr = "ordered locus";
} else {
synonymDescr = "symbol";
}
// all gene names are synonyms
// ORF is already identifer, so skip
// TODO if name is empty something has gone wrong
if (!type.equals("ORF") && !name.equals("")) {
Item syn = createSynonym(gene.getIdentifier(), synonymDescr, name,
getDataSource(dbName).getIdentifier());
if (syn != null) {
writer.store(ItemHelper.convert(syn));
}
}
}
}
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
private String setGeneVars(Map<String, String> designations,
Map<String, String> nameTypeToName,
Map<String, String> variableLookup,
String srcType, String src, String var) {
if (srcType == null) {
return var;
}
if (srcType.equals("datasource") && designations != null) {
return designations.get(src);
} else if (srcType.equals("name") && nameTypeToName != null) {
return nameTypeToName.get(src);
} else if (srcType.equals("variable") && variableLookup != null) {
if (src.equals("NULL")) {
return null;
}
return variableLookup.get(src);
}
return var;
}
/**
* Convenience method for creating a new Item
* @param className the name of the class
* @return a new Item
*/
protected Item createItem(String className) {
return UniprotConverter.this.createItem(className);
}
}
/**
* Which datasource to use with which organism
* @author Julie Sullivan
*/
public static class UniProtGeneDataMap
{
private String attribute;
private String source;
private String primaryIdentifierSrc;
private String primaryIdentifierSrcType;
private String identifierSrcType;
private String identifierSrc;
/**
* Constructor
* @param attribute Which variable to use for the gene's unique identifier
*/
public UniProtGeneDataMap(String attribute) {
this.attribute = attribute;
}
/**
* What to use as the uniqueGeneIdentifier
* e.g. genePrimaryIdentifier or geneIdentifier
* @return What to use as the uniqueGeneIdentifier
*/
public String getAttribute () {
return attribute;
}
/**
* @param source Sources appear as source for gene name synonym and
* are used for links out from the webapp
*/
public void setSource (String source) {
this.source = source;
}
/**
* @return Sources appear as source for gene name synonym and are used for links out
* from the webapp
*/
public String getSource () {
return source;
}
/**
* @param primaryIdentifierSrcType What kind of source to use, e.g. variable,
* datasource, or name
* @param primaryIdentifierSrc What source to use, e.g. WormBase or ORF
*/
public void setPrimaryIdentifier(String primaryIdentifierSrcType,
String primaryIdentifierSrc) {
this.primaryIdentifierSrcType = primaryIdentifierSrcType;
this.primaryIdentifierSrc = primaryIdentifierSrc;
}
/**
* @return What type of source to use to set genePrimaryIdentifier,
* e.g. variable, datasource, or name
*/
public String getPrimaryIdentifierSrcType() {
return primaryIdentifierSrcType;
}
/**
* @return What source to use to set genePrimaryIdentifier, e.g. WormBase, ORF, etc
*/
public String getPrimaryIdentifierSrc() {
return primaryIdentifierSrc;
}
/**
* @param identifierSrcType What kind of source to use, e.g. variable or datasource
* @param identifierSrc Which source to use, e.g. genePrimaryIdentifier, Ensembl
*/
public void setIdentifier(String identifierSrcType, String identifierSrc) {
this.identifierSrcType = identifierSrcType;
this.identifierSrc = identifierSrc;
}
/**
* @return What kind of source to use to set geneIdentifier, e.g. variable or datasource
*/
public String getIdentifierSrcType() {
return identifierSrcType;
}
/**
* @return Which source to use to set geneIdentifier, e.g. genePrimaryIdentifier,
* Ensembl
*/
public String getIdentifierSrc() {
return identifierSrc;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "attribute: " + attribute
+ ", source: " + source
+ ", primaryIdentifierSrcType: " + primaryIdentifierSrcType
+ ", primaryIdentifierSrc: " + primaryIdentifierSrc
+ ", identifierSrcType: " + identifierSrcType
+ ", identifierSrc: " + identifierSrc;
}
}
}
|
package ru.job4j;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Task 7.4.2.
* Create realisation ThreadPool
*
* @author Anton Vasilyuk on 10.08.2017.
* @version 1.0.
*/
public class ThreadPool{
/**.
* @workQueue is queue for new task
*/
private final Queue<Runnable> workQueue = new ConcurrentLinkedQueue<>();
/**.
* @MAXTHREAD is count thread
*/
private static final int MAXTHREAD = Runtime.getRuntime().availableProcessors();
/**.
* @queueThreads is array for create thread
*/
private Thread[] queueThreads = new Thread[MAXTHREAD];
/**.
* @lock for locking
*/
private Object lock = new Object();
/**.
* Constructor for this class
* @throws InterruptedException is may be exception
*/
public ThreadPool() throws InterruptedException {
for(int i = 0; i < MAXTHREAD; i++) {
queueThreads[i] = new Thread(new TaskWorker());
queueThreads[i].start();
}
}
/**.
* Method for adding new task
* @param work is runnuble
*/
public void add(Work work) {
synchronized (lock) {
this.workQueue.add(work);
lock.notifyAll();
}
}
/**.
* Method for end working
*/
public void shutdown() {
while(!workQueue.isEmpty()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(Thread thread : queueThreads) {
thread.interrupt();
}
}
/**.
* Class for create new thread
*/
private final class TaskWorker extends Thread {
@Override
public void run() {
Runnable thread;
while(!isInterrupted()) {
synchronized (lock) {
while (workQueue.isEmpty()) {
try {
lock.wait();
} catch (InterruptedException e) {
return;
}
}
thread = workQueue.poll();
try {
thread.run();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
}
/**.
* Method for printing count threads
*/
public void printCountProcessor() {
System.out.printf("Used %d threads.%n", MAXTHREAD);
}
}
|
package net.java.sip.communicator.impl.contactlist;
import java.util.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.protocol.*;
/**
* A default implementation of a meta contact.
* @author Emil Ivov
*/
public class MetaContactImpl
implements MetaContact, Comparable
{
/**
* A vector containing all protocol specific contacts merged in this
* MetaContact.
*
*/
private Vector protoContacts = new Vector();
/**
* The accumulated status index of all proto contacts merged in this
* meta contact.
*/
private int totalStatus = 0;
/**
* An id uniquely identifying the meta contact in this contact list.
*/
private String uid = null;
/**
* Returns a human readable string used by the UI to display the contact.
*/
private String displayName = "";
/**
* A callback to the meta contact group that is currently our parent. If
* this is an orphan meta contact that has not yet been added or has been
* removed from a group this callback is going to be null.
*/
private MetaContactGroupImpl parentGroup = null;
/**
* A sync lock for use when modifying the parentGroup field.
*/
private Object parentGroupModLock = new Object();
MetaContactImpl()
{
//create the uid
this.uid = String.valueOf( System.currentTimeMillis())
+ String.valueOf(hashCode());
}
/**
* Returns the number of protocol speciic <tt>Contact</tt>s that this
* <tt>MetaContact</tt> contains.
*
* @return an int indicating the number of protocol specific contacts
* merged in this <tt>MetaContact</tt>
*/
public int getContactCount()
{
return protoContacts.size();
}
/**
* Returns a Contact, encapsulated by this MetaContact and coming from
* the specified ProtocolProviderService.
* <p>
* In order to prevent problems with concurrency, the <tt>Iterator</tt>
* returned by this method is not be over the actual list of contacts but
* over a copy of that list.
*
* @param provider a reference to the <tt>ProtocolProviderService</tt>
* that we'd like to get a <tt>Contact</tt> for.
* @return a <tt>Contact</tt> encapsulated in this <tt>MetaContact</tt>
* and originating from the specified provider.
*/
public Iterator getContactsForProvider(ProtocolProviderService provider)
{
Iterator contactsIter = protoContacts.iterator();
LinkedList providerContacts = new LinkedList();
while (contactsIter.hasNext())
{
Contact contact = (Contact)contactsIter.next();
if(contact.getProtocolProvider() == provider)
providerContacts.add( contact );
}
return providerContacts.iterator();
}
/**
* Returns a contact encapsulated by this meta contact, having the specified
* contactAddress and coming from the indicated ownerProvider.
* <p>
* @param contactAddress the address of the contact who we're looking for.
* @param ownerProvider a reference to the ProtocolProviderService that
* the contact we're looking for belongs to.
* @return a reference to a <tt>Contact</tt>, encapsulated by this
* MetaContact, carrying the specified address and originating from the
* specified ownerProvider or null if no such contact exists..
*/
public Contact getContact(String contactAddress,
ProtocolProviderService ownerProvider)
{
Iterator contactsIter = protoContacts.iterator();
while (contactsIter.hasNext())
{
Contact contact = (Contact)contactsIter.next();
if( contact.getProtocolProvider() == ownerProvider
&& contact.getAddress().equals(contactAddress))
return contact;
}
return null;
}
/**
* Returns a <tt>java.util.Iterator</tt> over all protocol specific
* <tt>Contacts</tt> encapsulated by this <tt>MetaContact</tt>.
* <p>
* In order to prevent problems with concurrency, the <tt>Iterator</tt>
* returned by this method is not over the actual list of contacts but over
* a copy of that list.
* <p>
* @return a <tt>java.util.Ierator</tt> over all protocol specific
* <tt>Contact</tt>s that were registered as subcontacts for this
* <tt>MetaContact</tt>
*/
public Iterator getContacts()
{
List contactsCopy = new LinkedList(protoContacts);
return contactsCopy.iterator();
}
/**
* Currently simply returns the first contact in the list of proto spec.
* contacts. We should do this more inteligently though and have it
* chose according to preconfigured preferences.
*
* @return the default <tt>Contact</tt> to use when communicating with
* this <tt>MetaContact</tt>
*/
public Contact getDefaultContact()
{
return (Contact)this.protoContacts.get(0);
}
/**
* Returns a String identifier (the actual contents is left to
* implementations) that uniquely represents this <tt>MetaContact</tt> in
* the containing <tt>MetaContactList</tt>
*
* @return a String uniquely identifying this meta contact.
*/
public String getMetaUID()
{
return uid;
}
/**
* Compares this meta contact with the specified object for order. Returns
* a negative integer, zero, or a positive integer as this meta contact is
* less than, equal to, or greater than the specified object.
* <p>
* The result of this method is calculated the following way:
* <p>
* (totalStatus - o.totalStatus) * 1 000 000 <br>
* + getDisplayName().compareTo(o.getDisplayName()) * 100 000
* + getMetaUID().compareTo(o.getMetaUID())<br>
* <p>
* Or in other words ordering of meta accounts would be first done by
* presence status, then display name, and finally (in order to avoid
* equalities) be the farely random meta contact metaUID.
* <p>
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*
* @throws ClassCastException if the specified object is not
* a MetaContactListImpl
*/
public int compareTo(Object o)
{
MetaContactImpl target = (MetaContactImpl)o;
return ( (PresenceStatus.MAX_STATUS_VALUE - totalStatus)
- (PresenceStatus.MAX_STATUS_VALUE - target.totalStatus))
* 1000000
+ getDisplayName().compareTo(target.getDisplayName()) * 100000
+ getMetaUID().compareToIgnoreCase(target.getMetaUID());
}
/**
* Returns a string representation of this contact, containing most of its
* representative details.
*
* @return a string representation of this contact.
*/
public String toString()
{
StringBuffer buff = new StringBuffer("MetaContact[ DisplayName=")
.append(getDisplayName()).append("]");
return buff.toString();
}
/**
* Returns a characteristic display name that can be used when including
* this <tt>MetaContact</tt> in user interface.
* @return a human readable String that represents this meta contact.
*/
public String getDisplayName()
{
return displayName;
}
/**
* Sets a name that can be used when displaying this contact in user
* interface components.
* @param displayName a human readable String representing this
* <tt>MetaContact</tt>
*/
void setDisplayName(String displayName)
{
synchronized (parentGroupModLock)
{
if (parentGroup != null)
{
parentGroup.lightRemoveMetaContact(this);
}
this.displayName = new String(displayName);
if (parentGroup != null)
{
parentGroup.lightAddMetaContact(this);
}
}
}
/**
* Adds the specified protocol specific contact to the list of contacts
* merged in this meta contact. The method also keeps up to date the
* totalStatus field which is used in the compareTo() method.
*
* @param contact the protocol specific Contact to add.
*/
void addProtoContact(Contact contact)
{
synchronized (parentGroupModLock)
{
if (parentGroup != null)
{
parentGroup.lightRemoveMetaContact(this);
}
this.totalStatus += contact.getPresenceStatus().getStatus();
this.protoContacts.add(contact);
//if this is our firt contact - set the display name too.
if(this.protoContacts.size() == 1){
//be careful not to use setDisplayName() here cause this will
//bring us into a deadlock.
this.displayName = new String(contact.getDisplayName().getBytes());
}
if (parentGroup != null)
{
parentGroup.lightAddMetaContact(this);
}
}
}
/**
* Called by MetaContactListServiceImpl after a contact has changed its
* status, so that ordering in the parent group is updated.
*/
void reevalContact()
{
synchronized (parentGroupModLock)
{
this.totalStatus = 0;
//first lightremove or otherwise we won't be able to get hold of the
//contact
if (parentGroup != null)
{
parentGroup.lightRemoveMetaContact(this);
}
Iterator protoContacts = this.protoContacts.iterator();
while (protoContacts.hasNext())
totalStatus += ( (Contact) protoContacts.next()).
getPresenceStatus()
.getStatus();
//now readd it and the contact would be automatically placed
//properly by the containing group
if (parentGroup != null)
{
parentGroup.lightAddMetaContact(this);
}
}
}
/**
* Removes the specified protocol specific contact from the contacts
* encapsulated in this <code>MetaContact</code>. The method also updates
* the total status field accordingly. And updates its ordered position
* in its parent group.
*
* @param contact the contact to remove
*/
void removeProtoContact(Contact contact)
{
synchronized (parentGroupModLock)
{
if (parentGroup != null)
{
parentGroup.lightRemoveMetaContact(this);
}
totalStatus -= contact.getPresenceStatus().getStatus();
this.protoContacts.remove(contact);
if (parentGroup != null)
{
parentGroup.lightAddMetaContact(this);
}
}
}
/**
* Removes all proto contacts that belong to the specified provider.
*
* @param provider the provider whose contacts we want removed.
*
* @return true if this <tt>MetaContact</tt> was modified and false
* otherwise.
*/
boolean removeContactsForProvider(ProtocolProviderService provider)
{
boolean modified = false;
Iterator contactsIter = protoContacts.iterator();
while(contactsIter.hasNext())
{
Contact contact = (Contact)contactsIter.next();
if (contact.getProtocolProvider() == provider)
{
contactsIter.remove();
modified = true;
}
}
return modified;
}
/**
* Sets <tt>parentGroup</tt> as a parent of this meta contact. Do not
* call this method with a null argument even if a group is removing
* this contact from itself as this could lead to race conditions (imagine
* another group setting itself as the new parent and you removing it).
* Use unsetParentGroup instead.
*
* @param parentGroup the <tt>MetaContactGroupImpl</tt> that is currently a
* parent of this meta contact.
* @throws NullPointerException if <tt>parentGroup</tt> is null.
*/
void setParentGroup(MetaContactGroupImpl parentGroup)
{
synchronized(parentGroupModLock)
{
if (parentGroup == null)
throw new NullPointerException(
"Do not call this method with a "
+ "null argument even if a group is removing this contact "
+ "from itself as this could lead to race conditions "
+ "(imagine another group setting itself as the new "
+"parent and you removing it). Use unsetParentGroup "
+"instead.");
this.parentGroup = parentGroup;
}
}
/**
* If <tt>parentGroup</tt> was the parent of this meta contact then it
* sets it to null. Call this method when removing this contact from a
* meta contact group.
* @param parentGroup the <tt>MetaContactGroupImpl</tt> that we don't want
* considered as a parent of this contact any more.
*/
void unsetParentGroup(MetaContactGroupImpl parentGroup)
{
synchronized(parentGroupModLock)
{
if (this.parentGroup == parentGroup)
this.parentGroup = null;
}
}
/**
* Returns the group that is currently holding this meta contact.
*
* @return the gorup that is currently holding this meta contact.
*/
MetaContactGroupImpl getParentGroup()
{
return parentGroup;
}
}
|
package net.littlebigisland.droidibus.ibus.systems;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import android.annotation.SuppressLint;
import net.littlebigisland.droidibus.ibus.IBusSystem;
public class TelephoneSystem extends IBusSystem{
/**
* Messages from the Navigation System to the Telephone
*/
class NavigationSystem extends IBusSystem{
private byte locationData = (byte) 0xA4;
private byte gpsData = (byte) 0xA2;
@SuppressLint("UseSparseArrays")
private Map<Byte, Method> IBusNavigationMap = new HashMap<Byte, Method>();
private String bcdToIntString(String value){
return String.format(Locale.US, "%02d", Integer.parseInt(value));
}
private double decimalMinsToDecimalDeg(String deg, String mins, String secs){
double degrees = Double.parseDouble(deg);
double minutes = Double.parseDouble(mins);
double seconds = Double.parseDouble(secs);
double minSecsInDecimal = (((minutes * 60) + seconds) / 3600);
return degrees+minSecsInDecimal;
}
public void parseGPSData(){
// Parse out coordinate data
List<String> coordData = new ArrayList<String>();
for (int i = 6; i < currentMessage.size(); i++){
// Convert to int to rid ourselves of preceding zeros. Yes, this is bad.
coordData.add(
String.valueOf(
Integer.parseInt(
bcdToStr(currentMessage.get(i))
)
)
);
}
String latitudeNorthSouth = (
bcdToIntString(coordData.get(3)).charAt(1) == '0'
) ? "N" : "S";
String longitudeEastWest = (
bcdToIntString(coordData.get(8)).charAt(1) == '0'
) ? "E" : "W";
triggerCallback("onUpdateGPSCoordinates",
String.format(
"%.4f%s%s %.4f%s%s",
//Latitude
decimalMinsToDecimalDeg(
coordData.get(0), coordData.get(1), coordData.get(2)
),
(char) 0x00B0,
latitudeNorthSouth,
//Longitude
decimalMinsToDecimalDeg(
coordData.get(4) + coordData.get(5),
coordData.get(6),
coordData.get(7)
),
(char) 0x00B0,
longitudeEastWest
)
);
// Parse out altitude data which is in meters and is stored as a byte coded decimal
int altitude = Integer.parseInt(
bcdToStr(currentMessage.get(15)) + bcdToStr(currentMessage.get(16))
);
triggerCallback("onUpdateGPSAltitude", altitude);
// Parse out time data which is in UTC
String gpsUTCTime = String.format(
"%s:%s",
bcdToIntString(bcdToStr(currentMessage.get(18))),
bcdToIntString(bcdToStr(currentMessage.get(19)))
);
triggerCallback("onUpdateGPSTime", gpsUTCTime);
}
public void setLocale(){
int lastData = 6;
while(currentMessage.get(lastData) != (byte) 0x00){
lastData++;
}
triggerCallback("onUpdateLocale", decodeMessage(currentMessage, 6, lastData-1));
}
public void setStreetLocation(){
int lastData = 6;
while(currentMessage.get(lastData) != (byte)0x3B){
lastData++;
}
triggerCallback("onUpdateStreetLocation", decodeMessage(currentMessage, 6, lastData-1));
}
NavigationSystem(){
try{
IBusNavigationMap.put((byte)0x00, this.getClass().getMethod("parseGPSData"));
IBusNavigationMap.put((byte)0x01, this.getClass().getMethod("setLocale"));
IBusNavigationMap.put((byte)0x02, this.getClass().getMethod("setStreetLocation"));
}catch(NoSuchMethodException e){
// First world anarchy
}
}
public void mapReceived(ArrayList<Byte> msg){
currentMessage = msg;
try{
if(msg.get(3) == locationData || msg.get(3) == gpsData){
IBusNavigationMap.get(msg.get(5)).invoke(this);
}
}catch(IllegalArgumentException | InvocationTargetException | IllegalAccessException e){
e.printStackTrace();
}
}
}
/**
* Message from the MFL to the Telephone
*/
class SteeringWheelSystem extends IBusSystem{
public void mapReceived(ArrayList<Byte> msg) {
currentMessage = msg;
if(currentMessage.get(3) == 0x3B){
if(currentMessage.get(4) == (byte) 0xA0){ // Voice Btn
triggerCallback("onVoiceBtnPress");
}
if(currentMessage.get(4) == (byte) 0x90){
triggerCallback("onVoiceBtnHold");
}
}
}
}
public TelephoneSystem(){
IBusDestinationSystems.put(
Devices.MultiFunctionSteeringWheel.toByte(),
new SteeringWheelSystem()
);
IBusDestinationSystems.put(
Devices.NavigationEurope.toByte(), new NavigationSystem()
);
}
}
|
package org.mockito.internal.creation.bytebuddy;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.dynamic.ClassLoadingStrategy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.instrumentation.FieldAccessor;
import net.bytebuddy.instrumentation.MethodDelegation;
import net.bytebuddy.instrumentation.attribute.MethodAttributeAppender;
import net.bytebuddy.instrumentation.attribute.TypeAttributeAppender;
import net.bytebuddy.modifier.Visibility;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.configuration.GlobalConfiguration;
import org.mockito.internal.creation.jmock.SearchingClassLoader;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import java.io.ObjectStreamException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static net.bytebuddy.instrumentation.method.matcher.MethodMatchers.*;
public class ByteBuddyMockMaker implements MockMaker {
private static interface SilentConstructor {
<T> T instantiate(Class<T> type);
static class UsingObjenesis implements SilentConstructor {
private final Objenesis objenesis;
public UsingObjenesis(Objenesis objenesis) {
this.objenesis = objenesis;
}
@Override
public <T> T instantiate(Class<T> type) {
return objenesis.newInstance(type);
}
}
static enum Unavailable implements SilentConstructor {
INSTANCE;
@Override
public <T> T instantiate(Class<T> type) {
throw new MockitoException("Could not create mock: Objenesis is missing on the class path");
}
}
}
private static class MockKey<T> {
private final Class<T> mockedType;
private final Set<Class> types;
private final boolean acrossClassLoaderSerialization;
private MockKey(Class<T> mockedType, Set<Class> interfaces, boolean acrossClassLoaderSerialization) {
this.mockedType = mockedType;
this.types = new HashSet<Class>(interfaces);
types.add(mockedType);
this.acrossClassLoaderSerialization = acrossClassLoaderSerialization;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
MockKey mockKey = (MockKey<?>) other;
if (acrossClassLoaderSerialization != mockKey.acrossClassLoaderSerialization) return false;
if (!mockedType.equals(mockKey.mockedType)) return false;
if (!types.equals(mockKey.types)) return false;
return true;
}
@Override
public int hashCode() {
int result = mockedType.hashCode();
result = 31 * result + types.hashCode();
result = 31 * result + (acrossClassLoaderSerialization ? 1 : 0);
return result;
}
}
private final SilentConstructor silentConstructor;
private final ByteBuddy byteBuddy;
private final Map<MockKey<?>, Class<?>> previousClasses;
private final Random random;
public ByteBuddyMockMaker() {
silentConstructor = makeSilentConstructor();
byteBuddy = new ByteBuddy(ClassFileVersion.JAVA_V6)
.withDefaultMethodAttributeAppender(MethodAttributeAppender.ForInstrumentedMethod.INSTANCE)
.withAttribute(TypeAttributeAppender.ForSuperType.INSTANCE);
previousClasses = new ConcurrentHashMap<MockKey<?>, Class<?>>();
random = new Random();
}
private static SilentConstructor makeSilentConstructor() {
try {
return new SilentConstructor.UsingObjenesis(new ObjenesisStd(new GlobalConfiguration().enableClassCache()));
} catch (Throwable throwable) {
return SilentConstructor.Unavailable.INSTANCE;
}
}
@Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
Class<? extends T> mockedType = getOrMakeMock(settings.getTypeToMock(),
settings.getExtraInterfaces(),
settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS);
T mock = silentConstructor.instantiate(mockedType);
MethodInterceptor.Access access = (MethodInterceptor.Access) mock;
access.setMockitoInterceptor(new MethodInterceptor(asInternalMockHandler(handler), settings));
return mock;
}
private <T> Class<? extends T> getOrMakeMock(Class<T> mockedType,
Set<Class> interfaces,
boolean acrossClassLoaderSerialization) {
MockKey<T> mockKey = new MockKey<T>(mockedType, interfaces, acrossClassLoaderSerialization);
Class<? extends T> mockType = lookup(mockKey);
if (mockType == null) {
synchronized (mockedType) {
mockType = lookup(mockKey);
if (mockType != null) {
return mockType;
}
try {
mockType = makeMock(mockedType, interfaces, acrossClassLoaderSerialization);
} catch (Exception e) {
prettify(mockedType, e);
}
previousClasses.put(mockKey, mockType);
}
}
return mockType;
}
@SuppressWarnings("unchecked")
private <T> Class<? extends T> lookup(MockKey<T> mockKey) {
return (Class<? extends T>) previousClasses.get(mockKey);
}
private static void prettify(Class<?> mockedType, Exception e) {
if (Modifier.isPrivate(mockedType.getModifiers())) {
throw new MockitoException("\n"
+ "Mockito cannot mock this class: " + mockedType
+ ".\n"
+ "Most likely it is a private class that is not visible by Mockito");
}
throw new MockitoException("\n"
+ "Mockito cannot mock this class: " + mockedType
+ "\n"
+ "Mockito can only mock visible & non-final classes."
+ "\n"
+ "If you're not sure why you're getting this error, please report to the mailing list.", e);
}
private <T> Class<? extends T> makeMock(Class<T> mockedType,
Set<Class> interfaces,
boolean acrossClassLoaderSerialization) {
DynamicType.Builder<T> builder = byteBuddy.subclass(mockedType, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.name(nameFor(mockedType))
.implement(interfaces.toArray(new Class<?>[interfaces.size()]))
.method(any()).intercept(MethodDelegation
.toInstanceField(MethodInterceptor.class, "mockitoInterceptor")
.filter(isDeclaredBy(MethodInterceptor.class)))
.implement(MethodInterceptor.Access.class).intercept(FieldAccessor.ofBeanProperty())
.method(isHashCode()).intercept(MethodDelegation.to(MethodInterceptor.ForHashCode.class))
.method(isEquals()).intercept(MethodDelegation.to(MethodInterceptor.ForEquals.class));
if (acrossClassLoaderSerialization) {
builder = builder.defineMethod("writeReplace", Object.class, Collections.<Class<?>>emptyList(), Visibility.PRIVATE)
.throwing(ObjectStreamException.class)
.intercept(MethodDelegation.to(MethodInterceptor.ForWriteReplace.class));
}
Class<?>[] allMockedTypes = new Class<?>[interfaces.size() + 1];
allMockedTypes[0] = mockedType;
int index = 1;
for (Class<?> type : interfaces) {
allMockedTypes[index++] = type;
}
return builder.make()
.load(SearchingClassLoader.combineLoadersOf(allMockedTypes), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
}
private String nameFor(Class<?> type) {
String typeName = type.getName();
if (typeName.startsWith("java.") || (type.getPackage() != null && type.getPackage().isSealed())) {
typeName = "codegen." + typeName;
}
return String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
}
@Override
public MockHandler getHandler(Object mock) {
if (!(mock instanceof MethodInterceptor.Access)) {
return null;
}
return ((MethodInterceptor.Access) mock).getMockitoInterceptor().getMockHandler();
}
@Override
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
((MethodInterceptor.Access) mock).setMockitoInterceptor(new MethodInterceptor(asInternalMockHandler(newHandler), settings));
}
private static InternalMockHandler asInternalMockHandler(MockHandler handler) {
if (!(handler instanceof InternalMockHandler)) {
throw new MockitoException("At the moment you cannot provide own implementations of MockHandler." +
"\nPlease see the javadocs for the MockMaker interface.");
}
return (InternalMockHandler) handler;
}
}
|
package org.objectweb.proactive.core.config;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.objectweb.proactive.core.config.xml.MasterFileHandler;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
public class ProActiveConfiguration {
protected HashMap loadedProperties;
protected HashMap addedProperties;
protected static ProActiveConfiguration singleton;
protected static boolean isLoaded = false;
private ProActiveConfiguration() {
this.loadedProperties = new HashMap();
this.addedProperties = new HashMap();
//setDefaultProActiveHome();
}
protected static synchronized void createConfiguration() {
if (ProActiveConfiguration.singleton == null) {
ProActiveConfiguration.singleton = new ProActiveConfiguration();
}
}
/**
* Load the default configuration
* The default file is located in the same directory as the ProActiceConfiguration
* class with the name proacticeConfiguration
* It is obtained using Class.geressource
* If the property proactive.configuration is set then its value is used
* as the configuration file
*/
public static void load() {
if (!isLoaded) {
String filename = null;
if (System.getProperty("proactive.configuration") != null) {
filename = System.getProperty("proactive.configuration");
} else {
filename = ProActiveConfiguration.class.getResource(
"ProActiveConfiguration.xml").toString();
}
ProActiveConfiguration.load(filename);
isLoaded = true;
}
}
/**
* Load the configuration given in filename
* @param filename an XML file name
*/
public static void load(String filename) {
if (!isLoaded) {
MasterFileHandler.createMasterFileHandler(filename,
ProActiveConfiguration.getConfiguration());
ProActiveConfiguration.getConfiguration().addProperties();
isLoaded = true;
}
}
public synchronized static ProActiveConfiguration getConfiguration() {
if (ProActiveConfiguration.singleton == null) {
ProActiveConfiguration.createConfiguration();
}
return singleton;
}
/**
* Called by the parser when a property has been found
* @param name name of the property
* @param value value of the property
*/
public void propertyFound(String name, String value) {
this.loadedProperties.put(name, value);
}
/**
* Add the loaded properties to the system
*/
public void addProperties() {
// we don't override existing value
Iterator it = loadedProperties.keySet().iterator();
String name = null;
String value = null;
while (it.hasNext()) {
name = (String) it.next();
value = (String) this.loadedProperties.get(name);
setProperty(name, value);
}
loadDefaultProperties();
}
// /**
// * Dump loaded properties, i.e properties found in the configuration file
// */
// public void dumpLoadedProperties() {
// Iterator it = loadedProperties.keySet().iterator();
// while (it.hasNext()) {
// String name = (String) it.next();
// // System.out.println("Name = " + name);
// // System.out.println("Value = " + this.loadedProperties.get(name));
// /**
// * Dump properties added to the system, i.e loaded properties
// * which were not already in the system
// */
// public void dumpAddedProperties() {
// Iterator it = addedProperties.keySet().iterator();
// while (it.hasNext()) {
// String name = (String) it.next();
// // System.out.println("Name = " + name);
// // System.out.println("Value = " + this.addedProperties.get(name));
public static String getLocationServerClass() {
return System.getProperty("proactive.locationserver");
}
public static String getLocationServerRmi() {
return System.getProperties().getProperty("proactive.locationserver.rmi");
}
public static String getACState() {
return System.getProperty("proactive.future.ac");
}
public static String getSchemaValidationState() {
return System.getProperty("schema.validation");
}
// FAULT TOLERANCE
public static String getFTState() {
return System.getProperty("proactive.ft");
}
public static String getCheckpointServer() {
return System.getProperty("proactive.ft.server.checkpoint");
}
public static String getLocationServer() {
return System.getProperty("proactive.ft.server.location");
}
public static String getRecoveryServer() {
return System.getProperty("proactive.ft.server.recovery");
}
public static String getGlobalFTServer() {
return System.getProperty("proactive.ft.server.global");
}
public static String getTTCValue() {
return System.getProperty("proactive.ft.ttc");
}
public static String getAttachedResourceServer() {
return System.getProperty("proactive.ft.server.resource");
}
public static String getFTProtocol(){
return System.getProperty("proactive.ft.protocol");
}
//To be used for the launcher
// /**
// * Sets the value of proactive.home if not already set
// */
// private void setDefaultProActiveHome() {
// File file = null;
// if (System.getProperty("proactive.home") == null) {
// String location = ProActiveConfiguration.class.getResource(
// "ProActiveConfiguration.class").getPath();
// try {
// file = new File(location, "/../../../../../../../../ProActive/").getCanonicalFile();
// String proactivehome = file.getCanonicalPath();
// System.setProperty("proactive.home", proactivehome);
// } catch (IOException e) {
// System.err.println(
// "WARNING: Unable to set proactive.home property. ProActive dir cannot be found! ");
/**
* Sets mandatory properties if forgotten by users
*/
private void loadDefaultProperties() {
setProperty("proactive.communication.protocol", "rmi");
setProperty("proactive.future.ac", "enable");
setProperty("schema.validation", "disable");
if (System.getProperty("log4j.configuration") == null) {
loadLogger();
}
setProperty("proactive.rmi.port", "1099");
setProperty("proactive.ft", "disable");
setProperty("proactive.ft.ttc", "30");
}
private void loadLogger() {
//if logger is not defined create default logger with level info that logs
// on the console
Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
logger.setAdditivity(false);
logger.setLevel(Level.INFO);
logger.addAppender(new ConsoleAppender(new PatternLayout()));
}
private void setProperty(String name, String value) {
if (System.getProperty(name) == null) {
System.setProperty(name, value);
this.addedProperties.put(name, value);
}
}
}
|
package protocolsupport.protocol.typeremapper.skipper.id;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingRegistry.EnumSkippingRegistry;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingRegistry.GenericSkippingRegistry;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingRegistry.IntSkippingRegistry;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingTable.ArrayBasedIntSkippingTable;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingTable.EnumSkippingTable;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingTable.GenericSkippingTable;
import protocolsupport.protocol.typeremapper.skipper.id.SkippingTable.HashMapBasedIntSkippingTable;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupport.protocol.utils.types.NetworkEntityType;
import protocolsupport.protocol.utils.types.WindowType;
public class IdSkipper {
public static final EnumSkippingRegistry<NetworkEntityType, EnumSkippingTable<NetworkEntityType>> ENTITY = new EnumSkippingRegistry<NetworkEntityType, EnumSkippingTable<NetworkEntityType>>() {
{
registerSkipEntry(NetworkEntityType.ARMOR_STAND_MOB, ProtocolVersionsHelper.BEFORE_1_8);
registerSkipEntry(NetworkEntityType.ARMOR_STAND_OBJECT, ProtocolVersionsHelper.BEFORE_1_8);
}
@Override
protected EnumSkippingTable<NetworkEntityType> createTable() {
return new EnumSkippingTable<>(NetworkEntityType.class);
}
};
public static final IntSkippingRegistry<HashMapBasedIntSkippingTable> ENCHANT = new IntSkippingRegistry<HashMapBasedIntSkippingTable>() {
{
//frost walker, mending
registerSkipEntry(9, ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry(70, ProtocolVersionsHelper.BEFORE_1_9);
//depth strider
registerSkipEntry(8, ProtocolVersionsHelper.BEFORE_1_8);
//lure, luck of the sea
registerSkipEntry(62, ProtocolVersionsHelper.BEFORE_1_7);
registerSkipEntry(61, ProtocolVersionsHelper.BEFORE_1_7);
}
@Override
protected HashMapBasedIntSkippingTable createTable() {
return new HashMapBasedIntSkippingTable();
}
};
public static final IntSkippingRegistry<ArrayBasedIntSkippingTable> EFFECT = new IntSkippingRegistry<ArrayBasedIntSkippingTable>() {
{
//glowing, levitation, luck, unluck
registerSkipEntry(24, ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry(25, ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry(26, ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry(27, ProtocolVersionsHelper.BEFORE_1_9);
//health boost, absorbtion, saturation
registerSkipEntry(21, ProtocolVersionsHelper.BEFORE_1_6);
registerSkipEntry(22, ProtocolVersionsHelper.BEFORE_1_6);
registerSkipEntry(23, ProtocolVersionsHelper.BEFORE_1_6);
}
@Override
protected ArrayBasedIntSkippingTable createTable() {
return new ArrayBasedIntSkippingTable(32);
}
};
public static final GenericSkippingRegistry<String, GenericSkippingTable<String>> ATTRIBUTES = new GenericSkippingRegistry<String, GenericSkippingTable<String>>() {
{
registerSkipEntry("generic.flyingSpeed", ProtocolVersionsHelper.BEFORE_1_12);
registerSkipEntry("generic.armorToughness", ProtocolVersionsHelper.BEFORE_1_9_1);
registerSkipEntry("generic.luck", ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry("generic.armor", ProtocolVersionsHelper.BEFORE_1_9);
registerSkipEntry("generic.attackSpeed", ProtocolVersionsHelper.BEFORE_1_9);
}
@Override
protected GenericSkippingTable<String> createTable() {
return new GenericSkippingTable<>();
}
};
public static final EnumSkippingRegistry<WindowType, EnumSkippingTable<WindowType>> INVENTORY = new EnumSkippingRegistry<WindowType, EnumSkippingTable<WindowType>>() {
{
registerSkipEntry(WindowType.HORSE, ProtocolVersionsHelper.BEFORE_1_6);
registerSkipEntry(WindowType.HOPPER, ProtocolVersionsHelper.BEFORE_1_5);
}
@Override
protected EnumSkippingTable<WindowType> createTable() {
return new EnumSkippingTable<>(WindowType.class);
}
};
}
|
package com.mapswithme.maps.purchase;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.android.billingclient.api.BillingClient;
import com.mapswithme.maps.PrivateVariables;
import com.mapswithme.maps.PurchaseOperationObservable;
import com.mapswithme.util.Utils;
public class PurchaseFactory
{
private PurchaseFactory()
{
// Utility class.
}
@NonNull
public static PurchaseController<PurchaseCallback> createAdsRemovalPurchaseController(
@NonNull Context context)
{
BillingManager<PlayStoreBillingCallback> billingManager
= new PlayStoreBillingManager(BillingClient.SkuType.SUBS);
PurchaseOperationObservable observable = PurchaseOperationObservable.from(context);
PurchaseValidator<ValidationCallback> validator = new DefaultPurchaseValidator(observable);
String yearlyProduct = PrivateVariables.adsRemovalYearlyProductId();
String monthlyProduct = PrivateVariables.adsRemovalMonthlyProductId();
String weeklyProduct = PrivateVariables.adsRemovalWeeklyProductId();
String[] productIds = Utils.concatArrays(PrivateVariables.adsRemovalNotUsedList(),
yearlyProduct, monthlyProduct, weeklyProduct);
return new SubscriptionPurchaseController(validator, billingManager,
SubscriptionType.ADS_REMOVAL, productIds);
}
@NonNull
public static PurchaseController<PurchaseCallback> createBookmarksSubscriptionPurchaseController(
@NonNull Context context)
{
BillingManager<PlayStoreBillingCallback> billingManager
= new PlayStoreBillingManager(BillingClient.SkuType.SUBS);
PurchaseOperationObservable observable = PurchaseOperationObservable.from(context);
PurchaseValidator<ValidationCallback> validator = new DefaultPurchaseValidator(observable);
String yearlyProduct = PrivateVariables.bookmarksSubscriptionYearlyProductId();
String monthlyProduct = PrivateVariables.bookmarksSubscriptionMonthlyProductId();
String[] productIds = Utils.concatArrays(PrivateVariables.bookmarksSubscriptionNotUsedList(),
yearlyProduct, monthlyProduct);
return new SubscriptionPurchaseController(validator, billingManager,
SubscriptionType.BOOKMARKS, productIds);
}
@NonNull
public static PurchaseController<PurchaseCallback> createBookmarkPurchaseController(
@NonNull Context context, @Nullable String productId, @Nullable String serverId)
{
BillingManager<PlayStoreBillingCallback> billingManager
= new PlayStoreBillingManager(BillingClient.SkuType.INAPP);
PurchaseOperationObservable observable = PurchaseOperationObservable.from(context);
PurchaseValidator<ValidationCallback> validator = new DefaultPurchaseValidator(observable);
return new BookmarkPurchaseController(validator, billingManager, productId, serverId);
}
@NonNull
public static PurchaseController<PurchaseCallback> createBookmarkPurchaseController(
@NonNull Context context)
{
return createBookmarkPurchaseController(context, null, null);
}
@NonNull
public static PurchaseController<FailedPurchaseChecker> createFailedBookmarkPurchaseController(
@NonNull Context context)
{
BillingManager<PlayStoreBillingCallback> billingManager
= new PlayStoreBillingManager(BillingClient.SkuType.INAPP);
PurchaseOperationObservable observable = PurchaseOperationObservable.from(context);
PurchaseValidator<ValidationCallback> validator = new DefaultPurchaseValidator(observable);
return new FailedBookmarkPurchaseController(validator, billingManager);
}
@NonNull
public static BillingManager<PlayStoreBillingCallback> createInAppBillingManager(
@NonNull Context context)
{
return new PlayStoreBillingManager(BillingClient.SkuType.INAPP);
}
@NonNull
public static BillingManager<PlayStoreBillingCallback> createSubscriptionBillingManager()
{
return new PlayStoreBillingManager(BillingClient.SkuType.SUBS);
}
}
|
package edu.mit.mobile.android.content.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import android.database.DatabaseUtils;
import edu.mit.mobile.android.content.AndroidVersions;
import edu.mit.mobile.android.content.ContentItem;
import edu.mit.mobile.android.content.DBTable;
import edu.mit.mobile.android.content.SQLGenUtils;
import edu.mit.mobile.android.content.SQLGenerationException;
import edu.mit.mobile.android.content.column.DBColumn;
import edu.mit.mobile.android.content.column.DBColumn.OnConflict;
import edu.mit.mobile.android.content.column.DBColumnType;
import edu.mit.mobile.android.content.column.DBForeignKeyColumn;
/**
* Generates SQL from a {@link ContentItem}. This inspects the class, parses all its
* annotations, and so on.
*
* @author <a href="mailto:spomeroy@mit.edu">Steve Pomeroy</a>
* @see DBColumn
*
*/
public class SQLExtractor {
private static final String DOUBLE_ESCAPE = DBColumnType.DEFAULT_VALUE_ESCAPE
+ DBColumnType.DEFAULT_VALUE_ESCAPE;
private final Class<? extends ContentItem> mDataItem;
private final String mTable;
public SQLExtractor(Class<? extends ContentItem> contentItem) throws SQLGenerationException {
mDataItem = contentItem;
mTable = extractTableName(mDataItem);
}
/**
* Inspects the {@link ContentItem} and extracts a table name from it. If there is a @DBTable
* annotation, uses that name. Otherwise, uses a lower-cased, sanitized version of the
* classname.
*
* @return a valid table name
* @throws SQLGenerationException
*/
public static String extractTableName(Class<? extends ContentItem> dataItem)
throws SQLGenerationException {
String tableName = null;
final DBTable tableNameAnnotation = dataItem.getAnnotation(DBTable.class);
if (tableNameAnnotation != null) {
tableName = tableNameAnnotation.value();
if (!SQLGenUtils.isValidName(tableName)) {
throw new SQLGenerationException("Illegal table name: '" + tableName + "'");
}
} else {
tableName = SQLGenUtils.toValidName(dataItem);
}
return tableName;
}
/**
* The table name is auto-generated using {@link #extractTableName(Class)}.
*
* @return the name of the table for this {@link ContentItem}.
*/
public String getTableName() {
return mTable;
}
/**
* For a given {@code field}, return the value of the field. All fields must be
* {@code static String}s whose content is the column name. This method ensures that they
* fit this requirement.
*
* @param field
* the {@code static String} field
* @return the value of the field.
* @throws SQLGenerationException
* if the field doesn't meet the necessary requirements.
*/
public String getDbColumnName(Field field) throws SQLGenerationException {
String dbColumnName;
try {
dbColumnName = (String) field.get(null);
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException("programming error", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("field '" + field.getName()
+ "' cannot be accessed", e);
} catch (final NullPointerException e) {
throw new SQLGenerationException("field '" + field.getName() + "' is not static", e);
}
if (!SQLGenUtils.isValidName(dbColumnName)) {
throw new SQLGenerationException("@DBColumn '" + dbColumnName
+ "' is not a valid SQLite column name.");
}
return dbColumnName;
}
private void appendColumnDef(StringBuilder tableSQL, DBColumn t, Field field,
List<String> preSql, List<String> postSql) throws IllegalAccessException,
InstantiationException {
@SuppressWarnings("rawtypes")
final Class<? extends DBColumnType> columnType = t.type();
@SuppressWarnings("rawtypes")
final DBColumnType typeInstance = columnType.newInstance();
final String colName = getDbColumnName(field);
tableSQL.append(typeInstance.toCreateColumn(colName));
if (t.primaryKey()) {
tableSQL.append(" PRIMARY KEY");
if (t.autoIncrement()) {
tableSQL.append(" AUTOINCREMENT");
}
}
if (t.unique()) {
tableSQL.append(" UNIQUE");
if (t.onConflict() != OnConflict.UNSPECIFIED) {
tableSQL.append(" ON CONFLICT");
}
switch (t.onConflict()) {
case ABORT:
tableSQL.append(" ABORT");
break;
case FAIL:
tableSQL.append(" FAIL");
break;
case IGNORE:
tableSQL.append(" IGNORE");
break;
case REPLACE:
tableSQL.append(" REPLACE");
break;
case ROLLBACK:
tableSQL.append(" ROLLBACK");
break;
case UNSPECIFIED:
break;
}
}
if (t.notnull()) {
tableSQL.append(" NOT NULL");
}
switch (t.collate()) {
case BINARY:
tableSQL.append(" COLLATE BINARY");
break;
case NOCASE:
tableSQL.append(" COLLATE NOCASE");
break;
case RTRIM:
tableSQL.append(" COLLATE RTRIM");
break;
case DEFAULT:
break;
}
final String defaultValue = t.defaultValue();
final int defaultValueInt = t.defaultValueInt();
final long defaultValueLong = t.defaultValueLong();
final float defaultValueFloat = t.defaultValueFloat();
final double defaultValueDouble = t.defaultValueDouble();
if (!DBColumn.NULL.equals(defaultValue)) {
tableSQL.append(" DEFAULT ");
// double-escape to insert the escape character literally.
if (defaultValue.startsWith(DOUBLE_ESCAPE)) {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue.substring(1));
} else if (defaultValue.startsWith(DBColumnType.DEFAULT_VALUE_ESCAPE)) {
tableSQL.append(defaultValue.substring(1));
} else {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue);
}
} else if (defaultValueInt != DBColumn.NULL_INT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueInt);
} else if (defaultValueLong != DBColumn.NULL_LONG) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueLong);
} else if (defaultValueFloat != DBColumn.NULL_FLOAT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueFloat);
} else if (defaultValueDouble != DBColumn.NULL_DOUBLE) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueDouble);
}
final String extraColDef = t.extraColDef();
if (!DBColumn.NULL.equals(extraColDef)) {
tableSQL.append(extraColDef);
}
final int flags = t.flags();
final String pre = typeInstance.preTableSql(mTable, colName, flags);
if (pre != null) {
preSql.add(pre);
}
final String post = typeInstance.postTableSql(mTable, colName, flags);
if (post != null) {
postSql.add(post);
}
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param fieldName
* the name of the field. This is whatever name you've used for the
* {@code static String}, not its value.
* @return the {@link DBColumnType} of the field
* @throws SQLGenerationException
* @throws NoSuchFieldException
*/
public Class<? extends DBColumnType<?>> getFieldType(String fieldName)
throws SQLGenerationException, NoSuchFieldException {
final Field field = mDataItem.getField(fieldName);
return getFieldType(field);
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param field
* the given {@code static String} field.
* @return the type of the field, as defined in the annotation or {@code null} if the given
* field has no {@link DBColumn} annotation.
* @throws SQLGenerationException
* if an annotation is present, but there's an error in the field definition.
*/
public Class<? extends DBColumnType<?>> getFieldType(Field field)
throws SQLGenerationException {
try {
final DBColumn t = field.getAnnotation(DBColumn.class);
if (t == null) {
return null;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
return t.type();
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
}
}
/**
* Generates SQL code for creating this object's table. Creation is done by inspecting the
* static strings that are marked with {@link DBColumn} annotations.
*
* @return CREATE TABLE code for creating this table.
* @throws SQLGenerationException
* if there were any problems creating the table
* @see DBColumn
* @see DBTable
*/
public List<String> getTableCreation() throws SQLGenerationException {
// pre, create table, post
final LinkedList<String> preTableSql = new LinkedList<String>();
final LinkedList<String> postTableSql = new LinkedList<String>();
try {
final StringBuilder tableSQL = new StringBuilder();
tableSQL.append("CREATE TABLE ");
tableSQL.append(mTable);
tableSQL.append(" (");
boolean needSep = false;
for (final Field field : mDataItem.getFields()) {
final DBColumn t = field.getAnnotation(DBColumn.class);
final DBForeignKeyColumn fk = field.getAnnotation(DBForeignKeyColumn.class);
if (t == null && fk == null) {
continue;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
if (needSep) {
tableSQL.append(',');
}
if (t != null) {
appendColumnDef(tableSQL, t, field, preTableSql, postTableSql);
} else if (fk != null) {
appendFKColumnDef(tableSQL, fk, field);
}
needSep = true;
}
tableSQL.append(")");
preTableSql.add(tableSQL.toString());
preTableSql.addAll(postTableSql);
return preTableSql;
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("default constructor not visible", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
} catch (final InstantiationException e) {
throw new SQLGenerationException("cannot instantiate field type class", e);
}
}
private void appendFKColumnDef(StringBuilder tableSQL, DBForeignKeyColumn fk, Field field)
throws IllegalArgumentException, IllegalAccessException {
tableSQL.append("'");
tableSQL.append(getDbColumnName(field));
tableSQL.append("' INTEGER");
if (fk.notnull()) {
tableSQL.append(" NOT NULL");
}
if (AndroidVersions.SQLITE_SUPPORTS_FOREIGN_KEYS) {
tableSQL.append(" REFERENCES ");
final String parentTable = extractTableName(fk.parent());
tableSQL.append("'");
tableSQL.append(parentTable);
tableSQL.append("' (");
tableSQL.append(ContentItem._ID);
tableSQL.append(") ON DELETE CASCADE"); // TODO make this configurable
}
}
}
|
package edu.psu.compbio.seqcode.projects.naomi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.distribution.NormalDistribution;
import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount;
import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager;
import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig;
import edu.psu.compbio.seqcode.deepseq.experiments.Sample;
import edu.psu.compbio.seqcode.genome.Genome;
import edu.psu.compbio.seqcode.genome.GenomeConfig;
import edu.psu.compbio.seqcode.genome.location.Region;
import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.projects.seed.SEEDConfig;
/**
* DifferentialMSR:
*
* Methods refer to two papers
* Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997)
*
* @author naomi yamada
*
**/
public class DifferentialMSR {
protected GenomeConfig gconfig;
protected ExptConfig econfig;
protected SEEDConfig sconfig;
protected int threePrimReadExt = 200;
protected int binWidth = 1;
//Map<chrm, Map<scale space, Set<segmentation>>>
protected Map<Region, Map<Integer,Set<Integer>>> segmentationTree;
public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){
gconfig = gcon;
econfig = econ;
sconfig = scon;
}
public void buildMSR(){
/*********************
* Gaussian scale space and window parameters
*/
// arbitrary number of scale
int numScale= 5;
double DELTA_TAU = 0.5*Math.log(2);
double MINIMUM_VALUE = Math.pow(10, -100); //arbitrary minimum value; I cannot use Double.MIN_VALUE because it can become zero
// I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size
double P_MIN = Math.pow(10,-3);
double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU));
double K_N = Math.ceil(K_MIN);
/*********************
* Linkage parameters
*/
double WEIGHT_I = 1.00;
double WEIGHT_G = 0.0000001;
double WEIGHT_M = 1000;
/*********************
* Matrices parameters
*/
double sigma[] = new double[numScale];
double radius[] = new double[numScale];
for (int i = 0; i<numScale;i++){
sigma[i] = 1;
radius[i] = 1;
}
ExperimentManager manager = new ExperimentManager(econfig);
Genome genome = gconfig.getGenome();
//test to print whole chromosomes
System.out.println(genome.getChromList());
//fix here to get parameters only if they are specified
binWidth = sconfig.getBinWidth();
threePrimReadExt = sconfig.getTag3PrimeExtension();
//test to print binWidth and threePrimReadExt
System.out.println("binWidth is: "+binWidth);
System.out.println("threePrimReadExt is: "+threePrimReadExt);
Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome);
//iterating each chromosome (each chromosome is a region).
while (chroms.hasNext()) {
Region currChrom = chroms.next();
int currchromSize = currChrom.getWidth();
int currchromBinSize = (int) Math.ceil(currchromSize/binWidth);
//primitive matrix to store signal and the subsequent convolved signals
//its index correspond to the coordinates
float[][] GaussianBlur = new float[currchromBinSize][2];
for (int i = 0;i<currchromBinSize;i++){
for (int j = 0; j<2;j++)
GaussianBlur[i][j] = 0;
}
//get StrandedBaseCount list for each chromosome
Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>();
for (Sample sample : manager.getSamples())
sampleCountsMap.put(sample,sample.getBases(currChrom));
//StrandedBasedCount object contains positive and negative strand separately
//store all base counts indexed by positions at column[1]
//extend reads to 3' end and bin according to bin size
for (Sample sample : manager.getSamples()){
List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample);
for (StrandedBaseCount hits: currentCounts){
for (int i = 0; i<threePrimReadExt+1; i++){
if (hits.getStrand()=='+' && hits.getCoordinate()+i<currchromSize){
GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount();
}else if (hits.getStrand()=='+' && hits.getCoordinate()-i >=0){
GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount();
}
}
}
currentCounts = null;
}
//testing
if (currchromSize > 200000000){
System.out.println("current Chrom is: "+currChrom.getChrom());
for (int i = 0; i< 100;i++)
System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]);
}
/*********************
* Starting nodes
*/
//linkageMap contains index of kids and parents
HashMap <Integer, Integer> linkageMap = new HashMap<Integer, Integer>();
//adding starting nodes; to qualify for the starting nodes the signal intensity needs to be different from the subsequent signal intensity
//adding the starting and end positions in the kids at start and end positions
//setting max & min signal intensity
float DImax = 0;
float DImin = (float) Integer.MAX_VALUE;
List <Integer> nonzeroList = new ArrayList<Integer>();
linkageMap.put(0,0);
for (int i = 0 ; i< GaussianBlur.length-1; i++){ //should I start
if (GaussianBlur[i][1] != GaussianBlur[i+1][1])
linkageMap.put(i,0);
if (GaussianBlur[i][1] > DImax)
DImax = GaussianBlur[i][1];
if (GaussianBlur[i][1] < DImin)
DImin = GaussianBlur[i][1];
if (GaussianBlur[i][1]!=0)
nonzeroList.add(i);
}
linkageMap.put(GaussianBlur.length-1,0);
//copy to segmentation tree
Map<Integer,Set<Integer>> currScale =new HashMap<Integer,Set<Integer>>();
currScale.put(1, linkageMap.keySet());
//determine the first nonzero and last nonzero from signal
//check here ; sometimes it produces zero for DImax, DImin, trailingZero, zeroEnd
int trailingZero = 0;
int zeroEnd = 0;
if (!nonzeroList.isEmpty()){
trailingZero = Collections.min(nonzeroList)-1;
zeroEnd = Collections.max(nonzeroList)+1;
}
if (trailingZero == -1)
trailingZero = 0;
System.out.println("DImax is: "+DImax+"\t"+"DImin is: "+DImin+
"\t"+"trailingZero: "+trailingZero+"\t"+"zeroEnd"+"\t"+zeroEnd);
for (int n = 1;n < numScale; n++){
/*********************
* Gaussian scale space
*/
double polyCoeffi[] = new double [currchromBinSize];
//first copy from column[1] to column[0];this procedure need to be repeated for each iteration of scale
//also copy from column[1] to array to store polynomial coefficient
for (int i = 0 ; i<currchromBinSize; i++){
GaussianBlur[i][0]=GaussianBlur[i][1];
if (GaussianBlur[i][1] != 0){
polyCoeffi[i]=GaussianBlur[i][1];
}else{
polyCoeffi[i]=MINIMUM_VALUE;
}
}
//sigma calculation
sigma[n] = Math.exp(n*DELTA_TAU);
// create normal distribution with mean zero and sigma[n]
NormalDistribution normDistribution = new NormalDistribution(0.00,sigma[n]);
//take inverse CDF based on the normal distribution using probability
double inverseCDF = normDistribution.inverseCumulativeProbability(P_MIN);
int windowSize = (int) (-Math.round(inverseCDF)*2+1);
//window calculation based on Gaussian(normal) distribution with sigma, mean=zero,x=X[i]
double window[] = new double[windowSize];
double windowSum = 0;
for (int i = 0;i<windowSize;i++){
window[i] = normDistribution.density(Math.round(inverseCDF)+i);
windowSum = windowSum+window[i];
}
double normalizedWindow[]=new double[windowSize];
for (int i = 0;i<windowSize;i++)
normalizedWindow[i] = window[i]/windowSum;
//multiplying by polynomial ; I have to test to see how this works
PolynomialFunction poly1 = new PolynomialFunction(polyCoeffi);
PolynomialFunction poly2 = new PolynomialFunction(normalizedWindow);
PolynomialFunction polyMultiplication=poly1.multiply(poly2);
double coefficients[]= polyMultiplication.getCoefficients();
//taking mid point of polynomial coefficients
int polyMid = (int) Math.floor(coefficients.length/2);
System.out.println("currchromBin Size is : "+currchromBinSize+"\t"+ "windowSize is: "+windowSize+"\t"+"coefficients length is: "+coefficients.length);
//copy Gaussian blur results to the column[1]
// I should check to make sure that it's not off by 1
for (int i = 0; i<currchromBinSize;i++){
if (currchromBinSize % 2 ==0 && coefficients.length/2 == 1)
GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i+1];
else
GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i];
}
//testing
if (currchromSize > 200000000){
System.out.println("current Chrom is: "+currChrom.getChrom());
for (int i = 0; i< 100;i++)
System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][0]+" : "+GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]);
}
/***************
* Search Volume
*/
double tempRadius;
if (n==1){
tempRadius = sigma[n];
}else{
tempRadius = Math.sqrt(Math.pow(sigma[n],2)-Math.pow(sigma[n-1], 2));
}
radius[n] = Math.ceil(K_MIN*tempRadius);
int DCPsize = (int) (Math.round(radius[n])*2+1);
int dcp[] = new int[DCPsize];
double distanceFactor[] = new double[DCPsize];
double affectionDistance;
double denom = -2*(Math.pow(sigma[n], 2)-Math.pow(sigma[n-1],2));
for (int i = 0; i<DCPsize;i++){
dcp[i] = (int) -Math.round(radius[n])+i;
// applying equation 7 in Vincken(1997)
affectionDistance=Math.exp(Math.pow(dcp[i], 2)/denom)/Math.exp(Math.pow(0.5*sigma[n],2)/denom);
//applying equation 8 in Vincken (1997)
if (Math.abs(dcp[i]) > 0.5*sigma[n]){distanceFactor[i]= affectionDistance;}
else{distanceFactor[i] = 1.0000;}
}
/***************
* Linkage Loop
*/
TreeMap<Integer, Integer> GvParents = new TreeMap<Integer,Integer>();
if (DCPsize < 50){
/***********
* Over window
*/
//build segmentTree
//First iteration only consider intensity differences between parent and kid and connect to the ones with the least difference.
//From the second iteration, we consider ground volume = number of nodes that parents are linked to the kids
//From third iteration, we increase the weight of the ground volume by 1e-7.
//Vincken paper said after 3-4 iteration, there would be no significant difference.
double intensityDiffScore = 0;
double groundVC = 0;
double groundVPmax = 0;
//updating ground volume and iterating to encourage convergence
for (int counter = 0; counter<5; counter++){
if (counter != 0){
for (Map.Entry<Integer,Integer> parent : GvParents.entrySet()){
if (parent.getValue()>groundVPmax)
groundVPmax = parent.getValue();
System.out.println("parent is : "+parent+"value is: "+parent.getValue());
}
}
for (Integer kid : linkageMap.keySet()){
//there is something wrong with iteration of DCPsize and updating parents
//iteration is always off by 2. is it important to adjust for that?
for (int i = 0; i<DCPsize; i++){
if ((kid + dcp[i]) >=0 && (kid + dcp[i]) <currchromBinSize){
if (counter ==0 || groundVPmax == 0){groundVC = 0.00;}
//ground volume is always zero... I need to fix this //this is where the problem is!
else{ groundVC = (WEIGHT_I+WEIGHT_G*counter)*GvParents.get(linkageMap.get(kid))/groundVPmax;}
intensityDiffScore = distanceFactor[i]*((1- Math.abs(GaussianBlur[kid][0] - GaussianBlur[kid+dcp[i]][1])/DImax)+groundVC);
if (intensityDiffScore > linkageMap.get(kid)){
linkageMap.put(kid,(kid+dcp[i]));
// System.out.println("intensityDiffScore is: "+intensityDiffScore+" DImax is "+DImax);
// System.out.println("kid is: "+kid+" value is "+(kid+dcp[i]));
}
}
}
}
//test
// if (currchromSize > 200000000){
// System.out.println("current Chrom is: "+currChrom.getChrom());
// System.out.println("printing linkangeMap content");
// for (Map.Entry<Integer, Integer> entry : linkageMap.entrySet()){
// System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue());
Integer lastParent = 0;
for (Integer parent : linkageMap.values()){
GvParents.put(parent, parent-lastParent);
lastParent = parent;
}
GvParents.put(GvParents.firstKey(), trailingZero-GvParents.firstKey());
GvParents.put(GaussianBlur.length,GaussianBlur.length-zeroEnd);
//test
if (currchromSize > 200000000){
System.out.println("current Chrom is: "+currChrom.getChrom());
System.out.println("printing GvParents content");
for (Map.Entry<Integer, Integer> entry : GvParents.entrySet()){
System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue());
}
}
}
// }else{
/***********
* Over kids
//I haven't understood this part from the matlab code
*
*/
}
//for each scaleNum, add the parents to the segmentationTree
currScale.put(n, GvParents.keySet());
}//end of scale space iteration
for (Integer scale : currScale.keySet()){
System.out.println("current scale is: "+scale);
Set<Integer> nodesSet = currScale.get(scale);
for (Integer node : nodesSet)
System.out.println(node);
}
// segmentationTree.put(currChrom, currScale);
// GaussianBlur = null;
}// end of chromosome iteration
manager.close();
}
public static void main(String[] args) {
GenomeConfig gconf = new GenomeConfig(args);
ExptConfig econf = new ExptConfig(gconf.getGenome(), args);
SEEDConfig sconf = new SEEDConfig(gconf, args);
DifferentialMSR profile = new DifferentialMSR (gconf, econf, sconf);
profile.buildMSR();
}
}
|
package edu.psu.compbio.seqcode.projects.naomi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.distribution.NormalDistribution;
import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount;
import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager;
import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig;
import edu.psu.compbio.seqcode.deepseq.experiments.Sample;
import edu.psu.compbio.seqcode.genome.Genome;
import edu.psu.compbio.seqcode.genome.GenomeConfig;
import edu.psu.compbio.seqcode.genome.location.Region;
import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.projects.seed.SEEDConfig;
/**
* DifferentialMSR:
*
* Methods refer to two papers
* Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997)
*
* @author naomi yamada
*
**/
public class DifferentialMSR {
protected GenomeConfig gconfig;
protected ExptConfig econfig;
protected SEEDConfig sconfig;
protected int threePrimReadExt = 200;
protected int binWidth = 1;
//Map<chrm, Map<scale space, Set<segmentation>>>
protected Map<Region, Map<Integer,Set<Integer>>> segmentationTree;
public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){
gconfig = gcon;
econfig = econ;
sconfig = scon;
}
public void buildMSR(){
/*********************
* Gaussian scale space and window parameters
*/
// arbitrary number of scale
int numScale= 10;
double DELTA_TAU = 0.5*Math.log(2);
// I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size
double P_MIN = Math.pow(10,-3);
double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU));
double K_N = Math.ceil(K_MIN);
/*********************
* Linkage parameters
*/
double WEIGHT_I = 1.00;
double WEIGHT_G = 0.0000001;
double WEIGHT_M = 1000;
/*********************
* Matrices parameters
*/
double sigma[] = new double[numScale];
double radius[] = new double[numScale];
for (int i = 0; i<numScale;i++){
sigma[i] = 1;
radius[i] = 1;
}
ExperimentManager manager = new ExperimentManager(econfig);
Genome genome = gconfig.getGenome();
binWidth = sconfig.getBinWidth();
threePrimReadExt = sconfig.getTag3PrimeExtension();
Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome);
//iterating each chromosome (each chromosome is a region).
while (chroms.hasNext()) {
Region currChrom = chroms.next();
//previously it was below. but I don't think I need +1 here
//int currchromSize= currChrom.getWidth()+1
int currchromSize= currChrom.getWidth();
//primitive matrix to store signal and the subsequent convolved signals
//its index correspond to the coordinates
float[][] GaussianBlur = new float[(int) Math.ceil(currchromSize/binWidth)][2];
for (int i = 0;i<(int) Math.ceil(currchromSize/binWidth);i++){
for (int j = 0; j<2;j++)
GaussianBlur[i][j] = 0;
}
//get StrandedBaseCount list for each chromosome
Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>();
for (Sample sample : manager.getSamples())
sampleCountsMap.put(sample,sample.getBases(currChrom));
//StrandedBasedCount object contains positive and negative strand separately
//store all base counts indexed by positions at column[1]
//extend reads to 3' end and bin according to bin size
for (Sample sample : manager.getSamples()){
List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample);
for (StrandedBaseCount hits: currentCounts){
for (int i = 0; i<threePrimReadExt; i++)
if (hits.getStrand()=='+')
GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount();
else
GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount();
}
}
//lets check up to here
System.out.println("current Chrom is: "+currChrom.getChrom());
if (currChrom.getChrom()=="chr1"){
for (int i = 0; i< 200;i++)
System.out.println(GaussianBlur[92943501+i]+"\t");
}
/***********
* Over kids
//I haven't understood this part from the matlab code
}
//for each scaleNum, add the parents to the segmentationTree
currScale.put(n, GvParents.keySet());
}//end of scale space iteration
segmentationTree.put(currChrom, currScale);
*/
}// end of chromosome iteration
}
public static void main(String[] args) {
GenomeConfig gconf = new GenomeConfig(args);
ExptConfig econf = new ExptConfig(gconf.getGenome(), args);
SEEDConfig sconf = new SEEDConfig(gconf, args);
DifferentialMSR diffMSR = new DifferentialMSR (gconf, econf, sconf);
}
}
|
package edu.washington.escience.myriad.parallel.ipc;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import com.google.common.base.Preconditions;
/**
* All IPCMessages derived from this class.
* */
public interface IPCMessage {
/**
* Header of IPCMessages in serialized version.
* */
enum Header {
EOS, BOS, CONNECT, DISCONNECT, PING, DATA
}
/**
* Meta IPCMessages, used inside the IPC module only.
* */
abstract class Meta implements IPCMessage {
/**
* EOS.
* */
static final Meta EOS = new Meta() {
private final ChannelBuffer serializeValue = ChannelBuffers.wrappedBuffer(new byte[] { (byte) Header.EOS
.ordinal() });
@Override
public ChannelBuffer serialize() {
return serializeValue;
}
@Override
public String toString() {
return "IPCMessage.Meta.EOS";
}
};
/**
* DISCONNECT.
* */
static final Meta DISCONNECT = new Meta() {
private final ChannelBuffer serializeValue = ChannelBuffers.wrappedBuffer(new byte[] { (byte) Header.DISCONNECT
.ordinal() });
@Override
public ChannelBuffer serialize() {
return serializeValue;
}
@Override
public String toString() {
return "IPCMessage.Meta.DISCONNECT";
}
};
/**
* BOS.
* */
static final class BOS extends Meta {
/**
* stream id.
* */
private final long streamID;
/**
* serialize value.
* */
private final ChannelBuffer serializeValue;
/**
* @param streamID stream id.
* */
public BOS(final long streamID) {
this.streamID = streamID;
ChannelBuffer bb = ChannelBuffers.buffer(1 + Long.SIZE / Byte.SIZE);
bb.writeByte((byte) Header.BOS.ordinal());
bb.writeLong(streamID);
serializeValue = ChannelBuffers.unmodifiableBuffer(bb);
}
/**
* @return the stream id.
* */
long getStreamID() {
return streamID;
}
@Override
public ChannelBuffer serialize() {
return serializeValue.duplicate();
}
/**
* @return De-serialize the BOS message.
* @param bb serialized data.
* */
public static BOS deSerialize(final ChannelBuffer bb) {
return new BOS(bb.readLong());
}
@Override
public String toString() {
return "IPCMessage.Meta.BOS(" + streamID + ")";
}
}
/**
* CONNECT.
* */
static final class CONNECT extends Meta {
/**
* remote ID.
* */
private final int remoteID;
/**
* serialize value.
* */
private final ChannelBuffer serializeValue;
/**
* @param remoteID the remote IPC ID.
* */
public CONNECT(final int remoteID) {
this.remoteID = remoteID;
ChannelBuffer bb = ChannelBuffers.buffer(1 + Integer.SIZE / Byte.SIZE);
bb.writeByte((byte) Header.CONNECT.ordinal());
bb.writeInt(remoteID);
serializeValue = ChannelBuffers.unmodifiableBuffer(bb);
}
/**
* @return get the remote IPC ID.
* */
public int getRemoteID() {
return remoteID;
}
@Override
public ChannelBuffer serialize() {
return serializeValue.duplicate();
}
/**
* @return Deserialize the CONNECT message.
* @param bb serialized data.
* */
public static CONNECT deSerialize(final ChannelBuffer bb) {
return new CONNECT(bb.readInt());
}
@Override
public String toString() {
return "IPCMessage.Meta.CONNECT(" + remoteID + ")";
}
}
/**
* PING.
* */
static final Meta PING = new Meta() {
private final ChannelBuffer serializeValue = ChannelBuffers.wrappedBuffer(new byte[] { (byte) Header.PING
.ordinal() });
@Override
public ChannelBuffer serialize() {
return serializeValue;
}
@Override
public String toString() {
return "IPCMessage.Meta.PING";
}
};
/**
* Serialize the message.
*
* @return serialize result.
* */
public abstract ChannelBuffer serialize();
/**
* @return deserialize meta messages
* @param bb serialized data.
* */
public static Meta deSerialize(final ChannelBuffer bb) {
byte type = bb.readByte();
if (type == Header.BOS.ordinal()) {
return BOS.deSerialize(bb);
} else if (type == Header.CONNECT.ordinal()) {
return CONNECT.deSerialize(bb);
} else if (type == Header.DISCONNECT.ordinal()) {
return DISCONNECT;
} else if (type == Header.EOS.ordinal()) {
return EOS;
} else if (type == Header.PING.ordinal()) {
return PING;
} else {
return null;
}
}
}
/**
* Unit of IPC transmission.
*
* @param <PAYLOAD> the type of payload.
* */
public class Data<PAYLOAD> implements IPCMessage {
/**
* the payload.
* */
private final PAYLOAD p;
/**
* the source remote id.
* */
private final int sourceRemote;
/**
* @param sourceRemote the source remote id
* @param p the payload.
* */
private Data(final int sourceRemote, final PAYLOAD p) {
this.p = p;
this.sourceRemote = sourceRemote;
}
/**
* @return the payload
* */
public PAYLOAD getPayload() {
return p;
}
/**
* @return the source remote id.
* */
public int getRemoteID() {
return sourceRemote;
}
/**
* serialize head.
* */
static final ChannelBuffer SERIALIZE_HEAD = ChannelBuffers
.wrappedBuffer(new byte[] { (byte) Header.DATA.ordinal() });
/**
* @param sourceRemote the source remote id.
* @param maybePayload either a paylod or a Data instance.
* @param <PAYLOAD> the payload type.
* @return the wrapped Data message.
* */
@SuppressWarnings("unchecked")
public static <PAYLOAD> Data<PAYLOAD> wrap(final int sourceRemote, final Object maybePayload) {
if (maybePayload instanceof Data) {
return (Data<PAYLOAD>) maybePayload;
} else {
return new Data<PAYLOAD>(sourceRemote, (PAYLOAD) maybePayload);
}
}
@Override
public String toString() {
return String.format("IPCMessage.Data(from:%1$d,payload:%2$s)", sourceRemote, p);
}
}
/**
* Unit of IPC Stream.
*
* @param <PAYLOAD> the type of payload.
* */
public final class StreamData<PAYLOAD> extends Data<PAYLOAD> {
/**
* the stream ID.
* */
private final long streamID;
/**
* @param sourceRemote the source remote ID.
* @param streamID stream ID.
* @param p the payload.
* */
private StreamData(final int sourceRemote, final long streamID, final PAYLOAD p) {
super(sourceRemote, Preconditions.checkNotNull(p));
this.streamID = streamID;
}
/**
* @param sourceRemote the source remote ID.
* @param streamID stream ID.
* */
private StreamData(final int sourceRemote, final long streamID) {
super(sourceRemote, null);
this.streamID = streamID;
}
/**
* @return the stream ID.
* */
public long getStreamID() {
return streamID;
}
/**
* @param <PAYLOAD> the payload type.
* @param sourceRemote the source remote ID.
* @param streamID stream ID.
* @return an EOS message.
* */
public static <PAYLOAD> StreamData<PAYLOAD> eos(final int sourceRemote, final long streamID) {
return new StreamData<PAYLOAD>(sourceRemote, streamID);
}
/**
* @param sourceRemote the source remote id.
* @param maybePayload either a paylod or a Data instance.
* @param <PAYLOAD> the payload type.
* @param streamID stream ID.
* @return the wrapped StreamData message.
* */
@SuppressWarnings("unchecked")
public static <PAYLOAD> StreamData<PAYLOAD> wrap(final int sourceRemote, final long streamID,
final Object maybePayload) {
if (maybePayload instanceof StreamData) {
return (StreamData<PAYLOAD>) maybePayload;
} else {
return new IPCMessage.StreamData<PAYLOAD>(sourceRemote, streamID, (PAYLOAD) maybePayload);
}
}
@Override
public String toString() {
return String.format("IPCMessage.StreamData(from:%1$d,stream:%1$d,payload:%3$s)", getRemoteID(), streamID,
getPayload());
}
}
}
|
package ch.unizh.ini.jaer.chip.multicamera;
/**
*
* @author Gemma
*
* MultiDAVIS240CCameraChip.java
*
*/
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import eu.seebetter.ini.chips.DavisChip;
import eu.seebetter.ini.chips.davis.DAVIS240C;
import eu.seebetter.ini.chips.davis.Davis240Config;
import java.util.ArrayList;
import java.util.TreeMap;
import net.sf.jaer.Description;
import net.sf.jaer.aemonitor.AEMonitorInterface;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.aemonitor.EventRaw;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.MultiCameraApsDvsEvent;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.hardwareinterface.HardwareInterface;
import net.sf.jaer.hardwareinterface.HardwareInterfaceFactory;
import net.sf.jaer.hardwareinterface.usb.USBInterface;
import net.sf.jaer.stereopsis.MultiCameraBiasgenHardwareInterface;
import net.sf.jaer.stereopsis.MultiCameraInterface;
import eu.seebetter.ini.chips.davis.DavisBaseCamera;
import eu.seebetter.ini.chips.davis.DavisConfig;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.JAERViewer;
import net.sf.jaer.aemonitor.AEPacket;
import net.sf.jaer.biasgen.Biasgen;
import net.sf.jaer.biasgen.BiasgenHardwareInterface;
import net.sf.jaer.chip.Chip;
import net.sf.jaer.chip.EventExtractor2D;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.graphics.AEFrameChipRenderer;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.BinocularDVSRenderer;
import net.sf.jaer.graphics.TwoCamera3DDisplayMethod;
import net.sf.jaer.graphics.MultiViewMultiCamera;
import net.sf.jaer.stereopsis.MultiCameraHardwareInterface;
import static net.sf.jaer.stereopsis.MultiCameraHardwareInterface.getNumberOfCameraChip;
import java.lang.Object;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import net.sf.jaer.graphics.ImageDisplay;
@Description("A multi Davis retina each on it's own USB interface with merged and presumably aligned fields of view")
@DevelopmentStatus(DevelopmentStatus.Status.InDevelopment)
abstract public class MultiDavisCameraChip extends DavisBaseCamera implements MultiCameraInterface {
public int NUM_CAMERAS=MultiCameraHardwareInterface.NUM_CAMERAS;
public int NUM_VIEWERS;
private AEChip chip= new AEChip();
private AEChip mainChip= new AEChip();
public AEChip[] cameras= new AEChip[NUM_CAMERAS];
public JAERViewer JAERV;
public AEViewer mainAEV;
public AEViewer[] camerasAEVs= new AEViewer[NUM_CAMERAS];
public ArrayList<HardwareInterface> hws = new ArrayList();
int nHW = HardwareInterfaceFactory.instance().getNumInterfacesAvailable();
private int sx;
private int sy;
private int displaycamera=NUM_CAMERAS;
private JFrame apsFrame = null;
public ImageDisplay[] apsDisplay= new ImageDisplay[NUM_CAMERAS];
private boolean displayAPSEnable=false;
private JMenu multiCameraMenu = null;
// public MulticameraDavisRenderer MultiDavisRenderer;
/** Creates a new instance of */
public MultiDavisCameraChip() {
super();
setName("MultiDavisCameraChip");
setEventClass(MultiCameraApsDvsEvent.class);
setEventExtractor(new Extractor(this));
getCanvas().addDisplayMethod(new TwoCamera3DDisplayMethod(getCanvas()));
getCanvas().addDisplayMethod(new MultiViewMultiCamera(getCanvas()));
}
@Override
public void onDeregistration() {
super.onDeregistration();
if (getAeViewer() == null) {
return;
}
if (multiCameraMenu != null) {
getAeViewer().removeMenu(multiCameraMenu);
multiCameraMenu = null;
}
}
@Override
public void onRegistration() {
super.onRegistration();
if (getAeViewer() == null) {
return;
}
multiCameraMenu = new JMenu("MultiCameraMenu");
multiCameraMenu.add(new JMenuItem(new SelectCamera()));
multiCameraMenu.add(new JMenuItem(new ApsDisplay()));
getAeViewer().addMenu(multiCameraMenu);
}
final public class ApsDisplay extends DavisMenuAction {
public ApsDisplay() {
super("ApsDisplay", "Display APS", "Display the sorted event in frames");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, java.awt.event.InputEvent.SHIFT_MASK));
}
@Override
public void actionPerformed(ActionEvent e) {
displayAPSEnable=true;
for (int c=0; c< NUM_CAMERAS; c++){
apsDisplay[c] = ImageDisplay.createOpenGLCanvas();
apsFrame = new JFrame("APS Frame");
apsFrame.setPreferredSize(new Dimension(400, 400));
apsFrame.getContentPane().add(apsDisplay[c], BorderLayout.CENTER);
apsFrame.setVisible(true);
apsFrame.pack();
}
}
}
final public class SelectCamera extends DavisMenuAction {
public SelectCamera() {
super("SelectCamera", "Select which camera display", "SelectCamera");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, java.awt.event.InputEvent.SHIFT_MASK));
}
@Override
public void actionPerformed(ActionEvent e) {
Object[] possibilities = new Object[NUM_CAMERAS+1];
for (int i=0; i<=NUM_CAMERAS; i++){
possibilities[i]=i;
}
Frame frame=new Frame();
displaycamera = (int)JOptionPane.showInputDialog(frame,"Select camera to display:","Choose Camera",JOptionPane.QUESTION_MESSAGE,null,possibilities,displaycamera);
}
}
public void setCameraChip(AEChip chip){
for (int i=0; i<NUM_CAMERAS; i++) {
cameras[i] = chip;
}
AEViewer.DEFAULT_CHIP_CLASS=chip.getName();
this.chip=chip;
sx=chip.getSizeX();
this.setSizeX(sx);
sy=chip.getSizeY();
this.setSizeY(sy);
}
public AEChip getChipType(){
AEChip chipType=this.chip;
return chipType;
}
public AEChip getMultiChip(){
mainChip=this;
return mainChip;
}
@Override
public int getNumCellTypes() {
return NUM_CAMERAS*2;
}
@Override
public int getNumCameras() {
return NUM_CAMERAS;
}
@Override
public void setCamera(int i, AEChip chip) {
cameras[i] = chip;
}
@Override
public AEChip getCamera(int i) {
return cameras[i];
}
/** Changes order of cameras according to list in permutation (which is not checked for uniqueness or bounds).
*
* @param permutation list of destination indices for elements of cameras.
*/
@Override
public void permuteCameras(int[] permutation) {
AEChip[] tmp = new AEChip[permutation.length];
System.arraycopy(cameras, 0, tmp, 0, permutation.length);
for (int i = 0; i < permutation.length; i++) {
cameras[i] = tmp[permutation[i]];
}
}
/** the event extractor for the multi chip.
* It extracts from each event the x,y,type of the event and in addition,
* it adds getNumCellTypes to each type to signal
* a right event (as opposed to a left event)
*/
public class Extractor extends DavisBaseCamera.DavisEventExtractor {
public Extractor(MultiDavisCameraChip chip) {
super(new DavisBaseCamera() {}); // they are the same type
}
/** extracts the meaning of the raw events and returns EventPacket containing BinocularEvent.
*@param in the raw events, can be null
*@return out the processed events. these are partially processed in-place. empty packet is returned if null is supplied as in.
*/
@Override
synchronized public ApsDvsEventPacket extractPacket(AEPacketRaw in) {
final int sx = getChipType().getSizeX()-1;
final int sy = getChipType().getSizeY()-1;
if (out == null) {
out = new ApsDvsEventPacket(MultiCameraApsDvsEvent.class);
}else {
out.clear();
}
if (in == null) {
return (ApsDvsEventPacket) out;
}
OutputEventIterator outItr = out.outputIterator();
DavisEventExtractor davisExtractor = new DavisEventExtractor((DavisBaseCamera) chip);
EventPacket davisExtractedPacket = davisExtractor.extractPacket(in);
int n =davisExtractedPacket.getSize();
int[] a = in.getAddresses();
for (int i = 0; i < n; i++) {
ApsDvsEvent davisExtractedEvent= (ApsDvsEvent) davisExtractedPacket.getEvent(i);
MultiCameraApsDvsEvent e= (MultiCameraApsDvsEvent) outItr.nextOutput();
e.copyFrom(davisExtractedEvent);
int address=e.address;
//if DVS
if (e.isDVSEvent() ){
e.camera = MultiCameraApsDvsEvent.getCameraFromRawAddressDVS(address);
}else if (e.isApsData()){
e.camera = MultiCameraApsDvsEvent.getCameraFromRawAddressAPS(address);
// System.out.println("DVS? "+ e.isDVSEvent()+" camera: " +e.camera+" x: "+ e.x+" y: "+e.y);
}
if(displaycamera<NUM_CAMERAS){
int chosencamera=displaycamera;
if(e.camera==chosencamera){
e.setFilteredOut(true);
}
}
if (displayAPSEnable && e.isApsData()){
apsDisplay[e.camera].setPixmapGray(e.x, e.y, e.getAdcSample());
if(e.isEndOfFrame()){
apsDisplay[e.camera].display();
}
}
}
return (ApsDvsEventPacket) out;
}
/** Reconstructs the raw packet after event filtering to include the binocular information
@param packet the filtered packet
@return the reconstructed packet
*/
@Override
public AEPacketRaw reconstructRawPacket(EventPacket oldPacket) {
AEPacketRaw newPacket = super.reconstructRawPacket(oldPacket);
int n=oldPacket.getSize();
// we also need to add camera info to raw events
for (int i = 0; i < n; i++) {
MultiCameraApsDvsEvent mce = (MultiCameraApsDvsEvent) oldPacket.getEvent(i);
EventRaw event = newPacket.getEvent(i);
int eventAddress=event.address;
int eventCamera=mce.camera;
if (mce.isDVSEvent()){
event.address=MultiCameraApsDvsEvent.setCameraNumberToRawAddressDVS(eventCamera, eventAddress);
}
if (mce.isApsData()){
event.address=MultiCameraApsDvsEvent.setCameraNumberToRawAddressAPS(mce.camera, event.address);
}
}
return newPacket;
}
}// extractor for
@Override
public void setHardwareInterface(HardwareInterface hw) {
if (hw != null) {
log.warning("trying to set hardware interface to " + hw + " but hardware interface should have been constructed as a MultiCameraHardwareInterface by this MultiDAVIS240CCameraChip");
}
if (hw != null && hw.isOpen()) {
log.info("closing hw interface");
hw.close();
}
super.setHardwareInterface(hw);
}
boolean deviceMissingWarningLogged = false;
/**Builds and returns a hardware interface for this multi camera device.
* Unlike other chip objects, this one actually invokes the HardwareInterfaceFactory to
* construct the interfaces and opens them, because this device depends on a particular set of interfaces.
* <p>
* The hardware serial number IDs are used to assign cameras.
* @return the hardware interface for this device
*/
@Override
public HardwareInterface getHardwareInterface() {
if (hardwareInterface != null) {
return hardwareInterface;
}
int n = HardwareInterfaceFactory.instance().getNumInterfacesAvailable();
log.info(nHW + " interfaces found!");
if (nHW <1) {
log.warning( " couldn't build MultiCameraHardwareInterface hardware interface because only " + nHW + " camera is available and at least 2 cameras are needed");
hardwareInterface= HardwareInterfaceFactory.instance().getInterface(nHW);
return hardwareInterface;
}
for (int i = 0; i < n; i++) {
HardwareInterface hw = HardwareInterfaceFactory.instance().getInterface(i);
if (hw instanceof AEMonitorInterface && hw instanceof BiasgenHardwareInterface) {
log.info("found AEMonitorInterface && BiasgenHardwareInterface " + hw);
hws.add(hw);
}
}
// TODO fix assignment of cameras according to serial number order
// make treemap (sorted map) of string serial numbers of cameras mapped to interfaces
TreeMap<String, AEMonitorInterface> map = new TreeMap();
for (HardwareInterface hw : hws) {
try {
hw.open();
USBInterface usb0 = (USBInterface) hw;
String[] sa = usb0.getStringDescriptors();
if (sa.length < 3) {
log.warning("interface " + hw.toString() + " has no serial number, cannot guarentee assignment of cameras");
} else {
map.put(sa[2], (AEMonitorInterface) hw);
}
} catch (Exception ex) {
log.warning("enumerating multiple cameras: " + ex.toString());
}
}
try {
Object[] oa=map.values().toArray();
AEMonitorInterface[] aemons=new AEMonitorInterface[oa.length];
int ind=0;
for(Object o:oa){
aemons[ind++]=(AEMonitorInterface)o;
}
hardwareInterface = new MultiCameraBiasgenHardwareInterface(aemons);
((MultiCameraBiasgenHardwareInterface) hardwareInterface).setChip(this);
hardwareInterface.close(); // will be opened later on by user
} catch (Exception e) {
log.warning("couldn't build correct multi camera hardware interface: " + e.getMessage());
return null;
}
deviceMissingWarningLogged = false;
return hardwareInterface;
}
public ArrayList<HardwareInterface> getNameHWs() {
return hws;
}
public void setNameHW(HardwareInterface hw) {
hws.add(hw);
}
// public void setBiasgenCameraViewers (AEChip chip){
// String biasName=chip.getBiasgen().getName();
// if (biasName=="DavisConfig") {
// DavisConfig davisconfig= (DavisConfig) chip.getBiasgen();
//// davisconfig.setCaptureFramesEnabled(false);
// davisconfig.setDisplayFrames(false);
// davisconfig.setImuEnabled(false);
// davisconfig.setDisplayImu(false);
// chip.setBiasgen(davisconfig);
// } else if (biasName=="Davis240Config"){
// Davis240Config davisconfig= (Davis240Config) chip.getBiasgen();
// davisconfig.setCaptureFramesEnabled(false);
// davisconfig.setDisplayFrames(false);
// davisconfig.setImuEnabled(false);
// davisconfig.setDisplayImu(false);
// chip.setBiasgen(davisconfig);
}
|
package com.WazaBe.HoloEverywhere;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class LayoutInflater extends android.view.LayoutInflater implements
Cloneable {
public static interface OnInitInflaterListener {
public void onInitInflate(LayoutInflater infaler);
}
private static boolean inited = false;
private static final Map<Context, LayoutInflater> INSTANCES_MAP = new WeakHashMap<Context, LayoutInflater>();
private static OnInitInflaterListener listener;
private static final Map<String, String> VIEWS_MAP = new HashMap<String, String>();
static {
putToMap(Settings.getWidgetsPackage(), "ProgressBar", "LinearLayout",
"Switch", "TextView", "CalendarView", "Spinner",
"NumberPicker", "DatePicker");
putToMap("android.support.v4.view", "ViewPager", "PagerTitleStrip");
putToMap("android.webkit", "WebView");
}
public static LayoutInflater from(android.view.LayoutInflater inflater) {
if (inflater instanceof LayoutInflater) {
return (LayoutInflater) inflater;
}
return new LayoutInflater(inflater, inflater.getContext());
}
public static LayoutInflater from(Context context) {
if (!INSTANCES_MAP.containsKey(context)) {
synchronized (INSTANCES_MAP) {
if (!INSTANCES_MAP.containsKey(context)) {
INSTANCES_MAP.put(context, new LayoutInflater(context));
}
}
}
return INSTANCES_MAP.get(context);
}
public static LayoutInflater from(View view) {
return from(view.getContext());
}
public static Object getSystemService(Object superService) {
if (superService instanceof android.view.LayoutInflater) {
if (superService instanceof LayoutInflater) {
return superService;
}
return LayoutInflater
.from((android.view.LayoutInflater) superService);
}
return superService;
}
public static View inflate(Context context, int resource) {
return from(context).inflate(resource, null);
}
public static View inflate(Context context, int resource, ViewGroup root) {
return from(context).inflate(resource, root);
}
public static View inflate(Context context, int resource, ViewGroup root,
boolean attachToRoot) {
return from(context).inflate(resource, root, attachToRoot);
}
public static View inflate(View view, int resource) {
return from(view).inflate(resource, null);
}
public static View inflate(View view, int resource, ViewGroup root) {
return from(view).inflate(resource, root);
}
public static View inflate(View view, int resource, ViewGroup root,
boolean attachToRoot) {
return from(view).inflate(resource, root, attachToRoot);
}
public static void putToMap(String prefix, String... classess) {
for (String clazz : classess) {
VIEWS_MAP.put(clazz, prefix + "." + clazz);
}
}
public static void setOnInitInflaterListener(OnInitInflaterListener listener) {
LayoutInflater.listener = listener;
}
protected LayoutInflater(android.view.LayoutInflater original,
Context newContext) {
super(original, newContext);
init();
}
protected LayoutInflater(Context context) {
super(context);
init();
}
@Override
public LayoutInflater cloneInContext(Context newContext) {
return new LayoutInflater(this, newContext);
}
public View inflate(int resource) {
return inflate(resource, null);
}
private void init() {
if (!inited) {
synchronized (LayoutInflater.class) {
if (!inited) {
inited = true;
if (listener != null) {
listener.onInitInflate(this);
}
}
}
}
}
@Override
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
name = name.intern();
if (VIEWS_MAP.containsKey(name)) {
return createView(VIEWS_MAP.get(name), null, attrs);
}
try {
return createView(name, "android.widget.", attrs);
} catch (ClassNotFoundException e) {
return createView(name, "android.view.", attrs);
}
}
}
|
package com.t28.sectionadapter;
import android.support.v7.widget.RecyclerView;
public class Section {
private static final Section EMPTY = new Section();
private final RecyclerView.Adapter mAdapter;
private int mHeaderPosition = RecyclerView.NO_POSITION;
Section(RecyclerView.Adapter adapter) {
if (adapter == null) {
throw new NullPointerException("adapter == null");
}
mAdapter = adapter;
}
private Section() {
mAdapter = new NullAdapter();
}
public boolean isEmpty() {
return mAdapter instanceof NullAdapter;
}
public boolean isHeaderPosition(int position) {
return mHeaderPosition == position;
}
public boolean containsItem(int position) {
final int positionStart = mHeaderPosition + 1;
final int positionEnd = mHeaderPosition + mAdapter.getItemCount();
return positionStart <= position && position <= positionEnd;
}
public int toItemPosition(int position) {
return position - mHeaderPosition - 1;
}
RecyclerView.Adapter getAdapter() {
return mAdapter;
}
void setHeaderPosition(int position) {
mHeaderPosition = position;
}
int getHeaderPosition() {
return mHeaderPosition;
}
static Section emptySection() {
return EMPTY;
}
}
|
package com.malhartech.api;
import com.malhartech.util.AttributeMap;
/**
*
* The base interface for context for all of the streaming platform objects<p>
* <br>
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public interface Context
{
public interface PortContext extends Context
{
public class AttributeKey<T> extends AttributeMap.AttributeKey<PortContext, T>
{
private AttributeKey(String name)
{
super(PortContext.class, name);
}
}
/**
* Number of tuples the poll buffer can cache without blocking the input stream to the port.
*/
public static final AttributeKey<Integer> BUFFER_SIZE = new AttributeKey<Integer>("bufferSize");
/**
* Poll period in milliseconds when the port buffer reaches its limits.
*/
public static final AttributeKey<Integer> SPIN_MILLIS = new AttributeKey<Integer>("spinMillis");
AttributeMap<PortContext> getAttributes();
}
public interface OperatorContext extends Context
{
public class AttributeKey<T> extends AttributeMap.AttributeKey<OperatorContext, T>
{
private AttributeKey(String name)
{
super(OperatorContext.class, name);
}
}
public static final AttributeKey<Integer> SPIN_MILLIS = new AttributeKey<Integer>("spinMillis");
public static final AttributeKey<Integer> RECOVERY_ATTEMPTS = new AttributeKey<Integer>("recoveryAttempts");
/**
* Initial partition count for an operator that supports partitioning. The
* number is interpreted as follows:
* <p>
* Default partitioning (operators that do not implement
* {@link PartitionableOperator}):<br>
* If the attribute is not present or set to 0 partitioning is off. Else the
* number of initial partitions (statically created during initialization.
* <p>
* Operator that implements {@link PartitionableOperator}:<br>
* Count 0 disables partitioning. Other values are ignored as number of
* initial partitions are determined by operator implementation.
*/
public static final AttributeKey<Integer> INITIAL_PARTITION_COUNT = new AttributeKey<Integer>("initialPartitionCount");
public static final AttributeKey<Integer> PARTITION_TPS_MIN = new AttributeKey<Integer>("partitionTpsMin");
public static final AttributeKey<Integer> PARTITION_TPS_MAX = new AttributeKey<Integer>("partitionTpsMax");
/**
* Attribute of the operator which conveys to the stram whether the Operator is stateful or stateless.
*/
public static final AttributeKey<Boolean> STATELESS = new AttributeKey<Boolean>("stateless");
/**
* Return the operator runtime id.
*
* @return String
*/
String getId();
AttributeMap<OperatorContext> getAttributes();
}
}
|
package com.malhartech.engine;
import com.malhartech.api.ActivationListener;
import com.malhartech.api.DAG;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.OutputPort;
import com.malhartech.api.Sink;
import com.malhartech.engine.Operators.PortMappingDescriptor;
import com.malhartech.tuple.CheckpointTuple;
import com.malhartech.tuple.EndStreamTuple;
import com.malhartech.tuple.EndWindowTuple;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @param <OPERATOR>
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public abstract class Node<OPERATOR extends Operator> implements Runnable
{
/*
* if the Component is capable of taking only 1 input, call it INPUT.
* if the Component is capable of providing only 1 output, call it OUTPUT.
*/
public static final String INPUT = "input";
public static final String OUTPUT = "output";
public final int id;
protected final HashMap<String, InternalCounterSink> outputs = new HashMap<String, InternalCounterSink>();
@SuppressWarnings(value = "VolatileArrayField")
protected volatile InternalCounterSink[] sinks = InternalCounterSink.NO_SINKS;
protected boolean alive;
protected final OPERATOR operator;
protected final PortMappingDescriptor descriptor;
protected long currentWindowId;
protected int applicationWindowCount;
protected long stramWindowSize;
protected long endWindowEmitTime = 0;
protected long lastSampleCpuTime = 0;
protected ThreadMXBean tmb;
protected HashMap<SweepableReservoir, Long> endWindowDequeueTimes = new HashMap<SweepableReservoir, Long>(); // end window dequeue time for input ports
protected long checkpointedWindowId;
public Node(int id, OPERATOR operator)
{
this.id = id;
this.operator = operator;
descriptor = new PortMappingDescriptor();
Operators.describe(operator, descriptor);
tmb = ManagementFactory.getThreadMXBean();
}
public Operator getOperator()
{
return operator;
}
public PortMappingDescriptor getPortMappingDescriptor()
{
return descriptor;
}
public void connectOutputPort(String port, final Sink<Object> sink)
{
@SuppressWarnings("unchecked")
OutputPort<Object> outputPort = (OutputPort<Object>)descriptor.outputPorts.get(port);
if (outputPort != null) {
if (sink instanceof InternalCounterSink) {
outputPort.setSink(sink);
outputs.put(port, (InternalCounterSink)sink);
}
else if (sink == null) {
outputPort.setSink(null);
outputs.remove(port);
}
else {
InternalCounterSink cs = new InternalCounterSink(sink);
outputPort.setSink(cs);
outputs.put(port, cs);
}
}
}
public abstract void connectInputPort(String port, final SweepableReservoir reservoir);
public void addSinks(Map<String, Sink<Object>> sinks)
{
for (Entry<String, Sink<Object>> e: sinks.entrySet()) {
InternalCounterSink ics = outputs.get(e.getKey());
if (ics != null) {
ics.sink = new ForkingSink(ics.sink, e.getValue());
}
}
}
public void removeSinks(Map<String, Sink<Object>> sinks)
{
for (Entry<String, Sink<Object>> e: sinks.entrySet()) {
InternalCounterSink ics = outputs.get(e.getKey());
if (ics != null && ics.sink instanceof ForkingSink) {
assert (((ForkingSink)ics.sink).second == e.getValue());
ics.sink = ((ForkingSink)ics.sink).first;
}
}
}
protected OperatorContext context;
@SuppressWarnings("unchecked")
public void activate(OperatorContext context)
{
boolean activationListener = operator instanceof ActivationListener;
activateSinks();
this.alive = true;
this.context = context;
this.applicationWindowCount = context.getAttributes().attrValue(OperatorContext.APPLICATION_WINDOW_COUNT, 1);
this.stramWindowSize = context.getApplicationAttributes().attrValue(DAG.STRAM_WINDOW_SIZE_MILLIS, 500);
if (activationListener) {
((ActivationListener)operator).activate(context);
}
run();
if (activationListener) {
((ActivationListener)operator).deactivate();
}
this.context = null;
emitEndStream();
deactivateSinks();
}
public void deactivate()
{
alive = false;
}
@Override
public String toString()
{
return String.valueOf(id);
}
protected void emitEndStream()
{
// logger.debug("{} sending EndOfStream", this);
/*
* since we are going away, we should let all the downstream operators know that.
*/
EndStreamTuple est = new EndStreamTuple(currentWindowId);
for (final InternalCounterSink output: outputs.values()) {
output.process(est);
}
}
protected void emitEndWindow()
{
// This function currently only gets called upon END_STREAM.
// DO NOT assume this will get called to emit an end window tuple
EndWindowTuple ewt = new EndWindowTuple(currentWindowId);
for (final Sink<Object> output: outputs.values()) {
output.process(ewt);
}
}
public void emitCheckpoint(long windowId)
{
CheckpointTuple ct = new CheckpointTuple(windowId);
ct.setWindowId(currentWindowId);
for (final InternalCounterSink output: outputs.values()) {
output.process(ct);
}
}
protected void handleRequests(long windowId)
{
endWindowEmitTime = System.currentTimeMillis();
/*
* we prefer to cater to requests at the end of the window boundary.
*/
try {
BlockingQueue<OperatorContext.NodeRequest> requests = context.getRequests();
int size;
if ((size = requests.size()) > 0) {
while (size
//logger.debug("endwindow: " + t.getWindowId() + " lastprocessed: " + context.getLastProcessedWindowId());
requests.remove().execute(operator, context.getId(), windowId);
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
OperatorStats stats = new OperatorStats();
reportStats(stats);
stats.checkpointedWindowId = checkpointedWindowId;
context.report(stats, windowId);
}
protected void reportStats(OperatorStats stats)
{
stats.outputPorts = new ArrayList<OperatorStats.PortStats>();
for (Entry<String, InternalCounterSink> e: outputs.entrySet()) {
//logger.info("end window emit time is {}", endWindowEmitTime);
stats.outputPorts.add(new OperatorStats.PortStats(e.getKey(), e.getValue().resetCount(), endWindowEmitTime));
}
long currentCpuTime = tmb.getCurrentThreadCpuTime();
stats.cpuTimeUsed = currentCpuTime - lastSampleCpuTime;
lastSampleCpuTime = currentCpuTime;
}
protected void activateSinks()
{
int size = outputs.size();
if (size == 0) {
sinks = InternalCounterSink.NO_SINKS;
}
else {
@SuppressWarnings("unchecked")
InternalCounterSink[] newSinks = (InternalCounterSink[])Array.newInstance(InternalCounterSink.class, size);
for (InternalCounterSink s: outputs.values()) {
newSinks[--size] = s;
}
sinks = newSinks;
}
}
protected void deactivateSinks()
{
sinks = InternalCounterSink.NO_SINKS;
}
public boolean isAlive()
{
return alive;
}
public long getBackupWindowId()
{
return checkpointedWindowId;
}
static class ForkingSink implements Sink<Object>
{
final Sink<Object> first;
final Sink<Object> second;
ForkingSink(Sink<Object> f, Sink<Object> s)
{
first = f;
second = s;
}
@Override
public void process(Object tuple)
{
first.process(tuple);
second.process(tuple);
}
}
protected static class InternalCounterSink implements Sink<Object>
{
@SuppressWarnings({"FieldNameHidesFieldInSuperclass", "VolatileArrayField"})
public static final InternalCounterSink[] NO_SINKS = new InternalCounterSink[0];
int count;
Sink<Object> sink;
InternalCounterSink(Sink<Object> sink)
{
this.sink = sink;
}
@Override
public void process(Object tuple)
{
count++;
sink.process(tuple);
}
public int getCount()
{
return count;
}
public int resetCount()
{
int ret = count;
count = 0;
return ret;
}
}
private static final Logger logger = LoggerFactory.getLogger(Node.class);
}
|
package jme3test.bullet;
import com.jme3.animation.AnimChannel;
import com.jme3.animation.AnimControl;
import com.jme3.animation.AnimEventListener;
import com.jme3.animation.Bone;
import com.jme3.animation.LoopMode;
import com.jme3.bullet.BulletAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.TextureKey;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.collision.RagdollCollisionListener;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.RagdollControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.joints.SixDofJoint;
import com.jme3.font.BitmapText;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.debug.SkeletonDebugger;
import com.jme3.scene.shape.Sphere;
import com.jme3.scene.shape.Sphere.TextureMode;
import com.jme3.texture.Texture;
/**
* PHYSICS RAGDOLLS ARE NOT WORKING PROPERLY YET!
* @author normenhansen
*/
public class TestBoneRagdoll extends SimpleApplication implements RagdollCollisionListener, AnimEventListener{
private BulletAppState bulletAppState;
Material matBullet;
Node model;
RagdollControl ragdoll;
float bulletSize = 1f;
Material mat;
Material mat3;
private Sphere bullet;
private SphereCollisionShape bulletCollisionShape;
public static void main(String[] args) {
TestBoneRagdoll app = new TestBoneRagdoll();
app.start();
}
public void simpleInitApp() {
initCrossHairs();
initMaterial();
cam.setLocation(new Vector3f(0.26924422f, 6.646658f, 22.265987f));
cam.setRotation(new Quaternion(-2.302544E-4f, 0.99302495f, -0.117888905f, -0.0019395084f));
bulletAppState = new BulletAppState();
bulletAppState.setEnabled(true);
stateManager.attach(bulletAppState);
bullet = new Sphere(32, 32, 1.0f, true, false);
bullet.setTextureMode(TextureMode.Projected);
bulletCollisionShape = new SphereCollisionShape(1.0f);
bulletAppState.getPhysicsSpace().enableDebug(assetManager);
PhysicsTestHelper.createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());
setupLight();
model = (Node) assetManager.loadModel("Models/Sinbad/Sinbad.mesh.xml");
// model.setLocalTranslation(5, 0, 5);
// model.setLocalRotation(new Quaternion().fromAngleAxis(FastMath.HALF_PI, Vector3f.UNIT_X));
//debug view
AnimControl control = model.getControl(AnimControl.class);
SkeletonDebugger skeletonDebug = new SkeletonDebugger("skeleton", control.getSkeleton());
Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/WireColor.j3md");
mat2.setColor("Color", ColorRGBA.Green);
mat2.getAdditionalRenderState().setDepthTest(false);
skeletonDebug.setMaterial(mat2);
skeletonDebug.setLocalTranslation(model.getLocalTranslation());
//Note: PhysicsRagdollControl is still TODO, constructor will change
ragdoll = new RagdollControl(0.5f);
setupSinbad(ragdoll);
ragdoll.addCollisionListener(this);
model.addControl(ragdoll);
float eighth_pi = FastMath.PI * 0.125f;
ragdoll.setJointLimit("Waist", eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi, eighth_pi);
ragdoll.setJointLimit("Chest", eighth_pi, eighth_pi, 0, 0, eighth_pi, eighth_pi);
//Oto's head is almost rigid
// ragdoll.setJointLimit("head", 0, 0, eighth_pi, -eighth_pi, 0, 0);
getPhysicsSpace().add(ragdoll);
speed = 1.3f;
rootNode.attachChild(model);
// rootNode.attachChild(skeletonDebug);
flyCam.setMoveSpeed(50);
animChannel = control.createChannel();
animChannel.setAnim("Dance");
control.addListener(this);
inputManager.addListener(new ActionListener() {
public void onAction(String name, boolean isPressed, float tpf) {
if (name.equals("toggle") && isPressed) {
Vector3f v=new Vector3f();
v.set(model.getLocalTranslation());
v.y=0;
model.setLocalTranslation(v);
Quaternion q=new Quaternion();
float[] angles=new float[3];
model.getLocalRotation().toAngles(angles);
q.fromAngleAxis(angles[1], Vector3f.UNIT_Y);
//q.lookAt(model.getLocalRotation().toRotationMatrix().getColumn(2), Vector3f.UNIT_Y);
model.setLocalRotation(q);
if(angles[0]<0){
ragdoll.blendControlToAnim("StandUpBack",animChannel);
}else{
ragdoll.blendControlToAnim("StandUpFront",animChannel);
}
}
if (name.equals("bullet+") && isPressed) {
bulletSize += 0.1f;
}
if (name.equals("bullet-") && isPressed) {
bulletSize -= 0.1f;
}
if (name.equals("shoot") && isPressed) {
// bulletSize = 0;
}
if (name.equals("stop") && isPressed) {
bulletAppState.setEnabled(!bulletAppState.isEnabled());
}
if (name.equals("shoot") && !isPressed) {
Geometry bulletg = new Geometry("bullet", bullet);
bulletg.setMaterial(matBullet);
bulletg.setLocalTranslation(cam.getLocation());
bulletg.setLocalScale(bulletSize);
bulletCollisionShape = new SphereCollisionShape(bulletSize);
RigidBodyControl bulletNode = new RigidBodyControl(bulletCollisionShape, bulletSize * 10);
bulletNode.setCcdMotionThreshold(0.001f);
bulletNode.setLinearVelocity(cam.getDirection().mult(80));
bulletg.addControl(bulletNode);
rootNode.attachChild(bulletg);
getPhysicsSpace().add(bulletNode);
}
if (name.equals("boom") && !isPressed) {
Geometry bulletg = new Geometry("bullet", bullet);
bulletg.setMaterial(matBullet);
bulletg.setLocalTranslation(cam.getLocation());
bulletg.setLocalScale(bulletSize);
bulletCollisionShape = new SphereCollisionShape(bulletSize);
BombControl bulletNode = new BombControl(assetManager, bulletCollisionShape, 1);
bulletNode.setForceFactor(10);
bulletNode.setExplosionRadius(30);
bulletNode.setCcdMotionThreshold(0.001f);
bulletNode.setLinearVelocity(cam.getDirection().mult(180));
bulletg.addControl(bulletNode);
rootNode.attachChild(bulletg);
getPhysicsSpace().add(bulletNode);
}
}
}, "toggle", "shoot", "stop", "bullet+", "bullet-","boom");
inputManager.addMapping("toggle", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping("shoot", new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addMapping("boom", new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addMapping("stop", new KeyTrigger(KeyInput.KEY_H));
inputManager.addMapping("bullet-", new KeyTrigger(KeyInput.KEY_COMMA));
inputManager.addMapping("bullet+", new KeyTrigger(KeyInput.KEY_PERIOD));
}
private void setupLight() {
// AmbientLight al = new AmbientLight();
// al.setColor(ColorRGBA.White.mult(1));
// rootNode.addLight(al);
DirectionalLight dl = new DirectionalLight();
dl.setDirection(new Vector3f(-0.1f, -0.7f, -1).normalizeLocal());
dl.setColor(new ColorRGBA(1f, 1f, 1f, 1.0f));
rootNode.addLight(dl);
}
private PhysicsSpace getPhysicsSpace() {
return bulletAppState.getPhysicsSpace();
}
public void initMaterial() {
matBullet = new Material(assetManager, "Common/MatDefs/Misc/SimpleTextured.j3md");
TextureKey key2 = new TextureKey("Textures/Terrain/Rock/Rock.PNG");
key2.setGenerateMips(true);
Texture tex2 = assetManager.loadTexture(key2);
matBullet.setTexture("ColorMap", tex2);
}
protected void initCrossHairs() {
guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
BitmapText ch = new BitmapText(guiFont, false);
ch.setSize(guiFont.getCharSet().getRenderedSize() * 2);
ch.setText("+"); // crosshairs
ch.setLocalTranslation( // center
settings.getWidth() / 2 - guiFont.getCharSet().getRenderedSize() / 3 * 2,
settings.getHeight() / 2 + ch.getLineHeight() / 2, 0);
guiNode.attachChild(ch);
}
public void collide(Bone bone, PhysicsCollisionObject object,PhysicsCollisionEvent event) {
if (object.getUserObject() != null && object.getUserObject() instanceof Geometry) {
Geometry geom = (Geometry) object.getUserObject();
if ("Floor".equals(geom.getName())) {
return;
}
}
if (!ragdoll.hasControl()) {
ragdoll.setControl(true);
}
}
private void setupSinbad(RagdollControl ragdoll) {
ragdoll.addBoneName("Ulna.L");
ragdoll.addBoneName("Ulna.R");
ragdoll.addBoneName("Chest");
ragdoll.addBoneName("Foot.L");
ragdoll.addBoneName("Foot.R");
ragdoll.addBoneName("Hand.R");
ragdoll.addBoneName("Hand.L");
ragdoll.addBoneName("Neck");
// ragdoll.addBoneName("Head");
ragdoll.addBoneName("Root");
ragdoll.addBoneName("Stomach");
ragdoll.addBoneName("Waist");
ragdoll.addBoneName("Humerus.L");
ragdoll.addBoneName("Humerus.R");
ragdoll.addBoneName("Thigh.L");
ragdoll.addBoneName("Thigh.R");
ragdoll.addBoneName("Calf.L");
ragdoll.addBoneName("Calf.R");
ragdoll.addBoneName("Clavicle.L");
ragdoll.addBoneName("Clavicle.R");
}
float elTime = 0;
boolean forward = true;
AnimControl animControl;
AnimChannel animChannel;
Vector3f direction = new Vector3f(0, 0, 1);
Quaternion rotate = new Quaternion().fromAngleAxis(FastMath.PI / 8, Vector3f.UNIT_Y);
boolean dance = true;
@Override
public void simpleUpdate(float tpf) {
// elTime += tpf;
// if (elTime > 3) {
// elTime = 0;
// if (dance) {
// rotate.multLocal(direction);
// if (Math.random() > 0.80) {
// dance = true;
// animChannel.setAnim("Dance");
// } else {
// dance = false;
// animChannel.setAnim("RunBase");
// rotate.fromAngleAxis(FastMath.QUARTER_PI * ((float) Math.random() - 0.5f), Vector3f.UNIT_Y);
// rotate.multLocal(direction);
// if (!ragdoll.hasControl() && !dance) {
// if (model.getLocalTranslation().getZ() < -10) {
// direction.z = 1;
// direction.normalizeLocal();
// } else if (model.getLocalTranslation().getZ() > 10) {
// direction.z = -1;
// direction.normalizeLocal();
// if (model.getLocalTranslation().getX() < -10) {
// direction.x = 1;
// direction.normalizeLocal();
// } else if (model.getLocalTranslation().getX() > 10) {
// direction.x = -1;
// direction.normalizeLocal();
// model.move(direction.multLocal(tpf * 8));
// direction.normalizeLocal();
// model.lookAt(model.getLocalTranslation().add(direction), Vector3f.UNIT_Y);
}
public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {
// if(channel.getAnimationName().equals("StandUpFront")){
// channel.setAnim("Dance");
if(channel.getAnimationName().equals("StandUpBack") || channel.getAnimationName().equals("StandUpFront")){
channel.setLoopMode(LoopMode.DontLoop);
channel.setAnim("IdleTop",5);
channel.setLoopMode(LoopMode.Loop);
}
// if(channel.getAnimationName().equals("IdleTop")){
// channel.setAnim("StandUpFront");
}
public void onAnimChange(AnimControl control, AnimChannel channel, String animName) {
}
}
|
package org.vitrivr.cineast.standalone.cli;
import com.github.rvesse.airline.annotations.Command;
import com.github.rvesse.airline.annotations.Option;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.vitrivr.cineast.standalone.importer.handlers.AsrDataImportHandler;
import org.vitrivr.cineast.standalone.importer.handlers.DataImportHandler;
import org.vitrivr.cineast.standalone.importer.handlers.JsonDataImportHandler;
import org.vitrivr.cineast.standalone.importer.handlers.OcrDataImportHandler;
import org.vitrivr.cineast.standalone.importer.handlers.ProtoDataImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.AudioTranscriptImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.CaptionTextImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.GoogleVisionImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.ObjectMetadataImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.TagImportHandler;
import org.vitrivr.cineast.standalone.importer.vbs2019.gvision.GoogleVisionCategory;
/**
* A CLI command that can be used to start import of pre-extracted data.
*
* @author Ralph Gasser
* @version 1.0
*/
@Command(name = "import", description = "Starts import of pre-extracted data.")
public class ImportCommand implements Runnable {
@Option(name = {"-t", "--type"}, description = "Type of data import that should be started. Possible values are PROTO, JSON, ASR, OCR, CAPTION, AUDIO, TAGS and VISION.")
private String type;
@Option(name = {"-i", "--input"}, description = "The source file or folder for data import. If a folder is specified, the entire content will be considered for import.")
private String input;
@Option(name = {"-b", "--batchsize"}, description = "The batch size used for the import. Imported data will be persisted in batches of the specified size.")
private int batchsize = 500;
@Override
public void run() {
System.out.println(String.format("Starting import of type %s for '%s'.", this.type.toString(), this.input));
final Path path = Paths.get(this.input);
final ImportType type = ImportType.valueOf(this.type.toUpperCase());
DataImportHandler handler;
switch (type) {
case PROTO:
handler = new ProtoDataImportHandler(2, this.batchsize);
handler.doImport(path);
break;
case JSON:
handler = new JsonDataImportHandler(2, this.batchsize);
handler.doImport(path);
break;
case ASR:
handler = new AsrDataImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case OCR:
handler = new OcrDataImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case CAPTION:
handler = new CaptionTextImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case AUDIO:
handler = new AudioTranscriptImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case TAGS:
handler = new TagImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case VISION:
doVisionImport(path);
break;
case METADATA:
handler = new ObjectMetadataImportHandler(1, this.batchsize);
handler.doImport(path);
break;
case VBS2020:
AudioTranscriptImportHandler audioHandler = new AudioTranscriptImportHandler(1, 15_000);
audioHandler.doImport(path.resolve("audiomerge.json"));
CaptionTextImportHandler captionHandler = new CaptionTextImportHandler(1, 25_000);
captionHandler.doImport(path.resolve("captions.json"));
doVisionImport(path.resolve("gvision.json"));
ObjectMetadataImportHandler metaHandler = new ObjectMetadataImportHandler(1, this.batchsize);
metaHandler.doImport(path.resolve("metamerge.json"));
TagImportHandler tagHandler = new TagImportHandler(1, 35_000);
tagHandler.doImport(path.resolve("tags.json"));
break;
}
System.out.println(String.format("Completed import of type %s for '%s'.", this.type.toString(), this.input));
}
private void doVisionImport(Path path) {
List<GoogleVisionImportHandler> handlers = new ArrayList<>();
for (GoogleVisionCategory category : GoogleVisionCategory.values()) {
GoogleVisionImportHandler _handler = new GoogleVisionImportHandler(1, 40_000, category, false);
_handler.doImport(path);
handlers.add(_handler);
if (category == GoogleVisionCategory.LABELS || category == GoogleVisionCategory.WEB) {
GoogleVisionImportHandler _handlerTrue = new GoogleVisionImportHandler(1, 40_000, category, true);
_handlerTrue.doImport(path);
handlers.add(_handlerTrue);
}
}
handlers.forEach(GoogleVisionImportHandler::waitForCompletion);
}
/**
* Enum of the available types of data imports.
*/
private enum ImportType {
PROTO, JSON, ASR, OCR, CAPTION, AUDIO, TAGS, VISION, VBS2020, METADATA
}
}
|
package com.BibleQuote.managers.tags.repository;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.BibleQuote.dal.dbLibraryHelper;
import com.BibleQuote.managers.bookmarks.BookmarksTags;
import com.BibleQuote.managers.bookmarks.repository.dbBookmarksTagsRepository;
import com.BibleQuote.managers.tags.Tag;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class dbTagRepository implements ITagRepository {
private final static String TAG = dbTagRepository.class.getSimpleName();
private dbBookmarksTagsRepository bmTagRepo = new dbBookmarksTagsRepository();
@Override
public long add(String tag) {
Log.w(TAG, String.format("Add tag %s", tag));
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
long id = addRow(db, tag);
dbLibraryHelper.closeDB();
return id;
}
@Override
public int update(Tag tag) {
Log.w(TAG, String.format("Update tag %s", tag.name));
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
int result = -1;
try {
ContentValues values = new ContentValues();
values.put(Tag.NAME, tag.name);
String[] whereArgs = new String[1];
whereArgs[0] = String.valueOf(tag.id);
result = db.update(dbLibraryHelper.TAGS_TABLE, values, Tag.KEY_ID + "=?", whereArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return result;
}
@Override
public int delete(Tag tag) {
Log.w(TAG, String.format("Delete tag %s", tag.name));
int result = -1;
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
try {
bmTagRepo.deleteTag(db, tag);
String[] whereArgs = new String[1];
whereArgs[0] = String.valueOf(tag.id);
result = db.delete(dbLibraryHelper.TAGS_TABLE, Tag.KEY_ID + "=?", whereArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return result;
}
@Override
public ArrayList<Tag> getAll() {
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
ArrayList<Tag> result = new ArrayList<Tag>();
try {
result = getAllRowsToArray(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return result;
}
public LinkedHashMap<Tag, String> getAllWithCount() {
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
LinkedHashMap<Tag, String> result = new LinkedHashMap<Tag, String>();
try {
Cursor allRows = db.rawQuery(
"SELECT " + dbLibraryHelper.TAGS_TABLE + "." + Tag.KEY_ID + ", "
+ dbLibraryHelper.TAGS_TABLE + "." + Tag.NAME + ", " +
" COUNT(" + dbLibraryHelper.BOOKMARKSTAGS_TABLE + "." + BookmarksTags.BOOKMARKSTAGS_KEY_ID + ") AS count " +
" FROM " + dbLibraryHelper.TAGS_TABLE + " " +
" LEFT OUTER JOIN " + dbLibraryHelper.BOOKMARKSTAGS_TABLE +
" ON " + dbLibraryHelper.TAGS_TABLE + "." + Tag.KEY_ID +
" = " + dbLibraryHelper.BOOKMARKSTAGS_TABLE + "." + BookmarksTags.BOOKMARKSTAGS_TAG_ID +
" GROUP BY " + dbLibraryHelper.TAGS_TABLE + "." + Tag.KEY_ID +
" ORDER BY " + dbLibraryHelper.TAGS_TABLE + ".name", null);
db.setTransactionSuccessful();
if (allRows.moveToFirst()) {
do {
result.put(new Tag(allRows.getInt(0), allRows.getString(1)), allRows.getString(2));
} while (allRows.moveToNext());
}
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return result;
}
@Override
public int deleteAll() {
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
int result = -1;
try {
result = db.delete(dbLibraryHelper.TAGS_TABLE, null, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return result;
}
@Override
public int deleteEmptyTags() {
SQLiteDatabase db = dbLibraryHelper.getLibraryDB();
db.beginTransaction();
try {
db.execSQL(
"DELETE FROM " + dbLibraryHelper.TAGS_TABLE
+ " WHERE " + Tag.KEY_ID
+ " IN (SELECT " + Tag.KEY_ID + " FROM " + dbLibraryHelper.TAGS_TABLE
+ " WHERE NOT " + Tag.KEY_ID
+ " IN (SELECT " + BookmarksTags.BOOKMARKSTAGS_TAG_ID + " FROM " + dbLibraryHelper.BOOKMARKSTAGS_TABLE + "))");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
dbLibraryHelper.closeDB();
return 0;
}
private ArrayList<Tag> getAllRowsToArray(SQLiteDatabase db) {
ArrayList<Tag> result = new ArrayList<Tag>();
Cursor allRows = db.query(true, dbLibraryHelper.TAGS_TABLE,
null, null, null, null, null, Tag.NAME, null);
if (allRows.moveToFirst()) {
do {
result.add(new Tag(
allRows.getInt(allRows.getColumnIndex(Tag.KEY_ID)),
allRows.getString(allRows.getColumnIndex(Tag.NAME))
)
);
} while (allRows.moveToNext());
}
allRows.close();
return result;
}
private long addRow(SQLiteDatabase db, String tag) {
long result;
db.beginTransaction();
try {
Cursor cur = db.query(dbLibraryHelper.TAGS_TABLE, null, Tag.NAME + "=?", new String[] {tag}, null, null, null);
if (cur.moveToFirst()) {
result = cur.getInt(0);
cur.close();
} else {
ContentValues values = new ContentValues();
values.put(Tag.NAME, tag);
result = db.insert(dbLibraryHelper.TAGS_TABLE, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
}
|
package com.android.phone.settings;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.sip.SipManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.util.Log;
import com.android.phone.R;
import com.android.services.telephony.sip.SipAccountRegistry;
import com.android.services.telephony.sip.SipSharedPreferences;
import com.android.services.telephony.sip.SipUtil;
import java.util.List;
public class PhoneAccountSettingsFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener,
AccountSelectionPreference.AccountSelectionListener {
private static final Intent CONNECTION_SERVICE_CONFIGURE_INTENT =
new Intent(TelecomManager.ACTION_CONNECTION_SERVICE_CONFIGURE)
.addCategory(Intent.CATEGORY_DEFAULT);
private static final String DEFAULT_OUTGOING_ACCOUNT_KEY = "default_outgoing_account";
private static final String CONFIGURE_CALL_ASSISTANT_PREF_KEY =
"wifi_calling_configure_call_assistant_preference";
private static final String CALL_ASSISTANT_CATEGORY_PREF_KEY =
"phone_accounts_call_assistant_settings_category_key";
private static final String SELECT_CALL_ASSISTANT_PREF_KEY =
"wifi_calling_call_assistant_preference";
private static final String SIP_SETTINGS_CATEGORY_PREF_KEY = "phone_accounts_sip_settings_key";
private static final String USE_SIP_PREF_KEY = "use_sip_calling_options_key";
private static final String SIP_RECEIVE_CALLS_PREF_KEY = "sip_receive_calls_key";
private String LOG_TAG = PhoneAccountSettingsFragment.class.getSimpleName();
private TelecomManager mTelecomManager;
private AccountSelectionPreference mDefaultOutgoingAccount;
private AccountSelectionPreference mSelectCallAssistant;
private Preference mConfigureCallAssistant;
private ListPreference mUseSipCalling;
private CheckBoxPreference mSipReceiveCallsPreference;
private SipSharedPreferences mSipSharedPreferences;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mTelecomManager = TelecomManager.from(getActivity());
}
@Override
public void onResume() {
super.onResume();
if (getPreferenceScreen() != null) {
getPreferenceScreen().removeAll();
}
addPreferencesFromResource(com.android.phone.R.xml.phone_account_settings);
mDefaultOutgoingAccount = (AccountSelectionPreference)
getPreferenceScreen().findPreference(DEFAULT_OUTGOING_ACCOUNT_KEY);
if (mTelecomManager.getAllPhoneAccountsCount() > 1) {
mDefaultOutgoingAccount.setListener(this);
updateDefaultOutgoingAccountsModel();
} else {
getPreferenceScreen().removePreference(mDefaultOutgoingAccount);
}
if (!mTelecomManager.getSimCallManagers().isEmpty()) {
mSelectCallAssistant = (AccountSelectionPreference)
getPreferenceScreen().findPreference(SELECT_CALL_ASSISTANT_PREF_KEY);
mSelectCallAssistant.setListener(this);
mSelectCallAssistant.setDialogTitle(
R.string.wifi_calling_select_call_assistant_summary);
mConfigureCallAssistant =
getPreferenceScreen().findPreference(CONFIGURE_CALL_ASSISTANT_PREF_KEY);
mConfigureCallAssistant.setOnPreferenceClickListener(this);
updateCallAssistantModel();
} else {
getPreferenceScreen().removePreference(
getPreferenceScreen().findPreference(CALL_ASSISTANT_CATEGORY_PREF_KEY));
}
if (SipUtil.isVoipSupported(getActivity())) {
mSipSharedPreferences = new SipSharedPreferences(getActivity());
mUseSipCalling = (ListPreference)
getPreferenceScreen().findPreference(USE_SIP_PREF_KEY);
mUseSipCalling.setEntries(!SipManager.isSipWifiOnly(getActivity())
? R.array.sip_call_options_wifi_only_entries
: R.array.sip_call_options_entries);
mUseSipCalling.setOnPreferenceChangeListener(this);
mUseSipCalling.setValueIndex(
mUseSipCalling.findIndexOfValue(mSipSharedPreferences.getSipCallOption()));
mUseSipCalling.setSummary(mUseSipCalling.getEntry());
mSipReceiveCallsPreference = (CheckBoxPreference)
getPreferenceScreen().findPreference(SIP_RECEIVE_CALLS_PREF_KEY);
mSipReceiveCallsPreference.setEnabled(SipUtil.isPhoneIdle(getActivity()));
mSipReceiveCallsPreference.setChecked(
mSipSharedPreferences.isReceivingCallsEnabled());
mSipReceiveCallsPreference.setOnPreferenceChangeListener(this);
} else {
getPreferenceScreen().removePreference(
getPreferenceScreen().findPreference(SIP_SETTINGS_CATEGORY_PREF_KEY));
}
}
/**
* Handles changes to the preferences.
*
* @param pref The preference changed.
* @param objValue The changed value.
* @return True if the preference change has been handled, and false otherwise.
*/
@Override
public boolean onPreferenceChange(Preference pref, Object objValue) {
if (pref == mUseSipCalling) {
String option = objValue.toString();
mSipSharedPreferences.setSipCallOption(option);
mUseSipCalling.setValueIndex(mUseSipCalling.findIndexOfValue(option));
mUseSipCalling.setSummary(mUseSipCalling.getEntry());
return true;
} else if (pref == mSipReceiveCallsPreference) {
final boolean isEnabled = !mSipReceiveCallsPreference.isChecked();
new Thread(new Runnable() {
public void run() {
handleSipReceiveCallsOption(isEnabled);
}
}).start();
return true;
}
return false;
}
@Override
public boolean onPreferenceClick(Preference pref) {
if (pref == mConfigureCallAssistant) {
try {
startActivity(CONNECTION_SERVICE_CONFIGURE_INTENT);
} catch (ActivityNotFoundException e) {
Log.d(LOG_TAG, "Could not resolve telecom connection service configure intent.");
}
return true;
}
return false;
}
/**
* Handles a phone account selection, namely when a call assistant has been selected.
*
* @param pref The account selection preference which triggered the account selected event.
* @param account The account selected.
* @return True if the account selection has been handled, and false otherwise.
*/
@Override
public boolean onAccountSelected(AccountSelectionPreference pref, PhoneAccountHandle account) {
if (pref == mDefaultOutgoingAccount) {
mTelecomManager.setUserSelectedOutgoingPhoneAccount(account);
return true;
} else if (pref == mSelectCallAssistant) {
mTelecomManager.setSimCallManager(account);
return true;
}
return false;
}
/**
* Repopulate the dialog to pick up changes before showing.
*
* @param pref The account selection preference dialog being shown.
*/
@Override
public void onAccountSelectionDialogShow(AccountSelectionPreference pref) {
if (pref == mDefaultOutgoingAccount) {
updateDefaultOutgoingAccountsModel();
} else if (pref == mSelectCallAssistant) {
updateCallAssistantModel();
}
}
/**
* Update the configure preference summary when the call assistant changes.
*/
@Override
public void onAccountChanged(AccountSelectionPreference pref) {
if (pref == mSelectCallAssistant) {
updateConfigureCallAssistantSummary();
}
}
private synchronized void handleSipReceiveCallsOption(boolean isEnabled) {
mSipSharedPreferences.setReceivingCallsEnabled(isEnabled);
SipUtil.useSipToReceiveIncomingCalls(getActivity(), isEnabled);
// Restart all Sip services to ensure we reflect whether we are receiving calls.
SipAccountRegistry sipAccountRegistry = SipAccountRegistry.getInstance();
sipAccountRegistry.restartSipService(getActivity());
}
/**
* Queries the telcomm manager to update the default outgoing account selection preference
* with the list of outgoing accounts and the current default outgoing account.
*/
private void updateDefaultOutgoingAccountsModel() {
mDefaultOutgoingAccount.setModel(
mTelecomManager,
mTelecomManager.getCallCapablePhoneAccounts(),
mTelecomManager.getUserSelectedOutgoingPhoneAccount(),
getString(R.string.phone_accounts_ask_every_time));
}
/**
* Queries the telecomm manager to update the account selection preference with the list of
* call assistants, and the currently selected call assistant.
*/
public void updateCallAssistantModel() {
List<PhoneAccountHandle> simCallManagers = mTelecomManager.getSimCallManagers();
mSelectCallAssistant.setModel(
mTelecomManager,
simCallManagers,
mTelecomManager.getSimCallManager(),
getString(R.string.wifi_calling_call_assistant_none));
updateConfigureCallAssistantSummary();
}
/**
* Updates the summary on the "configure call assistant" preference. If it is the last entry,
* show the summary for when no call assistant is selected. Otherwise, display the currently
* selected call assistant.
*/
private void updateConfigureCallAssistantSummary() {
if (mSelectCallAssistant.getEntries().length - 1
== mSelectCallAssistant.findIndexOfValue(mSelectCallAssistant.getValue())) {
mConfigureCallAssistant.setSummary(
R.string.wifi_calling_call_assistant_configure_no_selection);
mConfigureCallAssistant.setEnabled(false);
} else {
mConfigureCallAssistant.setSummary(null);
mConfigureCallAssistant.setEnabled(true);
}
}
}
|
package alexsong.com.snake;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import jp.wasabeef.blurry.Blurry;
public class GameActivity extends AppCompatActivity {
public enum DIRECTION { LEFT, RIGHT, UP, DOWN }
public Context thisContext = this;
public TableLayout gameTable;
public SnakeNode snakeHead;
public Random random = new Random();
public int foodX = 0;
public int foodY = 0;
public List<int[]> goldList = new ArrayList<>();
public List<int[]> forbiddenList = new ArrayList<>();
public DIRECTION currDirection;
private Handler handler = new Handler();
private Runnable gameStartTask;
private Runnable countdownTask;
private TextView countdownView;
private int countdownNum = 4;
private static final int TABLE_WIDTH = 21;
private static final int TABLE_HEIGHT = 25;
private static final int SNAKE_START_X = TABLE_HEIGHT/2;
private static final int SNAKE_START_Y = TABLE_WIDTH/2;
private static final int GOLD_RANGE = 5;
private static final int GOLD_BONUS = 2;
private static final int FOOD_IMAGE = R.drawable.food_3;
private static final int GOLD_IMAGE = R.drawable.gold_2;
private static final int BACKGROUND_TILE = R.drawable.background_tile_2;
public static int SNAKE_IMAGE = R.drawable.snake_1;
public static int speed = SettingsActivity.NORMAL;
public TextView scoreView;
public int score = 0;
private boolean gameOver = false;
private boolean snakeStopped = false;
private boolean startup = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// Set custom font
scoreView = (TextView) findViewById(R.id.score);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Fipps-Regular.otf");
scoreView.setTypeface(font);
// Set speed, if already selected
SharedPreferences sharedPref = getSharedPreferences("Settings", MODE_PRIVATE);
int value = sharedPref.getInt("speedDropdown", -1);
if(value != -1) {
if (value == 0) {
GameActivity.speed = SettingsActivity.SLOW;
} else if (value == 1) {
GameActivity.speed = SettingsActivity.NORMAL;
} else if (value == 2) {
GameActivity.speed = SettingsActivity.FAST;
}
}
// Set snake color, if already selected
boolean greenBtnClicked = sharedPref.getBoolean("greenSnake", true);
boolean pinkBtnClicked = sharedPref.getBoolean("pinkSnake", true);
if(greenBtnClicked) {
SNAKE_IMAGE = R.drawable.snake_1;
} else if(pinkBtnClicked) {
SNAKE_IMAGE = R.drawable.snake_2;
}
forbiddenList.add(new int[]{SNAKE_START_X, SNAKE_START_Y});
generateFoodLocation();
createGameTable();
int index = random.nextInt(4);
currDirection = DIRECTION.values()[index];
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus) {
ViewGroup viewgroup = (ViewGroup) findViewById(android.R.id.content);
Blurry.with(this).radius(8).sampling(3).onto(viewgroup);
countdownView = new TextView(this);
countdownView.setText(String.valueOf(countdownNum));
countdownView.setTextSize(120);
countdownView.setTextColor(Color.WHITE);
countdownView.setGravity(Gravity.CENTER);
viewgroup.addView(countdownView);
startup = true;
countDown();
}
}
@Override
public void onBackPressed() {
if(startup) {
finishGame();
} else if(!gameOver) {
pauseGame();
} else {
finishGame();
}
}
/**
* Create the table where the game will be played.
*/
private void createGameTable() {
gameTable = (TableLayout) findViewById(R.id.gameTable);
gameTable.setStretchAllColumns(true);
for(int i = 0; i < TABLE_HEIGHT; i++) {
TableRow row = new TableRow(this);
row.setId(i);
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(tableParams);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT);
//rowParams.setMargins(10,10,10,10);
for(int j = 0; j < TABLE_WIDTH; j++) {
ImageView cellView = new ImageView(this);
cellView.setLayoutParams(rowParams);
cellView.setTag(new TableCell(i, j));
// Add snake to starting cell
if(i == SNAKE_START_X && j == SNAKE_START_Y) {
cellView.setImageResource(SNAKE_IMAGE);
snakeHead = new SnakeNode(cellView);
}
else {
// Add Food to a cell
if (i == foodX && j == foodY) {
cellView.setImageResource(FOOD_IMAGE);
}
// Add background tile to all other cells
else {
cellView.setImageResource(BACKGROUND_TILE);
}
}
cellView.setScaleType(ImageView.ScaleType.FIT_XY);
row.addView(cellView);
}
gameTable.addView(row);
}
}
/**
* Countdown before starting game
*/
private void countDown() {
countdownTask = new Runnable() {
@Override
public void run() {
if(!gameOver) {
countdownNum
if(countdownNum > 0) {
countdownView.setText(String.valueOf(countdownNum));
handler.postDelayed(countdownTask, 800);
} else {
countdownView.setVisibility(View.GONE);
startup = false;
snakeStopped = false;
Blurry.delete((ViewGroup) findViewById(android.R.id.content));
startSnake();
setSwipeListener();
}
}
}
};
countdownTask.run();
}
/**
* Start moving the snake by repeatedly calling moveSnake
*/
private void startSnake() {
gameOver = false;
snakeStopped = false;
gameStartTask = new Runnable() {
@Override
public void run() {
if(!snakeStopped) {
boolean validStatus = moveSnake();
if(validStatus) {
handler.postDelayed(gameStartTask, speed);
} else {
gameOver = true;
Toast.makeText(thisContext, "GAME OVER", Toast.LENGTH_SHORT).show();
}
}
}
};
gameStartTask.run();
}
/**
* Pause the game
*/
private void pauseGame() {
snakeStopped = true;
ViewGroup viewgroup = (ViewGroup) findViewById(android.R.id.content);
Blurry.with(this).radius(8).sampling(3).onto(viewgroup);
TextView pausedTextView = new TextView(this);
pausedTextView.setText("Quit game?");
pausedTextView.setTextSize(30);
pausedTextView.setPadding(0,100,0,0);
pausedTextView.setTextColor(Color.BLACK);
pausedTextView.setGravity(Gravity.CENTER);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(pausedTextView);
builder.setCancelable(false);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
gameOver = true;
snakeStopped = true;
GameActivity.this.finish();
dialog.cancel();
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Blurry.delete((ViewGroup) findViewById(android.R.id.content));
gameStartTask.run();
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Finish game and go back to landing page
*/
public void finishGame() {
gameOver = true;
snakeStopped = true;
countdownNum = 4;
this.finish();
}
/**
* Move the snake to the next cell. The direction is indicated by currDirection.
* It returns whether or not the snake is still in a valid state after moving
* @return boolean
*/
public boolean moveSnake() {
TableCell currCell = (TableCell) snakeHead.getView().getTag();
ViewGroup row = (ViewGroup) snakeHead.getView().getParent();
int currX = currCell.getX();
int currY = currCell.getY();
int[] xyDirection = setDirection();
int xdelta = xyDirection[0];
int ydelta = xyDirection[1];
currX += xdelta;
currY += ydelta;
// return false if the snake head goes out of bounds or hits its body
if(!inBounds(currX, currY) || hasHitBody(currX, currY)) {
return false;
}
row = (ViewGroup) gameTable.getChildAt(row.getId()+xdelta);
ImageView newCellView = (ImageView) row.getChildAt(currY);
newCellView.setImageResource(SNAKE_IMAGE);
forbiddenList.add(new int[]{currX, currY});
SnakeNode newSnakeHead = new SnakeNode(newCellView);
newSnakeHead.setNext(snakeHead);
SnakeNode prev = newSnakeHead;
SnakeNode curr = snakeHead;
while(curr.getNext() != null) {
prev = curr;
curr = curr.getNext();
}
boolean foundFood = (currX == foodX && currY == foodY);
// The next cell has the food - generate a new food location and update the score
if(foundFood) {
generateFoodLocation();
updateFoodLocation();
updateScore();
if(score > 0 && score%GOLD_RANGE == 0) {
generateNewGold();
}
}
// No food was found, - remove snake tail and remove its location from forbiddenList
else {
curr.getView().setImageResource(BACKGROUND_TILE);
int tailX = ((TableCell) curr.getView().getTag()).getX();
int tailY = ((TableCell) curr.getView().getTag()).getY();
removeFromForbiddenList(tailX, tailY);
prev.setNext(null);
}
for(int[] gCell : goldList) {
// Found gold
if(currX == gCell[0] && currY == gCell[1]) {
// Vibrate phone if snake hits gold
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
// remove gold from goldList and reduce snake size
goldList.remove(gCell);
reduceSnakeSize();
break;
}
}
snakeHead = newSnakeHead;
return true;
}
/**
* Set the x and y direction that the snake should move, based on currentDirection.
* @return an array with xdelta at index 0 and ydelta at index 1.
*/
private int[] setDirection() {
int ydelta = 0;
int xdelta = 0;
switch (currDirection) {
case LEFT:
ydelta = -1;
break;
case RIGHT:
ydelta = 1;
break;
case UP:
xdelta = -1;
break;
case DOWN:
xdelta = 1;
break;
}
return new int[] {xdelta, ydelta};
}
/**
* Check if Snake is inside the gameTable
* @param x x coordinate of the snake
* @param y y coordinate of the snake
* @return boolean
*/
private boolean inBounds(int x, int y) {
return (x >= 0 && x < TABLE_HEIGHT && y >= 0 && y < TABLE_WIDTH);
}
/**
* Check if Snake has hit its own body
* @param x x coordinate of the snake
* @param y y coordinate of the snake
* @return boolean whether or not the snake head has hit the body
*/
private boolean hasHitBody(int x, int y) {
for(int[] cell : forbiddenList) {
if(cell[0] == x && cell[1] == y) {
return true;
}
}
return false;
}
/**
* Remove the location indicated by the x and y coordinates from the forbidden list
* @param x x coordinate of cell to remove
* @param y y coordinate of cell to remove
*/
private void removeFromForbiddenList(int x, int y) {
for(int[] cell : forbiddenList) {
if(cell[0] == x && cell[1] == y) {
forbiddenList.remove(cell);
break;
}
}
}
/**
* Reduce the size of the snake when it eats a gold
*/
private void reduceSnakeSize() {
SnakeNode curr = snakeHead;
SnakeNode prev = curr;
for(int i = 0; i < forbiddenList.size()-(1+GOLD_BONUS); i++) {
prev = curr;
curr = curr.getNext();
}
prev.setNext(null);
while(curr != null) {
ImageView view = curr.getView();
TableCell cell = (TableCell) view.getTag();
view.setImageResource(BACKGROUND_TILE);
removeFromForbiddenList(cell.getX(), cell.getY());
curr = curr.getNext();
}
}
/**
* Generate random x and y coordinates for the food.
*/
private void generateFoodLocation() {
int lastX = foodX;
int lastY = foodY;
while(true) {
foodX = random.nextInt(TABLE_HEIGHT);
foodY = random.nextInt(TABLE_WIDTH);
// check if food location is same as before
boolean isSame = (foodX == lastX && foodY == lastY);
// check if food location is same as a gold
boolean hitGold = false;
for(int[] gCell : goldList) {
if(gCell[0] == foodX && gCell[1] == foodY) {
hitGold = true;
break;
}
}
// check if food location hits the snake
boolean hitSnake = false;
for(int[] cell : forbiddenList) {
if((cell[0] == foodX && cell[1] == foodY)) {
hitSnake = true;
break;
}
}
// break out of loop if the new position does not conflict with any of the cases
if(!isSame && !hitGold && !hitSnake) {
break;
}
}
}
/**
* Add the food to a new location on the game table
*/
private void updateFoodLocation() {
ViewGroup newFoodRow = (ViewGroup) gameTable.getChildAt(foodX);
ImageView newFoodCell = (ImageView) newFoodRow.getChildAt(foodY);
newFoodCell.setImageResource(FOOD_IMAGE);
}
/**
* Generate random x and y coordinates for the gold and add it to the goldList and game map.
*/
private void generateNewGold() {
int goldX;
int goldY;
while(true) {
goldX = random.nextInt(TABLE_HEIGHT);
goldY = random.nextInt(TABLE_WIDTH);
// check if gold location is same as the food
boolean hitFood = false;
if (goldX == foodX && goldY == foodY) {
hitFood = true;
}
// check if gold location is part of the snake's body
boolean hitSnake = false;
for (int[] cell : forbiddenList) {
if (goldX == cell[0] && goldY == cell[1]) {
hitSnake = true;
break;
}
}
// check if gold location is already in goldList
boolean alreadyExists = false;
for (int[] gCell : goldList) {
if (goldX == gCell[0] && goldY == gCell[1]) {
alreadyExists = true;
break;
}
}
// break out of loop if the new position does not conflict with any of the cases
if (!hitFood && !hitSnake && !alreadyExists) {
break;
}
}
ViewGroup newGoldRow = (ViewGroup) gameTable.getChildAt(goldX);
ImageView newFoodCell = (ImageView) newGoldRow.getChildAt(goldY);
newFoodCell.setImageResource(GOLD_IMAGE);
goldList.add(new int[]{goldX, goldY});
}
/**
* Update the current score
*/
private void updateScore() {
score++;
scoreView.setText(String.valueOf(score));
}
/**
* Set listener to screen for swipe gestures
*/
private void setSwipeListener() {
View rootView = getWindow().getDecorView().getRootView();
rootView.setOnTouchListener(new OnSwipeTouchListener(this) {
public void onSwipeLeft() {
int forbiddenListSize = forbiddenList.size();
if(forbiddenListSize == 1 || (forbiddenListSize > 1 && currDirection != DIRECTION.RIGHT)) {
currDirection = DIRECTION.LEFT;
}
}
public void onSwipeRight() {
int forbiddenListSize = forbiddenList.size();
if(forbiddenListSize == 1 || (forbiddenListSize > 1 && currDirection != DIRECTION.LEFT)) {
currDirection = DIRECTION.RIGHT;
}
}
public void onSwipeTop() {
int forbiddenListSize = forbiddenList.size();
if(forbiddenListSize == 1 || (forbiddenListSize > 1 && currDirection != DIRECTION.DOWN)) {
currDirection = DIRECTION.UP;
}
}
public void onSwipeBottom() {
int forbiddenListSize = forbiddenList.size();
if(forbiddenListSize == 1 || (forbiddenListSize > 1 && currDirection != DIRECTION.UP)) {
currDirection = DIRECTION.DOWN;
}
}
});
}
}
|
package edu.umass.cs.ciir.waltz.coders.sorter;
import ciir.jfoley.chai.collections.list.IntList;
import ciir.jfoley.chai.collections.util.MapFns;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author jfoley
*/
public class GeometricItemMerger {
public static final ExecutorService asyncExec = ForkJoinPool.commonPool();
public static final int DEFAULT_MERGE_FACTOR = 10;
public static final boolean useThreads = true; // almost 2x slower building positions on robust without this
final MergeFn mergeFn;
// Logical size only: 0: [...], 1: [...] ... whenever we get 10 level 0s we upgrade them to a level 1... etc.
final Map<Integer, List<Integer>> itemsByLevel;
AtomicInteger liveJobs;
protected final int mergeFactor;
private int nextId;
public GeometricItemMerger(int mergeFactor, MergeFn mergeFn) {
this.mergeFactor = mergeFactor;
nextId = 0;
liveJobs = new AtomicInteger(0);
itemsByLevel = new ConcurrentHashMap<>();
this.mergeFn = mergeFn;
}
public synchronized void doAsync(Runnable r) {
liveJobs.incrementAndGet();
if(useThreads) {
asyncExec.submit(() -> {
try {
r.run();
} catch (Throwable err) {
System.err.println("Error on live-job:");
err.printStackTrace(System.err);
}
liveJobs.decrementAndGet();
});
} else {
r.run();
liveJobs.decrementAndGet();
}
}
public synchronized int allocate() {
return nextId++;
}
public synchronized void insert(int id, int level) {
MapFns.extendListInMap(itemsByLevel, level, id);
}
public void addNewItem(int itemId) {
insert(itemId, 0);
}
public void close() throws IOException {
finish();
}
public void finish() throws IOException {
do {
checkIfWeCanMergeItems();
try {
Thread.sleep(100);
} catch (InterruptedException ignored) { }
} while(liveJobs.get() > 0);
}
public void waitForCurrentJobs() {
while(liveJobs.get() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) { }
}
}
public IntList getFinalItems() throws IOException {
finish();
IntList total = new IntList();
for (List<Integer> liveIds : itemsByLevel.values()) {
total.addAll(liveIds);
}
return total;
}
public synchronized void checkIfWeCanMergeItems() throws IOException {
while(true) {
boolean changed = false;
for (Map.Entry<Integer, List<Integer>> kv : itemsByLevel.entrySet()) {
int level = kv.getKey();
List<Integer> runs = kv.getValue();
if (runs.size() >= mergeFactor) {
itemsByLevel.remove(level);
doAsync(() -> {
try {
int newId = allocate();
mergeFn.apply(runs, newId);
insert(newId, level+1);
} catch (Throwable e) {
e.printStackTrace(System.err);
throw new RuntimeException(e);
}
});
changed = true;
break;
}
}
if(!changed) break;
}
}
public interface MergeFn {
void apply(List<Integer> inputs, int output) throws IOException;
}
}
|
package com.i906.mpt.alarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import com.i906.mpt.BuildConfig;
import com.i906.mpt.date.DateTimeHelper;
import com.i906.mpt.extension.Extension;
import com.i906.mpt.internal.Dagger;
import com.i906.mpt.internal.ServiceModule;
import com.i906.mpt.prayer.Prayer;
import com.i906.mpt.prayer.PrayerContext;
import com.i906.mpt.prayer.PrayerManager;
import com.i906.mpt.prefs.NotificationPreferences;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;
import static android.os.Build.VERSION.SDK_INT;
/**
* @author Noorzaini Ilhami
*/
public class AlarmService extends Service {
public static final String ACTION_UPDATE_REMINDER = BuildConfig.APPLICATION_ID + ".action.ACTION_UPDATE_REMINDER";
public static final String ACTION_NOTIFICATION_PRAYER = BuildConfig.APPLICATION_ID + ".action.NOTIFICATION_PRAYER";
public static final String ACTION_NOTIFICATION_REMINDER = BuildConfig.APPLICATION_ID + ".action.NOTIFICATION_REMINDER";
public static final String ACTION_NOTIFICATION_CANCEL = BuildConfig.APPLICATION_ID + ".action.NOTIFICATION_CANCEL";
public static final String EXTRA_PRAYER_INDEX = "prayer_index";
public static final String EXTRA_PRAYER_TIME = "prayer_time";
public static final String EXTRA_PRAYER_LOCATION = "prayer_location";
private final CompositeSubscription mSubscription = new CompositeSubscription();
private AlarmManager mAlarmManager;
private PrayerContext mPrayerContext;
private Deque<Pair<String, Integer>> mQueue = new ArrayDeque<>();
@Inject
DateTimeHelper mDateHelper;
@Inject
NotificationPreferences mNotificationPreferences;
@Inject
NotificationHelper mNotificationHelper;
@Inject
PrayerManager mPrayerManager;
@Override
public void onCreate() {
super.onCreate();
Dagger.getGraph(this)
.serviceGraph(new ServiceModule(this))
.inject(this);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
startObservable();
}
private void startObservable() {
Subscription s = mPrayerManager.getPrayerContext(false)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<PrayerContext>() {
@Override
public void call(PrayerContext prayerContext) {
handleUpdatedPrayerContext(prayerContext);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Timber.w(throwable, "Unable to get prayer context.");
stopSelf();
}
});
mSubscription.add(s);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
final String action = intent.getAction();
if (mPrayerContext == null) {
mQueue.add(Pair.create(action, startId));
} else {
handleAction(action, mPrayerContext, startId);
}
return START_STICKY;
}
stopSelf();
return START_NOT_STICKY;
}
private void handleUpdatedPrayerContext(PrayerContext prayerContext) {
mPrayerContext = prayerContext;
while (!mQueue.isEmpty()) {
Pair<String, Integer> pair = mQueue.remove();
handleAction(pair.first, mPrayerContext, pair.second);
}
}
private void handleAction(String action, PrayerContext prayerContext, int startId) {
if (Extension.ACTION_PRAYER_CONTEXT_UPDATED.equals(action)) {
setupInitialAlarm(prayerContext);
stopSelf(startId);
} else if (ACTION_UPDATE_REMINDER.equals(action)) {
updateReminderAlarm(prayerContext, startId);
}
}
private void setupInitialAlarm(PrayerContext prayerContext) {
Prayer next = prayerContext.getNextPrayer();
String location = prayerContext.getLocationName();
long appearBefore = mNotificationPreferences.getAppearBeforeDuration();
long alarmOffset = mNotificationPreferences.getAlarmOffset();
long clearAfter = mNotificationPreferences.getClearAfterDuration();
long reminderTime = -appearBefore + alarmOffset;
long notificationTime = alarmOffset + 250;
long clearTime = clearAfter + alarmOffset;
int npi = next.getIndex();
long npt = next.getDate().getTime();
if (appearBefore > 0) {
setAlarm(ACTION_NOTIFICATION_REMINDER, npi, npt, reminderTime, location);
}
setAlarm(ACTION_NOTIFICATION_PRAYER, npi, npt, notificationTime, location);
if (clearAfter > 0) {
setAlarm(ACTION_NOTIFICATION_CANCEL, npi, npt, clearTime, location);
}
}
private void updateReminderAlarm(PrayerContext prayerContext, final int startId) {
Prayer next = prayerContext.getNextPrayer();
final String location = prayerContext.getLocationName();
long appearBefore = mNotificationPreferences.getAppearBeforeDuration();
final long alarmOffset = mNotificationPreferences.getAlarmOffset();
int updates = (int) (appearBefore / 60000);
final int npi = next.getIndex();
final long npt = next.getDate().getTime();
Subscription s = Observable.range(0, updates)
.concatMap(new Func1<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> call(Integer integer) {
long initial = integer == 0 ? 0 : TimeUnit.MINUTES.toMillis(1);
long delay = initial + alarmOffset;
return Observable.just(integer)
.delay(delay, TimeUnit.MILLISECONDS);
}
})
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
mNotificationHelper.showPrayerReminder(npi, npt, location, integer == 0);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Timber.w(throwable);
}
}, new Action0() {
@Override
public void call() {
stopSelf(startId);
}
});
mSubscription.add(s);
}
private void setAlarm(String action, int index, long time, long triggerOffset, String location) {
Intent i = createIntent(action, index, time, location);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
if (SDK_INT < Build.VERSION_CODES.M) {
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, time + triggerOffset, pi);
} else {
mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time + triggerOffset, pi);
}
Timber.i("Created alarm %s: %s %s %s", index, action, new Date(time + triggerOffset), location);
}
private Intent createIntent(String action, int index, long time, String location) {
Intent h = new Intent(this, AlarmReceiver.class);
h.setAction(action);
h.setData(Uri.parse("mpt://" + action + "/" + index));
h.putExtra(EXTRA_PRAYER_INDEX, index);
h.putExtra(EXTRA_PRAYER_TIME, time);
h.putExtra(EXTRA_PRAYER_LOCATION, location);
return h;
}
@Override
public void onDestroy() {
super.onDestroy();
mSubscription.clear();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
|
package org.gnucash.android.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import org.gnucash.android.db.adapter.AccountsDbAdapter;
import java.sql.Timestamp;
/**
* A split amount in a transaction.
* Every transaction is made up of at least two splits (representing a double entry transaction)
* <p>The split amount is always stored in the database as the absolute value alongside its transaction type of CREDIT/DEBIT<br/>
* This is independent of the negative values which are shown in the UI (for user convenience).
* The actual movement of the balance in the account depends on the type of normal balance of the account and the
* transaction type of the split.</p>
*
* @author Ngewi Fet <ngewif@gmail.com>
*/
public class Split extends BaseModel implements Parcelable{
/**
* Flag indicating that the split has been reconciled
*/
public static final char FLAG_RECONCILED = 'y';
/**
* Flag indicating that the split has not been reconciled
*/
public static final char FLAG_NOT_RECONCILED = 'n';
/**
* Flag indicating that the split has been cleared, but not reconciled
*/
public static final char FLAG_CLEARED = 'c';
/**
* Amount value of this split which is in the currency of the transaction
*/
private Money mValue;
/**
* Amount of the split in the currency of the account to which the split belongs
*/
private Money mQuantity;
/**
* Transaction UID which this split belongs to
*/
private String mTransactionUID = "";
/**
* Account UID which this split belongs to
*/
private String mAccountUID;
/**
* The type of this transaction, credit or debit
*/
private TransactionType mSplitType = TransactionType.CREDIT;
/**
* Memo associated with this split
*/
private String mMemo;
private char mReconcileState = FLAG_NOT_RECONCILED;
/**
* Database required non-null field
*/
private Timestamp mReconcileDate = new Timestamp(System.currentTimeMillis());
/**
* Initialize split with a value amount and account
* @param value Money value amount of this split
* @param accountUID String UID of transfer account
*/
public Split(@NonNull Money value, @NonNull Money quantity, String accountUID){
setQuantity(quantity);
setValue(value);
setAccountUID(accountUID);
//NOTE: This is a rather simplististic approach to the split type.
//It typically also depends on the account type of the account. But we do not want to access
//the database everytime a split is created. So we keep it simple here. Set the type you want explicity.
mSplitType = value.isNegative() ? TransactionType.DEBIT : TransactionType.CREDIT;
}
/**
* Initialize split with a value amount and account
* @param amount Money value amount of this split. Value is always in the currency the owning transaction.
* This amount will be assigned as both the value and the quantity of this split
* @param accountUID String UID of owning account
*/
public Split(@NonNull Money amount, String accountUID){
this(amount, new Money(amount), accountUID);
}
/**
* Clones the <code>sourceSplit</code> to create a new instance with same fields
* @param sourceSplit Split to be cloned
* @param generateUID Determines if the clone should have a new UID or should maintain the one from source
*/
public Split(Split sourceSplit, boolean generateUID){
this.mMemo = sourceSplit.mMemo;
this.mAccountUID = sourceSplit.mAccountUID;
this.mSplitType = sourceSplit.mSplitType;
this.mTransactionUID = sourceSplit.mTransactionUID;
this.mValue = new Money(sourceSplit.mValue);
this.mQuantity = new Money(sourceSplit.mQuantity);
//todo: clone reconciled status
if (generateUID){
generateUID();
} else {
setUID(sourceSplit.getUID());
}
}
/**
* Returns the value amount of the split
* @return Money amount of the split with the currency of the transaction
* @see #getQuantity()
*/
public Money getValue() {
return mValue;
}
/**
* Sets the value amount of the split.<br>
* The value is in the currency of the containing transaction
* @param value Money value of this split
* @see #setQuantity(Money)
*/
public void setValue(Money value) {
mValue = value;
}
/**
* Returns the quantity amount of the split.
* <p>The quantity is in the currency of the account to which the split is associated</p>
* @return Money quantity amount
* @see #getValue()
*/
public Money getQuantity() {
return mQuantity;
}
/**
* Sets the quantity value of the split
* @param quantity Money quantity amount
* @see #setValue(Money)
*/
public void setQuantity(Money quantity) {
this.mQuantity = quantity;
}
/**
* Returns transaction GUID to which the split belongs
* @return String GUID of the transaction
*/
public String getTransactionUID() {
return mTransactionUID;
}
/**
* Sets the transaction to which the split belongs
* @param transactionUID GUID of transaction
*/
public void setTransactionUID(String transactionUID) {
this.mTransactionUID = transactionUID;
}
/**
* Returns the account GUID of this split
* @return GUID of the account
*/
public String getAccountUID() {
return mAccountUID;
}
/**
* Sets the GUID of the account of this split
* @param accountUID GUID of account
*/
public void setAccountUID(String accountUID) {
this.mAccountUID = accountUID;
}
/**
* Returns the type of the split
* @return {@link TransactionType} of the split
*/
public TransactionType getType() {
return mSplitType;
}
/**
* Sets the type of this split
* @param splitType Type of the split
*/
public void setType(TransactionType splitType) {
this.mSplitType = splitType;
}
/**
* Returns the memo of this split
* @return String memo of this split
*/
public String getMemo() {
return mMemo;
}
/**
* Sets this split memo
* @param memo String memo of this split
*/
public void setMemo(String memo) {
this.mMemo = memo;
}
/**
* Creates a split which is a pair of this instance.
* A pair split has all the same attributes except that the SplitType is inverted and it belongs
* to another account.
* @param accountUID GUID of account
* @return New split pair of current split
* @see TransactionType#invert()
*/
public Split createPair(String accountUID){
Split pair = new Split(mValue.abs(), accountUID);
pair.setType(mSplitType.invert());
pair.setMemo(mMemo);
pair.setTransactionUID(mTransactionUID);
pair.setQuantity(mQuantity);
return pair;
}
/**
* Clones this split and returns an exact copy.
* @return New instance of a split which is a copy of the current one
*/
protected Split clone() throws CloneNotSupportedException {
super.clone();
Split split = new Split(mValue, mAccountUID);
split.setUID(getUID());
split.setType(mSplitType);
split.setMemo(mMemo);
split.setTransactionUID(mTransactionUID);
split.setQuantity(mQuantity);
return split;
}
/**
* Checks is this <code>other</code> is a pair split of this.
* <p>Two splits are considered a pair if they have the same amount and opposite split types</p>
* @param other the other split of the pair to be tested
* @return whether the two splits are a pair
*/
public boolean isPairOf(Split other) {
return mValue.abs().equals(other.mValue.abs())
&& mSplitType.invert().equals(other.mSplitType);
}
/**
* Returns the formatted amount (with or without negation sign) for the split value
* @return Money amount of value
* @see #getFormattedAmount(Money, String, TransactionType)
*/
public Money getFormattedValue(){
return getFormattedAmount(mValue, mAccountUID, mSplitType);
}
/**
* Returns the formatted amount (with or without negation sign) for the quantity
* @return Money amount of quantity
* @see #getFormattedAmount(Money, String, TransactionType)
*/
public Money getFormattedQuantity(){
return getFormattedAmount(mQuantity, mAccountUID, mSplitType);
}
/**
* Splits are saved as absolute values to the database, with no negative numbers.
* The type of movement the split causes to the balance of an account determines its sign, and
* that depends on the split type and the account type
* @param amount Money amount to format
* @param accountUID GUID of the account
* @param splitType Transaction type of the split
* @return -{@code amount} if the amount would reduce the balance of {@code account}, otherwise +{@code amount}
*/
public static Money getFormattedAmount(Money amount, String accountUID, TransactionType splitType){
boolean isDebitAccount = AccountsDbAdapter.getInstance().getAccountType(accountUID).hasDebitNormalBalance();
Money absAmount = amount.abs();
boolean isDebitSplit = splitType == TransactionType.DEBIT;
if (isDebitAccount) {
if (isDebitSplit) {
return absAmount;
} else {
return absAmount.negate();
}
} else {
if (isDebitSplit) {
return absAmount.negate();
} else {
return absAmount;
}
}
}
/**
* Return the reconciled state of this split
* <p>
* The reconciled state is one of the following values:
* <ul>
* <li><b>y</b>: means this split has been reconciled</li>
* <li><b>n</b>: means this split is not reconciled</li>
* <li><b>c</b>: means split has been cleared, but not reconciled</li>
* </ul>
* </p> <br>
* You can check the return value against the reconciled flags {@link #FLAG_RECONCILED}, {@link #FLAG_NOT_RECONCILED}, {@link #FLAG_CLEARED}
* @return Character showing reconciled state
*/
public char getReconcileState() {
return mReconcileState;
}
/**
* Check if this split is reconciled
* @return {@code true} if the split is reconciled, {@code false} otherwise
*/
public boolean isReconciled(){
return mReconcileState == FLAG_RECONCILED;
}
/**
* Set reconciled state of this split.
* <p>
* The reconciled state is one of the following values:
* <ul>
* <li><b>y</b>: means this split has been reconciled</li>
* <li><b>n</b>: means this split is not reconciled</li>
* <li><b>c</b>: means split has been cleared, but not reconciled</li>
* </ul>
* </p>
* @param reconcileState One of the following flags {@link #FLAG_RECONCILED}, {@link #FLAG_NOT_RECONCILED}, {@link #FLAG_CLEARED}
*/
public void setReconcileState(char reconcileState) {
this.mReconcileState = reconcileState;
}
/**
* Return the date of reconciliation
* @return Timestamp
*/
public Timestamp getReconcileDate() {
return mReconcileDate;
}
/**
* Set reconciliation date for this split
* @param reconcileDate Timestamp of reconciliation
*/
public void setReconcileDate(Timestamp reconcileDate) {
this.mReconcileDate = reconcileDate;
}
@Override
public String toString() {
return mSplitType.name() + " of " + mValue.toString() + " in account: " + mAccountUID;
}
/**
* Returns a string representation of the split which can be parsed again using {@link org.gnucash.android.model.Split#parseSplit(String)}
* <p>The string is formatted as:<br/>
* "<uid>;<valueNum>;<valueDenom>;<valueCurrencyCode>;<quantityNum>;<quantityDenom>;<quantityCurrencyCode>;<transaction_uid>;<account_uid>;<type>;<memo>"
* </p>
* <p><b>Only the memo field is allowed to be null</b></p>
* @return the converted CSV string of this split
*/
public String toCsv(){
String sep = ";";
//TODO: add reconciled state and date
String splitString = getUID() + sep + mValue.getNumerator() + sep + mValue.getDenominator()
+ sep + mValue.getCommodity().getCurrencyCode() + sep + mQuantity.getNumerator()
+ sep + mQuantity.getDenominator() + sep + mQuantity.getCommodity().getCurrencyCode()
+ sep + mTransactionUID + sep + mAccountUID + sep + mSplitType.name();
if (mMemo != null){
splitString = splitString + sep + mMemo;
}
return splitString;
}
/**
* Parses a split which is in the format:<br/>
* "<uid>;<valueNum>;<valueDenom>;<currency_code>;<quantityNum>;<quantityDenom>;<currency_code>;<transaction_uid>;<account_uid>;<type>;<memo>".
* <p>Also supports parsing of the deprecated format "<amount>;<currency_code>;<transaction_uid>;<account_uid>;<type>;<memo>".
* The split input string is the same produced by the {@link Split#toCsv()} method
*</p>
* @param splitCsvString String containing formatted split
* @return Split instance parsed from the string
*/
public static Split parseSplit(String splitCsvString) {
//TODO: parse reconciled state and date
String[] tokens = splitCsvString.split(";");
if (tokens.length < 8) { //old format splits
Money amount = new Money(tokens[0], tokens[1]);
Split split = new Split(amount, tokens[2]);
split.setTransactionUID(tokens[3]);
split.setType(TransactionType.valueOf(tokens[4]));
if (tokens.length == 6) {
split.setMemo(tokens[5]);
}
return split;
} else {
long valueNum = Long.parseLong(tokens[1]);
long valueDenom = Long.parseLong(tokens[2]);
String valueCurrencyCode = tokens[3];
long quantityNum = Long.parseLong(tokens[4]);
long quantityDenom = Long.parseLong(tokens[5]);
String qtyCurrencyCode = tokens[6];
Money value = new Money(valueNum, valueDenom, valueCurrencyCode);
Money quantity = new Money(quantityNum, quantityDenom, qtyCurrencyCode);
Split split = new Split(value, tokens[8]);
split.setUID(tokens[0]);
split.setQuantity(quantity);
split.setTransactionUID(tokens[7]);
split.setType(TransactionType.valueOf(tokens[9]));
if (tokens.length == 11) {
split.setMemo(tokens[10]);
}
return split;
}
}
/**
* Two splits are considered equivalent if all the fields (excluding GUID and timestamps - created, modified, reconciled) are equal.
* Any two splits which are equal are also equivalent, but the reverse is not true
* <p>The difference with to {@link #equals(Object)} is that the GUID of the split is not considered.
* This is useful in cases where a new split is generated for a transaction with the same properties,
* but a new GUID is generated e.g. when editing a transaction and modifying the splits</p>
*
* @param split Other split for which to test equivalence
* @return {@code true} if both splits are equivalent, {@code false} otherwise
*/
public boolean isEquivalentTo(Split split){
if (this == split) return true;
if (super.equals(split)) return true;
if (mReconcileState != split.mReconcileState) return false;
if (!mValue.equals(split.mValue)) return false;
if (!mQuantity.equals(split.mQuantity)) return false;
if (!mTransactionUID.equals(split.mTransactionUID)) return false;
if (!mAccountUID.equals(split.mAccountUID)) return false;
if (mSplitType != split.mSplitType) return false;
return mMemo != null ? mMemo.equals(split.mMemo) : split.mMemo == null;
}
/**
* Two splits are considered equal if all their properties excluding timestampes (created, modified, reconciled) are equal.
* @param o Other split to compare for equality
* @return {@code true} if this split is equal to {@code o}, {@code false} otherwise
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Split split = (Split) o;
if (mReconcileState != split.mReconcileState) return false;
if (!mValue.equals(split.mValue)) return false;
if (!mQuantity.equals(split.mQuantity)) return false;
if (!mTransactionUID.equals(split.mTransactionUID)) return false;
if (!mAccountUID.equals(split.mAccountUID)) return false;
if (mSplitType != split.mSplitType) return false;
return mMemo != null ? mMemo.equals(split.mMemo) : split.mMemo == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + mValue.hashCode();
result = 31 * result + mQuantity.hashCode();
result = 31 * result + mTransactionUID.hashCode();
result = 31 * result + mAccountUID.hashCode();
result = 31 * result + mSplitType.hashCode();
result = 31 * result + (mMemo != null ? mMemo.hashCode() : 0);
result = 31 * result + (int) mReconcileState;
return result;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getUID());
dest.writeString(mAccountUID);
dest.writeString(mTransactionUID);
dest.writeString(mSplitType.name());
dest.writeLong(mValue.getNumerator());
dest.writeLong(mValue.getDenominator());
dest.writeString(mValue.getCommodity().getCurrencyCode());
dest.writeLong(mQuantity.getNumerator());
dest.writeLong(mQuantity.getDenominator());
dest.writeString(mQuantity.getCommodity().getCurrencyCode());
dest.writeString(mMemo == null ? "" : mMemo);
dest.writeString(String.valueOf(mReconcileState));
dest.writeString(mReconcileDate.toString());
}
/**
* Constructor for creating a Split object from a Parcel
* @param source Source parcel containing the split
* @see #CREATOR
*/
private Split(Parcel source){
setUID(source.readString());
mAccountUID = source.readString();
mTransactionUID = source.readString();
mSplitType = TransactionType.valueOf(source.readString());
long valueNum = source.readLong();
long valueDenom = source.readLong();
String valueCurrency = source.readString();
mValue = new Money(valueNum, valueDenom, valueCurrency);
long qtyNum = source.readLong();
long qtyDenom = source.readLong();
String qtyCurrency = source.readString();
mQuantity = new Money(qtyNum, qtyDenom, qtyCurrency);
String memo = source.readString();
mMemo = memo.isEmpty() ? null : memo;
mReconcileState = source.readString().charAt(0);
mReconcileDate = Timestamp.valueOf(source.readString());
}
/**
* Creates new Parcels containing the information in this split during serialization
*/
public static final Parcelable.Creator<Split> CREATOR
= new Parcelable.Creator<Split>() {
@Override
public Split createFromParcel(Parcel source) {
return new Split(source);
}
@Override
public Split[] newArray(int size) {
return new Split[size];
}
};
}
|
package mil.nga.giat.mage.map;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.common.collect.Sets;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageCache;
import mil.nga.geopackage.GeoPackageManager;
import mil.nga.geopackage.core.contents.Contents;
import mil.nga.geopackage.core.contents.ContentsDao;
import mil.nga.geopackage.extension.link.FeatureTileTableLinker;
import mil.nga.geopackage.factory.GeoPackageFactory;
import mil.nga.geopackage.features.index.FeatureIndexManager;
import mil.nga.geopackage.features.user.FeatureCursor;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.geom.GeoPackageGeometryData;
import mil.nga.geopackage.map.geom.GoogleMapShape;
import mil.nga.geopackage.map.geom.GoogleMapShapeConverter;
import mil.nga.geopackage.map.tiles.overlay.BoundedOverlay;
import mil.nga.geopackage.map.tiles.overlay.FeatureOverlay;
import mil.nga.geopackage.map.tiles.overlay.FeatureOverlayQuery;
import mil.nga.geopackage.map.tiles.overlay.GeoPackageOverlayFactory;
import mil.nga.geopackage.projection.Projection;
import mil.nga.geopackage.projection.ProjectionConstants;
import mil.nga.geopackage.projection.ProjectionFactory;
import mil.nga.geopackage.projection.ProjectionTransform;
import mil.nga.geopackage.tiles.TileBoundingBoxUtils;
import mil.nga.geopackage.tiles.features.DefaultFeatureTiles;
import mil.nga.geopackage.tiles.features.FeatureTiles;
import mil.nga.geopackage.tiles.features.custom.NumberFeaturesTile;
import mil.nga.geopackage.tiles.user.TileDao;
import mil.nga.giat.mage.MAGE;
import mil.nga.giat.mage.R;
import mil.nga.giat.mage.filter.DateTimeFilter;
import mil.nga.giat.mage.filter.Filter;
import mil.nga.giat.mage.filter.FilterActivity;
import mil.nga.giat.mage.map.GoogleMapWrapper.OnMapPanListener;
import mil.nga.giat.mage.map.cache.CacheOverlay;
import mil.nga.giat.mage.map.cache.CacheOverlayType;
import mil.nga.giat.mage.map.cache.CacheProvider;
import mil.nga.giat.mage.map.cache.CacheProvider.OnCacheOverlayListener;
import mil.nga.giat.mage.map.cache.GeoPackageCacheOverlay;
import mil.nga.giat.mage.map.cache.GeoPackageFeatureTableCacheOverlay;
import mil.nga.giat.mage.map.cache.GeoPackageTileTableCacheOverlay;
import mil.nga.giat.mage.map.cache.XYZDirectoryCacheOverlay;
import mil.nga.giat.mage.map.marker.LocationMarkerCollection;
import mil.nga.giat.mage.map.marker.MyHistoricalLocationMarkerCollection;
import mil.nga.giat.mage.map.marker.ObservationMarkerCollection;
import mil.nga.giat.mage.map.marker.PointCollection;
import mil.nga.giat.mage.map.marker.StaticGeometryCollection;
import mil.nga.giat.mage.map.preference.MapPreferencesActivity;
import mil.nga.giat.mage.observation.ObservationEditActivity;
import mil.nga.giat.mage.observation.ObservationFormPickerActivity;
import mil.nga.giat.mage.observation.ObservationLocation;
import mil.nga.giat.mage.sdk.Temporal;
import mil.nga.giat.mage.sdk.datastore.layer.Layer;
import mil.nga.giat.mage.sdk.datastore.layer.LayerHelper;
import mil.nga.giat.mage.sdk.datastore.location.LocationHelper;
import mil.nga.giat.mage.sdk.datastore.location.LocationProperty;
import mil.nga.giat.mage.sdk.datastore.observation.Observation;
import mil.nga.giat.mage.sdk.datastore.observation.ObservationHelper;
import mil.nga.giat.mage.sdk.datastore.staticfeature.StaticFeatureHelper;
import mil.nga.giat.mage.sdk.datastore.user.EventHelper;
import mil.nga.giat.mage.sdk.datastore.user.User;
import mil.nga.giat.mage.sdk.datastore.user.UserHelper;
import mil.nga.giat.mage.sdk.event.ILocationEventListener;
import mil.nga.giat.mage.sdk.event.IObservationEventListener;
import mil.nga.giat.mage.sdk.event.IStaticFeatureEventListener;
import mil.nga.giat.mage.sdk.exceptions.LayerException;
import mil.nga.giat.mage.sdk.exceptions.UserException;
import mil.nga.giat.mage.sdk.location.LocationService;
import mil.nga.wkb.geom.Geometry;
import mil.nga.wkb.geom.GeometryType;
public class MapFragment extends Fragment implements OnMapReadyCallback, OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener, OnInfoWindowClickListener, OnMapPanListener, OnMyLocationButtonClickListener, OnClickListener, LocationSource, LocationListener, OnCacheOverlayListener,
IObservationEventListener, ILocationEventListener, IStaticFeatureEventListener {
private static final String LOG_NAME = MapFragment.class.getName();
private static final String MAP_VIEW_STATE = "MAP_VIEW_STATE";
private static final String OBSERVATION_FILTER_TYPE = "Observation";
private static final String LOCATION_FILTER_TYPE = "Location";
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private MAGE mage;
private MapView mapView;
private GoogleMap map;
private boolean mapInitialized = false;
private View searchLayout;
private SearchView searchView;
private Menu menu;
private Location location;
private boolean followMe = false;
private GoogleMapWrapper mapWrapper;
protected User currentUser = null;
private OnLocationChangedListener locationChangedListener;
private static final int REFRESHMARKERINTERVALINSECONDS = 300;
private static final int REFRESHOBSERVATIONMARKERINTERVALINSECONDS = 60;
private ScheduledFuture refreshLocationsMarkersTask;
private ScheduledFuture refreshMyHistoricLocationsMarkersTask;
private ScheduledFuture refreshObservationMarkersTask;
private final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(64);
private final ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8, 10, TimeUnit.SECONDS, queue);
private ScheduledExecutorService scheduledExecutorService;
private PointCollection<Observation> observations;
private PointCollection<Pair<mil.nga.giat.mage.sdk.datastore.location.Location, User>> locations;
private PointCollection<Pair<mil.nga.giat.mage.sdk.datastore.location.Location, User>> historicLocations;
private StaticGeometryCollection staticGeometryCollection;
private List<Marker> searchMarkers = new ArrayList<>();
private Map<String, CacheOverlay> cacheOverlays = new HashMap<>();
// GeoPackage cache of open GeoPackage connections
private GeoPackageCache geoPackageCache;
private BoundingBox addedCacheBoundingBox;
private FloatingActionButton searchButton;
private FloatingActionButton zoomToLocationButton;
private LocationService locationService;
SharedPreferences preferences;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
setHasOptionsMenu(true);
staticGeometryCollection = new StaticGeometryCollection();
zoomToLocationButton = (FloatingActionButton) view.findViewById(R.id.zoom_button);
searchButton = (FloatingActionButton) view.findViewById(R.id.map_search_button);
Drawable drawable = DrawableCompat.wrap(searchButton.getDrawable());
searchButton.setImageDrawable(drawable);
DrawableCompat.setTintList(drawable, AppCompatResources.getColorStateList(getContext(), R.color.toggle_button_selected));
searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
search();
}
});
view.findViewById(R.id.new_observation_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onNewObservation();
}
});
mage = (MAGE) getActivity().getApplication();
locationService = mage.getLocationService();
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
searchLayout = view.findViewById(R.id.search_layout);
searchView = (SearchView) view.findViewById(R.id.search_view);
searchView.setIconifiedByDefault(false);
searchView.setIconified(false);
searchView.clearFocus();
MapsInitializer.initialize(getActivity().getApplicationContext());
ImageButton mapSettings = (ImageButton) view.findViewById(R.id.map_settings);
mapSettings.setOnClickListener(this);
mapWrapper = new GoogleMapWrapper(getActivity().getApplicationContext());
mapWrapper.addView(view);
mapView = (MapView) view.findViewById(R.id.mapView);
Bundle mapState = (savedInstanceState != null) ? savedInstanceState.getBundle(MAP_VIEW_STATE): null;
mapView.onCreate(mapState);
mapView.getMapAsync(this);
// Initialize the GeoPackage cache with a GeoPackage manager
GeoPackageManager geoPackageManager = GeoPackageFactory.getManager(getActivity().getApplicationContext());
geoPackageCache = new GeoPackageCache(geoPackageManager);
return mapWrapper;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
ObservationHelper.getInstance(getActivity().getApplicationContext()).removeListener(this);
LocationHelper.getInstance(getActivity().getApplicationContext()).removeListener(this);
if (observations != null) {
observations.clear();
observations = null;
}
if (locations != null) {
locations.clear();
locations = null;
}
if (historicLocations != null) {
historicLocations.clear();
historicLocations = null;
}
if (searchMarkers != null) {
for (Marker m : searchMarkers) {
m.remove();
}
searchMarkers.clear();
}
// Close all open GeoPackages
geoPackageCache.closeAll();
cacheOverlays.clear();
staticGeometryCollection = null;
currentUser = null;
map = null;
mapInitialized = false;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.filter, menu);
this.menu = menu;
getFilterTitle();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.filter_button:
Intent intent = new Intent(getActivity(), FilterActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
initializeMap();
}
private void initializeMap() {
if (map == null) return;
if (!mapInitialized) {
mapInitialized = true;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setOnMapClickListener(this);
map.setOnMarkerClickListener(this);
map.setOnMapLongClickListener(this);
map.setOnMyLocationButtonClickListener(this);
map.setOnInfoWindowClickListener(this);
zoomToLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Location location = locationService.getLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
map.animateCamera(cameraUpdate);
}
});
ObservationHelper.getInstance(getActivity().getApplicationContext()).addListener(this);
LocationHelper.getInstance(getActivity().getApplicationContext()).addListener(this);
CacheProvider.getInstance(getActivity().getApplicationContext()).registerCacheOverlayListener(this);
StaticFeatureHelper.getInstance(getActivity().getApplicationContext()).addListener(this);
}
updateMapView();
// Set visibility on map markers as preferences may have changed
if (observations != null) {
observations.clear();
}
observations = new ObservationMarkerCollection(getActivity(), map);
observations.setVisibility(preferences.getBoolean(getResources().getString(R.string.showObservationsKey), true));
ObservationLoadTask observationLoad = new ObservationLoadTask(getActivity(), observations);
observationLoad.addFilter(getTemporalFilter("timestamp", getTimeFilterId(), OBSERVATION_FILTER_TYPE));
observationLoad.executeOnExecutor(executor);
if (locations != null) {
locations.clear();
}
locations = new LocationMarkerCollection(getActivity(), map);
locations.setVisibility(preferences.getBoolean(getResources().getString(R.string.showLocationsKey), true));
LocationLoadTask locationLoad = new LocationLoadTask(getActivity(), locations);
locationLoad.setFilter(getTemporalFilter("timestamp", getLocationTimeFilterId(), LOCATION_FILTER_TYPE));
locationLoad.executeOnExecutor(executor);
if (historicLocations != null) {
historicLocations.clear();
}
historicLocations = new MyHistoricalLocationMarkerCollection(getActivity(), map);
historicLocations.setVisibility(preferences.getBoolean(getResources().getString(R.string.showMyLocationHistoryKey), false));
HistoricLocationLoadTask myHistoricLocationLoad = new HistoricLocationLoadTask(getActivity(), historicLocations);
myHistoricLocationLoad.executeOnExecutor(executor);
initializePeriodicTasks();
updateStaticFeatureLayers();
// Check if any map preferences changed that I care about
if (locationService != null && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
map.setMyLocationEnabled(true);
map.setLocationSource(this);
locationService.registerOnLocationListener(this);
} else {
map.setMyLocationEnabled(false);
map.setLocationSource(null);
}
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(getFilterTitle());
}
private void initializePeriodicTasks() {
scheduledExecutorService = Executors.newScheduledThreadPool(4);
// task to refresh location markers ever x seconds
refreshLocationsMarkersTask = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
locations.refreshMarkerIcons(getTemporalFilter("timestamp", getLocationTimeFilterId(), LOCATION_FILTER_TYPE));
}
});
}
}, 0, REFRESHMARKERINTERVALINSECONDS, TimeUnit.SECONDS);
// task to refresh my historic location markers every x seconds
refreshMyHistoricLocationsMarkersTask = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
historicLocations.refreshMarkerIcons(getTemporalFilter("timestamp", getLocationTimeFilterId(), LOCATION_FILTER_TYPE));
}
}, 0, REFRESHMARKERINTERVALINSECONDS, TimeUnit.SECONDS);
// task to refresh observation markers every x seconds
refreshObservationMarkersTask = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
observations.refreshMarkerIcons(getTemporalFilter("timestamp", getTimeFilterId(), OBSERVATION_FILTER_TYPE));
}
}, 0, REFRESHOBSERVATIONMARKERINTERVALINSECONDS, TimeUnit.SECONDS);
}
private void stopPeriodicTasks() {
if (refreshLocationsMarkersTask != null) {
refreshLocationsMarkersTask.cancel(true);
refreshLocationsMarkersTask = null;
}
if (refreshMyHistoricLocationsMarkersTask != null) {
refreshMyHistoricLocationsMarkersTask.cancel(true);
refreshMyHistoricLocationsMarkersTask = null;
}
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdown();
scheduledExecutorService = null;
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onResume() {
super.onResume();
try {
currentUser = UserHelper.getInstance(getActivity().getApplicationContext()).readCurrentUser();
} catch (UserException ue) {
Log.e(LOG_NAME, "Could not find current user.", ue);
}
mapView.onResume();
initializeMap();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (StringUtils.isNoneBlank(query)) {
new GeocoderTask(getActivity(), map, searchMarkers).execute(query);
}
searchView.clearFocus();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (StringUtils.isEmpty(newText)) {
if (searchMarkers != null) {
for (Marker m : searchMarkers) {
m.remove();
}
searchMarkers.clear();
}
}
return true;
}
});
}
@Override
public void onPause() {
super.onPause();
stopPeriodicTasks();
mapView.onPause();
CacheProvider.getInstance(getActivity().getApplicationContext()).unregisterCacheOverlayListener(this);
StaticFeatureHelper.getInstance(getActivity().getApplicationContext()).removeListener(this);
if (map != null) {
saveMapView();
map.setLocationSource(null);
if (locationService != null) {
locationService.unregisterOnLocationListener(this);
}
mapInitialized = false;
}
}
private void search() {
boolean isVisible = searchLayout.getVisibility() == View.VISIBLE;
searchLayout.setVisibility(isVisible ? View.GONE : View.VISIBLE);
searchButton.setSelected(!isVisible);
if (isVisible) {
searchView.clearFocus();
} else {
searchView.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
}
private void onNewObservation() {
ObservationLocation location = null;
// if there is not a location from the location service, then try to pull one from the database.
if (locationService.getLocation() == null) {
List<mil.nga.giat.mage.sdk.datastore.location.Location> tLocations = LocationHelper.getInstance(getActivity().getApplicationContext()).getCurrentUserLocations(1, true);
if (!tLocations.isEmpty()) {
mil.nga.giat.mage.sdk.datastore.location.Location tLocation = tLocations.get(0);
Geometry geo = tLocation.getGeometry();
Map<String, LocationProperty> propertiesMap = tLocation.getPropertiesMap();
String provider = ObservationLocation.MANUAL_PROVIDER;
if (propertiesMap.get("provider").getValue() != null) {
provider = propertiesMap.get("provider").getValue().toString();
}
location = new ObservationLocation(provider, geo);
location.setTime(tLocation.getTimestamp().getTime());
if (propertiesMap.get("accuracy").getValue() != null) {
location.setAccuracy(Float.valueOf(propertiesMap.get("accuracy").getValue().toString()));
}
}
} else {
location = new ObservationLocation(locationService.getLocation());
}
if (!UserHelper.getInstance(getActivity().getApplicationContext()).isCurrentUserPartOfCurrentEvent()) {
new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getResources().getString(R.string.location_no_event_title))
.setMessage(getActivity().getResources().getString(R.string.location_no_event_message))
.setPositiveButton(android.R.string.ok, null)
.show();
} else if (location != null) {
newObservation(location);
} else {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getResources().getString(R.string.location_missing_title))
.setMessage(getActivity().getResources().getString(R.string.location_missing_message))
.setPositiveButton(android.R.string.ok, null)
.show();
} else {
new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getResources().getString(R.string.location_access_observation_title))
.setMessage(getActivity().getResources().getString(R.string.location_access_observation_message))
.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.show();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onNewObservation();
}
break;
}
}
}
@Override
public void onObservationCreated(Collection<Observation> o, Boolean sendUserNotifcations) {
if (observations != null) {
ObservationTask task = new ObservationTask(getActivity(), ObservationTask.Type.ADD, observations);
task.addFilter(getTemporalFilter("last_modified", getTimeFilterId(), OBSERVATION_FILTER_TYPE));
task.executeOnExecutor(executor, o.toArray(new Observation[o.size()]));
}
}
@Override
public void onObservationUpdated(Observation o) {
if (observations != null) {
ObservationTask task = new ObservationTask(getActivity(), ObservationTask.Type.UPDATE, observations);
task.addFilter(getTemporalFilter("last_modified", getTimeFilterId(), OBSERVATION_FILTER_TYPE));
task.executeOnExecutor(executor, o);
}
}
@Override
public void onObservationDeleted(Observation o) {
if (observations != null) {
new ObservationTask(getActivity(), ObservationTask.Type.DELETE, observations).executeOnExecutor(executor, o);
}
}
@Override
public void onLocationCreated(Collection<mil.nga.giat.mage.sdk.datastore.location.Location> ls) {
for (mil.nga.giat.mage.sdk.datastore.location.Location l : ls) {
if (currentUser != null && !currentUser.getRemoteId().equals(l.getUser().getRemoteId())) {
if (locations != null) {
LocationTask task = new LocationTask(getActivity(), LocationTask.Type.ADD, locations);
task.setFilter(getTemporalFilter("timestamp", getLocationTimeFilterId(), LOCATION_FILTER_TYPE));
task.executeOnExecutor(executor, l);
}
} else {
if (historicLocations != null) {
new LocationTask(getActivity(), LocationTask.Type.ADD, historicLocations).executeOnExecutor(executor, l);
}
}
}
}
@Override
public void onLocationUpdated(mil.nga.giat.mage.sdk.datastore.location.Location l) {
if (currentUser != null && !currentUser.getRemoteId().equals(l.getUser().getRemoteId())) {
if (locations != null) {
LocationTask task = new LocationTask(getActivity(), LocationTask.Type.UPDATE, locations);
task.setFilter(getTemporalFilter("timestamp", getLocationTimeFilterId(), LOCATION_FILTER_TYPE));
task.executeOnExecutor(executor, l);
}
} else {
if (historicLocations != null) {
new LocationTask(getActivity(), LocationTask.Type.UPDATE, historicLocations).executeOnExecutor(executor, l);
}
}
}
@Override
public void onLocationDeleted(Collection<mil.nga.giat.mage.sdk.datastore.location.Location> l) {
// this is slowing the app down a lot! Moving the delete like code into the add methods of the collections
/*
if (currentUser != null && !currentUser.getRemoteId().equals(l.getUser().getRemoteId())) {
if (locations != null) {
new LocationTask(LocationTask.Type.DELETE, locations).execute(l);
}
} else {
if (myHistoricLocations != null) {
new LocationTask(LocationTask.Type.DELETE, myHistoricLocations).execute(l);
}
}
*/
}
@Override
public void onInfoWindowClick(Marker marker) {
observations.onInfoWindowClick(marker);
locations.onInfoWindowClick(marker);
}
@Override
public boolean onMarkerClick(Marker marker) {
hideKeyboard();
observations.offMarkerClick();
// search marker
if(searchMarkers != null) {
for(Marker m :searchMarkers) {
if(marker.getId().equals(m.getId())) {
m.showInfoWindow();
return true;
}
}
}
// You can only have one marker click listener per map.
// Lets listen here and shell out the click event to all
// my marker collections. Each one need to handle
// gracefully if it does not actually contain the marker
if (observations.onMarkerClick(marker)) {
return true;
}
if (locations.onMarkerClick(marker)) {
return true;
}
if (historicLocations.onMarkerClick(marker)) {
return true;
}
// static layer
if(marker.getSnippet() != null) {
View markerInfoWindow = LayoutInflater.from(getActivity()).inflate(R.layout.static_feature_infowindow, null, false);
WebView webView = ((WebView) markerInfoWindow.findViewById(R.id.static_feature_infowindow_content));
webView.loadData(marker.getSnippet(), "text/html; charset=UTF-8", null);
new AlertDialog.Builder(getActivity())
.setView(markerInfoWindow)
.setPositiveButton(android.R.string.yes, null)
.show();
}
return true;
}
@Override
public void onMapClick(LatLng latLng) {
hideKeyboard();
// remove old accuracy circle
((LocationMarkerCollection) locations).offMarkerClick();
observations.offMarkerClick();
observations.onMapClick(latLng);
staticGeometryCollection.onMapClick(map, latLng, getActivity());
if(!cacheOverlays.isEmpty()) {
StringBuilder clickMessage = new StringBuilder();
for (CacheOverlay cacheOverlay : cacheOverlays.values()) {
String message = cacheOverlay.onMapClick(latLng, mapView, map);
if(message != null){
if(clickMessage.length() > 0){
clickMessage.append("\n\n");
}
clickMessage.append(message);
}
}
if(clickMessage.length() > 0) {
new AlertDialog.Builder(getActivity())
.setMessage(clickMessage.toString())
.setPositiveButton(android.R.string.yes, null)
.show();
}
}
}
@Override
public void onMapLongClick(LatLng point) {
hideKeyboard();
if(!UserHelper.getInstance(getActivity().getApplicationContext()).isCurrentUserPartOfCurrentEvent()) {
new AlertDialog.Builder(getActivity())
.setTitle(getActivity().getResources().getString(R.string.location_no_event_title))
.setMessage(getActivity().getResources().getString(R.string.location_no_event_message))
.setPositiveButton(android.R.string.ok, null)
.show();
} else {
ObservationLocation location = new ObservationLocation(ObservationLocation.MANUAL_PROVIDER, point);
location.setAccuracy(0.0f);
location.setTime(new Date().getTime());
newObservation(location);
}
}
private void newObservation(ObservationLocation location) {
Intent intent;
// show form picker or go to
JsonArray formDefinitions = EventHelper.getInstance(getActivity()).getCurrentEvent().getForms();
if (formDefinitions.size() == 0) {
intent = new Intent(getActivity(), ObservationEditActivity.class);
} else if (formDefinitions.size() == 1) {
JsonObject form = (JsonObject) formDefinitions.iterator().next();
intent = new Intent(getActivity(), ObservationEditActivity.class);
intent.putExtra(ObservationEditActivity.OBSERVATION_FORM_ID, form.get("id").getAsLong());
} else {
intent = new Intent(getActivity(), ObservationFormPickerActivity.class);
}
intent.putExtra(ObservationEditActivity.LOCATION, location);
intent.putExtra(ObservationEditActivity.INITIAL_LOCATION, map.getCameraPosition().target);
intent.putExtra(ObservationEditActivity.INITIAL_ZOOM, map.getCameraPosition().zoom);
startActivity(intent);
}
@Override
public void onClick(View view) {
// close keyboard
hideKeyboard();
switch (view.getId()) {
case R.id.map_settings: {
Intent intent = new Intent(getActivity(), MapPreferencesActivity.class);
startActivity(intent);
break;
}
}
}
@Override
public boolean onMyLocationButtonClick() {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
float zoom = map.getCameraPosition().zoom < 15 ? 15 : map.getCameraPosition().zoom;
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom), new CancelableCallback() {
@Override
public void onCancel() {
mapWrapper.setOnMapPanListener(MapFragment.this);
followMe = true;
}
@Override
public void onFinish() {
mapWrapper.setOnMapPanListener(MapFragment.this);
followMe = true;
}
});
}
return true;
}
@Override
public void activate(OnLocationChangedListener listener) {
Log.i(LOG_NAME, "map location, activate");
locationChangedListener = listener;
if (location != null) {
Log.i(LOG_NAME, "map location, activate we have a location, let our listener know");
locationChangedListener.onLocationChanged(location);
}
}
@Override
public void deactivate() {
Log.i(LOG_NAME, "map location, deactivate");
locationChangedListener = null;
}
@Override
public void onMapPan() {
mapWrapper.setOnMapPanListener(null);
followMe = false;
}
@Override
public void onLocationChanged(Location location) {
this.location = location;
Log.d(LOG_NAME, "Map location updated.");
if (locationChangedListener != null) {
locationChangedListener.onLocationChanged(location);
}
if (followMe) {
LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (!bounds.contains(latLng)) {
// Move the camera to the user's location once it's available!
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onCacheOverlay(List<CacheOverlay> cacheOverlays) {
// Add all overlays that are in the preferences
// Track enabled cache overlays
Map<String, CacheOverlay> enabledCacheOverlays = new HashMap<>();
// Track enabled GeoPackages
Set<String> enabledGeoPackages = new HashSet<>();
// Reset the bounding box for newly added caches
addedCacheBoundingBox = null;
for (CacheOverlay cacheOverlay : cacheOverlays) {
// If this cache overlay potentially replaced by a new version
if(cacheOverlay.isAdded()){
if(cacheOverlay.getType() == CacheOverlayType.GEOPACKAGE){
geoPackageCache.close(cacheOverlay.getName());
}
}
// The user has asked for this overlay
if (cacheOverlay.isEnabled()) {
// Handle each type of cache overlay
switch(cacheOverlay.getType()) {
case XYZ_DIRECTORY:
addXYZDirectoryCacheOverlay(enabledCacheOverlays, (XYZDirectoryCacheOverlay) cacheOverlay);
break;
case GEOPACKAGE:
addGeoPackageCacheOverlay(enabledCacheOverlays, enabledGeoPackages, (GeoPackageCacheOverlay)cacheOverlay);
break;
}
}
cacheOverlay.setAdded(false);
}
// Remove any overlays that are on the map but no longer selected in
// preferences, update the tile overlays to the enabled tile overlays
for (CacheOverlay cacheOverlay : this.cacheOverlays.values()) {
cacheOverlay.removeFromMap();
}
this.cacheOverlays = enabledCacheOverlays;
// Close GeoPackages no longer enabled
geoPackageCache.closeRetain(enabledGeoPackages);
// If a new cache was added, zoom to the bounding box area
if(addedCacheBoundingBox != null){
final LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
boundsBuilder.include(new LatLng(addedCacheBoundingBox.getMinLatitude(), addedCacheBoundingBox
.getMinLongitude()));
boundsBuilder.include(new LatLng(addedCacheBoundingBox.getMinLatitude(), addedCacheBoundingBox
.getMaxLongitude()));
boundsBuilder.include(new LatLng(addedCacheBoundingBox.getMaxLatitude(), addedCacheBoundingBox
.getMinLongitude()));
boundsBuilder.include(new LatLng(addedCacheBoundingBox.getMaxLatitude(), addedCacheBoundingBox
.getMaxLongitude()));
try {
map.animateCamera(CameraUpdateFactory.newLatLngBounds(
boundsBuilder.build(), 0));
} catch (Exception e) {
Log.e(LOG_NAME, "Unable to move camera to newly added cache location", e);
}
}
}
/**
* Add XYZ Directory tile cache overlay
* @param enabledCacheOverlays
* @param xyzDirectoryCacheOverlay
*/
private void addXYZDirectoryCacheOverlay(Map<String, CacheOverlay> enabledCacheOverlays, XYZDirectoryCacheOverlay xyzDirectoryCacheOverlay){
// Retrieve the cache overlay if it already exists (and remove from cache overlays)
CacheOverlay cacheOverlay = cacheOverlays.remove(xyzDirectoryCacheOverlay.getCacheName());
if(cacheOverlay == null){
// Create a new tile provider and add to the map
TileProvider tileProvider = new FileSystemTileProvider(256, 256, xyzDirectoryCacheOverlay.getDirectory().getAbsolutePath());
TileOverlayOptions overlayOptions = createTileOverlayOptions(tileProvider);
// Set the tile overlay in the cache overlay
TileOverlay tileOverlay = map.addTileOverlay(overlayOptions);
xyzDirectoryCacheOverlay.setTileOverlay(tileOverlay);
cacheOverlay = xyzDirectoryCacheOverlay;
}
// Add the cache overlay to the enabled cache overlays
enabledCacheOverlays.put(cacheOverlay.getCacheName(), cacheOverlay);
}
/**
* Add a GeoPackage cache overlay, which contains tile and feature tables
* @param enabledCacheOverlays
* @param enabledGeoPackages
* @param geoPackageCacheOverlay
*/
private void addGeoPackageCacheOverlay(Map<String, CacheOverlay> enabledCacheOverlays, Set<String> enabledGeoPackages, GeoPackageCacheOverlay geoPackageCacheOverlay){
// Check each GeoPackage table
for(CacheOverlay tableCacheOverlay: geoPackageCacheOverlay.getChildren()){
// Check if the table is enabled
if(tableCacheOverlay.isEnabled()){
// Get and open if needed the GeoPackage
GeoPackage geoPackage = geoPackageCache.getOrOpen(geoPackageCacheOverlay.getName());
enabledGeoPackages.add(geoPackage.getName());
// Handle tile and feature tables
try {
switch (tableCacheOverlay.getType()) {
case GEOPACKAGE_TILE_TABLE:
addGeoPackageTileCacheOverlay(enabledCacheOverlays, (GeoPackageTileTableCacheOverlay) tableCacheOverlay, geoPackage, false);
break;
case GEOPACKAGE_FEATURE_TABLE:
addGeoPackageFeatureCacheOverlay(enabledCacheOverlays, (GeoPackageFeatureTableCacheOverlay) tableCacheOverlay, geoPackage);
break;
default:
throw new UnsupportedOperationException("Unsupported GeoPackage type: " + tableCacheOverlay.getType());
}
}catch(Exception e){
Log.e(LOG_NAME, "Failed to add GeoPackage overlay. GeoPackage: " + geoPackage.getName() + ", Name: " + tableCacheOverlay.getName(), e);
}
// If a newly added cache, update the bounding box for zooming
if(geoPackageCacheOverlay.isAdded()){
try {
ContentsDao contentsDao = geoPackage.getContentsDao();
Contents contents = contentsDao.queryForId(tableCacheOverlay.getName());
BoundingBox contentsBoundingBox = contents.getBoundingBox();
Projection projection = ProjectionFactory
.getProjection(contents.getSrs().getOrganizationCoordsysId());
ProjectionTransform transform = projection.getTransformation(ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM);
BoundingBox boundingBox = transform.transform(contentsBoundingBox);
boundingBox = TileBoundingBoxUtils.boundWgs84BoundingBoxWithWebMercatorLimits(boundingBox);
if (addedCacheBoundingBox == null) {
addedCacheBoundingBox = boundingBox;
} else {
addedCacheBoundingBox = TileBoundingBoxUtils.union(addedCacheBoundingBox, boundingBox);
}
}catch(Exception e){
Log.e(LOG_NAME, "Failed to retrieve GeoPackage Table bounding box. GeoPackage: "
+ geoPackage.getName() + ", Table: " + tableCacheOverlay.getName(), e);
}
}
}
}
}
/**
* Add the GeoPackage Tile Table Cache Overlay
* @param enabledCacheOverlays
* @param tileTableCacheOverlay
* @param geoPackage
* @param linkedToFeatures
*/
private void addGeoPackageTileCacheOverlay(Map<String, CacheOverlay> enabledCacheOverlays, GeoPackageTileTableCacheOverlay tileTableCacheOverlay, GeoPackage geoPackage, boolean linkedToFeatures){
// Retrieve the cache overlay if it already exists (and remove from cache overlays)
CacheOverlay cacheOverlay = cacheOverlays.remove(tileTableCacheOverlay.getCacheName());
if(cacheOverlay != null){
// If the existing cache overlay is being replaced, create a new cache overlay
if(tileTableCacheOverlay.getParent().isAdded()){
cacheOverlay = null;
}
}
if(cacheOverlay == null){
// Create a new GeoPackage tile provider and add to the map
TileDao tileDao = geoPackage.getTileDao(tileTableCacheOverlay.getName());
BoundedOverlay geoPackageTileProvider = GeoPackageOverlayFactory.getBoundedOverlay(tileDao);
TileOverlayOptions overlayOptions = null;
if(linkedToFeatures){
overlayOptions = createFeatureTileOverlayOptions(geoPackageTileProvider);
}else {
overlayOptions = createTileOverlayOptions(geoPackageTileProvider);
}
TileOverlay tileOverlay = map.addTileOverlay(overlayOptions);
tileTableCacheOverlay.setTileOverlay(tileOverlay);
// Check for linked feature tables
tileTableCacheOverlay.clearFeatureOverlayQueries();
FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage);
List<FeatureDao> featureDaos = linker.getFeatureDaosForTileTable(tileDao.getTableName());
for(FeatureDao featureDao: featureDaos){
// Create the feature tiles
FeatureTiles featureTiles = new DefaultFeatureTiles(getActivity(), featureDao);
// Create an index manager
FeatureIndexManager indexer = new FeatureIndexManager(getActivity(), geoPackage, featureDao);
featureTiles.setIndexManager(indexer);
// Add the feature overlay query
FeatureOverlayQuery featureOverlayQuery = new FeatureOverlayQuery(getActivity(), geoPackageTileProvider, featureTiles);
tileTableCacheOverlay.addFeatureOverlayQuery(featureOverlayQuery);
}
cacheOverlay = tileTableCacheOverlay;
}
// Add the cache overlay to the enabled cache overlays
enabledCacheOverlays.put(cacheOverlay.getCacheName(), cacheOverlay);
}
/**
* Add the GeoPackage Feature Table Cache Overlay
* @param enabledCacheOverlays
* @param featureTableCacheOverlay
* @param geoPackage
*/
private void addGeoPackageFeatureCacheOverlay(Map<String, CacheOverlay> enabledCacheOverlays, GeoPackageFeatureTableCacheOverlay featureTableCacheOverlay, GeoPackage geoPackage){
// Retrieve the cache overlay if it already exists (and remove from cache overlays)
CacheOverlay cacheOverlay = cacheOverlays.remove(featureTableCacheOverlay.getCacheName());
if(cacheOverlay != null){
// If the existing cache overlay is being replaced, create a new cache overlay
if(featureTableCacheOverlay.getParent().isAdded()){
cacheOverlay = null;
}
for(GeoPackageTileTableCacheOverlay linkedTileTable: featureTableCacheOverlay.getLinkedTileTables()){
if(cacheOverlay != null){
// Add the existing linked tile cache overlays
addGeoPackageTileCacheOverlay(enabledCacheOverlays, linkedTileTable, geoPackage, true);
}
cacheOverlays.remove(linkedTileTable.getCacheName());
}
}
if(cacheOverlay == null) {
// Add the features to the map
FeatureDao featureDao = geoPackage.getFeatureDao(featureTableCacheOverlay.getName());
// If indexed, add as a tile overlay
if(featureTableCacheOverlay.isIndexed()){
FeatureTiles featureTiles = new DefaultFeatureTiles(getActivity(), featureDao);
Integer maxFeaturesPerTile = null;
if(featureDao.getGeometryType() == GeometryType.POINT){
maxFeaturesPerTile = getResources().getInteger(R.integer.geopackage_feature_tiles_max_points_per_tile);
}else{
maxFeaturesPerTile = getResources().getInteger(R.integer.geopackage_feature_tiles_max_features_per_tile);
}
featureTiles.setMaxFeaturesPerTile(maxFeaturesPerTile);
NumberFeaturesTile numberFeaturesTile = new NumberFeaturesTile(getActivity());
// Adjust the max features number tile draw paint attributes here as needed to
// change how tiles are drawn when more than the max features exist in a tile
featureTiles.setMaxFeaturesTileDraw(numberFeaturesTile);
featureTiles.setIndexManager(new FeatureIndexManager(getActivity(), geoPackage, featureDao));
// Adjust the feature tiles draw paint attributes here as needed to change how
// features are drawn on tiles
FeatureOverlay featureOverlay = new FeatureOverlay(featureTiles);
featureOverlay.setMinZoom(featureTableCacheOverlay.getMinZoom());
FeatureTileTableLinker linker = new FeatureTileTableLinker(geoPackage);
List<TileDao> tileDaos = linker.getTileDaosForFeatureTable(featureDao.getTableName());
featureOverlay.ignoreTileDaos(tileDaos);
FeatureOverlayQuery featureOverlayQuery = new FeatureOverlayQuery(getActivity(), featureOverlay);
featureTableCacheOverlay.setFeatureOverlayQuery(featureOverlayQuery);
TileOverlayOptions overlayOptions = createFeatureTileOverlayOptions(featureOverlay);
TileOverlay tileOverlay = map.addTileOverlay(overlayOptions);
featureTableCacheOverlay.setTileOverlay(tileOverlay);
}
// Not indexed, add the features to the map
else {
int maxFeaturesPerTable = 0;
if(featureDao.getGeometryType() == GeometryType.POINT){
maxFeaturesPerTable = getResources().getInteger(R.integer.geopackage_features_max_points_per_table);
}else{
maxFeaturesPerTable = getResources().getInteger(R.integer.geopackage_features_max_features_per_table);
}
Projection projection = featureDao.getProjection();
GoogleMapShapeConverter shapeConverter = new GoogleMapShapeConverter(projection);
FeatureCursor featureCursor = featureDao.queryForAll();
try {
final int totalCount = featureCursor.getCount();
int count = 0;
while (featureCursor.moveToNext()) {
try {
FeatureRow featureRow = featureCursor.getRow();
GeoPackageGeometryData geometryData = featureRow.getGeometry();
if (geometryData != null && !geometryData.isEmpty()) {
mil.nga.wkb.geom.Geometry geometry = geometryData.getGeometry();
if (geometry != null) {
GoogleMapShape shape = shapeConverter.toShape(geometry);
// Set the Shape Marker, PolylineOptions, and PolygonOptions here if needed to change color and style
featureTableCacheOverlay.addShapeToMap(featureRow.getId(), shape, map);
if (++count >= maxFeaturesPerTable) {
if (count < totalCount) {
Toast.makeText(getActivity().getApplicationContext(), featureTableCacheOverlay.getCacheName()
+ "- added " + count + " of " + totalCount, Toast.LENGTH_LONG).show();
}
break;
}
}
}
}catch(Exception e){
Log.e(LOG_NAME, "Failed to display feature. GeoPackage: " + geoPackage.getName()
+ ", Table: " + featureDao.getTableName() + ", Row: " + featureCursor.getPosition(), e);
}
}
} finally {
featureCursor.close();
}
}
// Add linked tile tables
for(GeoPackageTileTableCacheOverlay linkedTileTable: featureTableCacheOverlay.getLinkedTileTables()){
addGeoPackageTileCacheOverlay(enabledCacheOverlays, linkedTileTable, geoPackage, true);
}
cacheOverlay = featureTableCacheOverlay;
}
// Add the cache overlay to the enabled cache overlays
enabledCacheOverlays.put(cacheOverlay.getCacheName(), cacheOverlay);
}
/**
* Create Feature Tile Overlay Options with the default z index for tile layers drawn from features
* @param tileProvider
* @return
*/
private TileOverlayOptions createFeatureTileOverlayOptions(TileProvider tileProvider){
return createTileOverlayOptions(tileProvider, -1);
}
/**
* Create Tile Overlay Options with the default z index for tile layers
* @param tileProvider
* @return
*/
private TileOverlayOptions createTileOverlayOptions(TileProvider tileProvider){
return createTileOverlayOptions(tileProvider, -2);
}
/**
* Create Tile Overlay Options for the Tile Provider using the z index
* @param tileProvider
* @param zIndex
* @return
*/
private TileOverlayOptions createTileOverlayOptions(TileProvider tileProvider, int zIndex){
TileOverlayOptions overlayOptions = new TileOverlayOptions();
overlayOptions.tileProvider(tileProvider);
overlayOptions.zIndex(zIndex);
return overlayOptions;
}
private void updateStaticFeatureLayers() {
removeStaticFeatureLayers();
try {
for (Layer l : LayerHelper.getInstance(getActivity().getApplicationContext()).readByEvent(EventHelper.getInstance(getActivity().getApplicationContext()).getCurrentEvent())) {
onStaticFeatureLayer(l);
}
} catch (LayerException e) {
Log.e(LOG_NAME, "Problem updating static features.", e);
}
}
private void removeStaticFeatureLayers() {
Set<String> selectedLayerIds = preferences.getStringSet(getResources().getString(R.string.staticFeatureLayersKey), Collections.<String> emptySet());
Set<String> eventLayerIds = new HashSet<>();
try {
for (Layer layer : LayerHelper.getInstance(getActivity()).readByEvent(EventHelper.getInstance(getActivity().getApplicationContext()).getCurrentEvent())) {
eventLayerIds.add(layer.getRemoteId());
}
} catch (LayerException e) {
Log.e(LOG_NAME, "Problem reading static layers", e);
}
Set<String> layersNotInEvent = Sets.difference(selectedLayerIds, eventLayerIds);
for (String layerId : staticGeometryCollection.getLayers()) {
if (!selectedLayerIds.contains(layerId) || layersNotInEvent.contains(layerId)) {
staticGeometryCollection.removeLayer(layerId);
}
}
}
@Override
public void onStaticFeaturesCreated(final Layer layer) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
onStaticFeatureLayer(layer);
}
});
}
private void onStaticFeatureLayer(Layer layer) {
Set<String> layers = preferences.getStringSet(getString(R.string.staticFeatureLayersKey), Collections.<String> emptySet());
// The user has asked for this feature layer
String layerId = layer.getId().toString();
if (layers.contains(layerId) && layer.isLoaded()) {
new StaticFeatureLoadTask(getActivity().getApplicationContext(), staticGeometryCollection, map).executeOnExecutor(executor, layer);
}
}
private void updateMapView() {
// Check the map type
map.setMapType(preferences.getInt(getString(R.string.baseLayerKey), getResources().getInteger(R.integer.baseLayerDefaultValue)));
// Check the map location and zoom
String xyz = preferences.getString(getString(R.string.recentMapXYZKey), getString(R.string.recentMapXYZDefaultValue));
if (xyz != null) {
String[] values = StringUtils.split(xyz, ",");
LatLng latLng = new LatLng(0.0, 0.0);
if(values.length > 1) {
try {
latLng = new LatLng(Double.valueOf(values[1]), Double.valueOf(values[0]));
} catch (NumberFormatException nfe) {
Log.e(LOG_NAME, "Could not parse lon,lat: " + String.valueOf(values[1]) + ", " + String.valueOf(values[0]));
}
}
float zoom = 1.0f;
if(values.length > 2) {
try {
zoom = Float.valueOf(values[2]);
} catch (NumberFormatException nfe) {
Log.e(LOG_NAME, "Could not parse zoom level: " + String.valueOf(values[2]));
}
}
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
}
private void saveMapView() {
CameraPosition position = map.getCameraPosition();
String xyz = new StringBuilder().append(Double.valueOf(position.target.longitude).toString()).append(",").append(Double.valueOf(position.target.latitude).toString()).append(",").append(Float.valueOf(position.zoom).toString()).toString();
preferences.edit().putString(getResources().getString(R.string.recentMapXYZKey), xyz).commit();
}
@Override
public void onError(Throwable error) {
}
private int getTimeFilterId() {
return preferences.getInt(getResources().getString(R.string.activeTimeFilterKey), getResources().getInteger(R.integer.time_filter_none));
}
private int getLocationTimeFilterId() {
return preferences.getInt(getResources().getString(R.string.activeLocationTimeFilterKey), getResources().getInteger(R.integer.time_filter_none));
}
private int getCustomTimeNumber(String filterType) {
if (filterType.equalsIgnoreCase(OBSERVATION_FILTER_TYPE)) {
return preferences.getInt(getResources().getString(R.string.customObservationTimeNumberFilterKey), 0);
} else {
return preferences.getInt(getResources().getString(R.string.customLocationTimeNumberFilterKey), 0);
}
}
private String getCustomTimeUnit(String filterType) {
if (filterType.equalsIgnoreCase(OBSERVATION_FILTER_TYPE)) {
return preferences.getString(getResources().getString(R.string.customObservationTimeUnitFilterKey), getResources().getStringArray(R.array.timeUnitEntries)[0]);
} else {
return preferences.getString(getResources().getString(R.string.customLocationTimeUnitFilterKey), getResources().getStringArray(R.array.timeUnitEntries)[0]);
}
}
private Filter<Temporal> getTemporalFilter(String columnName, int filterId, String filterType) {
Filter<Temporal> filter = null;
Calendar c = Calendar.getInstance();
if (filterId == getResources().getInteger(R.integer.time_filter_last_month)) {
c.add(Calendar.MONTH, -1);
} else if (filterId == getResources().getInteger(R.integer.time_filter_last_week)) {
c.add(Calendar.DAY_OF_MONTH, -7);
} else if (filterId == getResources().getInteger(R.integer.time_filter_last_24_hours)) {
c.add(Calendar.HOUR, -24);
} else if (filterId == getResources().getInteger(R.integer.time_filter_today)) {
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
} else if (filterId == getResources().getInteger(R.integer.time_filter_custom)) {
String customFilterTimeUnit = getCustomTimeUnit(filterType);
int customTimeNumber = getCustomTimeNumber(filterType);
switch (customFilterTimeUnit) {
case "Hours":
c.add(Calendar.HOUR, -1 * customTimeNumber);
break;
case "Days":
c.add(Calendar.DAY_OF_MONTH, -1 * customTimeNumber);
break;
case "Months":
c.add(Calendar.MONTH, -1 * customTimeNumber);
break;
default:
c.add(Calendar.MINUTE, -1 * customTimeNumber);
break;
}
} else {
// no filter
c = null;
}
if (c != null) {
filter = new DateTimeFilter(c.getTime(), null, columnName);
}
return filter;
}
private String getFilterTitle() {
if (getTimeFilterId() != getResources().getInteger(R.integer.time_filter_none)
|| getLocationTimeFilterId() != getResources().getInteger(R.integer.time_filter_none)
|| preferences.getBoolean(getResources().getString(R.string.activeImportantFilterKey), false)
|| preferences.getBoolean(getResources().getString(R.string.activeFavoritesFilterKey), false)) {
return "Showing filtered results.";
} else {
return "";
}
}
private void hideKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (getActivity().getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
}
}
|
package org.redcross.openmapkit;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.widget.Toast;
import com.mapbox.mapboxsdk.tileprovider.tilesource.MBTilesLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer;
import com.mapbox.mapboxsdk.views.MapView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Basemap {
public static final String ONLINE = "Online Humanitarian OpenStreetMap";
private static final String PREVIOUS_BASEMAP = "org.redcross.openmapkit.PREVIOUS_BASEMAP";
private MapActivity mapActivity;
private MapView mapView;
private Context context;
private static String selectedBasemap;
/**
* This is how you select a basemap from outside of the MapActivity.
* We set a selected basemap static property, and when the MapActivity
* starts, it it instantiates a Basemap instance. In the constructor,
* it looks to see if we have a basemap that matches, and sets it
* accordingly.
*
* @param basemap - Either Basemap.ONLINE or a file path to an MBTiles file
*/
public static void select(String basemap) {
selectedBasemap = basemap;
}
public Basemap(MapActivity mapActivity) {
this.mapActivity = mapActivity;
this.mapView = mapActivity.getMapView();
this.context = mapActivity.getApplicationContext();
final SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE);
selectedBasemap = sharedPreferences.getString(PREVIOUS_BASEMAP, null);
if (selectedBasemap != null) {
// was online basemap
if (selectedBasemap.equals(ONLINE)) {
selectOnlineBasemap();
} else {
selectMBTilesBasemap(selectedBasemap);
}
} else {
presentBasemapsOptions();
}
}
public void presentBasemapsOptions() {
//shared preferences private to mapActivity
final SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE);
String previousBasemap = sharedPreferences.getString(PREVIOUS_BASEMAP, null);
//create an array of all mbtile options
final List<String> basemaps = new ArrayList<>();
//when device is connected, HOT OSM Basemap is the first option
if(Connectivity.isConnected(context)) {
basemaps.add(ONLINE);
}
//add mbtiles names from external storage
File[] mbtiles = ExternalStorage.fetchMBTilesFiles();
if (mbtiles.length > 0) {
for (File file : mbtiles) {
String filePath = file.getAbsolutePath();
basemaps.add(filePath);
}
}
if (basemaps.size() == 0) {
Toast prompt = Toast.makeText(context, "Device is offline. Please add .mbtiles file to " + ExternalStorage.getMBTilesDir() + " or check out a deployment.", Toast.LENGTH_LONG);
prompt.show();
return;
}
//create dialog of mbtiles choices
AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity);
builder.setTitle(mapActivity.getString(R.string.mbtilesChooserDialogTitle));
int len = basemaps.size();
String[] names = new String[len];
for (int i = 0; i < len; ++i) {
String basemap = basemaps.get(i);
if (basemap.equals(ONLINE)) {
names[i] = basemap;
} else {
names[i] = new File(basemap).getName();
}
}
//default mbtiles option is based on previous selections (persisted in shared preferences) or connectivity state of device
int defaultRadioButtonIndex = 0;
if(previousBasemap == null) {
//if user DID NOT previously choose an mbtiles option...
if(Connectivity.isConnected(context)) {
//the first radio button (for HOT OSM) will be selected by default
defaultRadioButtonIndex = 0;
//the default selected option is HOT OSM
selectedBasemap = basemaps.get(0); //default choice
} else {
defaultRadioButtonIndex = -1; //no selected radio button by default
}
} else {
//if user previously chose an mbtiles option ...
for(int i = 0; i < basemaps.size(); ++i) {
String filePath = basemaps.get(i);
if(filePath.equals(previousBasemap)) {
defaultRadioButtonIndex = i;
selectedBasemap = filePath;
}
}
if (selectedBasemap == null) {
selectedBasemap = basemaps.get(0);
}
}
//add choices to dialog
builder.setSingleChoiceItems(names, defaultRadioButtonIndex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setSelectedBasemap(basemaps.get(which));
}
});
//handle OK tap event of dialog
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked OK
if(selectedBasemap.equals(ONLINE)) {
selectOnlineBasemap();
} else {
selectMBTilesBasemap(selectedBasemap);
}
}
});
//handle cancel button tap event of dialog
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked cancel
}
});
//present dialog to user
builder.show();
}
private void selectOnlineBasemap() {
//create OSM tile layer
String defaultTilePID = mapActivity.getString(R.string.defaultTileLayerPID);
String defaultTileURL = mapActivity.getString(R.string.defaultTileLayerURL);
String defaultTileName = mapActivity.getString(R.string.defaultTileLayerName);
String defaultTileAttribution = mapActivity.getString(R.string.defaultTileLayerAttribution);
WebSourceTileLayer ws = new WebSourceTileLayer(defaultTilePID, defaultTileURL);
ws.setName(defaultTileName).setAttribution(defaultTileAttribution);
setSelectedBasemap(ONLINE);
//add OSM tile layer to map
mapView.setTileSource(ws);
}
private void selectMBTilesBasemap(String mbtilesPath) {
File mbtilesFile = new File(mbtilesPath);
if(!mbtilesFile.exists()) {
AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity);
builder.setTitle("Offline Basemap Not Found");
builder.setMessage("Please add MBTiles to " + ExternalStorage.getMBTilesDir());
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//placeholder
}
});
AlertDialog dialog = builder.create();
dialog.show();
return;
}
//add mbtiles to map
mapView.setTileSource(new MBTilesLayer(mbtilesFile));
setSelectedBasemap(mbtilesPath);
}
private void setSelectedBasemap(String basemap) {
selectedBasemap = basemap;
SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PREVIOUS_BASEMAP, selectedBasemap);
editor.apply();
}
}
|
package org.wikipedia.main;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.drawerlayout.widget.FixedDrawerLayout;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.SingleFragmentActivity;
import org.wikipedia.appshortcuts.AppShortcuts;
import org.wikipedia.auth.AccountUtil;
import org.wikipedia.feed.FeedFragment;
import org.wikipedia.history.HistoryFragment;
import org.wikipedia.navtab.NavTab;
import org.wikipedia.notifications.NotificationActivity;
import org.wikipedia.onboarding.InitialOnboardingActivity;
import org.wikipedia.page.PageActivity;
import org.wikipedia.page.tabs.TabActivity;
import org.wikipedia.settings.AboutActivity;
import org.wikipedia.settings.Prefs;
import org.wikipedia.settings.SettingsActivity;
import org.wikipedia.suggestededits.SuggestedEditsTasksFragment;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ResourceUtil;
import org.wikipedia.views.FrameLayoutNavMenuTriggerer;
import org.wikipedia.views.ImageZoomHelper;
import org.wikipedia.views.TabCountsView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static org.wikipedia.Constants.ACTIVITY_REQUEST_INITIAL_ONBOARDING;
public class MainActivity extends SingleFragmentActivity<MainFragment>
implements MainFragment.Callback, FrameLayoutNavMenuTriggerer.Callback {
@BindView(R.id.navigation_drawer) FixedDrawerLayout drawerLayout;
@BindView(R.id.navigation_drawer_view) MainDrawerView drawerView;
@BindView(R.id.navigation_drawer_triggerer) FrameLayoutNavMenuTriggerer triggererView;
@BindView(R.id.single_fragment_toolbar) Toolbar toolbar;
@BindView(R.id.drawer_icon_layout) View drawerIconLayout;
@BindView(R.id.drawer_icon_dot) View drawerIconDot;
@BindView(R.id.hamburger_and_wordmark_layout) View hamburgerAndWordmarkLayout;
private ImageZoomHelper imageZoomHelper;
private boolean controlNavTabInFragment;
public static Intent newIntent(@NonNull Context context) {
return new Intent(context, MainActivity.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
AppShortcuts.setShortcuts(this);
imageZoomHelper = new ImageZoomHelper(this);
if (Prefs.isInitialOnboardingEnabled() && savedInstanceState == null) {
// Updating preference so the search multilingual tooltip
// is not shown again for first time users
Prefs.setMultilingualSearchTutorialEnabled(false);
// Use startActivityForResult to avoid preload the Feed contents before finishing the initial onboarding.
// The ACTIVITY_REQUEST_INITIAL_ONBOARDING has not been used in any onActivityResult
startActivityForResult(InitialOnboardingActivity.newIntent(this), ACTIVITY_REQUEST_INITIAL_ONBOARDING);
}
setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.nav_tab_background_color));
setSupportActionBar(getToolbar());
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerStateChanged(int newState) {
if (newState == DrawerLayout.STATE_DRAGGING || newState == DrawerLayout.STATE_SETTLING) {
drawerView.updateState();
if (drawerIconDot.getVisibility() == VISIBLE) {
Prefs.setShowActionFeedIndicator(false);
setUpHomeMenuIcon();
}
}
}
});
drawerView.setCallback(new DrawerViewCallback());
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,
drawerLayout, toolbar,
R.string.main_drawer_open, R.string.main_drawer_close);
drawerToggle.syncState();
getToolbar().setNavigationIcon(null);
setUpHomeMenuIcon();
FeedbackUtil.setToolbarButtonLongPressToast(drawerIconLayout);
triggererView.setCallback(this);
}
@Override
public void onResume() {
super.onResume();
// update main nav drawer after rotating screen
drawerView.updateState();
setUpHomeMenuIcon();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
getFragment().requestUpdateToolbarElevation();
MenuItem tabsItem = menu.findItem(R.id.menu_tabs);
if (WikipediaApp.getInstance().getTabCount() < 1 || (getFragment().getCurrentFragment() instanceof SuggestedEditsTasksFragment)) {
tabsItem.setVisible(false);
} else {
tabsItem.setVisible(true);
TabCountsView tabCountsView = new TabCountsView(this, null);
tabCountsView.setOnClickListener(v -> {
if (WikipediaApp.getInstance().getTabCount() == 1) {
startActivity(PageActivity.newIntent(MainActivity.this));
} else {
startActivityForResult(TabActivity.newIntent(MainActivity.this), Constants.ACTIVITY_REQUEST_BROWSE_TABS);
}
});
tabCountsView.updateTabCount();
tabCountsView.setContentDescription(getString(R.string.menu_page_show_tabs));
tabsItem.setActionView(tabCountsView);
tabsItem.expandActionView();
FeedbackUtil.setToolbarButtonLongPressToast(tabCountsView);
}
return true;
}
@LayoutRes
@Override
protected int getLayout() {
return R.layout.activity_main;
}
@Override protected MainFragment createFragment() {
return MainFragment.newInstance();
}
@Override
public void onTabChanged(@NonNull NavTab tab) {
if (tab.equals(NavTab.EXPLORE)) {
hamburgerAndWordmarkLayout.setVisibility(VISIBLE);
toolbar.setTitle("");
controlNavTabInFragment = false;
} else {
if (tab.equals(NavTab.HISTORY) && getFragment().getCurrentFragment() != null) {
((HistoryFragment) getFragment().getCurrentFragment()).refresh();
}
if (tab.equals(NavTab.SUGGESTED_EDITS)) {
getFragment().hideNavTabOverlayLayout();
}
hamburgerAndWordmarkLayout.setVisibility(GONE);
toolbar.setTitle(tab.text());
controlNavTabInFragment = true;
}
getFragment().requestUpdateToolbarElevation();
}
void setUpHomeMenuIcon() {
drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() ? VISIBLE : GONE);
}
@OnClick(R.id.drawer_icon_layout) void onDrawerOpenClicked() {
drawerLayout.openDrawer(GravityCompat.START);
}
@Override
public void onNavMenuTriggered() {
drawerLayout.post(() -> {
onDrawerOpenClicked();
});
}
@Override
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
super.onSupportActionModeStarted(mode);
if (!controlNavTabInFragment) {
getFragment().setBottomNavVisible(false);
}
}
@Override
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
super.onSupportActionModeFinished(mode);
getFragment().setBottomNavVisible(true);
}
@Override
public void updateToolbarElevation(boolean elevate) {
if (elevate) {
setToolbarElevationDefault();
} else {
clearToolbarElevation();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
getFragment().handleIntent(intent);
}
@Override
protected void onGoOffline() {
getFragment().onGoOffline();
}
@Override
protected void onGoOnline() {
getFragment().onGoOnline();
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
if (getFragment().onBackPressed()) {
return;
}
super.onBackPressed();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
return imageZoomHelper.onDispatchTouchEvent(event) || super.dispatchTouchEvent(event);
}
public void closeMainDrawer() {
drawerLayout.closeDrawer(GravityCompat.START);
}
public Toolbar getToolbar() {
return toolbar;
}
protected void setToolbarElevationDefault() {
getToolbar().setElevation(DimenUtil.dpToPx(DimenUtil.getDimension(R.dimen.toolbar_default_elevation)));
}
protected void clearToolbarElevation() {
getToolbar().setElevation(0f);
}
private class DrawerViewCallback implements MainDrawerView.Callback {
@Override public void loginLogoutClick() {
if (AccountUtil.isLoggedIn()) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(R.string.logout_prompt)
.setNegativeButton(R.string.logout_dialog_cancel_button_text, null)
.setPositiveButton(R.string.preference_title_logout, (dialog, which) -> {
WikipediaApp.getInstance().logOut();
FeedbackUtil.showMessage(MainActivity.this, R.string.toast_logout_complete);
Prefs.setReadingListsLastSyncTime(null);
Prefs.setReadingListSyncEnabled(false);
getFragment().resetNavTabLayouts();
}).show();
} else {
getFragment().onLoginRequested();
}
closeMainDrawer();
}
@Override public void notificationsClick() {
if (AccountUtil.isLoggedIn()) {
startActivity(NotificationActivity.newIntent(MainActivity.this));
closeMainDrawer();
}
}
@Override public void settingsClick() {
getFragment().startActivityForResult(SettingsActivity.newIntent(MainActivity.this), Constants.ACTIVITY_REQUEST_SETTINGS);
closeMainDrawer();
}
@Override public void configureFeedClick() {
if (getFragment().getCurrentFragment() instanceof FeedFragment) {
((FeedFragment) getFragment().getCurrentFragment()).showConfigureActivity(-1);
}
closeMainDrawer();
}
@Override public void aboutClick() {
startActivity(new Intent(MainActivity.this, AboutActivity.class));
closeMainDrawer();
}
}
}
|
package com.gmail.alexellingsen.namelesswol.utils;
import com.gmail.alexellingsen.namelesswol.devices.Device;
import java.net.InetAddress;
/**
* Collection of validation methods.
*/
public class ValidateUtils {
/**
* Validates given host address by trying to parse it to a {@link java.net.InetAddress}.
*
* @param host The host address to validate.
* @return Returns {@code true} if the host address is valid, {@code false} otherwise.
*/
public static boolean validateHost(String host) {
try {
InetAddress.getByName(host);
} catch (Throwable t) {
return false;
}
return true;
}
/**
* Validates given MAC address.
*
* @param mac The MAC address to validate.
* @return Returns {@code true} if the MAC address is valid, {@code false} otherwise.
*/
public static boolean validateMAC(final String mac) {
try {
Device.validateMac(mac);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Validates given port number, checking if it's too low or too high.
*
* @param port The port to validate.
* @return Returns {@code true} if the port is valid, {@code false} otherwise.
*/
public static boolean validatePort(int port) {
return port >= 1 && port <= 65535;
}
}
|
package org.wikipedia.main;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.SingleFragmentActivity;
import org.wikipedia.appshortcuts.AppShortcuts;
import org.wikipedia.auth.AccountUtil;
import org.wikipedia.feed.FeedFragment;
import org.wikipedia.history.HistoryFragment;
import org.wikipedia.navtab.NavTab;
import org.wikipedia.notifications.NotificationActivity;
import org.wikipedia.onboarding.InitialOnboardingActivity;
import org.wikipedia.onboarding.SuggestedEditsOnboardingActivity;
import org.wikipedia.page.PageActivity;
import org.wikipedia.page.tabs.TabActivity;
import org.wikipedia.readinglist.ReadingListSyncBehaviorDialogs;
import org.wikipedia.readinglist.database.ReadingListDbHelper;
import org.wikipedia.settings.AboutActivity;
import org.wikipedia.settings.Prefs;
import org.wikipedia.settings.SettingsActivity;
import org.wikipedia.suggestededits.SuggestedEditsTasksActivity;
import org.wikipedia.util.AnimationUtil;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.views.TabCountsView;
import org.wikipedia.views.WikiDrawerLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static org.wikipedia.Constants.ACTIVITY_REQUEST_INITIAL_ONBOARDING;
public class MainActivity extends SingleFragmentActivity<MainFragment>
implements MainFragment.Callback {
@BindView(R.id.navigation_drawer) WikiDrawerLayout drawerLayout;
@BindView(R.id.navigation_drawer_view) MainDrawerView drawerView;
@BindView(R.id.single_fragment_toolbar) Toolbar toolbar;
@BindView(R.id.drawer_icon_layout) View drawerIconLayout;
@BindView(R.id.drawer_icon_dot) View drawerIconDot;
@BindView(R.id.hamburger_and_wordmark_layout) View hamburgerAndWordmarkLayout;
private boolean controlNavTabInFragment;
public static Intent newIntent(@NonNull Context context) {
return new Intent(context, MainActivity.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WikipediaApp.getInstance().checkCrashes(this);
ButterKnife.bind(this);
AnimationUtil.setSharedElementTransitions(this);
AppShortcuts.setShortcuts(this);
if (Prefs.isInitialOnboardingEnabled() && savedInstanceState == null) {
// Updating preference so the search multilingual tooltip
// is not shown again for first time users
Prefs.setMultilingualSearchTutorialEnabled(false);
// Use startActivityForResult to avoid preload the Feed contents before finishing the initial onboarding.
// The ACTIVITY_REQUEST_INITIAL_ONBOARDING has not been used in any onActivityResult
startActivityForResult(InitialOnboardingActivity.newIntent(this), ACTIVITY_REQUEST_INITIAL_ONBOARDING);
}
setSupportActionBar(getToolbar());
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
drawerLayout.setDragEdgeWidth(getResources().getDimensionPixelSize(R.dimen.drawer_drag_margin));
drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerStateChanged(int newState) {
if (newState == DrawerLayout.STATE_DRAGGING || newState == DrawerLayout.STATE_SETTLING) {
drawerView.updateState();
if (drawerIconDot.getVisibility() == VISIBLE) {
Prefs.setShowActionFeedIndicator(false);
setUpHomeMenuIcon();
}
}
}
});
drawerView.setCallback(new DrawerViewCallback());
shouldShowMainDrawer(true);
setUpHomeMenuIcon();
FeedbackUtil.setToolbarButtonLongPressToast(drawerIconLayout);
}
@Override
public void onResume() {
super.onResume();
// update main nav drawer after rotating screen
drawerView.updateState();
setUpHomeMenuIcon();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem tabsItem = menu.findItem(R.id.menu_tabs);
if (WikipediaApp.getInstance().getTabCount() < 1) {
tabsItem.setVisible(false);
} else {
tabsItem.setVisible(true);
TabCountsView tabCountsView = new TabCountsView(this);
tabCountsView.setOnClickListener(v -> {
if (WikipediaApp.getInstance().getTabCount() == 1) {
startActivity(PageActivity.newIntent(MainActivity.this));
} else {
startActivityForResult(TabActivity.newIntent(MainActivity.this), Constants.ACTIVITY_REQUEST_BROWSE_TABS);
}
});
tabCountsView.updateTabCount();
tabsItem.setActionView(tabCountsView);
tabsItem.expandActionView();
FeedbackUtil.setToolbarButtonLongPressToast(tabCountsView);
}
return true;
}
@LayoutRes
@Override
protected int getLayout() {
return R.layout.activity_main;
}
@Override protected MainFragment createFragment() {
return MainFragment.newInstance();
}
@Override
public void onTabChanged(@NonNull NavTab tab) {
if (tab.equals(NavTab.EXPLORE)) {
hamburgerAndWordmarkLayout.setVisibility(VISIBLE);
toolbar.setTitle("");
controlNavTabInFragment = false;
} else {
if (tab.equals(NavTab.HISTORY) && getFragment().getCurrentFragment() != null) {
((HistoryFragment) getFragment().getCurrentFragment()).refresh();
}
if (tab.equals(NavTab.NEARBY)) { // TODO: replace with Suggested Edits tab
getFragment().hideNavTabOverlayLayout();
Prefs.shouldShowBookmarkToolTip(false);
}
hamburgerAndWordmarkLayout.setVisibility(GONE);
toolbar.setTitle(tab.text());
controlNavTabInFragment = true;
}
shouldShowMainDrawer(!controlNavTabInFragment);
getFragment().requestUpdateToolbarElevation();
}
void setUpHomeMenuIcon() {
drawerIconDot.setVisibility(AccountUtil.isLoggedIn() && Prefs.showActionFeedIndicator() ? VISIBLE : GONE);
}
@OnClick(R.id.drawer_icon_layout) void onDrawerOpenClicked() {
drawerLayout.openDrawer(GravityCompat.START);
}
@Override
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
super.onSupportActionModeStarted(mode);
if (!controlNavTabInFragment) {
getFragment().setBottomNavVisible(false);
}
}
@Override
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
super.onSupportActionModeFinished(mode);
getFragment().setBottomNavVisible(true);
}
@Override
public void updateToolbarElevation(boolean elevate) {
if (elevate) {
setToolbarElevationDefault();
} else {
clearToolbarElevation();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
getFragment().handleIntent(intent);
}
@Override
protected void onGoOffline() {
getFragment().onGoOffline();
}
@Override
protected void onGoOnline() {
getFragment().onGoOnline();
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
if (getFragment().onBackPressed()) {
return;
}
super.onBackPressed();
}
public void closeMainDrawer() {
drawerLayout.closeDrawer(GravityCompat.START);
}
public Toolbar getToolbar() {
return toolbar;
}
public void shouldShowMainDrawer(boolean enabled) {
drawerLayout.setSlidingEnabled(enabled);
if (enabled) {
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,
drawerLayout, toolbar,
R.string.main_drawer_open, R.string.main_drawer_close);
drawerToggle.syncState();
getToolbar().setNavigationIcon(null);
}
}
protected void setToolbarElevationDefault() {
getToolbar().setElevation(DimenUtil.dpToPx(DimenUtil.getDimension(R.dimen.toolbar_default_elevation)));
}
protected void clearToolbarElevation() {
getToolbar().setElevation(0f);
}
private class DrawerViewCallback implements MainDrawerView.Callback {
@Override public void loginLogoutClick() {
if (AccountUtil.isLoggedIn()) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(R.string.logout_prompt)
.setNegativeButton(R.string.logout_dialog_cancel_button_text, null)
.setPositiveButton(R.string.preference_title_logout, (dialog, which) -> {
WikipediaApp.getInstance().logOut();
FeedbackUtil.showMessage(MainActivity.this, R.string.toast_logout_complete);
if (Prefs.isReadingListSyncEnabled() && !ReadingListDbHelper.instance().isEmpty()) {
ReadingListSyncBehaviorDialogs.removeExistingListsOnLogoutDialog(MainActivity.this);
}
Prefs.setReadingListsLastSyncTime(null);
Prefs.setReadingListSyncEnabled(false);
Prefs.setSuggestedEditsAddDescriptionsUnlocked(false);
Prefs.setSuggestedEditsTranslateDescriptionsUnlocked(false);
}).show();
} else {
getFragment().onLoginRequested();
}
closeMainDrawer();
}
@Override public void notificationsClick() {
if (AccountUtil.isLoggedIn()) {
startActivity(NotificationActivity.newIntent(MainActivity.this));
closeMainDrawer();
}
}
@Override public void settingsClick() {
startActivityForResult(SettingsActivity.newIntent(MainActivity.this), Constants.ACTIVITY_REQUEST_SETTINGS);
closeMainDrawer();
}
@Override public void configureFeedClick() {
if (getFragment().getCurrentFragment() instanceof FeedFragment) {
((FeedFragment) getFragment().getCurrentFragment()).showConfigureActivity(-1);
}
closeMainDrawer();
}
@Override
public void editingTasksClick() {
Prefs.setShowEditMenuOptionIndicator(false);
drawerView.maybeShowIndicatorDots();
startActivity(Prefs.showEditTaskOnboarding() ? SuggestedEditsOnboardingActivity.newIntent(MainActivity.this, Constants.InvokeSource.MAIN_ACTIVITY)
: SuggestedEditsTasksActivity.newIntent(MainActivity.this, Constants.InvokeSource.MAIN_ACTIVITY));
closeMainDrawer();
}
@Override public void aboutClick() {
startActivity(new Intent(MainActivity.this, AboutActivity.class));
closeMainDrawer();
}
}
}
|
package com.redhat.ceylon.compiler.typechecker.treegen;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
public class Generate {
private static final String GENERATED_PACKAGE_DIR = "gensrc/com/redhat/ceylon/compiler/typechecker/tree/";
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
tree(file);
//builder(file);
walker(file);
visitor(file);
visitorAdaptor(file);
validator(file);
}
private static void tree(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
TreegenLexer lexer = new TreegenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
TreegenParser parser = new TreegenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "Tree.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}
/*private static void builder(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
BuildergenLexer lexer = new BuildergenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
BuildergenParser parser = new BuildergenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "Builder.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}*/
private static void walker(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
WalkergenLexer lexer = new WalkergenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
WalkergenParser parser = new WalkergenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "Walker.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}
private static void visitor(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
VisitorgenLexer lexer = new VisitorgenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
VisitorgenParser parser = new VisitorgenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "Visitor.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}
private static void visitorAdaptor(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
VisitorAdaptorgenLexer lexer = new VisitorAdaptorgenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
VisitorAdaptorgenParser parser = new VisitorAdaptorgenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "VisitorAdaptor.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}
private static void validator(File file) throws Exception {
InputStream is = new FileInputStream( file );
ANTLRInputStream input = new ANTLRInputStream(is);
ValidatorgenLexer lexer = new ValidatorgenLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ValidatorgenParser parser = new ValidatorgenParser(tokens);
File out = new File( GENERATED_PACKAGE_DIR + "Validator.java" );
out.createNewFile();
Util.out=new PrintStream(out);
parser.nodeList();
}
}
|
package org.ow2.proactive.authentication.crypto;
import java.io.Serializable;
import org.objectweb.proactive.annotation.PublicAPI;
/**
* Dummy class used to properly separate login, password and key:
* will be serialized and encrypted
*
* @author The ProActive Team
* @since ProActive Scheduling 2.2
*/
@PublicAPI
public class CredData implements Serializable {
private String login = null;
private String pass = null;
// windows domain name, optionnal
private String domain = null;
//Optionnal ssh key
private byte[] key = null;
/**
* Extract the Windows domain name from the full login
* parseDomain("domain\\user") returns domain
* parseDomain("user") returns null
* @param fullLogin the login to parse
* @return the domain name, null if no domain is specified
* @since Scheduling 3.0.1
*/
public static final String parseDomain(String fullLogin) {
if (fullLogin.contains("\\")) {
String domain = fullLogin.substring(0, fullLogin.indexOf("\\"));
if ("".equals(domain.trim())) {
return null;
}
return "".equals(domain.trim()) ? null : domain;
} else {
return null;
}
}
/**
* Extract the user name from the full login
* parseDomain("domain\\user") returns user
* parseDomain("user") returns user
* @param fullLogin the login to parse
* @return the user name
* @since Scheduling 3.0.1
*/
public static final String parseLogin(String fullLogin) {
if (fullLogin.contains("\\")) {
String login = fullLogin.substring(fullLogin.indexOf("\\") + 1, fullLogin.length());
return login;
} else {
return fullLogin;
}
}
public CredData() {
}
public CredData(String login, String pass) {
this.login = login;
this.pass = pass;
}
/**
* @since Scheduling 3.0.1
*/
public CredData(String login, String domain, String pass) {
this.login = login;
this.pass = pass;
this.domain = domain;
}
public CredData(String login, String pass, byte[] key) {
this.login = login;
this.pass = pass;
this.key = key;
}
/**
* @since Scheduling 3.0.1
*/
public CredData(String login, String domain, String pass, byte[] key) {
this.login = login;
this.pass = pass;
this.key = key;
this.domain = domain;
}
/**
* Get the login
*
* @return the login
*/
public String getLogin() {
return login;
}
/**
* Set the login value to the given login value
*
* @param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* Get the password
*
* @return the password
*/
public String getPassword() {
return pass;
}
/**
* Set the password value to the given pass value
*
* @param pass the password to set
*/
public void setPassword(String pass) {
this.pass = pass;
}
/**
* Get the key
*
* @return the key
*/
public byte[] getKey() {
return key;
}
/**
* Set the key value to the given key value
*
* @param key the key to set
*/
public void setKey(byte[] key) {
this.key = key;
}
/**
* Return the domain of this user or null if no domain has been specified.
* @return the domain of this user or null if no domain has been specified.
* @since Scheduling 3.0.1
*/
public String getDomain() {
return domain;
}
/**
* Set a domain for this user. Domain is optionnal.
* @param domain the domain to set
* @since Scheduling 3.0.1
*/
public void setDomain(String domain) {
this.domain = domain;
}
/**
* Return the login and password as a string array.
* where element at index 0 is login and element at index 1 is password.
*
* @return the login and password as a string array.
*/
public String[] getLoginPassword() {
return new String[] { login, pass };
}
}
|
package dyvil.tools.compiler.ast.generic;
import dyvil.reflect.Modifiers;
import dyvil.tools.asm.TypeAnnotatableVisitor;
import dyvil.tools.asm.TypePath;
import dyvil.tools.asm.TypeReference;
import dyvil.tools.compiler.ast.annotation.AnnotationList;
import dyvil.tools.compiler.ast.annotation.IAnnotation;
import dyvil.tools.compiler.ast.classes.IClass;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.expression.ClassOperator;
import dyvil.tools.compiler.ast.expression.IValue;
import dyvil.tools.compiler.ast.expression.TypeOperator;
import dyvil.tools.compiler.ast.field.IDataMember;
import dyvil.tools.compiler.ast.method.IMethod;
import dyvil.tools.compiler.ast.method.MethodMatchList;
import dyvil.tools.compiler.ast.parameter.IArguments;
import dyvil.tools.compiler.ast.structure.IClassCompilableList;
import dyvil.tools.compiler.ast.type.IType;
import dyvil.tools.compiler.ast.type.IType.TypePosition;
import dyvil.tools.compiler.ast.type.builtin.Types;
import dyvil.tools.compiler.ast.type.compound.IntersectionType;
import dyvil.tools.compiler.ast.type.typevar.CovariantTypeVarType;
import dyvil.tools.compiler.backend.MethodWriter;
import dyvil.tools.compiler.backend.exception.BytecodeException;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.compiler.util.Markers;
import dyvil.tools.compiler.util.Util;
import dyvil.tools.parsing.Name;
import dyvil.tools.parsing.marker.Marker;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.parsing.position.ICodePosition;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.annotation.ElementType;
import static dyvil.tools.compiler.ast.type.builtin.Types.isSuperClass;
import static dyvil.tools.compiler.ast.type.builtin.Types.isSuperType;
public final class TypeParameter implements ITypeParameter
{
protected ICodePosition position;
private AnnotationList annotations;
protected Variance variance = Variance.INVARIANT;
protected Name name;
protected IType[] upperBounds = new IType[1];
protected int upperBoundCount;
protected IType lowerBound;
// Metadata
private int index;
private int parameterIndex;
private ITypeParametric generic;
private ReifiedKind reifiedKind = ReifiedKind.NOT_REIFIED;
private IType defaultType = Types.OBJECT;
private IType covariantType = new CovariantTypeVarType(this);
public TypeParameter(ITypeParametric generic)
{
this.generic = generic;
}
public TypeParameter(ITypeParametric generic, Name name)
{
this.name = name;
this.generic = generic;
}
public TypeParameter(ICodePosition position, ITypeParametric generic)
{
this.position = position;
this.generic = generic;
}
public TypeParameter(ICodePosition position, ITypeParametric generic, Name name, Variance variance)
{
this.position = position;
this.name = name;
this.generic = generic;
this.variance = variance;
}
@Override
public ITypeParametric getGeneric()
{
return this.generic;
}
@Override
public void setIndex(int index)
{
this.index = index;
}
@Override
public int getIndex()
{
return this.index;
}
@Override
public void setVariance(Variance variance)
{
this.variance = variance;
}
@Override
public Variance getVariance()
{
return this.variance;
}
@Override
public ReifiedKind getReifiedKind()
{
return this.reifiedKind;
}
@Override
public int getParameterIndex()
{
return this.parameterIndex;
}
@Override
public void setName(Name name)
{
this.name = name;
}
@Override
public Name getName()
{
return this.name;
}
@Override
public void setPosition(ICodePosition position)
{
this.position = position;
}
@Override
public ICodePosition getPosition()
{
return this.position;
}
@Override
public AnnotationList getAnnotations()
{
return this.annotations;
}
@Override
public void setAnnotations(AnnotationList annotations)
{
this.annotations = annotations;
}
@Override
public void addAnnotation(IAnnotation annotation)
{
if (this.annotations == null)
{
this.annotations = new AnnotationList();
}
this.annotations.addAnnotation(annotation);
}
@Override
public boolean addRawAnnotation(String type, IAnnotation annotation)
{
switch (type)
{
case "Ldyvil/annotation/_internal/Covariant;":
this.variance = Variance.COVARIANT;
return false;
case "Ldyvil/annotation/_internal/Contravariant;":
this.variance = Variance.CONTRAVARIANT;
return false;
}
return true;
}
@Override
public IAnnotation getAnnotation(IClass type)
{
return this.annotations == null ? null : this.annotations.getAnnotation(type);
}
@Override
public ElementType getElementType()
{
return ElementType.TYPE_PARAMETER;
}
@Override
public void addBoundAnnotation(IAnnotation annotation, int index, TypePath typePath)
{
this.upperBounds[index] = IType.withAnnotation(this.upperBounds[index], annotation, typePath, 0,
typePath.getLength());
}
@Override
public IType getDefaultType()
{
return this.defaultType;
}
@Override
public IType getCovariantType()
{
return this.covariantType;
}
@Override
public int upperBoundCount()
{
return this.upperBoundCount;
}
@Override
public void setUpperBound(int index, IType bound)
{
this.upperBounds[index] = bound;
}
@Override
public void addUpperBound(IType bound)
{
int index = this.upperBoundCount++;
if (index >= this.upperBounds.length)
{
IType[] temp = new IType[this.upperBoundCount];
System.arraycopy(this.upperBounds, 0, temp, 0, index);
this.upperBounds = temp;
}
this.upperBounds[index] = bound;
}
@Override
public IType getUpperBound(int index)
{
return this.upperBounds[index];
}
@Override
public IType[] getUpperBounds()
{
return this.upperBounds;
}
@Override
public void setLowerBound(IType bound)
{
this.lowerBound = bound;
}
@Override
public IType getLowerBound()
{
return this.lowerBound;
}
@Override
public IClass getTheClass()
{
if (this.lowerBound != null || this.upperBoundCount == 0)
{
return Types.OBJECT_CLASS;
}
return this.upperBounds[0].getTheClass();
}
@Override
public boolean isAssignableFrom(IType type, ITypeContext typeContext)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (!isSuperType(this.upperBounds[i].getConcreteType(typeContext), type))
{
return false;
}
}
if (this.lowerBound != null)
{
if (!isSuperType(type, this.lowerBound.getConcreteType(typeContext)))
{
return false;
}
}
return true;
}
@Override
public boolean isSameType(IType superType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (Types.isSameType(superType, this.upperBounds[i]))
{
return true;
}
}
if (this.lowerBound != null)
{
if (Types.isSameType(this.lowerBound, superType))
{
return true;
}
}
return false;
}
@Override
public boolean isSameClass(IType superType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (Types.isSameClass(superType, this.upperBounds[i]))
{
return true;
}
}
if (this.lowerBound != null)
{
if (Types.isSameClass(this.lowerBound, superType))
{
return true;
}
}
return false;
}
@Override
public boolean isSuperTypeOf(IType subType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (!isSuperType(this.upperBounds[i], subType))
{
return false;
}
}
if (this.lowerBound != null)
{
if (!isSuperType(subType, this.lowerBound))
{
return false;
}
}
return true;
}
@Override
public boolean isSuperClassOf(IType subType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (!isSuperClass(this.upperBounds[i], subType))
{
return false;
}
}
if (this.lowerBound != null)
{
if (!isSuperClass(subType, this.lowerBound))
{
return false;
}
}
return true;
}
@Override
public boolean isSubTypeOf(IType superType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (isSuperType(superType, this.upperBounds[i]))
{
return true;
}
}
if (this.lowerBound != null)
{
if (isSuperType(this.lowerBound, superType))
{
return true;
}
}
return Types.isSameType(superType, Types.OBJECT);
}
@Override
public boolean isSubClassOf(IType superType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
if (isSuperClass(superType, this.upperBounds[i]))
{
return true;
}
}
if (this.lowerBound != null)
{
if (isSuperClass(this.lowerBound, superType))
{
return true;
}
}
return Types.isSameClass(superType, Types.OBJECT);
}
@Override
public int getSuperTypeDistance(IType superType)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
int m = this.upperBounds[i].getSuperTypeDistance(superType);
if (m > 0)
{
return m;
}
}
return 2;
}
@Override
public IDataMember resolveField(Name name)
{
IDataMember field;
for (int i = 0; i < this.upperBoundCount; i++)
{
field = this.upperBounds[i].resolveField(name);
if (field != null)
{
return field;
}
}
return null;
}
@Override
public void getMethodMatches(MethodMatchList list, IValue instance, Name name, IArguments arguments)
{
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].getMethodMatches(list, instance, name, arguments);
}
}
@Override
public void resolveTypes(MarkerList markers, IContext context)
{
if (this.lowerBound != null)
{
this.lowerBound = this.lowerBound.resolveType(markers, context);
}
if (this.upperBoundCount > 0)
{
// The first upper bound is meant to be a class bound.
IType type = this.upperBounds[0] = this.upperBounds[0].resolveType(markers, context);
IClass iclass = type.getTheClass();
if (iclass != null && iclass.hasModifier(Modifiers.INTERFACE_CLASS))
{
// shift the entire array one to the right and insert
// Types.OBJECT at index 0
if (++this.upperBoundCount > this.upperBounds.length)
{
IType[] temp = new IType[this.upperBoundCount];
type = temp[0] = Types.OBJECT;
System.arraycopy(this.upperBounds, 0, temp, 1, this.upperBoundCount - 1);
this.upperBounds = temp;
}
else
{
System.arraycopy(this.upperBounds, 0, this.upperBounds, 1, this.upperBoundCount - 1);
type = this.upperBounds[0] = Types.OBJECT;
}
}
this.defaultType = type;
// Check if the remaining upper bounds are interfaces
for (int i = 1; i < this.upperBoundCount; i++)
{
type = this.upperBounds[i] = this.upperBounds[i].resolveType(markers, context);
this.defaultType = IntersectionType.combine(this.defaultType, type, null);
iclass = type.getTheClass();
if (iclass != null && !iclass.hasModifier(Modifiers.INTERFACE_CLASS))
{
final Marker marker = Markers.semanticError(type.getPosition(), "typeparameter.bound.class");
marker.addInfo(Markers.getSemantic("class.declaration", Util.classSignatureToString(iclass)));
markers.add(marker);
}
}
}
if (this.annotations != null)
{
this.annotations.resolveTypes(markers, context, this);
IAnnotation reifiedAnnotation = this.annotations.getAnnotation(Types.REIFIED_CLASS);
if (reifiedAnnotation != null)
{
final IValue erasure = reifiedAnnotation.getArguments().getFirstValue();
if (erasure != null && erasure.booleanValue())
{
this.reifiedKind = ReifiedKind.REIFIED_ERASURE;
}
else
{
this.reifiedKind = ReifiedKind.REIFIED_TYPE;
}
}
}
}
@Override
public void resolve(MarkerList markers, IContext context)
{
if (this.annotations != null)
{
this.annotations.resolve(markers, context);
}
if (this.lowerBound != null)
{
this.lowerBound.resolve(markers, context);
}
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].resolve(markers, context);
}
}
@Override
public void checkTypes(MarkerList markers, IContext context)
{
if (this.annotations != null)
{
this.annotations.checkTypes(markers, context);
}
if (this.lowerBound != null)
{
this.lowerBound.checkType(markers, context, TypePosition.SUPER_TYPE_ARGUMENT);
}
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].checkType(markers, context, TypePosition.SUPER_TYPE_ARGUMENT);
}
}
@Override
public void check(MarkerList markers, IContext context)
{
if (this.annotations != null)
{
this.annotations.check(markers, context, ElementType.TYPE_PARAMETER);
}
if (this.lowerBound != null)
{
this.lowerBound.check(markers, context);
}
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].check(markers, context);
}
}
@Override
public void foldConstants()
{
if (this.annotations != null)
{
this.annotations.foldConstants();
}
if (this.lowerBound != null)
{
this.lowerBound.foldConstants();
}
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].foldConstants();
}
}
@Override
public void cleanup(IContext context, IClassCompilableList compilableList)
{
if (this.annotations != null)
{
this.annotations.cleanup(context, compilableList);
}
if (this.lowerBound != null)
{
this.lowerBound.cleanup(context, compilableList);
}
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i].cleanup(context, compilableList);
}
}
@Override
public void appendSignature(StringBuilder buffer)
{
buffer.append(this.name).append(':');
if (this.upperBoundCount > 0)
{
if (this.upperBounds[0] != Types.OBJECT || this.upperBoundCount == 1)
{
this.upperBounds[0].appendSignature(buffer);
}
for (int i = 1; i < this.upperBoundCount; i++)
{
buffer.append(':');
this.upperBounds[i].appendSignature(buffer);
}
}
else
{
buffer.append("Ljava/lang/Object;");
}
}
@Override
public void appendParameterDescriptor(StringBuilder buffer)
{
if (this.reifiedKind == ReifiedKind.REIFIED_ERASURE)
{
buffer.append("Ljava/lang/Class;");
}
else if (this.reifiedKind == ReifiedKind.REIFIED_TYPE)
{
buffer.append("Ldyvilx/lang/model/type/Type;");
}
}
@Override
public void appendParameterSignature(StringBuilder buffer)
{
this.appendParameterDescriptor(buffer);
}
@Override
public void writeParameter(MethodWriter writer) throws BytecodeException
{
final IType type;
if (this.reifiedKind == ReifiedKind.REIFIED_ERASURE)
{
type = ClassOperator.LazyFields.CLASS;
}
else if (this.reifiedKind == ReifiedKind.REIFIED_TYPE)
{
type = TypeOperator.LazyFields.TYPE;
}
else
{
return;
}
this.parameterIndex = writer.localCount();
writer.visitParameter(this.parameterIndex, "reify$" + this.getName().qualified, type, Modifiers.MANDATED);
}
@Override
public void writeArgument(MethodWriter writer, IType type) throws BytecodeException
{
if (this.reifiedKind == ReifiedKind.REIFIED_ERASURE)
{
type.writeClassExpression(writer);
}
else if (this.reifiedKind == ReifiedKind.REIFIED_TYPE)
{
type.writeTypeExpression(writer);
}
}
@Override
public void write(TypeAnnotatableVisitor visitor)
{
boolean method = this.generic instanceof IMethod;
int typeRef = TypeReference.newTypeParameterReference(
method ? TypeReference.METHOD_TYPE_PARAMETER : TypeReference.CLASS_TYPE_PARAMETER, this.index);
if (this.variance != Variance.INVARIANT)
{
String type = this.variance == Variance.CONTRAVARIANT ?
"Ldyvil/annotation/_internal/Contravariant;" :
"Ldyvil/annotation/_internal/Covariant;";
visitor.visitTypeAnnotation(typeRef, null, type, true).visitEnd();
}
if (this.annotations != null)
{
for (int i = 0, count = this.annotations.annotationCount(); i < count; i++)
{
this.annotations.getAnnotation(i).write(visitor, typeRef, null);
}
}
for (int i = 0; i < this.upperBoundCount; i++)
{
final int boundTypeRef = TypeReference.newTypeParameterBoundReference(
method ? TypeReference.METHOD_TYPE_PARAMETER_BOUND : TypeReference.CLASS_TYPE_PARAMETER_BOUND,
this.index, i);
this.upperBounds[i].writeAnnotations(visitor, boundTypeRef, "");
}
}
@Override
public void write(DataOutput out) throws IOException
{
out.writeUTF(this.name.qualified);
Variance.write(this.variance, out);
IType.writeType(this.lowerBound, out);
out.writeShort(this.upperBoundCount);
for (int i = 0; i < this.upperBoundCount; i++)
{
IType.writeType(this.upperBounds[i], out);
}
}
@Override
public void read(DataInput in) throws IOException
{
this.name = Name.getQualified(in.readUTF());
this.variance = Variance.read(in);
this.lowerBound = IType.readType(in);
this.upperBoundCount = in.readShort();
for (int i = 0; i < this.upperBoundCount; i++)
{
this.upperBounds[i] = IType.readType(in);
}
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
this.toString("", builder);
return builder.toString();
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.annotations != null)
{
int count = this.annotations.annotationCount();
for (int i = 0; i < count; i++)
{
this.annotations.getAnnotation(i).toString(prefix, buffer);
buffer.append(' ');
}
}
this.variance.appendPrefix(buffer);
buffer.append(this.name);
if (this.lowerBound != null)
{
Formatting.appendSeparator(buffer, "type.bound", ">:");
this.lowerBound.toString(prefix, buffer);
}
if (this.upperBoundCount > 0)
{
Formatting.appendSeparator(buffer, "type.bound", "<:");
this.upperBounds[0].toString(prefix, buffer);
for (int i = 1; i < this.upperBoundCount; i++)
{
Formatting.appendSeparator(buffer, "type.bound.separator", '&');
this.upperBounds[i].toString(prefix, buffer);
}
}
}
}
|
package processing.app.debug;
import org.junit.Before;
import org.junit.Test;
import processing.app.AbstractWithPreferencesTest;
import processing.app.helpers.PreferencesMap;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class UploaderFactoryTest extends AbstractWithPreferencesTest {
private TargetPackage targetPackage;
@Before
public void setUp() throws Exception {
targetPackage = new TargetPackage("arduino", new File(".", "hardware/arduino/"));
}
@Test
public void shouldCreateAnInstanceOfHttpUploader() throws Exception {
TargetBoard board = targetPackage.getPlatforms().get("avr").getBoards().get("yun");
Uploader uploader = new UploaderFactory().newUploader(board, "192.168.0.1 (yun)");
assertTrue(uploader instanceof HttpUploader);
}
@Test
public void shouldCreateAnInstanceOfBasicUploaderWhenHTTPIsUnsupported() throws Exception {
TargetBoard board = targetPackage.getPlatforms().get("avr").getBoards().get("uno");
Uploader uploader = new UploaderFactory().newUploader(board, "192.168.0.1 (myyun)");
assertTrue(uploader instanceof BasicUploader);
}
@Test
public void shouldCreateAnInstanceOfBasicUploaderWhenPortIsSerial() throws Exception {
TargetBoard board = targetPackage.getPlatforms().get("avr").getBoards().get("uno");
Uploader uploader = new UploaderFactory().newUploader(board, "/dev/ttyACM0 (Arduino Leonardo)");
assertTrue(uploader instanceof BasicUploader);
}
}
|
package dyvil.tools.compiler.ast.header;
import dyvil.collection.Map;
import dyvil.collection.mutable.IdentityHashMap;
import dyvil.reflect.Modifiers;
import dyvil.tools.compiler.DyvilCompiler;
import dyvil.tools.compiler.ast.classes.IClass;
import dyvil.tools.compiler.ast.context.IContext;
import dyvil.tools.compiler.ast.context.IStaticContext;
import dyvil.tools.compiler.ast.expression.IValue;
import dyvil.tools.compiler.ast.external.ExternalClass;
import dyvil.tools.compiler.ast.field.IDataMember;
import dyvil.tools.compiler.ast.imports.ImportDeclaration;
import dyvil.tools.compiler.ast.member.IClassMember;
import dyvil.tools.compiler.ast.method.IMethod;
import dyvil.tools.compiler.ast.method.MatchList;
import dyvil.tools.compiler.ast.operator.IOperator;
import dyvil.tools.compiler.ast.operator.Operator;
import dyvil.tools.compiler.ast.parameter.IArguments;
import dyvil.tools.compiler.ast.structure.Package;
import dyvil.tools.compiler.ast.type.IType;
import dyvil.tools.compiler.ast.type.alias.ITypeAlias;
import dyvil.tools.compiler.ast.type.alias.TypeAlias;
import dyvil.tools.compiler.backend.IClassCompilable;
import dyvil.tools.compiler.config.Formatting;
import dyvil.tools.parsing.Name;
import dyvil.tools.parsing.ast.IASTNode;
import dyvil.tools.parsing.position.ICodePosition;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public abstract class AbstractHeader implements IHeaderUnit, IContext
{
protected PackageDeclaration packageDeclaration;
protected HeaderDeclaration headerDeclaration;
protected ImportDeclaration[] importDeclarations = new ImportDeclaration[8];
protected int importCount;
protected ITypeAlias[] typeAliases;
protected int typeAliasCount;
protected IOperator[] operators;
protected int operatorCount;
// Metadata
protected Name name;
protected Package pack;
protected Map<Name, IOperator> infixOperatorMap;
public AbstractHeader()
{
}
public AbstractHeader(Name name)
{
this.name = name;
}
@Override
public boolean isHeader()
{
return true;
}
@Override
public IContext getContext()
{
return new HeaderContext(this);
}
@Override
public ICodePosition getPosition()
{
return ICodePosition.ORIGIN;
}
@Override
public void setPosition(ICodePosition position)
{
}
@Override
public Name getName()
{
return this.name;
}
@Override
public void setName(Name name)
{
this.name = name;
}
@Override
public Package getPackage()
{
return this.pack;
}
@Override
public void setPackage(Package pack)
{
this.pack = pack;
}
@Override
public PackageDeclaration getPackageDeclaration()
{
return this.packageDeclaration;
}
@Override
public void setPackageDeclaration(PackageDeclaration packageDecl)
{
this.packageDeclaration = packageDecl;
}
@Override
public HeaderDeclaration getHeaderDeclaration()
{
return this.headerDeclaration;
}
@Override
public void setHeaderDeclaration(HeaderDeclaration declaration)
{
this.headerDeclaration = declaration;
}
@Override
public int importCount()
{
return this.importCount;
}
@Override
public void addImport(ImportDeclaration component)
{
final int index = this.importCount++;
if (index >= this.importDeclarations.length)
{
ImportDeclaration[] temp = new ImportDeclaration[index * 2];
System.arraycopy(this.importDeclarations, 0, temp, 0, this.importDeclarations.length);
this.importDeclarations = temp;
}
this.importDeclarations[index] = component;
}
@Override
public ImportDeclaration getImport(int index)
{
return this.importDeclarations[index];
}
@Override
public boolean hasMemberImports()
{
return this.importCount > 0;
}
// Operators
@Override
public int operatorCount()
{
return this.operatorCount;
}
@Override
public IOperator getOperator(int index)
{
return this.operators[index];
}
@Override
public void setOperator(int index, IOperator operator)
{
this.operators[index] = operator;
}
@Override
public void addOperator(IOperator operator)
{
if (this.operators == null)
{
this.operators = new Operator[4];
this.operators[0] = operator;
this.operatorCount = 1;
return;
}
final int index = this.operatorCount++;
if (index >= this.operators.length)
{
final IOperator[] temp = new IOperator[index * 2];
System.arraycopy(this.operators, 0, temp, 0, index);
this.operators = temp;
}
this.operators[index] = operator;
this.putOperator(operator);
}
private void putOperator(IOperator operator)
{
if (operator.getType() != IOperator.INFIX)
{
return;
}
final Name name = operator.getName();
if (this.infixOperatorMap == null)
{
this.infixOperatorMap = new IdentityHashMap<>();
this.infixOperatorMap.put(name, operator);
return;
}
final IOperator existing = this.infixOperatorMap.get(name);
if (existing == null)
{
this.infixOperatorMap.put(name, operator);
}
}
// Type Aliases
@Override
public int typeAliasCount()
{
return this.typeAliasCount;
}
@Override
public ITypeAlias getTypeAlias(int index)
{
return this.typeAliases[index];
}
@Override
public void setTypeAlias(int index, ITypeAlias typeAlias)
{
this.typeAliases[index] = typeAlias;
typeAlias.setEnclosingHeader(this);
}
@Override
public void addTypeAlias(ITypeAlias typeAlias)
{
typeAlias.setEnclosingHeader(this);
if (this.typeAliases == null)
{
this.typeAliases = new ITypeAlias[8];
this.typeAliases[0] = typeAlias;
this.typeAliasCount = 1;
return;
}
final int index = this.typeAliasCount++;
if (index >= this.typeAliases.length)
{
final ITypeAlias[] temp = new ITypeAlias[index * 2];
System.arraycopy(this.typeAliases, 0, temp, 0, index);
this.typeAliases = temp;
}
this.typeAliases[index] = typeAlias;
}
// Classes
@Override
public int classCount()
{
return 0;
}
@Override
public IClass getClass(Name name)
{
return null;
}
@Override
public void addClass(IClass iclass)
{
}
@Override
public IClass getClass(int index)
{
return null;
}
@Override
public int innerClassCount()
{
return 0;
}
@Override
public void addInnerClass(IClassCompilable iclass)
{
}
@Override
public IClassCompilable getInnerClass(int index)
{
return null;
}
// IContext override implementations
@Override
public IHeaderUnit getHeader()
{
return this;
}
@Override
public IHeaderUnit resolveHeader(Name name)
{
return name == this.name ? this : null;
}
@Override
public ITypeAlias resolveTypeAlias(Name name, int arity)
{
ITypeAlias candidate = null;
for (int i = 0; i < this.typeAliasCount; i++)
{
final ITypeAlias typeAlias = this.typeAliases[i];
if (typeAlias.getName() != name)
{
continue;
}
if (typeAlias.typeParameterCount() == arity)
{
return typeAlias;
}
if (candidate == null)
{
candidate = typeAlias;
}
}
return candidate;
}
@Override
public IOperator resolveOperator(Name name, int type)
{
if (type == IOperator.INFIX && this.infixOperatorMap != null)
{
final IOperator operator = this.infixOperatorMap.get(name);
if (operator != null)
{
return operator;
}
}
IOperator candidate = null;
for (int i = 0; i < this.operatorCount; i++)
{
final IOperator operator = this.operators[i];
if (operator.getName() != name)
{
continue;
}
if (operator.getType() == type)
{
return operator;
}
if (candidate == null)
{
candidate = operator;
}
}
return candidate;
}
@Override
public byte getVisibility(IClassMember member)
{
IClass iclass = member.getEnclosingClass();
int access = member.getAccessLevel();
if ((access & Modifiers.INTERNAL) != 0)
{
if (iclass instanceof ExternalClass)
{
return INTERNAL;
}
// Clear the INTERNAL bit by ANDing with 0b1111
access &= 0b1111;
}
if (access == Modifiers.PUBLIC)
{
return VISIBLE;
}
if (access == Modifiers.PROTECTED || access == Modifiers.PACKAGE)
{
IHeaderUnit header = iclass.getHeader();
if (header != null && (header == this || this.pack == header.getPackage()))
{
return VISIBLE;
}
}
return INVISIBLE;
}
// Compilation
@Override
public String getFullName()
{
return this.pack.getFullName() + '.' + this.name;
}
@Override
public String getFullName(Name name)
{
if (name != this.name)
{
return this.pack.getFullName() + '.' + this.name.qualified + '.' + name.qualified;
}
return this.pack.getFullName() + '.' + name.qualified;
}
@Override
public String getInternalName()
{
return this.pack.getInternalName() + this.name;
}
@Override
public String getInternalName(Name name)
{
if (name != this.name)
{
return this.pack.getInternalName() + this.name.qualified + '$' + name;
}
return this.pack.getInternalName() + name.qualified;
}
@Override
public void write(DataOutput out) throws IOException
{
// Header Name
this.headerDeclaration.write(out);
// Import Declarations
int imports = this.importCount;
out.writeShort(imports);
for (int i = 0; i < imports; i++)
{
this.importDeclarations[i].write(out);
}
// Operators Definitions
out.writeShort(this.operatorCount);
for (int i = 0; i < this.operatorCount; i++)
{
this.operators[i].writeData(out);
}
// Type Aliases
out.writeShort(this.typeAliasCount);
for (int i = 0; i < this.typeAliasCount; i++)
{
this.typeAliases[i].write(out);
}
// Classes
out.writeShort(0);
}
@Override
public void read(DataInput in) throws IOException
{
this.headerDeclaration = new HeaderDeclaration(this);
this.headerDeclaration.read(in);
this.name = this.headerDeclaration.getName();
// Import Declarations
int imports = in.readShort();
for (int i = 0; i < imports; i++)
{
ImportDeclaration id = new ImportDeclaration(null);
id.read(in);
this.addImport(id);
}
int operators = in.readShort();
for (int i = 0; i < operators; i++)
{
Operator op = Operator.read(in);
this.addOperator(op);
}
int typeAliases = in.readShort();
for (int i = 0; i < typeAliases; i++)
{
TypeAlias ta = new TypeAlias();
ta.read(in);
this.addTypeAlias(ta);
}
}
@Override
public String toString()
{
return IASTNode.toString(this);
}
@Override
public void toString(String prefix, StringBuilder buffer)
{
if (this.packageDeclaration != null)
{
buffer.append(prefix);
this.packageDeclaration.toString(prefix, buffer);
buffer.append(";\n");
if (Formatting.getBoolean("package.newline"))
{
buffer.append('\n');
}
}
if (this.importCount > 0)
{
for (int i = 0; i < this.importCount; i++)
{
buffer.append(prefix);
this.importDeclarations[i].toString(prefix, buffer);
buffer.append(";\n");
}
if (Formatting.getBoolean("import.newline"))
{
buffer.append('\n');
}
}
if (this.operatorCount > 0)
{
for (int i = 0; i < this.operatorCount; i++)
{
buffer.append(prefix);
this.operators[i].toString(buffer);
buffer.append(";\n");
}
if (Formatting.getBoolean("import.newline"))
{
buffer.append('\n');
}
}
if (this.typeAliasCount > 0)
{
for (int i = 0; i < this.typeAliasCount; i++)
{
buffer.append(prefix);
this.typeAliases[i].toString(prefix, buffer);
buffer.append(";\n");
}
if (Formatting.getBoolean("import.newline"))
{
buffer.append('\n');
}
}
if (this.headerDeclaration != null)
{
this.headerDeclaration.toString(prefix, buffer);
buffer.append('\n');
buffer.append('\n');
}
}
}
class HeaderContext implements IStaticContext
{
private AbstractHeader header;
public HeaderContext(AbstractHeader header)
{
this.header = header;
}
@Override
public DyvilCompiler getCompilationContext()
{
return this.header.getCompilationContext();
}
@Override
public IHeaderUnit getHeader()
{
return this.header;
}
@Override
public Package resolvePackage(Name name)
{
return this.header.resolvePackage(name);
}
@Override
public IHeaderUnit resolveHeader(Name name)
{
return this.header.resolveHeader(name);
}
@Override
public ITypeAlias resolveTypeAlias(Name name, int arity)
{
final ITypeAlias candidate = this.header.resolveTypeAlias(name, arity);
if (candidate != null && candidate.typeParameterCount() == arity)
{
return candidate;
}
for (int i = 0; i < this.header.importCount; i++)
{
final ITypeAlias includedTypeAlias = this.header.importDeclarations[i].getContext()
.resolveTypeAlias(name, arity);
if (includedTypeAlias != null && includedTypeAlias.typeParameterCount() == arity)
{
return includedTypeAlias;
}
}
return candidate;
}
@Override
public IOperator resolveOperator(Name name, int type)
{
final IOperator candidate = this.header.resolveOperator(name, type);
if (candidate != null && candidate.getType() == type)
{
return candidate;
}
for (int i = 0; i < this.header.importCount; i++)
{
final IOperator operator = this.header.importDeclarations[i].getContext().resolveOperator(name, type);
if (operator != null && operator.getType() == type)
{
return operator;
}
}
return candidate;
}
@Override
public IClass resolveClass(Name name)
{
IClass theClass = this.header.resolveClass(name);
if (theClass != null)
{
return theClass;
}
// Imported Classes
for (int i = 0; i < this.header.importCount; i++)
{
theClass = this.header.importDeclarations[i].getContext().resolveClass(name);
if (theClass != null)
{
return theClass;
}
}
if (this.header.pack != null)
{
return this.header.pack.resolveClass(name);
}
return null;
}
@Override
public IDataMember resolveField(Name name)
{
IDataMember field = this.header.resolveField(name);
if (field != null)
{
return field;
}
for (int i = 0; i < this.header.importCount; i++)
{
field = this.header.importDeclarations[i].getContext().resolveField(name);
if (field != null)
{
return field;
}
}
return null;
}
@Override
public void getMethodMatches(MatchList<IMethod> list, IValue receiver, Name name, IArguments arguments)
{
// For ordinary headers, this is a no-op, since they (currently) cannot host any free-standing functions
// The REPL however can, so we need this call
this.header.getMethodMatches(list, receiver, name, arguments);
if (!list.isEmpty())
{
return;
}
for (int i = 0; i < this.header.importCount; i++)
{
this.header.importDeclarations[i].getContext().getMethodMatches(list, receiver, name, arguments);
}
}
@Override
public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType)
{
// See comment in getMethodMatches for rationale
this.header.getImplicitMatches(list, value, targetType);
if (!list.isEmpty())
{
return;
}
for (int i = 0; i < this.header.importCount; i++)
{
this.header.importDeclarations[i].getContext().getImplicitMatches(list, value, targetType);
}
}
}
|
package com.sequenceiq.cloudbreak.logger;
import java.util.Arrays;
import javax.inject.Inject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.common.anonymizer.AnonymizerUtil;
@Component
@Aspect
public class ControllerLogContextAspects {
private static final Logger LOGGER = LoggerFactory.getLogger(ControllerLogContextAspects.class);
@Inject
private LogContextService logContextService;
@Pointcut("execution(public * com.sequenceiq.cloudbreak..*.*Controller.*(..))")
public void interceptControllerMethodCalls() {
}
@Before("com.sequenceiq.cloudbreak.logger.ControllerLogContextAspects.interceptControllerMethodCalls()")
public void buildLogContextForControllerCalls(JoinPoint joinPoint) {
try {
Object[] args = joinPoint.getArgs();
CodeSignature sig = (CodeSignature) joinPoint.getSignature();
String[] paramNames = sig.getParameterNames();
logContextService.buildMDCParams(joinPoint.getTarget(), paramNames, args);
MDCBuilder.addRequestId(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString()));
LOGGER.debug("A controller method has been intercepted: {} with params {}, {}, MDC logger context is built.", joinPoint.toShortString(),
sig.getParameterNames(), AnonymizerUtil.anonymize(Arrays.toString(args)));
} catch (Exception any) {
LOGGER.warn("MDCContext build failed: ", any);
}
}
}
|
package org.lemurproject.galago.core.tools.apps;
import java.io.PrintStream;
import org.lemurproject.galago.core.index.IndexPartReader;
import org.lemurproject.galago.core.index.KeyIterator;
import org.lemurproject.galago.core.index.disk.DiskIndex;
import org.lemurproject.galago.core.retrieval.iterator.MovableCountIterator;
import org.lemurproject.galago.core.retrieval.processing.ScoringContext;
import org.lemurproject.galago.core.tools.AppFunction;
import org.lemurproject.galago.tupleflow.Parameters;
/**
*
* @author sjh
*/
public class DumpTermStatisticsFn extends AppFunction {
@Override
public String getName() {
return "dump-term-stats";
}
@Override
public String getHelpString() {
return "galago dump-term-stats <index-part> \n\n"
+ " Dumps <term> <frequency> <document count> statsistics from the"
+ " the specified index part.\n";
}
@Override
public void run(String[] args, PrintStream output)
throws Exception {
IndexPartReader reader = DiskIndex.openIndexPart(args[1]);
KeyIterator iterator = reader.getIterator();
ScoringContext sc = new ScoringContext();
while (!iterator.isDone()) {
MovableCountIterator mci = (MovableCountIterator) iterator.getValueIterator();
mci.setContext(sc);
long frequency = 0;
long documentCount = 0;
while (!mci.isDone()) {
sc.document = mci.currentCandidate();
if (mci.hasMatch(mci.currentCandidate())) {
frequency += mci.count();
documentCount++;
}
mci.movePast(mci.currentCandidate());
}
output.printf("%s\t%d\t%d\n", iterator.getKeyString(), frequency, documentCount);
iterator.nextKey();
}
reader.close();
}
@Override
public void run(Parameters p, PrintStream output) throws Exception {
String indexPath = p.getString("indexPath");
run(new String[]{"", indexPath}, output);
}
}
|
package org.folio.rest.tools;
import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.Properties;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ResourceInfo;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
/**
* @author shale
*
*/
public enum PomReader {
INSTANCE;
private String moduleName = null;
private String version = null;
private Properties props = null;
private List<Dependency> dependencies = null;
private String rmbVersion = null;
private final Logger log = LoggerFactory.getLogger(PomReader.class);
@SuppressWarnings("checkstyle:methodlength")
private PomReader() {
try {
System.out.print("Attempting to read in the module name from....");
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
Model model = null;
String currentRunningJar =
PomReader.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
System.out.println(currentRunningJar);
if(currentRunningJar != null && (currentRunningJar.contains("domain-models-runtime")
|| currentRunningJar.contains("domain-models-interface-extensions"))){
//the runtime is the jar run when deploying during unit tests
//the interface-extensions is the jar run when running build time tools,
//like MDGenerator, ClientGenerator, etc..
//this is build time - not runtime, so just use the pom
File pomFile = new File("pom.xml");
model = mavenreader.read(new FileReader(pomFile));
}
else{
//this is runtime, the jar called via java -jar is the module's jar
ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
ImmutableSet<ResourceInfo> resources = classPath.getResources();
for (ResourceInfo info : resources) {
if(info.getResourceName().endsWith("pom.xml")){
//maven sets the classpath order according to the pom, so the poms project will be the first entry
model = mavenreader.read(PomReader.class.getResourceAsStream("/"+info.getResourceName()));
break;
}
}
}
if(model.getParent() != null){
moduleName = model.getParent().getArtifactId();
version = model.getParent().getVersion();
}
else{
moduleName = model.getArtifactId();
}
if(version == null){
version = model.getVersion();
if(version == null){
version = "1.0.0";
}
}
version = version.replaceAll("-.*", "");
moduleName = moduleName.replaceAll("-", "_");
props = model.getProperties();
dependencies = model.getDependencies();
for (int i = 0; i < dependencies.size(); i++) {
if("domain-models-runtime".equals(dependencies.get(i).getArtifactId())){
rmbVersion = dependencies.get(i).getVersion();
}
}
if(rmbVersion == null){
//if we are in the rmb jar - build time
rmbVersion = version;
}
//props.list(System.out);
log.info("module name: " + moduleName + ", version: " + version);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public String getVersion() {
return version;
}
public String getModuleName() {
return moduleName;
}
public Properties getProps() {
return props;
}
public List<Dependency> getDependencies() {
return dependencies;
}
public String getRmbVersion() {
return rmbVersion;
}
}
|
package org.apache.tinkerpop.gremlin.orientdb;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.storage.ORecordDuplicatedException;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.orientdb.traversal.step.sideEffect.OrientGraphStep;
import org.apache.tinkerpop.gremlin.orientdb.traversal.strategy.optimization.OrientGraphStepStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class OrientGraphIndexTest {
public static final String URL = "memory:" + OrientGraphIndexTest.class.getSimpleName();
// public static final String URL = "remote:localhost/test";
private OrientGraph newGraph() {
return new OrientGraphFactory(URL + UUID.randomUUID(), "root", "root").getNoTx();
}
String vertexLabel1 = "SomeVertexLabel1";
String vertexLabel2 = "SomeVertexLabel2";
String edgeLabel1 = "SomeEdgeLabel1";
String edgeLabel2 = "SomeEdgeLabel2";
String key = "indexedKey";
@Test
public void vertexUniqueConstraint() {
OrientGraph graph = newGraph();
createVertexIndexLabel1(graph);
String value = "value1";
graph.addVertex(T.label, vertexLabel1, key, value);
graph.addVertex(T.label, vertexLabel2, key, value);
// no duplicates allowed for vertex with label1
try {
graph.addVertex(T.label, vertexLabel1, key, value);
Assert.fail("must throw duplicate key here!");
} catch (ORecordDuplicatedException e) {
}
// allow duplicate for vertex with label2
graph.addVertex(T.label, vertexLabel2, key, value);
}
@Test
public void edgeUniqueConstraint() {
OrientGraph graph = newGraph();
createUniqueEdgeIndex(graph, edgeLabel1);
String value = "value1";
Vertex v1 = graph.addVertex(T.label, vertexLabel1);
Vertex v2 = graph.addVertex(T.label, vertexLabel1);
v1.addEdge(edgeLabel1, v2, key, value);
// no duplicates allowed for edge with label1
try {
v1.addEdge(edgeLabel1, v2, key, value);
Assert.fail("must throw duplicate key here!");
} catch (ORecordDuplicatedException e) {
}
// allow duplicate for vertex with label2
v2.addEdge(edgeLabel2, v1, key, value);
}
@Test
public void vertexUniqueIndexLookupWithValue() {
OrientGraph graph = newGraph();
createVertexIndexLabel1(graph);
String value = "value1";
// verify index created
Assert.assertEquals(graph.getIndexedKeys(Vertex.class, vertexLabel1), new HashSet<>(Collections.singletonList(key)));
Assert.assertEquals(graph.getIndexedKeys(Vertex.class, vertexLabel2), new HashSet<>(Collections.emptyList()));
Assert.assertEquals(graph.getIndexedKeys(Edge.class, vertexLabel1), new HashSet<>(Collections.emptyList()));
Vertex v1 = graph.addVertex(T.label, vertexLabel1, key, value);
Vertex v2 = graph.addVertex(T.label, vertexLabel2, key, value);
// looking deep into the internals here - I can't find a nicer way to
// auto verify that an index is actually used
GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V().has(T.label, P.eq(vertexLabel1)).has(key, P.eq(value));
OIndex index = findUsedIndex(traversal).get().index;
Assert.assertEquals(1, index.getSize());
Assert.assertEquals(v1.id(), index.get(value));
List<Vertex> result = traversal.toList();
Assert.assertEquals(1, result.size());
Assert.assertEquals(v1.id(), result.get(0).id());
}
@Test
public void vertexUniqueIndexLookupWithMultipleValues() {
OrientGraph graph = newGraph();
createVertexIndexLabel1(graph);
// verify index created
Assert.assertEquals(graph.getIndexedKeys(Vertex.class, vertexLabel1), new HashSet<>(Collections.singletonList(key)));
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";
Vertex v1 = graph.addVertex(T.label, vertexLabel1, key, value1);
Vertex v2 = graph.addVertex(T.label, vertexLabel1, key, value2);
Vertex v3 = graph.addVertex(T.label, vertexLabel1, key, value3);
// looking deep into the internals here - I can't find a nicer way to
// auto verify that an index is actually used
// GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V().has(T.label, P.eq(vertexLabel1)).has(key, P.eq(value1));
GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V().has(T.label, P.eq(vertexLabel1)).has(key, P.within(value1, value2));
OIndex index = findUsedIndex(traversal).get().index;
Assert.assertEquals(3, index.getSize());
Assert.assertEquals(v1.id(), index.get(value1));
Assert.assertEquals(v2.id(), index.get(value2));
List<Vertex> result = traversal.toList();
Assert.assertEquals(2, result.size());
Assert.assertEquals(v1.id(), result.get(0).id());
Assert.assertEquals(v2.id(), result.get(1).id());
}
@Test
public void edgeUniqueIndexLookupWithValue() {
OrientGraph graph = newGraph();
createUniqueEdgeIndex(graph, edgeLabel1);
String value = "value1";
Assert.assertEquals(graph.getIndexedKeys(Edge.class, edgeLabel1), new HashSet<>(Collections.singletonList(key)));
Assert.assertEquals(graph.getIndexedKeys(Edge.class, edgeLabel2), new HashSet<>(Collections.emptyList()));
Assert.assertEquals(graph.getIndexedKeys(Vertex.class, vertexLabel1), new HashSet<>(Collections.emptyList()));
Vertex v1 = graph.addVertex(T.label, vertexLabel1);
Vertex v2 = graph.addVertex(T.label, vertexLabel1);
Edge e1 = v1.addEdge(edgeLabel1, v2, key, value);
Edge e2 = v1.addEdge(edgeLabel2, v2, key, value);
{
// Verify that the traversal hits the index for the edges with label1
GraphTraversal<Edge, Edge> traversal1 = graph.traversal().E().has(T.label, P.eq(edgeLabel1)).has(key, P.eq(value));
Optional<OrientIndexQuery> orientIndexQuery = findUsedIndex(traversal1);
Assert.assertTrue(orientIndexQuery.isPresent());
OIndex index = orientIndexQuery.get().index;
Assert.assertEquals(1, index.getSize());
Assert.assertEquals(e1.id(), index.get(value));
List<Edge> result1 = traversal1.toList();
Assert.assertEquals(1, result1.size());
Assert.assertEquals(e1.id(), result1.get(0).id());
}
{
// Verify that the traversal doesn't try to hit the index for the edges with label2
GraphTraversal<Edge, Edge> traversal2 = graph.traversal().E().has(T.label, P.eq(edgeLabel2)).has(key, P.eq(value));
Assert.assertFalse(findUsedIndex(traversal2).isPresent());
List<Edge> result2 = traversal2.toList();
Assert.assertEquals(1, result2.size());
Assert.assertEquals(e2.id(), result2.get(0).id());
}
}
@Test
public void edgeNotUniqueIndexLookupWithValue() {
OrientGraph graph = newGraph();
createNotUniqueEdgeIndex(graph, edgeLabel1);
String value = "value1";
Assert.assertEquals(graph.getIndexedKeys(Edge.class, edgeLabel1), new HashSet<>(Collections.singletonList(key)));
Assert.assertEquals(graph.getIndexedKeys(Edge.class, edgeLabel2), new HashSet<>(Collections.emptyList()));
Assert.assertEquals(graph.getIndexedKeys(Vertex.class, vertexLabel1), new HashSet<>(Collections.emptyList()));
Vertex v1 = graph.addVertex(T.label, vertexLabel1);
Vertex v2 = graph.addVertex(T.label, vertexLabel1);
Edge e1 = v1.addEdge(edgeLabel1, v2, key, value);
Edge e2 = v1.addEdge(edgeLabel1, v2, key, value);
Edge e3 = v1.addEdge(edgeLabel1, v2);
// Verify that the traversal hits the index for the edges with label1
GraphTraversal<Edge, Edge> traversal1 = graph.traversal().E().has(T.label, P.eq(edgeLabel1)).has(key, P.eq(value));
Optional<OrientIndexQuery> orientIndexQuery = findUsedIndex(traversal1);
Assert.assertTrue(orientIndexQuery.isPresent());
OIndex index = orientIndexQuery.get().index;
Assert.assertEquals(2, index.getSize());
Assert.assertTrue(((Collection) index.get(value)).contains(e1.id()));
Assert.assertTrue(((Collection) index.get(value)).contains(e2.id()));
Assert.assertFalse(((Collection) index.get(value)).contains(e3.id()));
List<Edge> result1 = traversal1.toList();
Assert.assertEquals(2, result1.size());
Assert.assertTrue(result1.stream().map(Edge::id).anyMatch(e1.id()::equals));
Assert.assertTrue(result1.stream().map(Edge::id).anyMatch(e2.id()::equals));
Assert.assertFalse(result1.stream().map(Edge::id).anyMatch(e3.id()::equals));
}
//TODO: fix
@Test
public void indexCollation() {
OrientGraph graph = newGraph();
String label = "VC1";
String key = "name";
String value = "bob";
Configuration config = new BaseConfiguration();
config.setProperty("type", "UNIQUE");
config.setProperty("keytype", OType.STRING);
config.setProperty("collate", "ci");
graph.createVertexIndex(key, label, config);
graph.addVertex(T.label, label, key, value);
// TODO: test with a "has" traversal, if/when that supports a case insensitive match predicate
// OrientIndexQuery indexRef = new OrientIndexQuery(true, Optional.of(label), key, value.toUpperCase());
// Iterator<OrientVertex> result = graph.getIndexedVertices(indexRef).iterator();
// Assert.assertEquals(result.hasNext(), true);
}
private Optional<OrientIndexQuery> findUsedIndex(GraphTraversal<?, ?> traversal) {
OrientGraphStepStrategy.instance().apply(traversal.asAdmin());
@SuppressWarnings("rawtypes")
OrientGraphStep orientGraphStep = (OrientGraphStep) traversal.asAdmin().getStartStep();
return orientGraphStep.findIndex();
}
private void createVertexIndexLabel1(OrientGraph graph) {
Configuration config = new BaseConfiguration();
config.setProperty("type", "UNIQUE");
config.setProperty("keytype", OType.STRING);
graph.createVertexIndex(key, vertexLabel1, config);
}
private void createUniqueEdgeIndex(OrientGraph graph, String label) {
Configuration config = new BaseConfiguration();
config.setProperty("type", OClass.INDEX_TYPE.UNIQUE.name());
config.setProperty("keytype", OType.STRING);
graph.createEdgeIndex(key, label, config);
}
private void createNotUniqueEdgeIndex(OrientGraph graph, String label) {
Configuration config = new BaseConfiguration();
config.setProperty("type", OClass.INDEX_TYPE.NOTUNIQUE.name());
config.setProperty("keytype", OType.STRING);
graph.createEdgeIndex(key, label, config);
}
}
|
package com.box.boxjavalibv2.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import com.box.boxjavalibv2.dao.BoxCollection;
import com.box.boxjavalibv2.dao.BoxResourceType;
import com.box.boxjavalibv2.dao.BoxTypedObject;
/**
* Utils class.
*/
public final class Utils {
/**
* Private constructor so the class cannot be instantiated.
*/
private Utils() {
}
/**
* Given a resource type, get the string for it's REST API container. For example, given a {@link BoxResourceType#FILE}, it it's container would be "files".
*
* @param type
* type
* @return container string
*/
public static String getContainerString(final BoxResourceType type) {
switch (type) {
case FILE_VERSION:
return "versions";
default:
return type.toPluralString();
}
}
/**
* Filter out a list of specified type BoxTypedObject's from a Collection
*
* @param collection
* collection to be filtered.
* @param cls
* class of the type to be filtered. e.g. BoxFile.class.
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends BoxTypedObject> List<T> getTypedObjects(BoxCollection collection, Class<T> cls) {
List<T> objects = new ArrayList<T>();
List<BoxTypedObject> list = collection.getEntries();
for (BoxTypedObject object : list) {
if (cls.isInstance(object)) {
objects.add((T) object);
}
}
return objects;
}
/**
* Ensures that the entity content is fully consumed and the content stream, if exists, is closed. The process is done, <i>quietly</i> , without throwing
* any IOException.
*
* @param entity
* the entity to consume.
*
*
* Copied from org.apache.http.util.EntityUtils
*/
public static void consumeHttpEntityQuietly(final HttpEntity entity) {
try {
consumeHttpEntity(entity);
}
catch (final IOException ignore) {
}
}
/**
* Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
*
* @param entity
* the entity to consume.
* @throws IOException
* if an error occurs reading the input stream
*
* Copied from org.apache.http.util.EntityUtils
*/
public static void consumeHttpEntity(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
final InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
}
|
package org.ocelotds.resolvers;
import org.ocelotds.spi.DataServiceException;
import org.ocelotds.spi.DataServiceResolver;
import org.ocelotds.spi.IDataServiceResolver;
import org.ocelotds.Constants;
import org.ocelotds.annotations.DataService;
import org.ocelotds.spi.Scope;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
/**
* Resolver of CDI
*
* @author hhfrancois
*/
@DataServiceResolver(Constants.Resolver.CDI)
public class CdiResolver implements IDataServiceResolver {
@Inject
BeanManager beanManager;
@Override
public <T> T resolveDataService(Class<T> clazz) throws DataServiceException {
// return CDI.current().select(clazz).get(); // equivalent, but no testable
Set<Bean<?>> beans = beanManager.getBeans(clazz);
for (Bean<?> b : beans) {
final CreationalContext context = beanManager.createCreationalContext(b);
return clazz.cast(beanManager.getReference(b, b.getBeanClass(), context));
}
throw new DataServiceException(clazz.getName());
}
@Override
public Scope getScope(Class clazz) {
for (Annotation anno : clazz.getAnnotations()) {
if (!anno.annotationType().equals(DataService.class)) {
String annoName = anno.annotationType().getName();
switch (annoName) {
case "javax.enterprise.context.Dependent":
return Scope.SESSION;
default:
}
}
}
return Scope.MANAGED;
}
}
|
package ca.mcgill.sable.soot.resources;
import org.eclipse.ui.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.*;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.*;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import ca.mcgill.sable.soot.attributes.*;
import ca.mcgill.sable.soot.editors.JimpleEditor;
import ca.mcgill.sable.soot.ui.*;
import ca.mcgill.sable.soot.*;
import java.util.*;
public class SootPartManager {
private boolean updateForOpen;
public void updatePart(IEditorPart part){
if (part == null) return;
if (part instanceof JimpleEditor){
AbstractAttributesComputer aac = new JimpleAttributesComputer();
SootAttributesJimpleColorer sajc = new SootAttributesJimpleColorer();
SootAttrJimpleIconGenerator saji = new SootAttrJimpleIconGenerator();
SourceViewer viewer = (SourceViewer)((AbstractTextEditor)part).getAdapter(ITextOperationTarget.class);
SootAttributesHandler handler = aac.getAttributesHandler((AbstractTextEditor)part);
if (handler != null){
if (isUpdateForOpen() || handler.isUpdate()){
sajc.setEditorPart(part);
sajc.setViewer(viewer);
sajc.setHandler(handler);
Thread cThread = new Thread(sajc);
cThread.start();
saji.setHandler(handler);
saji.setRec((IFile)aac.getRec());
Thread iThread = new Thread(saji);
iThread.start();
handler.setUpdate(false);
}
}
handleKeys(handler);
handleTypes(handler, (IFile)aac.getRec());
}
else if (part instanceof AbstractTextEditor){
IEditorInput input= ((AbstractTextEditor)part).getEditorInput();
IJavaElement jElem = (IJavaElement) ((IAdaptable) input).getAdapter(IJavaElement.class);
if (!(jElem instanceof ICompilationUnit)) return;
AbstractAttributesComputer aac = new JavaAttributesComputer();
SootAttributesJavaColorer sajc = new SootAttributesJavaColorer();
SootAttrJavaIconGenerator saji = new SootAttrJavaIconGenerator();
SourceViewer viewer = (SourceViewer)((AbstractTextEditor)part).getAdapter(ITextOperationTarget.class);
SootAttributesHandler handler = aac.getAttributesHandler((AbstractTextEditor)part);
if (handler != null){
if (isUpdateForOpen() || handler.isUpdate()){
sajc.setEditorPart(part);
sajc.setViewer(viewer);
sajc.setHandler(handler);
Thread cThread = new Thread(sajc);
cThread.start();
saji.setHandler(handler);
saji.setRec((IFile)aac.getRec());
Thread iThread = new Thread(saji);
iThread.start();
handler.setUpdate(false);
}
}
handleKeys(handler);
handleTypes(handler, (IFile)aac.getRec());
}
setUpdateForOpen(false);
}
private void handleTypes(SootAttributesHandler handler, IFile file){
IWorkbenchPage page = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
ArrayList types = computeTypes(handler);
if (!types.isEmpty()){
IViewPart view = page.findView(ISootConstants.ANALYSIS_TYPES_VIEW_ID);
try {
if (view == null) {
IWorkbenchPart activePart = page.getActivePart();
page.showView(ISootConstants.ANALYSIS_TYPES_VIEW_ID);
//restore focus stolen by the creation of the console
IViewPart shownPart = page.findView(ISootConstants.ANALYSIS_TYPES_VIEW_ID);
if (shownPart != null){
((AnalysisTypeView)shownPart).setFile(file);
((AnalysisTypeView)shownPart).setAllTypesChecked(handler.isShowAllTypes());
((AnalysisTypeView)shownPart).setTypesChecked(handler.getTypesToShow());
((AnalysisTypeView)shownPart).setInputTypes(types);
}
page.activate(activePart);
}
else {
if (view != null){
((AnalysisTypeView)view).setFile(file);
((AnalysisTypeView)view).setAllTypesChecked(handler.isShowAllTypes());
((AnalysisTypeView)view).setTypesChecked(handler.getTypesToShow());
((AnalysisTypeView)view).setInputTypes(types);
}
}
}
catch (PartInitException pie) {
System.out.println(pie.getMessage());
}
}
}
private ArrayList computeTypes(SootAttributesHandler handler){
ArrayList types = new ArrayList();
if ((handler != null) && (handler.getAttrList() != null)){
Iterator attrsIt = handler.getAttrList().iterator();
while (attrsIt.hasNext()){
SootAttribute sa = (SootAttribute)attrsIt.next();
Iterator typesIt = sa.getAnalysisTypes().iterator();
while (typesIt.hasNext()){
String val = (String)typesIt.next();
if (!types.contains(val)){
types.add(val);
}
}
}
}
return types;
}
private void handleKeys(SootAttributesHandler handler){
// make a new view and put it in properties
// area (bring to top if necessary - make list of keys
IWorkbenchPage page = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
IViewPart viewPart = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ISootConstants.ANALYSIS_KEY_VIEW_ID);
try {
if (viewPart == null) {
IWorkbenchPart activePart = page.getActivePart();
page.showView(ISootConstants.ANALYSIS_KEY_VIEW_ID);
//restore focus stolen by the creation of the console
IViewPart shownPart = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ISootConstants.ANALYSIS_KEY_VIEW_ID);
if (shownPart != null){
((AnalysisKeyView)shownPart).setInputKeys(handler.getKeyList());
}
page.activate(activePart);
}
else {
if (viewPart != null){
((AnalysisKeyView)viewPart).setInputKeys(handler.getKeyList());
}
}
}
catch (PartInitException pie) {
System.out.println(pie.getMessage());
}
if (viewPart != null){
((AnalysisKeyView)viewPart).setInputKeys(handler.getKeyList());
}
}
/**
* @return
*/
public boolean isUpdateForOpen() {
return updateForOpen;
}
/**
* @param b
*/
public void setUpdateForOpen(boolean b) {
updateForOpen = b;
}
}
|
package org.openlca.ecospold2;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
public class DataSet {
private Activity activity;
private List<Classification> classifications = new ArrayList<>();
private Geography geography;
private Technology technology;
private TimePeriod timePeriod;
private MacroEconomicScenario macroEconomicScenario;
private Representativeness representativeness;
private AdministrativeInformation administrativeInformation;
private List<ElementaryExchange> elementaryExchanges = new ArrayList<>();
private List<IntermediateExchange> intermediateExchanges = new ArrayList<>();
private List<Parameter> parameters = new ArrayList<>();
private UserMasterData masterData;
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
public List<Classification> getClassifications() {
return classifications;
}
public Geography getGeography() {
return geography;
}
public void setGeography(Geography geography) {
this.geography = geography;
}
public Technology getTechnology() {
return technology;
}
public void setTechnology(Technology technology) {
this.technology = technology;
}
public TimePeriod getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(TimePeriod timePeriod) {
this.timePeriod = timePeriod;
}
public MacroEconomicScenario getMacroEconomicScenario() {
return macroEconomicScenario;
}
public void setMacroEconomicScenario(
MacroEconomicScenario macroEconomicScenario) {
this.macroEconomicScenario = macroEconomicScenario;
}
public List<ElementaryExchange> getElementaryExchanges() {
return elementaryExchanges;
}
public List<IntermediateExchange> getIntermediateExchanges() {
return intermediateExchanges;
}
public List<Parameter> getParameters() {
return parameters;
}
public Representativeness getRepresentativeness() {
return representativeness;
}
public void setRepresentativeness(Representativeness representativeness) {
this.representativeness = representativeness;
}
public AdministrativeInformation getAdministrativeInformation() {
return administrativeInformation;
}
public void setAdministrativeInformation(
AdministrativeInformation administrativeInformation) {
this.administrativeInformation = administrativeInformation;
}
public void setMasterData(UserMasterData masterData) {
this.masterData = masterData;
}
public UserMasterData getMasterData() {
return masterData;
}
static DataSet fromXml(Document doc) {
Element root = getRootElement(doc);
if (root == null)
return null;
DataSet dataSet = new DataSet();
readActivityDescription(root, dataSet);
readFlowData(root, dataSet);
dataSet.representativeness = Representativeness.fromXml(In.child(root,
"modellingAndValidation", "representativeness"));
dataSet.administrativeInformation = AdministrativeInformation
.fromXml(In.child(root, "administrativeInformation"));
return dataSet;
}
private static void readFlowData(Element root, DataSet dataSet) {
Element flowData = In.child(root, "flowData");
if (flowData == null)
return;
List<Element> elementaryExchanges = In.childs(flowData,
"elementaryExchange");
for (Element e : elementaryExchanges) {
ElementaryExchange exchange = ElementaryExchange.fromXml(e);
if (exchange != null)
dataSet.getElementaryExchanges().add(exchange);
}
List<Element> intermediateExchanges = In.childs(flowData,
"intermediateExchange");
for (Element e : intermediateExchanges) {
IntermediateExchange exchange = IntermediateExchange.fromXml(e);
if (exchange != null)
dataSet.getIntermediateExchanges().add(exchange);
}
List<Element> parameters = In.childs(flowData, "parameter");
for (Element e : parameters) {
Parameter p = Parameter.fromXml(e);
if (p != null)
dataSet.getParameters().add(p);
}
}
private static void readActivityDescription(Element root, DataSet dataSet) {
Element description = In.child(root, "activityDescription");
Element activity = In.child(description, "activity");
dataSet.setActivity(Activity.fromXml(activity));
List<Element> classifications = In
.childs(description, "classification");
for (Element e : classifications) {
Classification classification = Classification.fromXml(e);
dataSet.getClassifications().add(classification);
}
dataSet.setGeography(Geography.fromXml(In.child(description,
"geography")));
dataSet.setTechnology(Technology.fromXml(In.child(description,
"technology")));
dataSet.setTimePeriod(TimePeriod.fromXml(In.child(description,
"timePeriod")));
dataSet.setMacroEconomicScenario(MacroEconomicScenario.fromXml(In
.child(description, "macroEconomicScenario")));
}
private static Element getRootElement(Document doc) {
if (doc == null)
return null;
Element root = doc.getRootElement();
if (!"ecoSpold".equals(root.getName()))
return null;
Element e = root.getChild("activityDataset", root.getNamespace());
if (e == null)
e = root.getChild("childActivityDataset", root.getNamespace());
return e;
}
Document toXml() {
Element root = new Element("ecoSpold", IO.NS);
Document document = new Document(root);
Element dataSetElement = Out.addChild(root, "activityDataset");
Element descriptionElement = Out.addChild(dataSetElement,
"activityDescription");
if (activity != null)
descriptionElement.addContent(activity.toXml());
for (Classification classification : classifications)
descriptionElement.addContent(classification.toXml());
if (geography != null)
descriptionElement.addContent(geography.toXml());
if (technology != null)
descriptionElement.addContent(technology.toXml());
if (timePeriod != null)
descriptionElement.addContent(timePeriod.toXml());
if (macroEconomicScenario != null)
descriptionElement.addContent(macroEconomicScenario.toXml());
Element flowData = Out.addChild(dataSetElement, "flowData");
writeFlowData(flowData);
Element mav = Out.addChild(dataSetElement, "modellingAndValidation");
if (representativeness != null)
mav.addContent(representativeness.toXml());
if (administrativeInformation != null)
dataSetElement.addContent(administrativeInformation.toXml());
if (masterData != null)
root.addContent(masterData.toXml());
return document;
}
private void writeFlowData(Element flowData) {
for (IntermediateExchange exchange : intermediateExchanges)
flowData.addContent(exchange.toXml());
for (ElementaryExchange exchange : elementaryExchanges)
flowData.addContent(exchange.toXml());
// TODO: now write all parameters
// for (Parameter parameter : parameters)
// flowData.addContent(parameter.toXml());
}
}
|
package eventBRefinementSlicer.ui.editors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableFontProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
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.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.part.FileEditorInput;
import org.eventb.core.IEventBRoot;
import org.eventb.core.IMachineRoot;
import org.eventb.core.ast.FormulaFactory;
import org.rodinp.core.IInternalElement;
import org.rodinp.core.IRodinFile;
import org.rodinp.core.RodinCore;
import eventBRefinementSlicer.internal.datastructures.EventBAction;
import eventBRefinementSlicer.internal.datastructures.EventBCondition;
import eventBRefinementSlicer.internal.datastructures.EventBContext;
import eventBRefinementSlicer.internal.datastructures.EventBDependencies;
import eventBRefinementSlicer.internal.datastructures.EventBElement;
import eventBRefinementSlicer.internal.datastructures.EventBEvent;
import eventBRefinementSlicer.internal.datastructures.EventBMachine;
import eventBRefinementSlicer.internal.datastructures.EventBTypes;
import eventBRefinementSlicer.internal.datastructures.EventBUnit;
import eventBRefinementSlicer.ui.jobs.EventBDependencyAnalysisJob;
import eventBRefinementSlicer.ui.wizards.MachineCreationWizard;
/**
* The editor in charge of selecting which parts of an Event-B machine to use in the slicing of refinements
*
* @author Aivar Kripsaar
*
*/
public class SelectionEditor extends EditorPart {
private static final String LABEL_ELEMENT = "Element";
private static final String LABEL_CONTENT = "Content";
private static final String LABEL_SPECIAL = "Special";
private static final String LABEL_COMMENT = "Comment";
private static final int ELEMENT_COLUMN = 0;
private static final int CONTENT_COLUMN = 1;
private static final int SPECIAL_COLUMN = 2;
private static final int COMMENT_COLUMN = 3;
private IRodinFile rodinFile;
private IMachineRoot machineRoot;
private EventBMachine machine;
// TODO: Replace with something more reasonable. Or get rid of it altogether.
private Map<String, EventBTreeSubcategory> treeCategories = new HashMap<>();
private Map<EventBElement, Integer> selectionDependees = new HashMap<>();
private Map<EventBElement, Integer> selectionDependers = new HashMap<>();
private Map<EventBElement, EventBTreeElement> elementToTreeElementMap = new HashMap<>();
private ContainerCheckedTreeViewer treeViewer = null;
@Override
public void doSave(IProgressMonitor monitor) {
}
@Override
public void doSaveAs() {
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
rodinFile = getRodinFileFromInput(input);
IInternalElement internalElementRoot = rodinFile.getRoot();
assert (internalElementRoot instanceof IMachineRoot);
machineRoot = (IMachineRoot) internalElementRoot;
try {
machine = new EventBMachine(machineRoot);
} catch (CoreException e) {
e.printStackTrace();
}
EventBDependencyAnalysisJob.doEventBDependencyAnalysis(machine);
}
/**
* Gets the internal representation of the Rodin File from the editor input
*
* @param input
* The editor's input
* @return Internal representation of the Rodin File
*/
protected IRodinFile getRodinFileFromInput(IEditorInput input) {
FileEditorInput editorInput = (FileEditorInput) input;
IFile inputFile = editorInput.getFile();
IRodinFile rodinFile = RodinCore.valueOf(inputFile);
return rodinFile;
}
/**
* Gets the internal Rodin File
*
* @return Internal representation of the Rodin File
*/
public IRodinFile getRodinFile() {
if (rodinFile == null) {
throw new IllegalStateException("Editor has not been initialized yet");
}
return rodinFile;
}
public FormulaFactory getFormulaFactory() {
return ((IEventBRoot) machineRoot).getFormulaFactory();
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
/**
* Creates a tree UI element, which is the main body of the selection editor
*
* @param parent
* The parent of the tree
*/
private void createTree(Composite parent) {
// We create a tree that allows for multiple selections and including checkbox behavior
Tree tree = new Tree(parent, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.CHECK | SWT.V_SCROLL | SWT.H_SCROLL);
tree.setLinesVisible(true);
tree.setHeaderVisible(true);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
tree.setLayoutData(gridData);
String[] titles = { LABEL_ELEMENT, LABEL_CONTENT, LABEL_SPECIAL, LABEL_COMMENT };
TreeColumn column;
for (String title : titles) {
column = new TreeColumn(tree, SWT.NONE);
column.setText(title);
column.setResizable(false);
}
createContainerCheckedTreeViewer(tree, titles);
// We resize the columns every time the tree component changes size
tree.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
packColumns();
}
});
// A workaround to allow better highlighting of elements when hovering or selecting them
// Without this, the highlight colors set by the Tree Viewer are removed, simply replaced by the
// standard selection & highlight colors of the OS
tree.addListener(SWT.EraseItem, new Listener() {
@Override
public void handleEvent(Event event) {
GC gc = event.gc;
TreeItem item = (TreeItem) event.item;
int width = tree.getClientArea().x + tree.getClientArea().width - event.x;
// Sets background and foreground color to the ones set by the Tree Viewer
gc.setBackground(item.getBackground(event.index));
gc.setForeground(item.getForeground(event.index));
gc.fillRectangle(event.x, event.y, width, event.height);
}
});
packColumns();
}
/**
* Adjusts size of columns to fit visible content. Also resizes last column to fill remainder of space.
*/
private void packColumns() {
Tree tree = treeViewer.getTree();
int columnsWidth = 0;
for (TreeColumn column : tree.getColumns()) {
column.pack();
}
// After packing all columns, we manually change the size of the last column
for (TreeColumn column : tree.getColumns()) {
columnsWidth += column.getWidth();
}
TreeColumn lastColumn = tree.getColumn(tree.getColumnCount() - 1);
columnsWidth -= lastColumn.getWidth();
Rectangle area = tree.getClientArea();
int width = area.width;
// We set the width of the last column to be the width of the tree area minus the width of every other
// column added up, filling up the rest of the area
if (lastColumn.getWidth() < width - columnsWidth) {
lastColumn.setWidth(width - columnsWidth);
}
}
/**
* Creates a tree viewer element with elements that can be checked off
*
* @param tree
* Parent tree element
* @param titles
* Titles for the columns
*/
private void createContainerCheckedTreeViewer(Tree tree, String[] titles) {
ContainerCheckedTreeViewer treeViewer = new ContainerCheckedTreeViewer(tree);
treeViewer.setColumnProperties(titles);
treeViewer.setUseHashlookup(true);
treeViewer.setLabelProvider(new LabelProvider());
// Any time the tree is either expanded or collapsed, the columns must once again be packed
treeViewer.addTreeListener(new ITreeViewerListener() {
@Override
public void treeExpanded(TreeExpansionEvent event) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
packColumns();
}
});
}
@Override
public void treeCollapsed(TreeExpansionEvent event) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
packColumns();
}
});
}
});
// Any time an element is checked or unchecked, we use a method to take care of additional
// highlighting and dependency related changes
treeViewer.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
setCheckedElement(event.getElement(), event.getChecked());
}
});
treeViewer.setContentProvider(new ITreeContentProvider() {
private EventBTreeSubcategory[] treeRootCategories;
private Map<EventBEvent, EventBTreeSubcategory[]> eventSubcategories = new HashMap<>();
private Map<EventBContext, EventBTreeSubcategory[]> contextSubcategories = new HashMap<>();
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public void dispose() {
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof EventBMachine) {
EventBMachine machine = (EventBMachine) element;
if (machine.getInvariants().isEmpty() && machine.getVariables().isEmpty()) {
return false;
}
return true;
}
if (element instanceof EventBTreeSubcategory) {
return ((EventBTreeSubcategory) element).getChildren().length > 0;
}
if (element instanceof EventBTreeElement) {
if (((EventBTreeElement) element).getOriginalElement() instanceof EventBEvent) {
EventBEvent event = (EventBEvent) ((EventBTreeElement) element).getOriginalElement();
return !(event.isEmpty());
}
if (((EventBTreeElement) element).getOriginalElement() instanceof EventBContext) {
EventBContext context = (EventBContext) ((EventBTreeElement) element).getOriginalElement();
return !(context.isEmpty());
}
}
return false;
}
@Override
public Object getParent(Object element) {
if (element instanceof EventBTreeElement) {
return ((EventBTreeElement) element).getParent();
}
return null;
}
@Override
public Object[] getElements(Object inputElement) {
EventBMachine machine = (EventBMachine) inputElement;
if (treeRootCategories == null) {
EventBTreeSubcategory invariants = new EventBTreeSubcategory("Invariants", machine, machine.getInvariants());
EventBTreeSubcategory variables = new EventBTreeSubcategory("Variables", machine, machine.getVariables());
EventBTreeSubcategory events = new EventBTreeSubcategory("Events", machine, machine.getEvents());
EventBTreeSubcategory contexts = new EventBTreeSubcategory("Seen Contexts", machine, machine.getSeenContexts());
EventBTreeSubcategory[] treeChildren = { invariants, variables, events, contexts };
addCategories(treeChildren);
treeRootCategories = treeChildren;
}
return treeRootCategories;
}
@Override
public Object[] getChildren(Object parentElement) {
if ((parentElement instanceof EventBMachine)) {
return getElements(parentElement);
}
if (parentElement instanceof EventBTreeSubcategory) {
return ((EventBTreeSubcategory) parentElement).children;
}
if (parentElement instanceof EventBTreeElement) {
if (!(((EventBTreeElement) parentElement).getOriginalElement() instanceof EventBEvent || ((EventBTreeElement) parentElement)
.getOriginalElement() instanceof EventBContext)) {
return null;
}
if (((EventBTreeElement) parentElement).getOriginalElement() instanceof EventBEvent) {
EventBEvent originalElement = (EventBEvent) ((EventBTreeElement) parentElement).getOriginalElement();
EventBTreeElement parent = (EventBTreeElement) parentElement;
if (!eventSubcategories.containsKey(originalElement)) {
EventBTreeSubcategory parameters = new EventBTreeSubcategory("Parameters", parent, originalElement.getParameters());
EventBTreeSubcategory witnesses = new EventBTreeSubcategory("Witnesses", parent, originalElement.getWitnesses());
EventBTreeSubcategory guards = new EventBTreeSubcategory("Guards", parent, originalElement.getGuards());
EventBTreeSubcategory actions = new EventBTreeSubcategory("Actions", parent, originalElement.getActions());
EventBTreeSubcategory[] children = { parameters, witnesses, guards, actions };
addCategories(children);
eventSubcategories.put(originalElement, children);
}
return eventSubcategories.get(originalElement);
}
if (((EventBTreeElement) parentElement).getOriginalElement() instanceof EventBContext) {
EventBContext originalElement = (EventBContext) ((EventBTreeElement) parentElement).getOriginalElement();
EventBTreeElement parent = (EventBTreeElement) parentElement;
if (!contextSubcategories.containsKey(originalElement)) {
EventBTreeSubcategory axioms = new EventBTreeSubcategory("Axioms", parent, originalElement.getAxioms());
EventBTreeSubcategory constants = new EventBTreeSubcategory("Constants", parent, originalElement.getConstants());
EventBTreeSubcategory carrierSets = new EventBTreeSubcategory("Carrier Sets", parent, originalElement.getCarrierSets());
EventBTreeSubcategory[] children = { axioms, constants, carrierSets };
addCategories(children);
contextSubcategories.put(originalElement, children);
}
return contextSubcategories.get(originalElement);
}
}
return null;
}
});
treeViewer.setInput(machine);
this.treeViewer = treeViewer;
}
/**
* Sets the checked status for the given element and its children. Also updates the dependency-related
* highlighting as necessary.
*
* @param element
* The element being checked or unchecked
* @param checked
* Desired checked state
*/
private void setCheckedElement(Object element, boolean checked) {
treeViewer.setSubtreeChecked(element, checked);
updateElement(element);
// Get dependency information and add it to the local maps
if (element instanceof EventBTreeElement) {
EventBDependencies dependencies = machine.getDependencies();
Set<EventBElement> dependees = dependencies.getDependeesForElement(((EventBTreeElement) element).getOriginalElement());
for (EventBElement dependee : dependees) {
updateSelectionDependency(dependee, true, checked);
}
Set<EventBElement> dependers = dependencies.getDependersForElement(((EventBTreeElement) element).getOriginalElement());
for (EventBElement depender : dependers) {
updateSelectionDependency(depender, false, checked);
}
}
// Update children of selected element and update their dependencies
handleChildren(element, checked);
// Correct checked state of parents
correctParentsChecked(element);
}
/**
* Gets all children of given parent element and sets their checked status as desired.
*
* @param parent
* Parent element of children we need to change
* @param checked
* Desired checked state for children of parent
*/
private void handleChildren(Object parent, boolean checked) {
ITreeContentProvider contentProvider = (ITreeContentProvider) treeViewer.getContentProvider();
if (!contentProvider.hasChildren(parent)) {
return;
}
for (Object child : contentProvider.getChildren(parent)) {
setCheckedElement(child, checked);
}
}
/**
* Corrects the parents's checked (selection) state based on child's changed checked status
*
* @param element
* The element which has had its checked status changed.
*/
private void correctParentsChecked(Object element) {
if (element instanceof EventBTreeElement) {
EventBTreeElement treeElement = (EventBTreeElement) element;
EventBTreeSubcategory parent = treeElement.getParent();
if (parent == null) {
return;
}
correctElementChecked(parent);
} else if (element instanceof EventBTreeSubcategory) {
EventBTreeSubcategory treeCategory = (EventBTreeSubcategory) element;
EventBTreeElement parent = treeCategory.getParentElement();
if (parent == null) {
return;
}
correctElementChecked(parent);
}
}
/**
* Checks element's current checked state based on checked states of children and corrects if necessary.
*
* @param element
* Tree element which needs to be checked and corrected
*/
private void correctElementChecked(Object element) {
ITreeContentProvider contentProvider = (ITreeContentProvider) treeViewer.getContentProvider();
if (!contentProvider.hasChildren(element)) {
return;
}
Boolean isChecked = true;
Boolean isPartiallyChecked = false;
for (Object child : contentProvider.getChildren(element)) {
if (treeViewer.getChecked(child) || treeViewer.getGrayed(child)) {
isPartiallyChecked = true;
} else if (!treeViewer.getChecked(child) || treeViewer.getGrayed(child)) {
isChecked = false;
}
}
if (isChecked) {
treeViewer.setChecked(element, true);
treeViewer.setGrayed(element, false);
correctParentsChecked(element);
} else if (isPartiallyChecked) {
treeViewer.setGrayChecked(element, true);
correctParentsChecked(element);
} else {
treeViewer.setChecked(element, false);
treeViewer.setGrayed(element, false);
correctParentsChecked(element);
}
}
/**
* Updates maps counting number of dependers and dependees that are currently selected (checked) and
* causes update so that dependencies are properly highlighted.
*
* @param dependecy
* Element for which we update dependency counts.
* @param dependee
* Boolean to signify whether the element is being depended on, or if it is depending on
* another element itself.
* @param increase
* True if dependency count needs to be increased (when another dependency partner of the given
* element has been selected).
*/
private void updateSelectionDependency(EventBElement dependecy, boolean dependee, boolean increase) {
Map<EventBElement, Integer> dependencyMap;
if (dependee) {
dependencyMap = selectionDependees;
} else {
dependencyMap = selectionDependers;
}
int count = dependencyMap.containsKey(dependecy) ? dependencyMap.get(dependecy) : 0;
count += increase ? 1 : -1;
if (count > 0) {
dependencyMap.put(dependecy, count);
} else {
dependencyMap.remove(dependecy);
}
// Element needs to be updated so that its highlighting is correct.
updateElement(findTreeElement(dependecy, false));
}
/**
* Updates an element as well as all of its parents in the editor's tree viewer.
*
* @param element
* Element to update
*/
private void updateElement(Object element) {
if (element == null) {
return;
}
treeViewer.update(element, null);
if (element instanceof EventBTreeElement) {
EventBTreeElement treeElement = (EventBTreeElement) element;
if (treeElement.getParent() != null) {
updateElement(treeElement.getParent());
}
}
if (element instanceof EventBTreeSubcategory) {
EventBTreeSubcategory treeCategory = (EventBTreeSubcategory) element;
if (treeCategory.getParentElement() != null) {
updateElement(treeCategory.getParentElement());
}
}
}
/**
* Container class for tree subcategories (e.g. Variables, Invariants, Events).
*
* @author Aivar Kripsaar
*
*/
public class EventBTreeSubcategory {
final String label;
final EventBUnit parentUnit;
final EventBTreeElement parentElement;
final EventBTreeElement[] children;
public EventBTreeSubcategory(String label, EventBUnit parent, List<? extends EventBElement> children) {
this.label = label;
this.parentUnit = parent;
this.parentElement = null;
List<EventBTreeElement> treeChildren = new ArrayList<>();
for (EventBElement originalChild : children) {
EventBTreeElement treeChild = new EventBTreeElement(this, originalChild);
treeChildren.add(treeChild);
}
this.children = treeChildren.toArray(new EventBTreeElement[treeChildren.size()]);
}
public EventBTreeSubcategory(String label, EventBTreeElement parent, List<? extends EventBElement> children) {
this.label = label;
this.parentElement = parent;
this.parentUnit = null;
List<EventBTreeElement> treeChildren = new ArrayList<>();
for (EventBElement originalChild : children) {
EventBTreeElement treeChild = new EventBTreeElement(this, originalChild);
treeChildren.add(treeChild);
}
this.children = treeChildren.toArray(new EventBTreeElement[treeChildren.size()]);
}
public String getLabel() {
return label;
}
public EventBUnit getParentUnit() {
return parentUnit;
}
public EventBTreeElement getParentElement() {
return parentElement;
}
public EventBTreeElement[] getChildren() {
return children;
}
/**
* Finds the tree container version of the given element.
*
* @param originalElement
* Editor internal representation of element
* @return Tree container element of the desired element
*/
public EventBTreeElement findTreeElement(EventBElement originalElement) {
for (EventBTreeElement child : children) {
if (child.getOriginalElement().equals(originalElement)) {
return child;
}
}
return null;
}
@Override
public String toString() {
return label;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((label == null) ? 0 : label.hashCode());
result = prime * result + ((parentElement == null) ? 0 : parentElement.hashCode());
result = prime * result + ((parentUnit == null) ? 0 : parentUnit.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventBTreeSubcategory other = (EventBTreeSubcategory) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
if (parentElement == null) {
if (other.parentElement != null)
return false;
} else if (!parentElement.equals(other.parentElement))
return false;
if (parentUnit == null) {
if (other.parentUnit != null)
return false;
} else if (!parentUnit.equals(other.parentUnit))
return false;
return true;
}
private SelectionEditor getOuterType() {
return SelectionEditor.this;
}
}
/**
* Container class for Event-B elements in tree
*
* @author Aivar Kripsaar
*
*/
public class EventBTreeElement {
final EventBTreeSubcategory parent;
final EventBElement originalElement;
public EventBTreeElement(EventBTreeSubcategory parent, EventBElement originalElement) {
this.parent = parent;
this.originalElement = originalElement;
elementToTreeElementMap.put(originalElement, this);
}
public EventBTreeSubcategory getParent() {
return parent;
}
public EventBElement getOriginalElement() {
return originalElement;
}
@Override
public String toString() {
return originalElement.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((originalElement == null) ? 0 : originalElement.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventBTreeElement other = (EventBTreeElement) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (originalElement == null) {
if (other.originalElement != null)
return false;
} else if (!originalElement.equals(other.originalElement))
return false;
return true;
}
private SelectionEditor getOuterType() {
return SelectionEditor.this;
}
}
/**
* Label provider for table viewer, implementing the necessary interfaces.
*
* @author Aivar Kripsaar
*
*/
class LabelProvider implements ITableLabelProvider, ITableColorProvider, ITableFontProvider {
@Override
public void addListener(ILabelProviderListener listener) {
// Intentionally left empty
}
@Override
public void dispose() {
// Intentionally left empty
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
// Intentionally left empty
}
@Override
public Font getFont(Object element, int columnIndex) {
return null;
}
@Override
public Color getForeground(Object element, int columnIndex) {
if (element instanceof EventBTreeSubcategory) {
// TODO: Add color coding for categories
return null;
}
if (element instanceof EventBTreeElement) {
if (treeViewer.getChecked(element) || selectionDependees.containsKey(((EventBTreeElement) element).getOriginalElement())) {
// If the element is being highlighted, we give the text a different color for easier
// readability.
switch (columnIndex) {
case ELEMENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_CYAN);
case CONTENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_MAGENTA);
case SPECIAL_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
case COMMENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_GREEN);
default:
break;
}
} else {
switch (columnIndex) {
case ELEMENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_DARK_CYAN);
case CONTENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_DARK_MAGENTA);
case SPECIAL_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY);
case COMMENT_COLUMN:
return Display.getDefault().getSystemColor(SWT.COLOR_DARK_GREEN);
default:
break;
}
}
}
return null;
}
@Override
public Color getBackground(Object element, int columnIndex) {
if (!(element instanceof EventBTreeElement)) {
// TODO: Add color coding for categories
return null;
}
if (treeViewer.getChecked(element)) {
// If the element is selected (checked)
return Display.getDefault().getSystemColor(SWT.COLOR_LIST_SELECTION);
}
if (selectionDependees.containsKey(((EventBTreeElement) element).getOriginalElement())) {
// If the element is depended upon by a currently selected element
return Display.getDefault().getSystemColor(SWT.COLOR_RED);
}
if (selectionDependers.containsKey(((EventBTreeElement) element).getOriginalElement())) {
// If the element depends on a currently selected element
return Display.getDefault().getSystemColor(SWT.COLOR_CYAN);
}
return null;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof EventBTreeSubcategory) {
// Categories only need their labels displayed
if (columnIndex == ELEMENT_COLUMN) {
return ((EventBTreeSubcategory) element).getLabel();
}
}
if (!(element instanceof EventBTreeElement)) {
return null;
}
element = ((EventBTreeElement) element).getOriginalElement();
if (!(element instanceof EventBElement)) {
return null;
}
EventBElement eventBElement = (EventBElement) element;
switch (columnIndex) {
case ELEMENT_COLUMN:
return eventBElement.getLabel();
case CONTENT_COLUMN:
if (eventBElement instanceof EventBCondition) {
return ((EventBCondition) eventBElement).getPredicate();
} else if (eventBElement instanceof EventBAction) {
return ((EventBAction) eventBElement).getAssignment();
}
return null;
case SPECIAL_COLUMN:
if (eventBElement instanceof EventBCondition) {
if (((EventBCondition) eventBElement).isTheorem()) {
return "theorem";
} else {
return "not theorem";
}
}
if (eventBElement instanceof EventBEvent) {
EventBEvent event = (EventBEvent) eventBElement;
String res = "";
if (event.isExtended()) {
res = res + "extended";
} else {
res = res + "not extended";
}
switch (event.getConvergence()) {
case ORDINARY:
res = res + ", ordinary";
break;
case CONVERGENT:
res = res + ", convergent";
break;
case ANTICIPATED:
res = res + ", anticipated";
break;
default:
break;
}
return res;
}
return null;
case COMMENT_COLUMN:
return eventBElement.getComment();
default:
return null;
}
}
}
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout();
layout.numColumns = 1;
parent.setLayout(layout);
createButtons(parent);
createTree(parent);
setPartName(machineRoot.getComponentName());
}
/**
* Creates buttons for editor
*
* @param parent
* The parent editor
*/
private void createButtons(Composite parent) {
Composite buttonBar = new Composite(parent, SWT.NONE);
buttonBar.setLayout(new RowLayout());
// Button for creating a new sub-refinement from the selected elements
Button newMachineButton = new Button(buttonBar, SWT.PUSH);
newMachineButton.setText("Create Sub-Refinement");
newMachineButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
WizardDialog wizardDialog = new WizardDialog(parent.getShell(), new MachineCreationWizard(rodinFile.getRodinProject(), machineRoot,
treeViewer.getCheckedElements()));
wizardDialog.setBlockOnOpen(true);
wizardDialog.open();
System.out.println();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
// A button to select all elements of the machine opened in the editor
Button selectAllButton = new Button(buttonBar, SWT.PUSH);
selectAllButton.setText("Select All");
selectAllButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
Object[] categories = ((ITreeContentProvider) treeViewer.getContentProvider()).getChildren(machine);
for (Object category : categories) {
setCheckedElement(category, true);
}
treeViewer.refresh();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
// A button to select all elements that currently selected elements depend on
Button selectAllDependenciesButton = new Button(buttonBar, SWT.PUSH);
selectAllDependenciesButton.setText("Select All Dependencies");
selectAllDependenciesButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
for (EventBElement dependee : selectionDependees.keySet()) {
EventBTreeElement element = findTreeElement(dependee, true);
if (element != null && !treeViewer.getChecked(element)) {
setCheckedElement(element, true);
}
}
treeViewer.refresh();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
}
@Override
public void setFocus() {
// TODO Auto-generated method stub
}
/**
* Finds the tree-internal container for a given editor-internal Event-B element
*
* @param element
* The Event-B element for which the tree-internal container is desired
* @param expand
* True if tree in editor should be expanded to have the element be visible
* @return Tree-internal container element for given Event-B element
*/
private EventBTreeElement findTreeElement(EventBElement element, boolean expand) {
EventBTreeElement treeElement = null;
if (!expand && elementToTreeElementMap.containsKey(element)) {
return elementToTreeElementMap.get(element);
}
ITreeContentProvider contentProvider = (ITreeContentProvider) treeViewer.getContentProvider();
switch (element.getType()) {
case EventBTypes.INVARIANT:
treeViewer.expandToLevel(treeCategories.get("Invariants"), 1);
treeElement = elementToTreeElementMap.get(element);
return treeElement;
case EventBTypes.VARIABLE:
treeViewer.expandToLevel(treeCategories.get("Variables"), 1);
return elementToTreeElementMap.get(element);
case EventBTypes.CONTEXT: {
EventBTreeSubcategory treeContexts = treeCategories.get("Seen Contexts");
treeViewer.expandToLevel(treeContexts, 1);
return elementToTreeElementMap.get(element);
}
case EventBTypes.CONSTANT:
case EventBTypes.AXIOM:
case EventBTypes.CARRIER_SET: {
EventBTreeSubcategory treeContexts = treeCategories.get("Seen Contexts");
for (EventBTreeElement treeContext : treeContexts.getChildren()) {
assert treeContext.getOriginalElement() instanceof EventBContext;
EventBContext context = (EventBContext) treeContext.getOriginalElement();
if (!context.containsElement(element)) {
continue;
}
if (expand) {
treeViewer.expandToLevel(treeContext, 1);
}
Object[] childrenOfContext = contentProvider.getChildren(treeContext);
for (Object child : childrenOfContext) {
// We pick out the correct subcategory for the element we are searching for
assert child instanceof EventBTreeSubcategory;
EventBTreeSubcategory subcategory = (EventBTreeSubcategory) child;
String label = "";
if (element.getType().equals(EventBTypes.CONSTANT)) {
label = "Constants";
} else if (element.getType().equals(EventBTypes.AXIOM)) {
label = "Axioms";
} else if (element.getType().equals(EventBTypes.CARRIER_SET)) {
label = "Carrier Sets";
}
if (subcategory.getLabel().equals(label)) {
if (expand) {
treeViewer.expandToLevel(subcategory, 1);
packColumns();
}
return elementToTreeElementMap.get(element);
}
}
}
}
case EventBTypes.EVENT: {
EventBTreeSubcategory treeEvents = treeCategories.get("Events");
treeViewer.expandToLevel(treeEvents, 1);
return elementToTreeElementMap.get(element);
}
case EventBTypes.GUARD:
case EventBTypes.ACTION: {
EventBTreeSubcategory treeEvents = treeCategories.get("Events");
for (EventBTreeElement treeEvent : treeEvents.getChildren()) {
assert treeEvent.getOriginalElement() instanceof EventBEvent;
EventBEvent event = (EventBEvent) treeEvent.getOriginalElement();
if (!event.containsElement(element)) {
continue;
}
if (expand) {
treeViewer.expandToLevel(treeEvent, 1);
}
Object[] childrenofEvent = contentProvider.getChildren(treeEvent);
for (Object child : childrenofEvent) {
// We pick out the correct subcategory for the searched element
assert child instanceof EventBTreeSubcategory;
EventBTreeSubcategory subcategory = (EventBTreeSubcategory) child;
String label = "";
if (element.getType().equals(EventBTypes.GUARD)) {
label = "Guards";
} else if (element.getType().equals(EventBTypes.ACTION)) {
label = "Actions";
}
if (subcategory.getLabel().equals(label)) {
if (expand) {
treeViewer.expandToLevel(subcategory, 1);
packColumns();
}
return elementToTreeElementMap.get(element);
}
}
}
}
default:
break;
}
return treeElement;
}
/**
* Add categories to internal label to category map
*
* @param categories
* Array of categories to add
*/
private void addCategories(EventBTreeSubcategory[] categories) {
// TODO: Need to rework this stuff
for (EventBTreeSubcategory category : categories) {
treeCategories.put(category.getLabel(), category);
}
}
}
|
package com.newsblur.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.activity.NbActivity;
import com.newsblur.database.BlurDatabaseHelper;
import com.newsblur.database.DatabaseConstants;
import com.newsblur.database.FeedProvider;
import com.newsblur.domain.Classifier;
import com.newsblur.domain.Feed;
import com.newsblur.domain.SocialFeed;
import com.newsblur.domain.Story;
import com.newsblur.domain.ValueMultimap;
import com.newsblur.network.APIManager;
import com.newsblur.network.domain.NewsBlurResponse;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.AppConstants;
public class FeedUtils {
private static BlurDatabaseHelper dbHelper;
public static void offerDB(BlurDatabaseHelper _dbHelper) {
if (_dbHelper.isOpen()) {
dbHelper = _dbHelper;
}
}
private static void triggerSync(Context c) {
Intent i = new Intent(c, NBSyncService.class);
c.startService(i);
}
private static void setStorySaved(final Story story, final boolean saved, final Context context, final APIManager apiManager) {
new AsyncTask<Void, Void, NewsBlurResponse>() {
@Override
protected NewsBlurResponse doInBackground(Void... arg) {
if (saved) {
return apiManager.markStoryAsStarred(story.feedId, story.storyHash);
} else {
return apiManager.markStoryAsUnstarred(story.feedId, story.storyHash);
}
}
@Override
protected void onPostExecute(NewsBlurResponse result) {
if (!result.isError()) {
Toast.makeText(context, (saved ? R.string.toast_story_saved : R.string.toast_story_unsaved), Toast.LENGTH_SHORT).show();
story.starred = saved;
Uri storyUri = FeedProvider.STORY_URI.buildUpon().appendPath(story.id).build();
ContentValues values = new ContentValues();
values.put(DatabaseConstants.STORY_STARRED, saved);
context.getContentResolver().update(storyUri, values, null, null);
} else {
Toast.makeText(context, result.getErrorMessage(context.getString(saved ? R.string.toast_story_save_error : R.string.toast_story_unsave_error)), Toast.LENGTH_LONG).show();
}
NbActivity.updateAllActivities();
}
}.execute();
}
public static void saveStory(final Story story, final Context context, final APIManager apiManager) {
setStorySaved(story, true, context, apiManager);
}
public static void unsaveStory(final Story story, final Context context, final APIManager apiManager) {
setStorySaved(story, false, context, apiManager);
}
public static void deleteFeed( final long feedId, final String folderName, final Context context, final APIManager apiManager) {
new AsyncTask<Void, Void, NewsBlurResponse>() {
@Override
protected NewsBlurResponse doInBackground(Void... arg) {
return apiManager.deleteFeed(feedId, folderName);
}
@Override
protected void onPostExecute(NewsBlurResponse result) {
if (!result.isError()) {
Toast.makeText(context, R.string.toast_feed_deleted, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, result.getErrorMessage(context.getString(R.string.toast_feed_delete_error)), Toast.LENGTH_LONG).show();
}
}
}.execute();
Uri feedUri = FeedProvider.FEEDS_URI.buildUpon().appendPath(Long.toString(feedId)).build();
context.getContentResolver().delete(feedUri, null, null);
}
public static void clearReadingSession(final Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg) {
try {
dbHelper.clearReadingSession();
} catch (Exception e) {
; // this one call can evade the on-upgrade DB wipe and throw exceptions
}
return null;
}
}.execute();
}
public static void markStoryUnread(final Story story, final Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg) {
setStoryReadState(story, context, false);
return null;
}
}.execute();
}
public static void markStoryAsRead(final Story story, final Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg) {
setStoryReadState(story, context, true);
return null;
}
}.execute();
}
private static void setStoryReadState(Story story, Context context, boolean read) {
if (story.read == read) { return; }
// it is imperative that we are idempotent. query the DB for a fresh copy of the story
// to ensure it isn't already in the requested state. if so, do not update feed counts
Cursor cursor = dbHelper.getStory(story.storyHash);
if (cursor.getCount() < 1) {
Log.w(FeedUtils.class.getName(), "can't mark story as read, not found in DB: " + story.id);
return;
}
Story freshStory = Story.fromCursor(cursor);
cursor.close();
if (freshStory.read == read) { return; }
// update the local object to show as read before DB is touched
story.read = read;
// update unread state and unread counts in the local DB
dbHelper.setStoryReadState(story, read);
// tell the sync service we need to mark read
dbHelper.enqueueActionStoryRead(story.storyHash, read);
triggerSync(context);
}
public static void markFeedsRead(final FeedSet fs, final Long olderThan, final Long newerThan, final Context context) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg) {
dbHelper.enqueueActionFeedRead(fs, olderThan, newerThan);
dbHelper.markFeedsRead(fs, olderThan, newerThan);
triggerSync(context);
return null;
}
}.execute();
}
public static void updateClassifier(final String feedId, final String key, final Classifier classifier, final int classifierType, final int classifierAction, final Context context) {
// first, update the server
new AsyncTask<Void, Void, NewsBlurResponse>() {
@Override
protected NewsBlurResponse doInBackground(Void... arg) {
APIManager apiManager = new APIManager(context);
return apiManager.trainClassifier(feedId, key, classifierType, classifierAction);
}
@Override
protected void onPostExecute(NewsBlurResponse result) {
if (result.isError()) {
Toast.makeText(context, result.getErrorMessage(context.getString(R.string.error_saving_classifier)), Toast.LENGTH_LONG).show();
}
}
}.execute();
// next, update the local DB
classifier.getMapForType(classifierType).put(key, classifierAction);
Uri classifierUri = FeedProvider.CLASSIFIER_URI.buildUpon().appendPath(feedId).build();
try {
// TODO: for feeds with many classifiers, this could be much faster by targeting just the row that changed
context.getContentResolver().delete(classifierUri, null, null);
for (ContentValues classifierValues : classifier.getContentValues()) {
context.getContentResolver().insert(classifierUri, classifierValues);
}
} catch (Exception e) {
Log.w(FeedUtils.class.getName(), "Could not update classifier in local storage.", e);
}
}
/**
* Gets the unread story count for a feed, filtered by view state.
*/
public static int getFeedUnreadCount(Feed feed, int currentState) {
if (feed == null ) return 0;
int count = 0;
count += feed.positiveCount;
if ((currentState == AppConstants.STATE_ALL) || (currentState == AppConstants.STATE_SOME)) {
count += feed.neutralCount;
}
if (currentState == AppConstants.STATE_ALL ) {
count += feed.negativeCount;
}
return count;
}
public static int getFeedUnreadCount(SocialFeed feed, int currentState) {
if (feed == null ) return 0;
int count = 0;
count += feed.positiveCount;
if ((currentState == AppConstants.STATE_ALL) || (currentState == AppConstants.STATE_SOME)) {
count += feed.neutralCount;
}
if (currentState == AppConstants.STATE_ALL ) {
count += feed.negativeCount;
}
return count;
}
public static int getCursorUnreadCount(Cursor cursor, int currentState) {
int count = 0;
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
count += cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstants.SUM_POS));
if ((currentState == AppConstants.STATE_ALL) || (currentState == AppConstants.STATE_SOME)) {
count += cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstants.SUM_NEUT));
}
if (currentState == AppConstants.STATE_ALL ) {
count += cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseConstants.SUM_NEG));
}
}
return count;
}
public static void shareStory(Story story, Context context) {
if (story == null ) { return; }
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intent.EXTRA_SUBJECT, Html.fromHtml(story.title));
final String shareString = context.getResources().getString(R.string.share);
intent.putExtra(Intent.EXTRA_TEXT, String.format(shareString, new Object[] { Html.fromHtml(story.title),
story.permalink }));
context.startActivity(Intent.createChooser(intent, "Share using"));
}
public static FeedSet feedSetFromFolderName(String folderName, Context context) {
Set<String> feedIds = dbHelper.getFeedsForFolder(folderName);
return FeedSet.folder(folderName, feedIds);
}
/**
* An interface usable by callers of this utility class that allows them to receive
* notification that the async methods here have finihed and may have updated the DB
* as a result.
*/
public interface ActionCompletionListener {
public abstract void actionCompleteCallback(boolean noMoreData);
}
}
|
package org.jetel.data.parser;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayDeque;
import java.util.Deque;
import javax.xml.parsers.SAXParser;
import org.apache.xmlbeans.impl.common.XMLChar;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;
public class JsonSaxParser extends SAXParser {
private static final String NAMESPACE_URI = ""; //$NON-NLS-1$
private static final String XML_NAME_OBJECT = "json_object"; //$NON-NLS-1$
private static final String XML_NAME_ARRAY = "json_array"; //$NON-NLS-1$
private static final String XML_ARRAY_DEPTH = "arrayDepth"; //$NON-NLS-1$
public static final String XML_ARRAY_ELEM = "arrayElem"; //$NON-NLS-1$
private static final JsonFactory JSON_FACTORY = new JsonFactory();
private static final Attributes EMPTY_ATTRIBUTES = new AttributesImpl();
private DefaultHandler handler;
private boolean xmlEscapeChars=false;
private boolean modifierCompatible = false; // if the parser should add additional code for schema tweaking
@Override
public org.xml.sax.Parser getParser() throws SAXException {
return null;
}
@Override
public XMLReader getXMLReader() throws SAXException {
return null;
}
@Override
public boolean isNamespaceAware() {
return false;
}
@Override
public boolean isValidating() {
return false;
}
@Override
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException {
//do nothing - no properties supported
}
@Override
public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
return null;
}
@Override
public void parse(InputSource is,DefaultHandler handler) throws IOException, SAXException{
this.handler=handler;
xmlEscapeChars=false;
doParse(is.getCharacterStream());
}
public void convertJSON2XML(Reader in,Writer out,boolean firstObjectOnly,boolean suppresNodeValues)throws IOException, SAXException{
this.handler=new JSON2XMLHandler(out,suppresNodeValues);
JsonParser parser;
try {
parser = JSON_FACTORY.createJsonParser(in);
} catch (JsonParseException e) {
throw new IOException(e);
}
Deque<JsonToken> tokens = new ArrayDeque<JsonToken>();
Deque<String> names = new ArrayDeque<String>();
Deque<Integer> depthCounter = new ArrayDeque<Integer>();
depthCounter.add(0);
JsonToken currentToken = null;
xmlEscapeChars=true;
handler.startDocument();
int startEndCounter = 0;
while ((currentToken = parser.nextToken()) != null) {
processToken(currentToken, parser, tokens, names, depthCounter);
if (currentToken == JsonToken.START_ARRAY || currentToken == JsonToken.START_OBJECT) {
startEndCounter++;
} else if (currentToken == JsonToken.END_ARRAY || currentToken == JsonToken.END_OBJECT) {
startEndCounter
}
if (startEndCounter == 0) {
break;
}
}
handler.endDocument();
}
protected void doParse(Reader reader)throws IOException, SAXException{
JsonParser parser;
try {
parser = JSON_FACTORY.createJsonParser(reader);
} catch (JsonParseException e) {
throw new IOException(e);
}
Deque<JsonToken> tokens = new ArrayDeque<JsonToken>();
Deque<String> names = new ArrayDeque<String>();
Deque<Integer> depthCounter = new ArrayDeque<Integer>();
depthCounter.add(0);
JsonToken currentToken = null;
handler.startDocument();
while ((currentToken = parser.nextToken()) != null) {
processToken(currentToken, parser, tokens, names, depthCounter);
}
handler.endDocument();
}
protected void processToken(final JsonToken token, JsonParser parser, Deque<JsonToken> tokens, Deque<String> names, Deque<Integer> depthCounter)
throws JsonParseException, IOException, SAXException {
if (token == null) {
return;
}
switch (token) {
case FIELD_NAME: {
names.add(parser.getText());
tokens.add(token);
break;
}
case START_ARRAY: {
if (names.isEmpty()) {
// top level array
names.add(XML_NAME_ARRAY);
if (depthCounter.size() == 1 && depthCounter.peek() == 0) {
tokens.addFirst(JsonToken.START_ARRAY);
depthCounter.add(1);
handler.startElement(NAMESPACE_URI, normalizeElementName(names.getFirst()), normalizeElementName(names.getFirst()), EMPTY_ATTRIBUTES);
}
} else if (tokens.peekLast() == JsonToken.FIELD_NAME) {
// named array - remove field token
tokens.removeLast();
} else if (tokens.peekLast() == JsonToken.START_ARRAY) {
// add nested element
AttributesImpl attributesImpl = new AttributesImpl();
String name = names.getLast();
int top = depthCounter.pollLast();
attributesImpl.addAttribute("", XML_ARRAY_DEPTH, XML_ARRAY_DEPTH, "CDATA", String.valueOf(top));
if (modifierCompatible) {
attributesImpl.addAttribute("", XML_ARRAY_ELEM, XML_ARRAY_ELEM, "CDATA", XML_ARRAY_ELEM);
}
top++;
depthCounter.add(top);
handler.startElement(NAMESPACE_URI, normalizeElementName(name), normalizeElementName(name), attributesImpl);
}
tokens.add(token);
break;
}
case START_OBJECT: {
AttributesImpl attributesImpl = new AttributesImpl();
if (names.isEmpty()) {
names.add(XML_NAME_OBJECT);
} else if (tokens.peekLast() == JsonToken.FIELD_NAME) {
// named object - remove field token
tokens.removeLast();
} else if (tokens.peekLast() == JsonToken.START_ARRAY) {
// add nested element
if (modifierCompatible) {
attributesImpl.addAttribute("", XML_ARRAY_ELEM, XML_ARRAY_ELEM, "CDATA", XML_ARRAY_ELEM);
}
}
tokens.add(token);
String name = names.getLast();
if (!depthCounter.isEmpty()) {
int top = depthCounter.peekLast();
if (top > 0) {
attributesImpl.addAttribute("", XML_ARRAY_DEPTH, XML_ARRAY_DEPTH, "CDATA", String.valueOf(top));
}
}
depthCounter.add(Integer.valueOf(0));
handler.startElement(NAMESPACE_URI, normalizeElementName(name),normalizeElementName(name), attributesImpl);
break;
}
case END_ARRAY: {
// remove corresponding start
tokens.removeLast();
String name = names.getLast();
int top = depthCounter.pollLast();
if (top > 0) {
top
}
depthCounter.add(top);
if (names.size() == 1) {
handler.endElement(NAMESPACE_URI, normalizeElementName(names.getFirst()), normalizeElementName(names.getFirst()));
names.removeLast();
} else if (!tokens.isEmpty() && tokens.peekLast() == JsonToken.START_ARRAY) {
// end nested array
handler.endElement(NAMESPACE_URI,normalizeElementName(name), normalizeElementName(name));
} else {
// remove name if not inside array
names.removeLast();
}
break;
}
case END_OBJECT: {
// remove corresponding start
tokens.removeLast();
// end current object
String name = names.getLast();
depthCounter.pollLast();
handler.endElement(NAMESPACE_URI, normalizeElementName(name), normalizeElementName(name));
if (tokens.isEmpty() || tokens.peekLast() != JsonToken.START_ARRAY) {
// remove name if not inside array
names.removeLast();
}
break;
}
}
if (token.isScalarValue()) {
String valueName = names.getLast();
switch (tokens.getLast()) {
case FIELD_NAME: {
// simple property
handler.startElement(NAMESPACE_URI, normalizeElementName(valueName), normalizeElementName(valueName), EMPTY_ATTRIBUTES);
processScalarValue(parser);
handler.endElement(NAMESPACE_URI, normalizeElementName(valueName), normalizeElementName(valueName));
tokens.removeLast();
names.removeLast();
break;
}
case START_ARRAY: {
// array item
AttributesImpl attributesImpl = new AttributesImpl();
String name = names.getLast();
attributesImpl.addAttribute("", XML_ARRAY_DEPTH, XML_ARRAY_DEPTH, "CDATA", String.valueOf(depthCounter.peekLast()));
if (modifierCompatible) {
attributesImpl.addAttribute("", XML_ARRAY_ELEM, XML_ARRAY_ELEM, "CDATA", XML_ARRAY_ELEM);
}
handler.startElement(NAMESPACE_URI, normalizeElementName(name), normalizeElementName(name), attributesImpl);
processScalarValue(parser);
handler.endElement(NAMESPACE_URI, normalizeElementName(name), normalizeElementName(name));
}
}
}
}
protected void processScalarValue(JsonParser parser) throws JsonParseException, IOException, SAXException {
if (parser.getCurrentToken() != JsonToken.VALUE_NULL) {
char[] chars;
if (xmlEscapeChars){
chars=URLEncoder.encode(parser.getText()).toCharArray();
}else{
chars= parser.getText().toCharArray();
}
handler.characters(chars, 0, chars.length);
}
}
private class JSON2XMLHandler extends DefaultHandler {
private final Writer out;
private final boolean suppressNodeValues;
private JSON2XMLHandler(Writer out, boolean suppresNodeValues){
this.out=out;
this.suppressNodeValues=suppresNodeValues;
}
@Override
public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {
try {
out.append("<").append(localName); //$NON-NLS-1$
for (int i = 0; i < attributes.getLength(); i++) {
//write attribute value
out.append(" "); //$NON-NLS-1$
out.append(attributes.getLocalName(i));
out.append("=\""); //$NON-NLS-1$
out.append(attributes.getValue(i));
out.append("\""); //$NON-NLS-1$
}
out.append(">"); //$NON-NLS-1$
} catch (IOException e) {
new SAXException(e);
}
}
@Override
public void endElement (String uri, String localName, String qName) throws SAXException{
try {
out.append("</").append(localName).append(">"); //$NON-NLS-1$//$NON-NLS-2$
} catch (IOException e) {
new SAXException(e);
}
}
@Override
public void characters (char ch[], int start, int length) throws SAXException{
if (suppressNodeValues) return;
try {
out.write(ch,start,length);
} catch (IOException e) {
new SAXException(e);
}
}
}
private static String normalizeElementName(String name) {
if(!XMLChar.isValidName(name)) {
if(name==null || name.trim().length()==0) {
name = "UNNAMED";
}
if(name.indexOf(' ')>=0) {
name = name.replaceAll(" ", "_");
}
if(!XMLChar.isValidName(name)) {
name = "_"+name;
}
if(!XMLChar.isValidName(name)) {
return "__INVALID_ELEMENT_NAME";
}
}
return name;
}
/**
* Set whether the parser should add additional attributes to the output xml (that will be used by XMLSchemaModifier)
* @param modifierCompatible
*/
public void setModifierCompatible(boolean modifierCompatible) {
this.modifierCompatible = modifierCompatible;
}
}
|
package org.jetel.util.joinKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jetel.data.Defaults;
import org.jetel.enums.OrderEnum;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.string.StringUtils;
public class JoinKeyUtils {
private final static Pattern TAIL_PATTERN = Pattern.compile("\\s*[;|:
// keyName [( order )]?
private final static Pattern ORDERED_KEY_PATTERN = Pattern.compile("([^\\(]+)(([\\(]([^\\)]+)[\\)])|$)");
private final static int MASTER = 0;
private final static int SLAVE = 1;
private final static int RECORD_INDEX = 0;
private final static int FIELD_INDEX = 1;
/**
* Parses join string for HashJoin component.
* @param joinBy Join string
* @param inMetadata collection of input metadata, master metadata must be first in the collection
* @return Each element of outer array contains array of arrays of strings. Each subarray represents one driver/slave key list.
* First element of outer array is for driver key lists, the second one is for slave key lists.(res[MASTER|SLAVE}[slaveNo][fieldNo])
* @throws ComponentNotReadyException
*/
public static String[][][] parseHashJoinKey(String joinBy, List<DataRecordMetadata> inMetadata)
throws ComponentNotReadyException {
if (StringUtils.isEmpty(joinBy)) return new String[2][0][0];
Iterator<DataRecordMetadata> itor = inMetadata != null ? inMetadata.iterator() : null;
DataRecordMetadata masterMetadata = itor != null ? itor.next() : null;
Map<String, Object[]> slaveMetadata = new LinkedHashMap<String, Object[]>(itor != null && inMetadata.size() > 1 ?
inMetadata.size() - 1 : 0);
if (itor != null) {
DataRecordMetadata metadata;
for (int i = 0; i < inMetadata.size() - 1; i++) {
metadata = itor.next();
if (metadata == null) {
throw new ComponentNotReadyException("Input metadata on port number " + i + " are null!!!");
}
slaveMetadata.put(metadata.getName(), new Object[]{metadata, i});
}
}
String[][][] res = new String[2][][];
String[] mappings = joinBy.split("
String[] recName = new String[mappings.length];
res[MASTER] = new String[mappings.length][];
res[SLAVE] = new String[mappings.length][];
String[] tmp;
Boolean isNumber = null;
for (int slaveNum = 0; slaveNum < mappings.length; slaveNum++) {
if (slaveNum > 0 && mappings[slaveNum].length() == 0) {
// use first mapping instead of the empty one
res[MASTER][slaveNum] = res[MASTER][0];
res[SLAVE][slaveNum] = res[SLAVE][0];
continue;
}
String[] pairs = mappings[slaveNum].split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX);
res[MASTER][slaveNum] = new String[pairs.length]; // master key
res[SLAVE][slaveNum] = new String[pairs.length]; // slave key
for (int fieldNum = 0; fieldNum < pairs.length; fieldNum++) {
String[] fields = pairs[fieldNum].split("\\s*=\\s*", 2);
if (fields.length == 0) {
throw new ComponentNotReadyException("Invalid key mapping: " + mappings[slaveNum]);
}
if (isNumber == null) {
tmp = splitFieldName(fields[0]);
if (tmp[RECORD_INDEX] != null) {
isNumber = StringUtils.isInteger(tmp[RECORD_INDEX]) == 0;
}else if (fields.length == 2){
tmp = splitFieldName(fields[1]);
if (tmp[RECORD_INDEX] != null) {
isNumber = StringUtils.isInteger(tmp[RECORD_INDEX]) == 0;
}
}
}
if (fields.length == 1 || fields[1].length() == 0) { // only master field is specified
res[MASTER][slaveNum][fieldNum] = res[SLAVE][slaveNum][fieldNum] = splitFieldName(fields[0])[FIELD_INDEX]; // use it for both master and slave
} else if (fields[0].length() == 0 && slaveNum > 0) { // only slave key is specified
res[MASTER][slaveNum][fieldNum] = res[MASTER][0][fieldNum]; // inherit master from first mapping
tmp = splitFieldName(fields[1]);
res[SLAVE][slaveNum][fieldNum] = tmp[1];
if (tmp[0] != null && recName[slaveNum] == null) {
recName[slaveNum] = tmp[RECORD_INDEX];
if (slaveMetadata.size() > 0) {//check name of metadata or port number
if ((isNumber && Integer.valueOf(tmp[RECORD_INDEX]) > inMetadata.size() - 1)
|| (!isNumber && !slaveMetadata.containsKey(tmp[RECORD_INDEX]))) {
throw new ComponentNotReadyException("Metadata " + StringUtils.quote(tmp[RECORD_INDEX]) +
" are not connected!!!");
}
}
}else if (tmp[RECORD_INDEX] != null && !tmp[RECORD_INDEX].equals(recName[slaveNum])) {
throw new ComponentNotReadyException("Wrong slave definition in " +
StringUtils.quote(mappings[slaveNum]) + " at or near " + StringUtils.quote(tmp[RECORD_INDEX]));
}
} else {//masterField=slaveField
res[MASTER][slaveNum][fieldNum] = splitFieldName(fields[0])[FIELD_INDEX];
tmp = splitFieldName(fields[1]);
res[SLAVE][slaveNum][fieldNum] = tmp[FIELD_INDEX];
if (tmp[RECORD_INDEX] != null && recName[slaveNum] == null) {
recName[slaveNum] = tmp[RECORD_INDEX];
if (slaveMetadata.size() > 0) {//check name of metadata or port number
if ((isNumber && Integer.valueOf(tmp[RECORD_INDEX]) > inMetadata.size() - 1)
|| (!isNumber && !slaveMetadata.containsKey(tmp[RECORD_INDEX]))) {
throw new ComponentNotReadyException("Metadata " + StringUtils.quote(tmp[RECORD_INDEX]) +
" are not connected!!!");
}
}
}else if (tmp[RECORD_INDEX] != null && !tmp[RECORD_INDEX].equals(recName[slaveNum])) {
throw new ComponentNotReadyException("Wrong slave definition in " +
StringUtils.quote(mappings[slaveNum]) + " at or near " + StringUtils.quote(tmp[RECORD_INDEX]));
}
}
}
}
//eventually reorder result
if (slaveMetadata != null && slaveMetadata.size() > 0) {
if (masterMetadata == null) {
throw new ComponentNotReadyException("Master metadata are null!!!");
}
String[][][] reorder = new String[2][mappings.length][];
int slaveNum;
DataRecordMetadata metadata;
for(int i = 0; i < recName.length; i++){
try {
if (recName[i] != null) {
slaveNum = isNumber ? Integer.parseInt(recName[i]) - 1 : (Integer) slaveMetadata.get(recName[i])[1];
metadata = isNumber ? inMetadata.get(slaveNum + 1) : (DataRecordMetadata) slaveMetadata.get(recName[i])[0];
reorder[MASTER][slaveNum] = res[MASTER][i];
reorder[SLAVE][slaveNum] = res[SLAVE][i];
} else {
slaveNum = i;
metadata = inMetadata.get(i + 1);
reorder[MASTER][i] = res[MASTER][i];
reorder[SLAVE][i] = res[SLAVE][i];
}
} catch (IndexOutOfBoundsException e) {
// reference to metadata number, that doesn't exist or more mappings, that number if input metadata
Pattern indexPattern = Pattern.compile("Index\\:\\s*(\\d+)");
Pattern sizePattern = Pattern.compile("Size\\:\\s*(\\d+)");
Matcher indexMatcher = indexPattern.matcher(e.getMessage());
Matcher sizeMatcher = sizePattern.matcher(e.getMessage());
throw new ComponentNotReadyException("Input port " + (indexMatcher.find() ? indexMatcher.group(1) : "?") +
" not defined or mapping has too many elements (number of input ports: " +
(sizeMatcher.find() ? sizeMatcher.group(1) : "?") + ")");
}
//check fields in metadata
//we can't do that, because if only master is given we can set slave directly later
// for (int j = 0; j < reorder[MASTER][slaveNum].length; j++) {
// if (masterMetadata.getFieldPosition(reorder[MASTER][slaveNum][j]) == -1){
// throw new ComponentNotReadyException("Field " + StringUtils.quote(reorder[MASTER][slaveNum][j]) +
// " specified as key field, doesn't exist in master metadata.");
// if (metadata.getFieldPosition(reorder[SLAVE][slaveNum][j]) == -1){
// throw new ComponentNotReadyException("Field " + StringUtils.quote(reorder[SLAVE][slaveNum][j]) +
// " specified as key field, doesn't exist in " + StringUtils.quote(metadata.getName()) + " metadata.");
}
res = reorder;
}
return res;
}
/**
* Parses join string for MergeJoin component
*
* Magda's notes: before was used also in GUI of keys of type "join" (CheckForeignKey, DataIntersection),
* parses also the "$field1=$aa;$field2=$bb" format, but expects complete mapping
*
* @param joinBy input string
* @param inMetadata collection of input metadata, master metadata must be first in the collection
* @return arrays of join keys: master keys and then slave keys in order as order of slave metadata in collection
* (res[portNo][fieldNo]). Difference from hash join key is that master key for all slaves has to be the same and
* length of join key must be the same for each slave.
* @throws ComponentNotReadyException
*/
public static OrderedKey[][] parseMergeJoinOrderedKey(String joinBy, List<DataRecordMetadata> inMetadata) throws ComponentNotReadyException {
if (StringUtils.isEmpty(joinBy)) return new OrderedKey[0][0];
Iterator<DataRecordMetadata> itor = inMetadata != null ? inMetadata.iterator() : null;
DataRecordMetadata masterMetadata = itor != null ? itor.next() : null;
Map<String, Object[]> slaveMetadata = new LinkedHashMap<String, Object[]>(itor != null && inMetadata.size() > 1 ?
inMetadata.size() - 1 : 0);
if (itor != null) {
if (masterMetadata == null) {
throw new ComponentNotReadyException("Master metadata are null!!!");
}
DataRecordMetadata metadata;
for (int i = 0; i < inMetadata.size() - 1; i++) {
metadata = itor.next();
if (metadata == null) {
throw new ComponentNotReadyException("Input metadata on port number " + (i + 1) + " are null!!!");
}
slaveMetadata.put(metadata.getName(), new Object[]{metadata, i});
}
}
String[] mappings = joinBy.split("
Map<Integer, String[]> result = new HashMap<Integer, String[]>();
int keyLenght = -1;
String[] masterTmp;
String[] slaveTmp;
String[] pairs;
String[] fields;
int portNo;
int tmpPortNo;
String[] tmpKey;
String[] tmpMasterKey;
Boolean isNumber = null;
for (int i = 0; i < mappings.length; i++) {
pairs = mappings[i].split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX);
if (i == 0) {
keyLenght = pairs.length;
}else if (pairs.length != keyLenght){
throw new ComponentNotReadyException("Wrong key length for " + StringUtils.quote(mappings[i]));
}
portNo = -1;
tmpKey = null;
for (int j = 0; j < pairs.length; j++) {
fields = pairs[j].split("\\s*=\\s*", 2);
if (fields.length == 0) {
throw new ComponentNotReadyException("Invalid key mapping: " + StringUtils.quote(mappings[i]));
}
//set one key or key pair: masterField=slaveField
masterTmp = fields.length == 1 ? null : splitFieldName(fields[0]);
slaveTmp = fields.length == 1 ? splitFieldName(fields[0]) : splitFieldName(fields[1]);
if (isNumber == null) {//notatation [$]recName.fieldName or [$]recNumber.fieldName ?
isNumber = (masterTmp != null && masterTmp[RECORD_INDEX] != null && StringUtils.isInteger(masterTmp[RECORD_INDEX]) == 0)
|| (slaveTmp[RECORD_INDEX] != null && StringUtils.isInteger(slaveTmp[RECORD_INDEX]) == 0);
}
//find port number for setting key
if (slaveTmp[RECORD_INDEX] == null) {//record name not given - we take order
tmpPortNo = masterTmp == null ? i : i + 1;//setting master or master and slave (masterfield = slaveField)
}else if ((isNumber && Integer.valueOf(slaveTmp[RECORD_INDEX]) == 0)
|| (!isNumber && slaveTmp[RECORD_INDEX].equals(masterMetadata.getName()))) {//set key for master
if (masterTmp != null) {//trying to set master on the right side of key pair (masterfield = slaveField)
throw new ComponentNotReadyException("Invalid key definition - master key has to be on the right side: " +
StringUtils.quote(pairs[j]));
}
tmpPortNo = 0;
}else if ((isNumber && Integer.valueOf(slaveTmp[RECORD_INDEX]) > inMetadata.size() -1)
|| (!isNumber && !slaveMetadata.containsKey(slaveTmp[RECORD_INDEX]))) {//found record name, which there isn't in input metadata collection
throw new ComponentNotReadyException("Metadata " + StringUtils.quote(slaveTmp[RECORD_INDEX]) +
" are not connected!!!");
}else{//found requested slave
tmpPortNo = isNumber ? Integer.valueOf(slaveTmp[RECORD_INDEX]) : ((Integer)slaveMetadata.get(slaveTmp[RECORD_INDEX])[1]) + 1;
}
if (portNo == -1) {//set new key
portNo = tmpPortNo;
tmpKey = new String[keyLenght];
result.put(portNo, tmpKey);
}else if (tmpPortNo != portNo) {//requested port number different then current one
throw new ComponentNotReadyException("Invalid slave in " + StringUtils.quote(mappings[i]) +
" at or near " + StringUtils.quote(pairs[j]));
}
if (masterTmp != null) {//mapping
if (!result.containsKey(MASTER)) {//master key has not been set yet
tmpMasterKey = new String[keyLenght];
result.put(MASTER, tmpMasterKey);
}else{//get master key set before
tmpMasterKey = result.get(MASTER);
}
if (tmpMasterKey[j] == null) {//master key has not been set yet
tmpMasterKey[j] = masterTmp[FIELD_INDEX];
}else if (!masterTmp[FIELD_INDEX].equals(tmpMasterKey[j])) {//curent master field different then the one set before
throw new ComponentNotReadyException("Master field was set to " + StringUtils.quote(tmpMasterKey[j]) +
" but found " + StringUtils.quote(masterTmp[FIELD_INDEX]) + " in " +
StringUtils.quote(mappings[i]));
}
}
tmpKey[j] = slaveTmp[FIELD_INDEX];
}
}
//set proper order in result
OrderedKey[][] keyOrdered = new OrderedKey[result.size()][];
DataRecordMetadata metadata = null;
String aTmp[];
for (int i = 0; i < keyOrdered.length; i++) {
aTmp = result.get(i);
keyOrdered[i] = new OrderedKey[aTmp.length];
if (itor != null) {
if (i >= inMetadata.size()) {
throw new ComponentNotReadyException("Key size (" + keyOrdered.length + ") is greater then number of input metadata ("
+ inMetadata.size() + ").");
}
metadata = inMetadata.get(i);
for (int k = 0; k < aTmp.length; k++) {
keyOrdered[i][k] = parseOrderedKey(aTmp[k]);
if (metadata.getFieldPosition(keyOrdered[i][k].getKeyName()) == -1) {
throw new ComponentNotReadyException("Field " + StringUtils.quote(keyOrdered[i][k].getKeyName()) +
" specified as key field, doesn't exist in " + StringUtils.quote(metadata.getName()) + " metadata.");
}
}
}
}
return keyOrdered;
}
/**
* Parses a field string with optional order notation.
* @param orderedKey
* @return
*/
private static OrderedKey parseOrderedKey(String orderedKey) {
Matcher matcher = ORDERED_KEY_PATTERN.matcher(orderedKey);
String sOrder;
if (!matcher.find() || (sOrder = matcher.group(4)) == null) {
return new OrderedKey(orderedKey, null);
}
return new OrderedKey(matcher.group(1), OrderEnum.fromString(sOrder));
}
public static String[][] parseMergeJoinKey(String joinBy, List<DataRecordMetadata> inMetadata)
throws ComponentNotReadyException{
OrderedKey[][] keyOrdered = parseMergeJoinOrderedKey(joinBy, inMetadata);
if (keyOrdered.length == 0) return new String[0][0];
String[][] sKeyOrdered;
sKeyOrdered = new String[keyOrdered.length][keyOrdered[0].length];
for (int i=0; i<keyOrdered.length; i++) {
for (int j=0; j<keyOrdered[0].length; j++) {
sKeyOrdered[i][j] = keyOrdered[i][j].getKeyName();
}
}
return sKeyOrdered;
}
/**
* Parses field name from form: <i>[$][recName.]fieldName</i> to array: <i>{recName, fieldName}</i>
*
* @param field
* @return
*/
public static String[] splitFieldName(String field){
if (field.startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {
field = field.substring(Defaults.CLOVER_FIELD_INDICATOR.length());
}
String[] res = field.split("\\.");
if (res.length == 2) return res;
if (res.length == 1) return new String[]{null, res[0]};
return new String[]{res[res.length - 1], res[res.length - 2]};
}
/**
* Splits mapping in form "target assignSign source" to array {target, source}. If target or source starts with
* CLOVER_FIELD_INDICATOR ($), removes it. If after <i>source</i> there are characters from set: ";|:#" they are
* removed (used for join keys). <br>
* Default second parameter is: Defaults.ASSIGN_SIGN + "|=". It is ":=" or "=". Eg. for string <i>$field1:=$field2</i>
* returns {field1, field2}
*
* @param mappingStr
* @param assignSignRegex
* @return
*/
public static String[] getMappingItemsFromMappingString(String mappingStr, String assignSignRegex) {
String[] mapping = mappingStr.split(assignSignRegex);
String target = mapping[0].trim();
if (target.startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {
target = target.substring(Defaults.CLOVER_FIELD_INDICATOR.length());
}
target = StringUtils.stringToSpecChar(target);
String source = null;
if (mapping.length > 1) {
source = mapping[1].trim();
if (source.startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {
source = source.substring(Defaults.CLOVER_FIELD_INDICATOR.length());
}
Matcher matcher = TAIL_PATTERN.matcher(source);
int index = -1;
while (matcher.find()) {
index = matcher.start();
}
if (index > -1) {
source = source.substring(0, index);
}
source = StringUtils.stringToSpecChar(source);
}
return new String[] { target, source };
}
/**
* Splits mapping in form "target := source" or "target = source" to array {target, source}. If target or source
* starts with CLOVER_FIELD_INDICATOR ($), removes it. <br>
* Eg. for string <i>$field1:=$field2</i> returns {field1, field2}
*
* @param mappingStr
* @return
*/
public static String[] getMappingItemsFromMappingString(String mappingStr) {
return getMappingItemsFromMappingString(mappingStr, Defaults.ASSIGN_SIGN + "|=");
}
public static String toString(OrderedKey[][] joiners) {
//TODO
StringBuffer joinStr = new StringBuffer();
for (int i = 0; i < joiners.length; i++) {
for (int j=0; j < joiners[i].length; j++) {
joinStr.append(joiners[i][j].getKeyName() + "(" + (joiners[i][j].getOrdering() == OrderEnum.ASC ? "a" : "d") + ")");
}
joinStr.append('
}
return joinStr.toString();
}
}
|
package de.gurkenlabs.litiengine.input;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.IGameLoop;
import de.gurkenlabs.litiengine.entities.IMovableEntity;
import de.gurkenlabs.litiengine.physics.MovementController;
import de.gurkenlabs.util.MathUtilities;
/**
* TODO: Apply friction to terrain in order to slow down acceleration and speed
* up deceleration.
*/
public class KeyboardEntityController<T extends IMovableEntity> extends MovementController<T> implements IKeyObserver {
private float dx;
private float dy;
private boolean movedX, movedY;
private final List<Integer> up, down, left, right;
private double velocityX, velocityY;
public KeyboardEntityController(final T entity) {
this(entity, KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D);
}
public KeyboardEntityController(final T entity, final int up, final int down, final int left, final int right) {
super(entity);
this.up = new ArrayList<>();
this.down = new ArrayList<>();
this.left = new ArrayList<>();
this.right = new ArrayList<>();
this.up.add(up);
this.down.add(down);
this.left.add(left);
this.right.add(right);
Input.KEYBOARD.registerForKeyDownEvents(this);
}
@Override
public void handlePressedKey(final KeyEvent keyCode) {
if (this.up.contains(keyCode.getKeyCode())) {
this.dy
this.movedY = true;
} else if (this.down.contains(keyCode.getKeyCode())) {
this.movedY = true;
this.dy++;
} else if (this.left.contains(keyCode.getKeyCode())) {
this.dx
this.movedX = true;
} else if (this.right.contains(keyCode.getKeyCode())) {
this.dx++;
this.movedX = true;
}
}
public void addUpKey(int keyCode) {
this.up.add(keyCode);
}
public void addDownKey(int keyCode) {
this.down.add(keyCode);
}
public void addLeftKey(int keyCode) {
this.left.add(keyCode);
}
public void addRightKey(int keyCode) {
this.right.add(keyCode);
}
@Override
public void handleReleasedKey(final KeyEvent keyCode) {
}
@Override
public void handleTypedKey(final KeyEvent keyCode) {
}
@Override
public void update(final IGameLoop loop) {
super.update(loop);
if (!this.isMovementAllowed()) {
return;
}
final long deltaTime = loop.getDeltaTime();
final double maxPixelsPerTick = this.getEntity().getVelocity() * 0.001 * deltaTime;
double inc = this.getEntity().getAcceleration() == 0 ? maxPixelsPerTick : deltaTime / (double) this.getEntity().getAcceleration() * maxPixelsPerTick;
final double dec = this.getEntity().getDeceleration() == 0 ? maxPixelsPerTick : deltaTime / (double) this.getEntity().getDeceleration() * maxPixelsPerTick;
final double STOP_THRESHOLD = 0.1;
if (this.movedX && this.movedY) {
// we don't want the entity to move faster when moving diagonally
// calculate a new x by dissolding the formula for diagonals of squares
// sqrt(2 * x^2)
inc /= Math.sqrt(2);
}
if (this.movedX) {
this.velocityX += this.dx * inc;
this.velocityX = MathUtilities.clamp(this.velocityX, -maxPixelsPerTick, maxPixelsPerTick);
this.dx = 0;
this.movedX = false;
} else {
if (this.velocityX > 0) {
if (dec > this.velocityX) {
this.velocityX = 0;
} else {
this.velocityX -= dec;
}
} else if (this.velocityX < 0) {
if (dec < this.velocityX) {
this.velocityX = 0;
} else {
this.velocityX += dec;
}
}
if (Math.abs(this.velocityX) < STOP_THRESHOLD) {
this.velocityX = 0;
}
}
if (this.movedY) {
this.velocityY += this.dy * inc;
this.velocityY = MathUtilities.clamp(this.velocityY, -maxPixelsPerTick, maxPixelsPerTick);
this.dy = 0;
this.movedY = false;
} else {
if (this.velocityY > 0) {
if (dec > this.velocityY) {
this.velocityY = 0;
} else {
this.velocityY -= dec;
}
} else if (this.velocityY < 0) {
if (dec < this.velocityY) {
this.velocityY = 0;
} else {
this.velocityY += dec;
}
}
if (Math.abs(this.velocityY) < STOP_THRESHOLD) {
this.velocityY = 0;
}
}
if (this.velocityX == 0 && this.velocityY == 0) {
return;
}
final Point2D newLocation = new Point2D.Double(this.getEntity().getLocation().getX() + this.velocityX, this.getEntity().getLocation().getY() + this.velocityY);
Game.getPhysicsEngine().move(this.getEntity(), newLocation);
}
}
|
package org.jetel.util;
import java.io.File;
import java.io.IOException;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.Parser;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.IParserExceptionHandler;
import org.jetel.exception.JetelException;
import org.jetel.exception.PolicyType;
import org.jetel.test.CloverTestCase;
import org.jetel.util.bytes.CloverBuffer;
public class MultiFileReaderTest extends CloverTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
initEngine();
}
/** Tests whether parser indicating File as preferred source really gets File
* (at least I guess there's no reason why it shouldn't get the File).
*/
public void testParserFileSource() throws Exception {
MultiFileReader reader = new MultiFileReader(new FileExpectingDummyParser(), new File(".").toURI().toURL(), "data/data.dat");
reader.init(null); // here parser checks if it got the File
}
private static class FileExpectingDummyParser implements Parser {
@Override
public DataRecord getNext() throws JetelException {
return null;
}
@Override
public int skip(int nRec) throws JetelException {
return 0;
}
@Override
public void init() throws ComponentNotReadyException {
}
@Override
public void setDataSource(Object inputDataSource) throws IOException, ComponentNotReadyException {
assertTrue("Input data source is not File", inputDataSource instanceof File);
}
@Override
public void setReleaseDataSource(boolean releaseInputSource) {
}
@Override
public void close() throws IOException {
}
@Override
public DataRecord getNext(DataRecord record) throws JetelException {
return null;
}
@Override
public void setExceptionHandler(IParserExceptionHandler handler) {
}
@Override
public IParserExceptionHandler getExceptionHandler() {
return null;
}
@Override
public PolicyType getPolicyType() {
return null;
}
@Override
public void reset() throws ComponentNotReadyException {
}
@Override
public Object getPosition() {
return null;
}
@Override
public void movePosition(Object position) throws IOException {
}
@Override
public void preExecute() throws ComponentNotReadyException {
}
@Override
public void postExecute() throws ComponentNotReadyException {
}
@Override
public void free() throws ComponentNotReadyException, IOException {
}
@Override
public boolean nextL3Source() {
return false;
}
@Override
public DataSourceType getPreferredDataSourceType() {
return DataSourceType.CHANNEL;
}
@Override
public boolean isDirectReadingSupported() {
return false;
}
@Override
public int getNextDirect(CloverBuffer buffer) throws JetelException {
throw new UnsupportedOperationException();
}
}
}
|
package dr.evomodel.continuous;
import dr.evolution.alignment.PatternList;
import dr.evolution.tree.NodeRef;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.*;
import dr.math.distributions.Distribution;
import dr.util.Citable;
import dr.util.Citation;
import dr.util.CommonCitations;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* A class to model multivariate ordered data as realizations from a latent (liability) multivariate Brownian diffusion
*
* @author Gabrila Cybis
* @author Marc A. Suchard
* @author Joe Felsenstein
* @version $Id$
*/
public class OrderedLatentLiabilityLikelihood extends AbstractModelLikelihood implements LatentTruncation, Citable, SoftThresholdLikelihood {
public final static String ORDERED_LATENT_LIABILITY_LIKELIHOOD = "orderedLatentLiabilityLikelihood";
public OrderedLatentLiabilityLikelihood(TreeModel treeModel, PatternList patternList, CompoundParameter tipTraitParameter, CompoundParameter thresholdParameter, Parameter numClasses, boolean isUnordered) {
super(ORDERED_LATENT_LIABILITY_LIKELIHOOD);
this.treeModel = treeModel;
this.patternList = patternList;
this.tipTraitParameter = tipTraitParameter;
this.thresholdParameter = thresholdParameter;
this.numClasses = numClasses;
this.isUnordered = isUnordered;
addVariable(tipTraitParameter);
addVariable(thresholdParameter);
for (int i=0; i<tipTraitParameter.getParameterCount();i++){
tipTraitParameter.getParameter(i).addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY,Double.NEGATIVE_INFINITY, tipTraitParameter.getParameter(0).getDimension()));
}
setTipDataValuesForAllNodes();
StringBuilder sb = new StringBuilder();
sb.append("Constructing a latent liability likelihood model:\n");
sb.append("\tBinary patterns: ").append(patternList.getId()).append("\n");
sb.append("\tPlease cite:\n").append(Citable.Utils.getCitationString(this));
Logger.getLogger("dr.evomodel.continous").info(sb.toString());
}
private void setTipDataValuesForAllNodes() {
if (tipData == null) {
tipData = new int[treeModel.getExternalNodeCount()][patternList.getPatternCount()];
}
for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
NodeRef node = treeModel.getExternalNode(i);
String id = treeModel.getTaxonId(i);
int index = patternList.getTaxonIndex(id);
setTipDataValuesForNode(node, index);
System.err.println("\t For node: " + i + " with ID " + id + " you get taxon " + index + " with ID " + patternList.getTaxonId(index));
}
}
private void setTipDataValuesForNode(NodeRef node, int index) {
// Set tip data values
int Nindex = node.getNumber();
// if (index != indexFromPatternList) {
// throw new RuntimeException("Need to figure out the indexing");
for (int datum = 0; datum < patternList.getPatternCount(); ++datum) {
tipData[Nindex][datum] = (int) patternList.getPattern(datum)[index];
if (DEBUG) {
Parameter oneTipTraitParameter = tipTraitParameter.getParameter(Nindex);
System.err.println("Data = " + tipData[Nindex][datum] + " : " + oneTipTraitParameter.getParameterValue(datum));
}
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
likelihoodKnown = false;
}
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
}
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood;
likelihoodKnown = true;
}
@Override
protected void acceptState() {
// do nothing
}
public void makeDirty() {
likelihoodKnown = false;
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
@Override
public void setPathParameter(double beta) {
pathParameter=beta;
}
@Override
public double getLikelihoodCorrection() {
boolean valid=true;
for (int tip = 0; tip < tipData.length && valid; ++tip) {
valid = validTraitForTip(tip);
}
if(valid)
{
return 0;
}
else{
return 1/(1-pathParameter);
}
}
public String toString() {
return getClass().getName() + "(" + getLogLikelihood() + ")";
}
protected double computeLogLikelihood() {
boolean valid = true;
for (int tip = 0; tip < tipData.length && valid; ++tip) {
valid = validTraitForTip(tip);
}
if (valid) {
return 0.0;
} else {
if(pathParameter==1)
return Double.NEGATIVE_INFINITY;
else{
return Math.log(1-pathParameter);
}
}
}
public boolean validTraitForTip(int tip) {
boolean valid = true;
Parameter oneTipTraitParameter = tipTraitParameter.getParameter(tip);
int[] data = tipData[tip];
if (!isUnordered){
int threshNum = 0;
for (int index = 0; index < data.length && valid; ++index) {
int datum = data[index];
double trait = oneTipTraitParameter.getParameterValue(index);
int dim = (int) numClasses.getParameterValue(index);
if (dim == 1.0) {
valid = true;
} else if (dim == 2.0){
if (trait == 0) {
valid = true;
}
else if(datum>1){
valid=true;
} else {
boolean positive = trait > 0.0;
if (positive) {
valid = (datum == 1.0);
} else {
valid = (datum == 0.0);
}
}
} else {
if (datum == 0) {
valid = trait <= 0.0;
} else if (datum == 1) {
valid = (trait >= 0 &&
trait <= thresholdParameter.getParameter(threshNum).getParameterValue(0));
} else if (datum == (dim - 1)) {
valid = trait >= thresholdParameter.getParameter(threshNum).getParameterValue(dim - 3);
} else if (datum > (dim-1)) {
valid=true;
}else {
valid = (trait >= thresholdParameter.getParameter(threshNum).getParameterValue(datum - 2) &&
trait <= thresholdParameter.getParameter(threshNum).getParameterValue(datum - 1));
}
threshNum++;
}
}
}else{
int LLpointer = 0;
for (int index = 0; index < data.length && valid; ++index) {
int datum = data[index];
int dim = (int) numClasses.getParameterValue(index);
if (dim == 1.0) {
valid = true;
LLpointer++;
} else if (dim == 2.0) {
double trait = oneTipTraitParameter.getParameterValue(LLpointer);
if (trait == 0) {
valid = true;
} else {
boolean positive = trait > 0.0;
if (positive) {
valid = (datum == 1.0);
} else {
valid = (datum == 0.0);
}
}
LLpointer++;
} else {
double[] trait = new double[dim];
trait[0] = 0.0;
for (int l=1; l<dim; l++){
trait[l]=oneTipTraitParameter.getParameterValue(LLpointer+l-1);
}
valid=isMax(trait, datum);
LLpointer += dim-1;
}
}
}
return valid;
}
/*
public boolean unorderedValidTraitForTip(int tip) {
boolean valid = true;
Parameter oneTipTraitParameter = tipTraitParameter.getParameter(tip);
int[] data = tipData[tip];
int LLpointer = 0;
for (int index = 0; index < data.length && valid; ++index) {
int datum = data[index];
int dim = (int) numClasses.getParameterValue(index);
if (dim == 1.0) {
valid = true;
LLpointer++;
} else if (dim == 2.0) {
double trait = oneTipTraitParameter.getParameterValue(LLpointer);
if (trait == 0) {
valid = true;
} else {
boolean positive = trait > 0.0;
if (positive) {
valid = (datum == 1.0);
} else {
valid = (datum == 0.0);
}
}
LLpointer++;
} else {
double[] trait = new double[dim];
trait[0] = 0.0;
for (int l=1; l<dim; l++){
trait[l]=oneTipTraitParameter.getParameterValue(LLpointer+l-1);
}
valid=isMax(trait, datum);
LLpointer += dim-1;
}
}
return valid;
}
*/
private boolean isMax(double[] trait, int datum) {
boolean isMax = true;
for (int j = 0; j < trait.length && isMax; j++) {
isMax = (trait[datum] >= trait[j]);
}
return isMax;
}
public double getNormalizationConstant(Distribution working) {
return normalizationDelegate.getNormalizationConstant(working); // delegate to abstract Delegate
}
private final LatentTruncation.Delegate normalizationDelegate = new Delegate() {
protected double computeNormalizationConstant(Distribution working) {
double constant = 0.0;
// TODO
return constant;
}
};
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String TIP_TRAIT = "tipTrait";
public final static String THRESHOLD_PARAMETER = "threshold";
public final static String NUM_CLASSES = "numClasses";
public static final String IS_UNORDERED = "isUnordered";
public final static String N_DATA="NData";
public final static String N_TRAITS="NTraits";
public String getParserName() {
return ORDERED_LATENT_LIABILITY_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
int numData;
int dimTrait;
if(xo.hasAttribute(N_DATA)&&xo.hasAttribute(N_TRAITS)){
String numDataTemp=(String) xo.getAttribute(N_DATA);
String dimTraitTemp=(String) xo.getAttribute(N_TRAITS);
numData= Integer.parseInt(numDataTemp);
dimTrait= Integer.parseInt(dimTraitTemp);
}
else {
AbstractMultivariateTraitLikelihood traitLikelihood = (AbstractMultivariateTraitLikelihood)
xo.getChild(AbstractMultivariateTraitLikelihood.class);
numData = traitLikelihood.getNumData();
dimTrait = traitLikelihood.getDimTrait();
}
PatternList patternList = (PatternList) xo.getChild(PatternList.class);
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
CompoundParameter tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
CompoundParameter thresholdParameter = (CompoundParameter) xo.getElementFirstChild(THRESHOLD_PARAMETER);
Parameter numClasses = (Parameter) xo.getElementFirstChild(NUM_CLASSES);
boolean isUnorderd = xo.getAttribute(IS_UNORDERED,false);
int numTaxa = treeModel.getTaxonCount();
if (tipTraitParameter.getDimension() != numTaxa * numData * dimTrait) {
throw new XMLParseException("Tip trait parameter is wrong dimension in latent liability model");
}
if (!isUnorderd){
if (patternList.getPatternCount() != numData * dimTrait) {
throw new XMLParseException("Data is wrong dimension in latent liability model");
}
}
return new OrderedLatentLiabilityLikelihood(treeModel, patternList, tipTraitParameter, thresholdParameter, numClasses,isUnorderd);
}
|
package org.curriki.gwt.client.search.columns;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.xpn.xwiki.gwt.api.client.Document;
import org.curriki.gwt.client.Constants;
import org.curriki.gwt.client.Main;
public class InstructionalTypeColumn extends ResultsColumn
{
public InstructionalTypeColumn()
{
this.header = Main.getTranslation("Instructional Type");
}
public InstructionalTypeColumn(String header, String columnStyle)
{
super(header, columnStyle);
}
public String getDisplayString(Document value)
{
String name = "";
if (value.getObject(Constants.ASSET_CLASS) != null){
value.use(Constants.ASSET_CLASS);
if (value.get(Constants.ASSET_INSTRUCTIONAL_COMPONENT_PROPERTY) != null){
name = value.get(Constants.ASSET_INSTRUCTIONAL_COMPONENT_PROPERTY);
}
}
return name;
}
public Widget getDisplayWidget(Document value)
{
String name = getDisplayString(value);
FlowPanel ret = new FlowPanel();
if (name.indexOf("
name = "Multiple:";
}
if (name.length() > 0){
String icon = name.replaceAll(":.*", "");
name = name.replaceFirst(icon+":", "");
if (icon.length() > 0) {
Image img = new Image(Constants.ICON_PATH+"ICTIcon-"+icon+".png");
img.setTitle(icon);
ret.add(img);
}
ret.add(new Label(name));
}
return ret;
}
}
|
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.templates.RobotMap;
/**
*
* @author 997robotics4
*/
public class shootThenDrive extends CommandGroup {
Timer myTimer;
public shootThenDrive() {
myTimer = new Timer();
myTimer.reset();
myTimer.start();
addSequential(new PrepShooter(RobotMap.DefaultSetPointForTheShooter));
addSequential(new WaitForHotGoal(myTimer));
addSequential(new Shoot());
addSequential(new DriveToSetpoint(RobotMap.distanceToDriveDuringAutonomous));
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
}
}
|
import org.uwcs.choob.*;
import org.uwcs.choob.modules.*;
import org.uwcs.choob.support.*;
import org.uwcs.choob.support.events.*;
import java.util.*;
public class Test
{
public void commandSecurity( Message con, Modules mods, IRCInterface irc )
{
List<String> params = mods.util.getParams( con );
String priv = params.get(1);
if ( mods.security.hasPerm( new ChoobPermission(priv), con.getNick() ) )
irc.sendContextReply(con, "You do indeed have " + priv + "!" );
else
irc.sendContextReply(con, "You don't have " + priv + "!" );
}
public void commandPirate( Message con, Modules mods, IRCInterface irc )
{
irc.sendContextReply(con, "Yarr!");
}
public void commandInMy( Message con, Modules mods, IRCInterface irc )
{
irc.sendContextMessage(con, "..Pants!");
}
public void commandExit( Message con, Modules mods, IRCInterface irc )
{
System.exit(1);
}
// Define the regex for the KarmaPlus filter.
public String filterFauxRegex = "^Faux sucks";
public void filterFaux( Message con, Modules modules, IRCInterface irc )
{
irc.sendContextReply( con, "I would almost certainly concur.");
}
public String filterBouncyRegex = "^bouncy bouncy";
public void filterBouncy( Message con, Modules modules, IRCInterface irc )
{
irc.sendContextReply( con, "Ooh, yes please.");
}
public void onJoin( ChannelJoin ev, Modules mod, IRCInterface irc )
{
irc.sendMessage(ev.getChannel(), "Hello, " + ev.getNick() + "!");
}
public void onPart( ChannelPart ev, Modules mod, IRCInterface irc )
{
irc.sendMessage(ev.getChannel(), "Bye, " + ev.getNick() + "!");
}
}
|
package edu.wustl.xipApplication.samples;
import java.awt.Font;
import java.awt.Frame;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.nema.dicom.wg23.ArrayOfObjectDescriptor;
import org.nema.dicom.wg23.ArrayOfObjectLocator;
import org.nema.dicom.wg23.ArrayOfUUID;
import org.nema.dicom.wg23.AvailableData;
import org.nema.dicom.wg23.ObjectDescriptor;
import org.nema.dicom.wg23.ObjectLocator;
import org.nema.dicom.wg23.Patient;
import org.nema.dicom.wg23.Rectangle;
import org.nema.dicom.wg23.Series;
import org.nema.dicom.wg23.State;
import org.nema.dicom.wg23.Study;
import org.nema.dicom.wg23.Uuid;
import edu.wustl.xipApplication.application.ApplicationTerminator;
import edu.wustl.xipApplication.applicationGUI.ExceptionDialog;
import edu.wustl.xipApplication.applicationGUI.TextDisplayPanel;
import edu.wustl.xipApplication.applicationGUI.XIPApplicationFrame;
import edu.wustl.xipApplication.application.WG23Application;
import edu.wustl.xipApplication.wg23.ApplicationImpl;
import edu.wustl.xipApplication.wg23.WG23Listener;
/**
* @author Jaroslaw Krych
*
*/
public class XIPAppLazyRetrieveTest extends WG23Application implements WG23Listener{
State appCurrentState;
public static final String OS = System.getProperty("os.name");
JFrame frame = new JFrame("XIP Application - Lazy Retrieve Test");
TextDisplayPanel txtArea = new TextDisplayPanel();
Font font = new Font("Tahoma", 1, 12);
public XIPAppLazyRetrieveTest (URL hostURL, URL appURL) {
super(hostURL, appURL);
if(OS.contains("Windows") || OS.contains("Mac OS X")){
frame.setUndecorated(true);
}else{
frame.setUndecorated(false);
frame.setTitle("XIP Application - Lazy Retrieve Test");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
txtArea.setFont(font);
JScrollPane scrollPane = new JScrollPane(txtArea);
frame.add(scrollPane);
/*Set application dimensions */
Rectangle rect = getClientToHost().getAvailableScreen(null);
frame.setBounds(rect.getRefPointX(), rect.getRefPointY(), rect.getWidth(), rect.getHeight());
frame.setVisible(true);
/*Notify Host application was launched*/
ApplicationImpl appImpl = new ApplicationImpl();
appImpl.addWG23Listener(this);
setAndDeployApplicationService(appImpl);
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
getClientToHost().notifyStateChanged(State.IDLE);
}
/**
* @param args
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
System.out.println("Number of parameters: " + args.length);
for (int i = 0; i < args.length; i++){
System.out.println(i + ". " + args[i]);
}
URL hostURL = null;
URL applicationURL = null;
for (int i = 0; i < args.length; i++){
if (args[i].equalsIgnoreCase("--hostURL")){
hostURL = new URL(args[i + 1]);
}else if(args[i].equalsIgnoreCase("--applicationURL")){
applicationURL = new URL(args[i + 1]);
}
}
//final XIPApplication_WashU app = new XIPApplication_WashU(new URL(args[0]), new URL(args[1]));
new XIPAppLazyRetrieveTest(hostURL, applicationURL);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (NullPointerException e){
new ExceptionDialog("List of parameters is not valid!",
"Ensure: -hostURL url1 -applicationURL url2",
"Launch Application Dialog");
System.exit(0);
}
}
ArrayOfUUID models;
ArrayOfUUID getModels(){
return models;
}
public boolean bringToFront() {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if(this != null) {
Rectangle size = getClientToHost().getAvailableScreen(null);
frame.setSize(size.getWidth(), size.getHeight());
frame.toFront();
frame.repaint();
}
}
});
/*if(XIPApplicationFrame.OS.contains("Windows") == false){
deiconify(frame);
}*/
return true;
}
public static void deiconify(Frame frame) {
int state = frame.getExtendedState();
state &= ~Frame.ICONIFIED;
frame.setExtendedState(state);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}
List<Uuid> uuids;
List<Uuid> getAllUUIDs(){
return uuids;
}
int notificationNumber = 1;
public void notifyDataAvailable(AvailableData availableData, boolean lastData) {
uuids = new ArrayList<Uuid>();
/*if(availableData.getObjectDescriptors() != null){
List<ObjectDescriptor> listObjDescs = availableData.getObjectDescriptors().getObjectDescriptor();
for(int i = 0; i < listObjDescs.size(); i++){
uuids.add(listObjDescs.get(i).getUuid());
}
}*/
txtArea.append("Notification: " + notificationNumber++ + "\r\n");
List<Patient> patients = availableData.getPatients().getPatient();
for(int i = 0; i < patients.size(); i++){
Patient patient = patients.get(i);
txtArea.append(" " + "\r\n");
txtArea.append(patient.getName() + "\r\n");
System.out.println(patient.getName());
List<Study> studies = patient.getStudies().getStudy();
for(int j = 0; j < studies.size(); j++){
Study study = studies.get(j);
txtArea.append(" " + study.getStudyUID() + "\r\n");
System.out.println(" " + study.getStudyUID());
List<Series> listOfSeries = study.getSeries().getSeries();
for(int k = 0; k < listOfSeries.size(); k++){
Series series = listOfSeries.get(k);
txtArea.append(" " + series.getSeriesUID() + "\r\n");
System.out.println(" " + series.getSeriesUID());
}
txtArea.append("\r\n");
txtArea.append("Items UUIDs: " + "\r\n");
for(int k = 0; k < listOfSeries.size(); k++){
Series series = listOfSeries.get(k);
ArrayOfObjectDescriptor descriptors = series.getObjectDescriptors();
List<ObjectDescriptor> listDescriptors = descriptors.getObjectDescriptor();
for(int m =0; m < listDescriptors.size(); m++){
ObjectDescriptor desc = listDescriptors.get(m);
uuids.add(desc.getUuid());
txtArea.append(desc.getUuid().getUuid() + "\r\n");
System.out.println(desc.getUuid().getUuid());
}
}
}
}
txtArea.append("Last item? " + lastData + "\r\n");
System.out.println("Last item? " + lastData);
ArrayOfUUID arrayUUIDs = new ArrayOfUUID();
List<Uuid> listUUIDs = arrayUUIDs.getUuid();
for(int i = 0; i < getAllUUIDs().size(); i++){
Uuid uuid = getAllUUIDs().get(i);
listUUIDs.add(uuid);
}
ArrayOfObjectLocator objLocs = getClientToHost().getDataAsFile(arrayUUIDs, true);
List<ObjectLocator> listObjectLocators = objLocs.getObjectLocator();
txtArea.append("\r\n");
txtArea.append("Items location: " + "\r\n");
for(ObjectLocator objectLocator : listObjectLocators){
txtArea.append(objectLocator.getUuid().getUuid() + " " + objectLocator.getUri() + "\r\n");
}
txtArea.append("Recieved data. Analysis being performed for 10s." + "\r\n");
//from 1 to 11
for(int i = 1; i < 30; i++) {
txtArea.append(" " + i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
txtArea.append("\r\n");
txtArea.append("Analysis complete." + "\r\n");
txtArea.append("Notifying host about available data." + "\r\n");
try {
//Thread.sleep(3000);
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtArea.append("Notifying host state changed to COMPLETED." + "\r\n");
try {
//Thread.sleep(3000);
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setState(State.COMPLETED);
txtArea.append("Notifying host state changed to IDLE." + "\r\n");
txtArea.append("
try {
//Thread.sleep(3000);
Thread.sleep(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setState(State.IDLE);
}
public boolean setState(State newState) {
if(State.valueOf(newState.toString()).equals(State.CANCELED)){
getClientToHost().notifyStateChanged(State.CANCELED);
appCurrentState = State.CANCELED;
//getClientToHost().notifyStateChanged(State.IDLE);
//appCurrentState = State.CANCELED;
}else if(State.valueOf(newState.toString()).equals(State.EXIT)){
getClientToHost().notifyStateChanged(State.EXIT);
appCurrentState = State.EXIT;
//terminating endpoint and existing system is accomplished through ApplicationTerminator
//and ApplicationScheduler. ApplicationSechduler is present to alow termination delay if needed (posible future use)
ApplicationTerminator terminator = new ApplicationTerminator(getEndPoint());
Thread t = new Thread(terminator);
t.start();
}else{
appCurrentState = newState;
getClientToHost().notifyStateChanged(newState);
}
return true;
}
@Override
public State getState() {
System.out.println("Application current state: " + appCurrentState);
return appCurrentState;
}
}
|
// ProdukControllerTest.java
// produk-api-service
package com.agung.produk.controller;
import com.agung.produk.ProdukApiApplication;
import com.agung.produk.entity.Produk;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import java.math.BigDecimal;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ProdukApiApplication.class)
@Sql(scripts = {"/mysql/delete-data.sql", "/mysql/sample-product.sql"})
@WebIntegrationTest(randomPort = true)
public class ProdukControllerTest {
private static final String BASE_URL = "/api/produk";
@Value("${local.server.port}")
int serverPort;
@Before
public void setup() {
RestAssured.port = serverPort;
}
@Test
public void testCreateProduk() {
Produk p = new Produk();
p.setCode("p-004");
p.setName("Produk-004");
p.setPrice(new BigDecimal(65000.0));
RestAssured.given()
.body(p)
.contentType(ContentType.JSON)
.when()
.post(BASE_URL + "/")
.then()
.statusCode(201)
.header("Location", CoreMatchers.containsString(BASE_URL + "/"))
.log().headers();
//kode kurang dari 3
Produk p2 = new Produk();
p2.setCode("PT");
p2.setName("Produk-test");
p2.setPrice(new BigDecimal(65000.0));
RestAssured.given()
.body(p2)
.contentType(ContentType.JSON)
.when()
.post(BASE_URL + "/")
.then()
.statusCode(400);
//Harga Negatif
Produk p2p3 = new Produk();
p2p3.setCode("P-006");
p2p3.setName("Produk-212");
p2p3.setPrice(new BigDecimal(-65000.0));
RestAssured.given()
.body(p2p3)
.contentType(ContentType.JSON)
.when()
.post(BASE_URL + "/")
.then()
.statusCode(400);
}
@Test
public void testFindAll() {
RestAssured.given()
.get(BASE_URL + "/")
.then()
.body("totalElements", CoreMatchers.equalTo(1))
.body("content.id", CoreMatchers.hasItems("test123"));
}
@Test
public void testFindById() {
RestAssured.given()
.get(BASE_URL + "/test123")
.then()
.statusCode(200)
.body("id", CoreMatchers.equalTo("test123"))
.body("code", CoreMatchers.equalTo("P-001"));
RestAssured.given().
get(BASE_URL + "/990")
.then()
.statusCode(500);
}
@Test
public void testUpdate() {
Produk p4 = new Produk();
p4.setCode("PX-009");
p4.setName("Product909");
p4.setPrice(BigDecimal.valueOf(2000));
RestAssured.given().
given()
.body(p4)
.contentType(ContentType.JSON)
.when()
.put(BASE_URL + "/test123")
.then()
.statusCode(200);
RestAssured.given().
get(BASE_URL + "/test123")
.then()
.statusCode(200)
.body("id", CoreMatchers.equalTo("test123"))
.body("code", CoreMatchers.equalTo("PX-009"))
.body("name", CoreMatchers.equalTo("Product909"));
}
@Test
public void testDelete() {
RestAssured.given().
delete(BASE_URL + "/test123")
.then()
.statusCode(200);
RestAssured.given().
get(BASE_URL + "/test123")
.then()
.statusCode(500);
}
}
|
package com.baomidou.mybatisplus.test.h2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baomidou.mybatisplus.test.h2.config.DBConfig;
import com.baomidou.mybatisplus.test.h2.config.MybatisPlusNoOptLockConfig;
import com.baomidou.mybatisplus.test.h2.entity.mapper.H2UserFillMapper;
import com.baomidou.mybatisplus.test.h2.entity.persistent.H2UserFill;
/**
* <p>
* </p>
*
* @author yuxiaobin
* @date 2017/5/31
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DBConfig.class, MybatisPlusNoOptLockConfig.class})
public class H2FillFieldTest extends H2Test {
@Autowired
H2UserFillMapper fillMapper;
@BeforeClass
public static void initDB() throws SQLException, IOException {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:h2/spring-test-h2.xml");
DataSource ds = (DataSource) context.getBean("dataSource");
try (Connection conn = ds.getConnection()) {
String createTableSql = readFile("user.ddl.sql");
Statement stmt = conn.createStatement();
stmt.execute(createTableSql);
stmt.execute("truncate table h2user");
executeSql(stmt, "user.insert.sql");
conn.commit();
}
}
@Test
public void testFill() {
H2UserFill u = new H2UserFill();
u.setName("ignoreTest");
u.setTestType(1);
u.setDesc("ignoreDesc");
Assert.assertEquals(1, fillMapper.insert(u).intValue());
Long id = u.getId();
Assert.assertNotNull(id);
H2UserFill dbUser = fillMapper.selectById(id);
Assert.assertNull(dbUser.getTestType());
Assert.assertNotNull(dbUser.getDesc());
dbUser.setTestType(2);
dbUser.setDesc("ignoreDesc2");
Assert.assertEquals(1, fillMapper.updateById(dbUser).intValue());
dbUser = fillMapper.selectById(id);
Assert.assertEquals("ignoreDesc", dbUser.getDesc());
Assert.assertEquals(2, dbUser.getTestType().intValue());
}
}
|
package com.faforever.api.data;
import com.faforever.api.clan.ClanMembershipRepository;
import com.faforever.api.clan.ClanRepository;
import com.faforever.api.client.ClientType;
import com.faforever.api.client.OAuthClient;
import com.faforever.api.client.OAuthClientRepository;
import com.faforever.api.data.domain.Clan;
import com.faforever.api.data.domain.ClanMembership;
import com.faforever.api.data.domain.Player;
import com.faforever.api.data.domain.User;
import com.faforever.api.player.PlayerRepository;
import com.faforever.api.user.UserRepository;
import lombok.SneakyThrows;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.WebApplicationContext;
import javax.inject.Inject;
import javax.servlet.Filter;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JsonApiClanTest {
private MockMvc mvc;
private WebApplicationContext context;
private Filter springSecurityFilterChain;
private ClanRepository clanRepository;
private UserRepository userRepository;
private ClanMembershipRepository clanMembershipRepository;
private PlayerRepository playerRepository;
private OAuthClientRepository oAuthClientRepository;
private ObjectMapper objectMapper;
private ShaPasswordEncoder shaPasswordEncoder;
private Player me;
private static final String OAUTH_CLIENT_ID = "1234";
private static final String OAUTH_SECRET = "secret";
public JsonApiClanTest() {
objectMapper = new ObjectMapper();
shaPasswordEncoder = new ShaPasswordEncoder(256);
}
@Inject
public void init(WebApplicationContext context,
ClanRepository clanRepository,
UserRepository userRepository,
PlayerRepository playerRepository,
OAuthClientRepository oAuthClientRepository,
Filter springSecurityFilterChain,
ClanMembershipRepository clanMembershipRepository) {
this.context = context;
this.clanRepository = clanRepository;
this.userRepository = userRepository;
this.playerRepository = playerRepository;
this.oAuthClientRepository = oAuthClientRepository;
this.springSecurityFilterChain = springSecurityFilterChain;
this.clanMembershipRepository = clanMembershipRepository;
}
@Before
public void setUp() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilter(springSecurityFilterChain)
.build();
me = null;
}
@After
public void tearDown() {
clanMembershipRepository.deleteAll();
clanRepository.deleteAll();
userRepository.deleteAll();
oAuthClientRepository.deleteAll();
assertEquals(0, clanMembershipRepository.count());
assertEquals(0, clanRepository.count());
assertEquals(0, userRepository.count());
assertEquals(0, oAuthClientRepository.count());
}
@SneakyThrows
public String createUserAndGetAccessToken(String login, String password) {
OAuthClient client = new OAuthClient()
.setId(OAUTH_CLIENT_ID)
.setName("test")
.setClientSecret(OAUTH_SECRET)
.setRedirectUris("test")
.setDefaultRedirectUri("test")
.setDefaultScope("test")
.setClientType(ClientType.PUBLIC);
oAuthClientRepository.save(client);
User user = (User) new User()
.setPassword(shaPasswordEncoder.encodePassword(password, null))
.setLogin(login)
.setEMail(login + "@faforever.com");
userRepository.save(user);
me = playerRepository.findOne(user.getId());
String authorization = "Basic "
+ new String(Base64Utils.encode((OAUTH_CLIENT_ID + ":" + OAUTH_SECRET).getBytes()));
ResultActions auth = mvc
.perform(
post("/oauth/token")
.header("Authorization", authorization)
.param("username", login)
.param("password", password)
.param("grant_type", "password"));
auth.andExpect(status().isOk());
JsonNode node = objectMapper.readTree(auth.andReturn().getResponse().getContentAsString());
return "Bearer " + node.get("access_token").asText();
}
private Player createPlayer(String login) {
User user = (User) new User()
.setPassword("foo")
.setLogin(login)
.setEMail(login + "@faforever.com");
userRepository.save(user);
return playerRepository.findOne(user.getId());
}
@Test
@SneakyThrows
public void cannotKickLeaderFromClan() {
String accessToken = createUserAndGetAccessToken("Dragonfire", "foo");
Clan clan = new Clan().setLeader(me).setTag("123").setName("abcClanName");
ClanMembership membership = new ClanMembership().setPlayer(me).setClan(clan);
clan.setMemberships(Collections.singletonList(membership));
clanRepository.save(clan);
assertEquals(1, clanMembershipRepository.count());
this.mvc.perform(delete("/data/clanMembership/" + membership.getId())
.header("Authorization", accessToken))
.andExpect(content().string("{\"errors\":[\"ForbiddenAccessException\"]}"))
.andExpect(status().is(403));
assertEquals(1, clanMembershipRepository.count());
}
@Test
@SneakyThrows
public void cannotKickAsMember() {
String accessToken = createUserAndGetAccessToken("Dragonfire", "foo");
Player bob = createPlayer("Bob");
Clan clan = new Clan().setLeader(bob).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
ClanMembership bobsMembership = new ClanMembership().setPlayer(bob).setClan(clan);
clan.setMemberships(Arrays.asList(myMembership, bobsMembership));
clanRepository.save(clan);
assertEquals(2, clanMembershipRepository.count());
this.mvc.perform(delete("/data/clanMembership/" + bobsMembership.getId())
.header("Authorization", accessToken))
.andExpect(content().string("{\"errors\":[\"ForbiddenAccessException\"]}"))
.andExpect(status().is(403));
assertEquals(2, clanMembershipRepository.count());
}
@Test
@SneakyThrows
public void canKickMember() {
String accessToken = createUserAndGetAccessToken("Dragonfire", "foo");
Player bob = createPlayer("Bob");
Clan clan = new Clan().setLeader(me).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
ClanMembership bobsMembership = new ClanMembership().setPlayer(bob).setClan(clan);
clan.setMemberships(Arrays.asList(myMembership, bobsMembership));
clanRepository.save(clan);
assertEquals(2, clanMembershipRepository.count());
this.mvc.perform(delete("/data/clanMembership/" + bobsMembership.getId())
.header("Authorization", accessToken))
.andExpect(status().is(204));
assertEquals(1, clanMembershipRepository.count());
}
@Test
@SneakyThrows
public void getFilteredPlayerForClanInvite() {
String[] players = new String[]{"Dragonfire", "DRAGON", "Fire of Dragon", "d r a g o n", "firedragon"};
Arrays.stream(players).forEach(name -> createPlayer(name));
assertEquals(players.length, playerRepository.count());
ResultActions action = this.mvc.perform(get("/data/player?filter=lowerCaseLogin==dragon*&sort=lowerCaseLogin"));
JsonNode node = objectMapper.readTree(action.andReturn().getResponse().getContentAsString());
assertEquals(2, node.get("data").size());
assertEquals(players[1], node.get("data").get(0).get("attributes").get("login").asText());
assertEquals(players[0], node.get("data").get(1).get("attributes").get("login").asText());
action.andExpect(status().isOk());
}
private String generateTransferLeadershipContent(int clanId, int newLeaderId) {
ObjectNode node = this.objectMapper.createObjectNode();
ObjectNode data = this.objectMapper.createObjectNode();
ObjectNode relationships = this.objectMapper.createObjectNode();
ObjectNode leaderData = this.objectMapper.createObjectNode();
ObjectNode leader = this.objectMapper.createObjectNode();
node.put("data", data);
data.put("id", clanId);
data.put("type", "clan");
data.put("relationships", relationships);
relationships.put("leader", leaderData);
leaderData.put("data", leader);
leader.put("id", newLeaderId);
leader.put("type", "player");
return node.toString();
}
@Test
@SneakyThrows
public void transferLeadership() {
String accessToken = createUserAndGetAccessToken("Leader", "foo");
Player bob = createPlayer("Bob");
Clan clan = new Clan().setLeader(me).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
ClanMembership bobsMembership = new ClanMembership().setPlayer(bob).setClan(clan);
clan.setMemberships(Arrays.asList(myMembership, bobsMembership));
clanRepository.save(clan);
String dataString = generateTransferLeadershipContent(clan.getId(), bob.getId());
clan = clanRepository.findOne(clan.getId());
assertEquals(me.getId(), clan.getLeader().getId());
ResultActions action = this.mvc.perform(patch("/data/clan/" + clan.getId())
.content(dataString)
.header("Authorization", accessToken));
action.andExpect(content().string(""))
.andExpect(status().is(204));
clan = clanRepository.findOne(clan.getId());
assertEquals(bob.getId(), clan.getLeader().getId());
}
@Test
@SneakyThrows
public void transferLeadershipToOldLeader() {
String accessToken = createUserAndGetAccessToken("Leader", "foo");
Clan clan = new Clan().setLeader(me).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
clan.setMemberships(Collections.singletonList(myMembership));
clanRepository.save(clan);
String dataString = generateTransferLeadershipContent(clan.getId(), me.getId());
clan = clanRepository.findOne(clan.getId());
assertEquals(me.getId(), clan.getLeader().getId());
ResultActions action = this.mvc.perform(patch("/data/clan/" + clan.getId())
.content(dataString)
.header("Authorization", accessToken));
action.andExpect(content().string(""))
.andExpect(status().is(204));
clan = clanRepository.findOne(clan.getId());
assertEquals(me.getId(), clan.getLeader().getId());
}
@Test
@SneakyThrows
public void transferLeadershipToNonClanMember() {
String accessToken = createUserAndGetAccessToken("Leader", "foo");
Player bob = createPlayer("Bob");
Clan clan = new Clan().setLeader(me).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
clan.setMemberships(Collections.singletonList(myMembership));
clanRepository.save(clan);
String dataString = generateTransferLeadershipContent(clan.getId(), bob.getId());
clan = clanRepository.findOne(clan.getId());
assertEquals(me.getId(), clan.getLeader().getId());
ResultActions action = this.mvc.perform(patch("/data/clan/" + clan.getId())
.content(dataString)
.header("Authorization", accessToken));
action.andExpect(status().is(422));
JsonNode resultNode = objectMapper.readTree(action.andReturn().getResponse().getContentAsString());
assertEquals(1, resultNode.get("errors").size());
assertEquals("Validation failed", resultNode.get("errors").get(0).get("title").asText());
clan = clanRepository.findOne(clan.getId());
assertEquals(me.getId(), clan.getLeader().getId());
}
@Test
@SneakyThrows
public void transferLeadershipAsNonLeader() {
String accessToken = createUserAndGetAccessToken("Leader", "foo");
Player bob = createPlayer("Bob");
Player charlie = createPlayer("Charlie");
Clan clan = new Clan().setLeader(bob).setTag("123").setName("abcClanName");
ClanMembership myMembership = new ClanMembership().setPlayer(me).setClan(clan);
ClanMembership bobsMembership = new ClanMembership().setPlayer(bob).setClan(clan);
ClanMembership charlieMembership = new ClanMembership().setPlayer(charlie).setClan(clan);
clan.setMemberships(Arrays.asList(myMembership, bobsMembership, charlieMembership));
clanRepository.save(clan);
String dataString = generateTransferLeadershipContent(clan.getId(), charlie.getId());
clan = clanRepository.findOne(clan.getId());
assertEquals(bob.getId(), clan.getLeader().getId());
ResultActions action = this.mvc.perform(patch("/data/clan/" + clan.getId())
.content(dataString)
.header("Authorization", accessToken));
action.andExpect(content().string("{\"errors\":[\"ForbiddenAccessException\"]}"))
.andExpect(status().is(403));
clan = clanRepository.findOne(clan.getId());
assertEquals(bob.getId(), clan.getLeader().getId());
}
}
|
package com.hpcloud.mon.domain.model;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import org.testng.annotations.Test;
import com.hpcloud.mon.common.model.alarm.AlarmExpression;
import com.hpcloud.mon.common.model.alarm.AlarmState;
/**
* @author Jonathan Halterman
*/
@Test
public class AlarmTest {
public void shouldBeUndeterminedIfAnySubAlarmIsUndetermined() {
AlarmExpression expr = new AlarmExpression(
"avg(hpcs.compute{instance_id=5,metric_name=cpu,device=1}, 1) > 5 times 3 AND avg(hpcs.compute{flavor_id=3,metric_name=mem}, 2) < 4 times 3");
SubAlarm subAlarm1 = new SubAlarm("123", "1", expr.getSubExpressions().get(0),
AlarmState.UNDETERMINED);
SubAlarm subAlarm2 = new SubAlarm("456", "1", expr.getSubExpressions().get(1), AlarmState.ALARM);
Alarm alarm = new Alarm("1", "joe", "test alarm", expr, Arrays.asList(subAlarm1, subAlarm2),
AlarmState.UNDETERMINED);
assertFalse(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.UNDETERMINED);
}
public void shouldEvaluateExpressionWithBooleanAnd() {
AlarmExpression expr = new AlarmExpression(
"avg(hpcs.compute{instance_id=5,metric_name=cpu,device=1}, 1) > 5 times 3 AND avg(hpcs.compute{flavor_id=3,metric_name=mem}, 2) < 4 times 3");
SubAlarm subAlarm1 = new SubAlarm("123", "1", expr.getSubExpressions().get(0));
SubAlarm subAlarm2 = new SubAlarm("456", "1", expr.getSubExpressions().get(1));
Alarm alarm = new Alarm("1", "joe", "test alarm", expr, Arrays.asList(subAlarm1, subAlarm2),
AlarmState.UNDETERMINED);
assertFalse(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.UNDETERMINED);
subAlarm1.setState(AlarmState.OK);
assertFalse(alarm.evaluate());
// UNDETERMINED -> OK
subAlarm2.setState(AlarmState.OK);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.OK);
subAlarm2.setState(AlarmState.ALARM);
assertFalse(alarm.evaluate());
// OK -> ALARM
subAlarm1.setState(AlarmState.ALARM);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.ALARM);
// ALARM -> UNDETERMINED
subAlarm1.setState(AlarmState.UNDETERMINED);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.UNDETERMINED);
}
public void shouldEvaluateExpressionWithBooleanOr() {
AlarmExpression expr = new AlarmExpression(
"avg(hpcs.compute{instance_id=5,metric_name=cpu,device=1}, 1) > 5 times 3 OR avg(hpcs.compute{flavor_id=3,metric_name=mem}, 2) < 4 times 3");
SubAlarm subAlarm1 = new SubAlarm("123", "1", expr.getSubExpressions().get(0));
SubAlarm subAlarm2 = new SubAlarm("456", "1", expr.getSubExpressions().get(1));
Alarm alarm = new Alarm("1", "joe", "test alarm", expr, Arrays.asList(subAlarm1, subAlarm2),
AlarmState.UNDETERMINED);
assertFalse(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.UNDETERMINED);
subAlarm1.setState(AlarmState.ALARM);
assertFalse(alarm.evaluate());
// UNDETERMINED -> ALARM
subAlarm2.setState(AlarmState.OK);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.ALARM);
// ALARM -> OK
subAlarm1.setState(AlarmState.OK);
subAlarm2.setState(AlarmState.OK);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.OK);
// OK -> ALARM
subAlarm2.setState(AlarmState.ALARM);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.ALARM);
// ALARM -> ALARM
assertFalse(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.ALARM);
// ALARM -> UNDETERMINED
subAlarm2.setState(AlarmState.UNDETERMINED);
assertTrue(alarm.evaluate());
assertEquals(alarm.getState(), AlarmState.UNDETERMINED);
}
public void shouldBuiltStateChangeReason() {
AlarmExpression expr = new AlarmExpression(
"avg(hpcs.compute{instance_id=5,metric_name=cpu,device=1}, 1) > 5 times 3 OR avg(hpcs.compute{flavor_id=3,metric_name=mem}, 2) < 4 times 3");
SubAlarm subAlarm1 = new SubAlarm("123", "1", expr.getSubExpressions().get(0));
SubAlarm subAlarm2 = new SubAlarm("456", "1", expr.getSubExpressions().get(1));
List<String> expressions = Arrays.asList(subAlarm1.getExpression().toString(),
subAlarm2.getExpression().toString());
assertEquals(
Alarm.buildStateChangeReason(AlarmState.UNDETERMINED, expressions),
"No data was present for the sub-alarms: [avg(hpcs.compute{device=1, instance_id=5, metric_name=cpu}, 1) > 5.0 times 3, avg(hpcs.compute{flavor_id=3, metric_name=mem}, 2) < 4.0 times 3]");
assertEquals(
Alarm.buildStateChangeReason(AlarmState.ALARM, expressions),
"Thresholds were exceeded for the sub-alarms: [avg(hpcs.compute{device=1, instance_id=5, metric_name=cpu}, 1) > 5.0 times 3, avg(hpcs.compute{flavor_id=3, metric_name=mem}, 2) < 4.0 times 3]");
}
}
|
package com.vmware.vim25.mo;
import com.utility.LoadVcenterProps;
import com.vmware.vim25.ws.CustomSSLTrustContextCreator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.X509TrustManager;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class ServiceInstanceIntTest {
@Before
public void setUp() throws Exception {
if (null == LoadVcenterProps.url || null == LoadVcenterProps.userName
|| null == LoadVcenterProps.password
|| null == LoadVcenterProps.secondUrl
|| null == LoadVcenterProps.badUrl
|| "".equals(LoadVcenterProps.url.trim())
|| "".equals(LoadVcenterProps.secondUrl.trim())
|| "".equals(LoadVcenterProps.badUrl.trim())
|| "".equals(LoadVcenterProps.userName.trim())
|| "".equals(LoadVcenterProps.password.trim())) {
throw new Exception("Vcenter credentials not loaded");
}
// ensure that the ssl context is re-initialized for every test, so behavior for different trust managers can be verified
CustomSSLTrustContextCreator.setContextAlreadyCreated(false);
}
@Test
public void testCreateServiceInstanceForUsernameAndPasswordAndIgnoreCertsNoTimeouts() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
@Test
public void testCreateServiceInstanceForUsernameAndPasswordAndIgnoreCertsWithTimeouts() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true, 5000, 5000);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
@Test
public void testCreateServiceInstanceForUsernameAndPasswordAndIgnoreCertsAndNamespaceNoTimeouts() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true, ServiceInstance.VIM25_NAMESPACE);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
@Test
public void testCreateServiceInstanceForUsernameAndPasswordAndIgnoreCertsAndNamespaceWithTimeouts() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true, ServiceInstance.VIM25_NAMESPACE, 5000, 5000);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
@Test
public void testCreateServiceInstanceForSessionStringAndIgnoreCertsAndNamespaceNoTimeouts() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
ServiceInstance siFromSessionString = new ServiceInstance(new URL(LoadVcenterProps.url), si.getServerConnection().getSessionStr(), true);
Assert.assertNotNull("Expected non-null service instance when creating with session string", siFromSessionString.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
/**
* Tests case when a trust all manager is passed to the service instance. Verifies no exceptions are thrown and that the connection is accepted.
*/
@Test
public void testCreateServiceInstanceForUsernameAndPasswordWithTrustAllManager() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, new TrustAllManager(), ServiceInstance.VIM25_NAMESPACE, 1000, 1000);
Assert.assertNotNull("Expected a non-null time from service instance", si.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
/**
* Tests case when no trust manager is provided and certs should not be ignored. Verifies an SSLHandshakeException occurs and the connection is not accepted.
* This must be run against a vCenter running on ssl and you should not have its cert in your keystore. This is because the default trust manager performs
* normal certificate verification against the JDK's default CA certs.
*/
@Test
public void testCreateServiceInstanceWithNullTrustManager() {
try {
new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, null, ServiceInstance.VIM25_NAMESPACE, 1000, 1000);
Assert.fail("Expected an SSLHandshakeException to have been thrown when no trust manager is provided and certs are not ignored.");
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.assertTrue("Expected an SSLHandshakeException to have been thrown when no trust manager is provided and certs are not ignored.", e.getCause() instanceof SSLHandshakeException);
}
}
/**
* Tests case when a trust manager is provided but the server is not trusted. Verifies an SSLHandshakeException occurs and the connection is not accepted.
*/
@Test
public void testCreateServiceInstanceWithProvidedTrustManagerServerNotTrusted() {
try {
X509TrustManager testUntrustedServerTrustManager = new UntrustedServerTrustManager();
new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, testUntrustedServerTrustManager, ServiceInstance.VIM25_NAMESPACE, 1000, 1000);
Assert.fail("Expected an SSLHandshakeException to have been thrown when the trust manager provided simulates an untrusted server.");
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
e.printStackTrace();
Assert.assertTrue("Expected an SSLHandshakeException to have been thrown when the trust manager provided simulates an untrusted server.", e.getCause() instanceof SSLHandshakeException);
}
}
/**
* Tests case when a trust all manager is passed to the service instance. Then the same trust manager is passed to a new service instance for a session string.
* Verifies no exceptions are thrown and that the connection is accepted for both service instances.
*/
@Test
public void testCreateServiceInstanceForSessionStringWithTrustAllManager() {
try {
TrustAllManager trustAllManager = new TrustAllManager();
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, trustAllManager);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
ServiceInstance siFromSessionString = new ServiceInstance(new URL(LoadVcenterProps.url), si.getServerConnection().getSessionStr(), trustAllManager);
Assert.assertNotNull("Expected non-null service instance when creating with session string", siFromSessionString.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
/**
* Tests case when a trust all manager is passed to the service instance. Then a null trust manager is passed to a new service instance for a session string.
* Verifies an SSLHandshakeException is thrown for the session string service instance.
*/
@Test
public void testCreateServiceInstanceForSessionStringWithNullTrustManager() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, new TrustAllManager(), ServiceInstance.VIM25_NAMESPACE, 1000, 1000);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
X509TrustManager nullTrustManager = null;
new ServiceInstance(new URL(LoadVcenterProps.url), si.getServerConnection().getSessionStr(), nullTrustManager);
Assert.fail("Expected an SSLHandshakeException to have been thrown when no trust manager is provided.");
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.assertTrue("Expected an SSLHandshakeException to have been thrown when no trust manager is provided.", e.getCause() instanceof SSLHandshakeException);
}
}
@Test
public void testServiceInstanceUsingSession() {
try {
ServiceInstance si = new ServiceInstance(new URL(LoadVcenterProps.url),
LoadVcenterProps.userName, LoadVcenterProps.password, true, 5000, 5000);
Assert.assertNotNull("Expected non-null service instance", si.currentTime());
ServiceInstance si2 = new ServiceInstance(new URL(LoadVcenterProps.url),
si.getServerConnection().getSessionStr(), true);
Assert.assertNotNull("Expected non-null service instance", si2.currentTime());
} catch(MalformedURLException e) {
Assert.fail("An error occurred creating a service instance due its url being malformed. " + e.getMessage());
} catch(RemoteException e) {
Assert.fail("An error occurred creating and reading from service instance. " + e.getMessage());
}
}
private static class TrustAllManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
}
private static class UntrustedServerTrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
throw new CertificateException("Intentional CertificateException to simulate an untrusted server.");
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
}
}
|
package com.byte_games.snake2.engine;
import java.util.ArrayList;
import java.util.List;
import com.byte_games.snake2.engine.GraphicsHelper.Location;
import com.byte_games.snake2.engine.GraphicsHelper.Size;
//This class is used for generating and maintaining Adventure objects which are used to track the progress and data for an adventure.
public class Adventure {
//TODO: Add more level types
public static enum LevelType {Size, Movement};
public List<Level> Levels = new ArrayList<Level>();
public final int Difficulty;
private int CurrentLevel = 0;
private int LastLevelLayoutIndex = -1; //Used in wall generation to prevent repeats
private int DeathCount = 0;
//Create new adventure object
public Adventure(int length, int Difficulty) {
this.Difficulty = Difficulty; //0 to 1
for (int count = 1; count <= length; count++) {
LevelType myType = null;
int Goal = 0;
//Set a random type
myType = LevelType.values()[(int)(Math.random() * LevelType.values().length)];
//Turn off layout check if this level does not have the same type as the last level
if (count == 1) {
LastLevelLayoutIndex = -1;
} else if (Levels.get(count - 2).Type != myType) {
//It's not a repeat
LastLevelLayoutIndex = -1;
}
//Configure goal
//TODO: Balance difficulty and goals
if (myType == LevelType.Size) {
Goal = 5 + (Difficulty * 2);
} else if (myType == LevelType.Movement) {
Goal = 1;
}
Levels.add(new Level(myType, Goal, Difficulty));
}
}
public int getCurrentLevelNumber() {
return CurrentLevel + 1;
}
public Level getCurrentLevel() {
return Levels.get(CurrentLevel);
}
public int getDeathCount() {
return DeathCount;
}
public void advanceDeathCount() {
DeathCount++;
}
//Returns false if adventure is completed
public boolean advanceLevel() {
CurrentLevel++;
if (CurrentLevel == Levels.size()) {
CurrentLevel = Levels.size() - 1;
return false;
}
return true;
}
//TODO: Saving? Maybe?
//This class creates objects that represent one level of the adventure and contain the data needed to build that level.
public class Level {
private LevelType Type;
private int Goal;
private Location GoalPoint = null;
public List<Location> Walls = new ArrayList<Location>();
Level(LevelType Type, int Goal, int Difficulty) {
this.Type = Type;
this.Goal = Goal;
//Init level based on type
if (Type == LevelType.Size) {
ConfigSizeLevel(Difficulty);
} else if (Type == LevelType.Movement) {
ConfigMovementLevel(Difficulty);
}
//For debugging:
/*Type = LevelType.Movement;
Goal = 1;
Walls.clear();
<wall code> */
}
public int getGoal() {
return Goal;
}
public LevelType getType() {
return Type;
}
public Location getGoalPoint() {
return GoalPoint;
}
private void ConfigSizeLevel(int Difficulty) {
final int Layouts = 9; //Total num of layouts
int Layout = 1 + (int)(Math.random() * ((Layouts - 1) + 1));
//Check for repeated wall layouts
boolean Good = false;
while (!Good) {
if (Layout == LastLevelLayoutIndex) {
Layout = 1 + (int)(Math.random() * ((Layouts - 1) + 1));
} else {
Good = true;
}
}
LastLevelLayoutIndex = Layout;
//Generate walls
if (Difficulty == 0) {
if (Layout == 1) {
// O O
// O O
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(48, 10), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(48, 27), new Size(3, 4));
} else if (Layout == 2) {
GraphicsHelper.AddRect(Walls, new Location(29, 10), new Size(3, 21));
} else if (Layout == 3) {
GraphicsHelper.AddRect(Walls, new Location(10, 19), new Size(41, 3));
} else if (Layout == 4) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(48, 10), new Size(3, 21));
} else if (Layout == 5) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 27), new Size(7, 4));
} else if (Layout == 6) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(10, 28), new Size(41, 3));
} else if (Layout == 7) {
GraphicsHelper.AddRect(Walls, new Location(25, 15), new Size(11, 11));
} else if (Layout == 8) {
GraphicsHelper.AddRect(Walls, new Location(10, 13), new Size(8, 15));
GraphicsHelper.AddRect(Walls, new Location(43, 13), new Size(8, 15));
} else if (Layout == 9) {
GraphicsHelper.AddRect(Walls, new Location(10, 19), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(29, 10), new Size(3, 21));
}
} else if (Difficulty == 1) {
if (Layout == 1) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 27), new Size(7, 4));
} else if (Layout == 2) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(10, 28), new Size(41, 3));
} else if (Layout == 3) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(48, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(13, 19), new Size(35, 3));
} else if (Layout == 4) {
// O O
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(10, 28), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(15, 19), new Size(3, 3));
GraphicsHelper.AddRect(Walls, new Location(43, 19), new Size(3, 3));
} else if (Layout == 5) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 10), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(44, 27), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(29, 10), new Size(3, 21));
} else if (Layout == 6) {
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(29, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(48, 10), new Size(3, 21));
} else if (Layout == 7) {
GraphicsHelper.AddRect(Walls, new Location(10, 15), new Size(11, 11));
GraphicsHelper.AddRect(Walls, new Location(25, 15), new Size(11, 11));
GraphicsHelper.AddRect(Walls, new Location(40, 15), new Size(11, 11));
} else if (Layout == 8) {
GraphicsHelper.AddRect(Walls, new Location(10, 13), new Size(8, 15));
GraphicsHelper.AddRect(Walls, new Location(25, 15), new Size(11, 11));
GraphicsHelper.AddRect(Walls, new Location(43, 13), new Size(8, 15));
} else if (Layout == 9) {
// O | O
// O | O
GraphicsHelper.AddRect(Walls, new Location(10, 19), new Size(41, 3));
GraphicsHelper.AddRect(Walls, new Location(29, 10), new Size(3, 21));
GraphicsHelper.AddRect(Walls, new Location(8, 8), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(50, 8), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(8, 29), new Size(3, 4));
GraphicsHelper.AddRect(Walls, new Location(50, 29), new Size(3, 4));
}
}
}
private void ConfigMovementLevel(int Difficulty) {
final int Layouts = 3; //Total num of layouts
int Layout = 1 + (int)(Math.random() * ((Layouts - 1) + 1));
//Check for repeated wall layouts
boolean Good = false;
while (!Good) {
if (Layout == LastLevelLayoutIndex) {
Layout = 1 + (int)(Math.random() * ((Layouts - 1) + 1));
} else {
Good = true;
}
}
LastLevelLayoutIndex = Layout;
//Generate walls
if (Difficulty == 0) {
if (Layout == 1) {
// | X o |
GoalPoint = new Location(20, 20);
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(42, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 14), new Size(4, 13));
GraphicsHelper.AddRect(Walls, new Location(48, 14), new Size(4, 13));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(29, 4));
GraphicsHelper.AddRect(Walls, new Location(42, 27), new Size(10, 4));
GraphicsHelper.AddRect(Walls, new Location(38, 20), new Size(5, 4));
} else if (Layout == 2) {
GoalPoint = new Location(55, 20);
GraphicsHelper.AddRect(Walls, new Location(15, 6), new Size(4, 35));
GraphicsHelper.AddRect(Walls, new Location(30, 0), new Size(4, 35));
GraphicsHelper.AddRect(Walls, new Location(45, 6), new Size(4, 35));
} else if (Layout == 3) {
GoalPoint = new Location(10, 34);
GraphicsHelper.AddRect(Walls, new Location(0, 11), new Size(25, 4));
GraphicsHelper.AddRect(Walls, new Location(30, 0), new Size(4, 15));
GraphicsHelper.AddRect(Walls, new Location(0, 25), new Size(45, 3));
}
} else if (Difficulty == 1) {
if (Layout == 1) {
GoalPoint = new Location(20, 20);
GraphicsHelper.AddRect(Walls, new Location(10, 10), new Size(42, 4));
GraphicsHelper.AddRect(Walls, new Location(10, 14), new Size(4, 13));
GraphicsHelper.AddRect(Walls, new Location(48, 14), new Size(4, 13));
GraphicsHelper.AddRect(Walls, new Location(10, 27), new Size(31, 4));
GraphicsHelper.AddRect(Walls, new Location(42, 27), new Size(10, 4));
GraphicsHelper.AddRect(Walls, new Location(37, 21), new Size(7, 4));
GraphicsHelper.AddRect(Walls, new Location(30, 15), new Size(4, 12));
} else if (Layout == 2) {
GoalPoint = new Location(55, 20);
GraphicsHelper.AddRect(Walls, new Location(30, 0), new Size(3, 35));
GraphicsHelper.AddRect(Walls, new Location(35, 6), new Size(3, 35));
GraphicsHelper.AddRect(Walls, new Location(40, 0), new Size(3, 35));
GraphicsHelper.AddRect(Walls, new Location(45, 6), new Size(3, 35));
} else if (Layout == 3) {
// X o
GoalPoint = new Location(10, 32);
GraphicsHelper.AddRect(Walls, new Location(0, 11), new Size(20, 4));
GraphicsHelper.AddRect(Walls, new Location(25, 0), new Size(4, 15));
GraphicsHelper.AddRect(Walls, new Location(0, 20), new Size(45, 4));
GraphicsHelper.AddRect(Walls, new Location(45, 5), new Size(4, 19));
GraphicsHelper.AddRect(Walls, new Location(25, 28), new Size(9, 9));
}
}
}
}
}
|
package com.jcabi.w3c;
import com.jcabi.http.mock.MkAnswer;
import com.jcabi.http.mock.MkContainer;
import com.jcabi.http.mock.MkGrizzlyContainer;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test case for {@link DefaultHtmlValidator}.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class DefaultHtmlValidatorTest {
/**
* DefaultHtmlValidator can validate HTML document.
*
* @throws Exception If something goes wrong inside
*/
@Test
public void validatesHtmlDocument() throws Exception {
final MkContainer container = new MkGrizzlyContainer().next(
new MkAnswer.Simple(this.validReturn())
).start();
final Validator validator = new DefaultHtmlValidator(container.home());
final ValidationResponse response = validator.validate("<html/>");
container.stop();
MatcherAssert.assertThat(response.toString(), response.valid());
}
/**
* Test if {@link DefaultHtmlValidator} validades invalid html.
* @throws Exception If something goes wrong inside
*/
@Test
public void validateInvalidHtml() throws Exception {
final MkContainer container = new MkGrizzlyContainer().next(
new MkAnswer.Simple(this.invalidHtmlResponse())
).start();
final Validator validator = new DefaultHtmlValidator(container.home());
final ValidationResponse response = validator
.validate("this is an invalid html");
container.stop();
MatcherAssert.assertThat(
"Validity must be invalid!",
!response.valid()
);
MatcherAssert.assertThat(
"Must has at least one error",
response.errors(),
this.withoutDefects()
);
MatcherAssert.assertThat(
"Must has at least one warning",
response.warnings(),
this.withoutDefects()
);
}
/**
* DefaultHtmlValidator throw IOException when W3C server error occurred.
*
* @throws Exception If something goes wrong inside
* @todo #10:30min DefaultHtmlValidator have to be updated to throw only
* IOException when W3C validation server is unavailable. Any other
* exception type can be confusing for users. Remove @Ignore
* annotation after finishing implementation.
*/
@Ignore
@Test
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public void throwsIOExceptionWhenValidationServerErrorOccurred()
throws Exception {
final Set<Integer> responses = new HashSet<Integer>(
Arrays.asList(
HttpURLConnection.HTTP_INTERNAL_ERROR,
HttpURLConnection.HTTP_NOT_IMPLEMENTED,
HttpURLConnection.HTTP_BAD_GATEWAY,
HttpURLConnection.HTTP_UNAVAILABLE,
HttpURLConnection.HTTP_GATEWAY_TIMEOUT,
HttpURLConnection.HTTP_VERSION
)
);
final Set<Integer> caught = new HashSet<Integer>();
for (final Integer status : responses) {
MkContainer container = null;
try {
container = new MkGrizzlyContainer().next(
new MkAnswer.Simple(status)
).start();
new DefaultHtmlValidator(container.home())
.validate("<html></html>");
} catch (final IOException ex) {
caught.add(status);
} finally {
container.stop();
}
}
final Integer[] data = responses.toArray(new Integer[responses.size()]);
MatcherAssert.assertThat(caught, Matchers.containsInAnyOrder(data));
}
/**
* Build a response with valid result from W3C.
* @return Response from W3C.
*/
private String validReturn() {
return StringUtils
.join(
"<env:Envelope",
" xmlns:env='http:
"<env:Body><m:markupvalidationresponse",
" xmlns:m='http:
"<m:validity>true</m:validity>",
"<m:checkedby>W3C</m:checkedby>",
"<m:doctype>text/html</m:doctype>",
"<m:charset>UTF-8</m:charset>",
"</m:markupvalidationresponse></env:Body></env:Envelope>"
);
}
/**
* Use a file to build the request.
* @return Request inside the file.
* @throws IOException if something goes wrong.
*/
private String invalidHtmlResponse() throws IOException {
final InputStream file = DefaultHtmlValidator.class
.getResourceAsStream("invalid-html-response.xml");
final String xml = IOUtils.toString(file);
IOUtils.closeQuietly(file);
return xml;
}
/**
* Matcher that checks if has no errors.
* @return Matcher
*/
private Matcher<Collection<Defect>> withoutDefects() {
return Matchers.not(Matchers.emptyCollectionOf(Defect.class));
}
}
|
package com.github.javadev.undescriptive.client;
import ch.qos.logback.classic.Level;
import com.github.javadev.undescriptive.protocol.request.SolutionRequest;
import com.github.javadev.undescriptive.protocol.response.GameResponse;
import com.github.javadev.undescriptive.protocol.response.WeatherResponse;
import com.github.javadev.undescriptive.protocol.response.SolutionResponse;
import org.junit.Test;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GameTest {
protected final static AsyncClient client = AsyncClient.createDefault();
@BeforeClass
public static void beforeClass() {
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(Level.INFO);
}
@Test
public void testRequest() throws Exception {
final SolutionRequest request = SolutionRequest.builder()
.scale(5)
.claw(5)
.wing(5)
.fire(5)
.build();
request.getScale();
request.getClaw();
request.getWing();
request.getFire();
}
@Test
public void testGame() throws Exception {
int victoryCount = 0;
for (int gameIndex = 0; gameIndex < 10; gameIndex += 1) {
final GameResponse game = client.getGame().get();
game.getGameResponseItem();
game.getGameResponseItem().getName();
game.getGameResponseItem().getAttack();
game.getGameResponseItem().getArmor();
game.getGameResponseItem().getAgility();
game.getGameResponseItem().getEndurance();
System.out.println(game);
WeatherResponse weatherResponse = client.getWeather(game.getGameId()).get();
weatherResponse.getTime();
weatherResponse.getCode();
weatherResponse.getMessage();
System.out.println(weatherResponse);
final SolutionRequest request = null;
if ("FUNDEFINEDG".equals(weatherResponse.getCode()) || "T E".equals(weatherResponse.getCode())) {
request = SolutionRequest.builder()
.scale(5)
.claw(5)
.wing(5)
.fire(5)
.build();
} else if ("HVA".equals(weatherResponse.getCode())) {
request = SolutionRequest.builder()
.scale(10)
.claw(10)
.wing(0)
.fire(0)
.build();
} else {
request = client.solveGame(game.getGameResponseItem());
}
System.out.println(request);
SolutionResponse response = client.putGame(game.getGameId(), request).get();
response.getStatus();
response.getMessage();
if ("Victory".equals(response.getStatus())) {
victoryCount += 1;
}
System.out.println(response);
}
System.out.println("victoryCount - " + victoryCount);
}
}
|
package com.jiahaodev.ch14_coolweather.db;
import org.litepal.crud.DataSupport;
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
|
package org.pentaho.ui.xul.components;
import org.pentaho.ui.xul.XulComponent;
public interface XulFileUpload extends XulComponent {
public String getAction();
public void setAction(String action);
public void setOnUploadSuccess(String method);
public void setOnUploadFailure(String method);
public String getOnUploadSuccess();
public String getOnUploadFailure();
public String getSeletedFile();
public void setSelectedFile(String name);
public void submit();
}
|
package org.xins.common.collections;
import java.util.ArrayList;
import java.util.Iterator;
import org.xins.common.MandatoryArgumentChecker;
/**
* Utility functions for collections.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.1.0
*/
public final class CollectionUtils extends Object {
// Class fields
// Class functions
public static ArrayList list(Iterator iterator)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("iterator", iterator);
// Create the ArrayList to store the elements in
ArrayList list = new ArrayList();
// Copy all elements from the Iterator to the ArrayList
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
// Constructor
/**
* Private constructor, no instances of this class should ever be
* constructed.
*/
private CollectionUtils() {
// empty
}
// Fields
// Methods
}
|
package com.randomcoder.taglibs.common;
import java.net.URL;
import java.util.*;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
public class RequestHelperTest extends TestCase
{
MockHttpServletRequest request;
@Override
public void setUp() throws Exception
{
request = new MockHttpServletRequest();
}
@Override
public void tearDown() throws Exception
{
request = null;
}
public void testParseParameters() throws Exception
{
String query = "?param1=test1¶m2=test2¶m3=test3¶m3=test3again";
Map<String, List<String>> params = RequestHelper.parseParameters(request, query);
assertNotNull(params);
List<String> param1 = params.get("param1");
assertNotNull(param1);
assertEquals(1, param1.size());
assertEquals("test1", param1.get(0));
List<String> param2 = params.get("param2");
assertNotNull(param2);
assertEquals(1, param2.size());
assertEquals("test2", param2.get(0));
List<String> param3 = params.get("param3");
assertNotNull(param3);
assertEquals(2, param3.size());
assertEquals("test3", param3.get(0));
assertEquals("test3again", param3.get(1));
}
public void testParseParametersNullQuery() throws Exception
{
Map<String, List<String>> params = RequestHelper.parseParameters(request, null);
assertNotNull(params);
assertEquals(0, params.keySet().size());
}
public void testAppendParameters() throws Exception
{
URL url = new URL("http:
Map<String, String> additionalParams = new HashMap<String, String>();
additionalParams.put("param3", "test3");
URL result = RequestHelper.appendParameters(request, url, additionalParams);
String ext = result.toExternalForm();
assertTrue(ext.contains("param3=test3"));
}
public void testAppendParametersDuplicate() throws Exception
{
URL url = new URL("http:
Map<String, String> additionalParams = new HashMap<String, String>();
additionalParams.put("param2", "test2updated");
URL result = RequestHelper.appendParameters(request, url, additionalParams);
String ext = result.toExternalForm();
assertFalse(ext.contains("param2=testorig"));
assertTrue(ext.contains("param2=test2updated"));
}
public void testSetParameters() throws Exception
{
Map<String, List<String>> params = new HashMap<String, List<String>>();
List<String> param1 = new ArrayList<String>();
param1.add("new1");
params.put("param1", param1);
List<String> param3 = new ArrayList<String>();
param3.add("new3");
params.put("param3", param3);
URL url = new URL("http:
URL result = RequestHelper.setParameters(request, url, params);
String ext = result.toExternalForm();
assertFalse(ext.contains("param1=test1"));
assertFalse(ext.contains("param2"));
assertTrue(ext.contains("param1=new1"));
assertTrue(ext.contains("param3=new3"));
}
public void testGetCurrentUrl() throws Exception
{
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
request.setQueryString("?param1=test1¶m2=test2");
request.setContextPath("/test");
request.setServletPath("/servlet");
request.setPathInfo("/index.jsp");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("http:
}
public void testGetCurrentUrlHttps() throws Exception
{
request.setScheme("https");
request.setServerName("www.example.com");
request.setServerPort(443);
request.setContextPath("");
request.setServletPath("/index.jsp");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("https:
}
public void testGetCurrentUrlRandomPort() throws Exception
{
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(8080);
request.setContextPath("");
request.setServletPath("/index.jsp");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("http:
}
public void testGetCurrentUrlNegativePort() throws Exception
{
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(-1);
request.setContextPath("");
request.setServletPath("/index.jsp");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("http:
}
public void testGetCurrentUrlMalformedQueryString() throws Exception
{
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
request.setContextPath("");
request.setServletPath("/index.jsp");
request.setQueryString("param1=test1");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("http:
}
public void testGetCurrentUrlForwardURI() throws Exception
{
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
request.setContextPath("");
request.setServletPath("/index.jsp");
request.setAttribute("javax.servlet.forward.request_uri", "/original/index.jsp");
request.setAttribute("javax.servlet.forward.query_string", "?original1=test1");
URL result = RequestHelper.getCurrentUrl(request);
String ext = result.toExternalForm();
assertEquals("http:
request.setAttribute("javax.servlet.forward.query_string", "original1=test1");
result = RequestHelper.getCurrentUrl(request);
ext = result.toExternalForm();
assertEquals("http:
}
}
|
package com.jigdraw.draw.service;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import com.jigdraw.draw.model.Difficulty;
import com.jigdraw.draw.model.ImageEntity;
import com.jigdraw.draw.service.impl.ImageServiceImpl;
/**
* Service to do jigsaw manipulations
*
* @author Jay Paulynice
*/
public class JigsawService {
private static final String TAG = "JigsawService";
private ImageService service;
public JigsawService(Context context) {
service = new ImageServiceImpl(context);
}
public boolean createJigsaw(Bitmap original, Difficulty level) {
sliceImage(original, Difficulty.getMatrixByDifficulty(level));
return true;
}
private void sliceImage(Bitmap original, int slices) {
int w = original.getWidth();
int h = original.getHeight();
int x_slices = w / slices;
int y_slices = h / slices;
for (int y = 0; y + y_slices <= h; y += y_slices) {
for (int x = 0; x + x_slices <= w; x += x_slices) {
String name = "tile-" + x + "-" + y + ".png";
String desc = "sub image " + name;
Log.d(TAG, "image name: " + name);
Bitmap sub = Bitmap.createBitmap(original, x, y, x_slices,
y_slices);
ImageEntity entity = new ImageEntity(sub, name, desc);
service.insert(entity);
}
}
}
}
|
package il.ac.bgu.cs.bp.bpjs.analysis;
import il.ac.bgu.cs.bp.bpjs.analysis.bprogramio.BProgramSyncSnapshotIO;
import il.ac.bgu.cs.bp.bpjs.internal.ExecutorServiceMaker;
import il.ac.bgu.cs.bp.bpjs.model.BProgram;
import il.ac.bgu.cs.bp.bpjs.model.SingleResourceBProgram;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
/**
* Basic benchmarks in Snapshot cloner
*
* @author acepace
*/
public class SnapshotBenchmarks {
private static int ITERATIONS = 15;
public static void main(String[] args) throws Exception {
VariableSizedArraysBenchmark.benchmarkVariableSizedArrays();
}
/*
This benchmarks a program of variableSizedArrays
For verification time benchmarks, each test is run ITERATIONS times, with a larger array step every time.
These should be pretty much identical
For snapshot size benchmarks, each test is run once, and we measure the snapshot size for each step.
Snapshot size should grow linearly.
*/
static class VariableSizedArraysBenchmark{
private static String IMPLEMENTATION = "benchmarks/variableSizedArrays.js";
private static String TEST_NAME = "variableSizedArrays.js";
private static int INITIAL_ARRAY_SIZE = 1;
private static int ARRAY_STEP = 5; //Size of each step, how many objects are we adding
private static int NUM_STEPS = 10; // How many steps to take
static void benchmarkVariableSizedArrays() throws Exception {
BenchmarkResult integerResults = measureIntegerSizes();
BenchmarkResult objectResults = measureObjectSize();
outputBenchResults(integerResults);
outputBenchResults(objectResults);
}
private static void outputBenchResults(BenchmarkResult result) throws IOException {
result.outputMemoryStats();
result.outputTimes();
result.outputToCsv(Paths.get("."));
}
private static BenchmarkResult measureIntegerSizes() throws Exception {
System.out.println("Measuring effect of integer size");
return measureProgram(0);
}
private static BenchmarkResult measureObjectSize() throws Exception {
System.out.println("Measuring effect of object size");
return measureProgram(1);
}
private static BenchmarkResult measureProgram(int object_type) throws Exception {
VisitedStateStore store = new BProgramStateVisitedStateStore();
DfsBProgramVerifier verifier = new DfsBProgramVerifier();
verifier.setVisitedNodeStore(store);
String testName = TEST_NAME + ((object_type==1) ? "object" : "integer");
/*
Test for variable num_steps
we want to see if there's a non linear increase in snapshot size
*/
int[][] snapshotSet = new int[ITERATIONS][];
long[][] verificationTimes = new long[ITERATIONS][];
BProgram[] programs = new BProgram[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++) {
System.out.printf("Measuring for array step of %d size\n", ARRAY_STEP + i);
BProgram programToTest = makeBProgram(INITIAL_ARRAY_SIZE, ARRAY_STEP + i, NUM_STEPS, object_type);
programs[i] = programToTest;
//have to clone the object because BPrograms are not reusable
snapshotSet[i] = getStateSizes(makeBProgram(INITIAL_ARRAY_SIZE, ARRAY_STEP + i, NUM_STEPS, object_type));
verificationTimes[i] = getVerificationTime(verifier,INITIAL_ARRAY_SIZE, ARRAY_STEP + i, NUM_STEPS, object_type,ITERATIONS);
}
return new BenchmarkResult(testName,programs,snapshotSet, verificationTimes);
}
private static BProgram makeBProgram(int init_array_size, int array_step, int num_steps, int object_type) {
// prepare b-program
final BProgram bprog = new SingleResourceBProgram(IMPLEMENTATION);
bprog.putInGlobalScope("INITIAL_ARRAY_SIZE", init_array_size);
bprog.putInGlobalScope("ARRAY_STEP", array_step);
bprog.putInGlobalScope("NUM_STEPS", num_steps);
bprog.putInGlobalScope("OBJECT_TYPE", object_type);
String name = String.format("%s_init_%d_stepSize_%d_numSteps_%d_type_%d", bprog.getName(), init_array_size, array_step, num_steps, object_type);
bprog.setName(name);
return bprog;
}
private static int[] getStateSizes(BProgram program) throws Exception {
ExecutorService execSvc = ExecutorServiceMaker.makeWithName("SnapshotStore");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
List<Node> snapshots = new ArrayList<>();
Node initial = Node.getInitialNode(program, execSvc);
snapshots.add(initial);
Node next = initial;
//Iteration 1,starts already at request state A
for (int i = 0; i < NUM_STEPS; i++) {
next = sut.getUnvisitedNextNode(next, execSvc);
snapshots.add(next);
}
BProgramSyncSnapshotIO io = new BProgramSyncSnapshotIO(program);
execSvc.shutdown();
return snapshots.stream().map(node -> {
try {
return io.serialize(node.getSystemState());
} catch (IOException e) {
return new byte[0];
}
}).mapToInt(serializedSnap -> serializedSnap.length).toArray();
}
private static long[] getVerificationTime( DfsBProgramVerifier vfr, int init_array_size, int array_step, int num_steps, int object_type, int iteration_count) {
return LongStream.range(0, iteration_count).map(i -> {
try {
VerificationResult res = vfr.verify(makeBProgram(init_array_size,array_step,num_steps,object_type));
return res.getTimeMillies();
} catch (Exception e) {
return 0;
}
}).toArray();
}
}
/**
* This consoli
*/
static class BenchmarkResult {
final String benchName;
final BProgram[] programs;
final int[][] snapshotSizes;
final long[][] verificationTimes;
final ArrayList<String> verificationHeaders = new ArrayList<>(Collections.singletonList("Iteration count"));
final ArrayList<String> snapshot_headers = new ArrayList<>(Collections.singletonList("Run instance"));
BenchmarkResult(String name, BProgram[] programs, int[][] snapshotSizes, long[][] verificationTimes) {
this.benchName = name;
this.programs = programs;
this.snapshotSizes = snapshotSizes;
this.verificationTimes = verificationTimes;
//assume they're all identical, they better be
IntStream.range(0, this.snapshotSizes[0].length).forEach(i -> snapshot_headers.add("raw " + i));
IntStream.range(0, this.verificationTimes[0].length).forEach(i -> verificationHeaders.add("raw " + i));
}
void outputMemoryStats() {
outputMemoryStats(5);
}
void outputMemoryStats(int num_final_steps) {
for (int i = snapshotSizes[0].length - num_final_steps; i < snapshotSizes[0].length; i++) {
final int currentStep = i;
IntSummaryStatistics stats = Arrays.stream(snapshotSizes).mapToInt(x -> x[currentStep]).summaryStatistics();
int min = stats.getMin();
int max = stats.getMax();
double avg = stats.getAverage();
long distinct = Arrays.stream(snapshotSizes).mapToInt(x -> x[currentStep]).distinct().count();
System.out.printf("At step %d the memory values for the snapshots " +
"\n\tmin %d\n\tmax %d\n\tavg %f\n", i, min, max, avg);
if (distinct != ITERATIONS) {
System.out.print("WARNING: Identical results despite different settings!\n");
}
System.out.println();
}
}
void outputTimes() {
for (int i = 0; i < verificationTimes.length; i++) {
LongSummaryStatistics stats = Arrays.stream(verificationTimes[i]).summaryStatistics();
long min = stats.getMin();
long max = stats.getMax();
double avg = stats.getAverage();
System.out.printf("The verification stats for the program at test iteration %d are " + "\n\tmin %d\n\tmax %d\n\tavg %f\n", i, min, max, avg);
System.out.println();
}
}
void outputToCsv(Path basePath) throws IOException {
outputTimesToCsv(basePath.resolve(benchName + "_times.csv"));
outputSnapToCsv(basePath.resolve(benchName + "_memory.csv"));
}
void outputTimesToCsv(Path filePath) throws IOException {
BufferedWriter out = Files.newBufferedWriter(filePath);
try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
.withHeader(verificationHeaders.toArray(new String[0])))) {
for (int i = 0; i < verificationTimes.length; i++) {
Object[] toPrint = new Object[verificationTimes[i].length+1];
toPrint[0] = i;
for (int j = 0; j < verificationTimes[i].length; j++) {
toPrint[j+1] = verificationTimes[i][j];
}
printer.printRecord(toPrint);
}
}
}
void outputSnapToCsv(Path filePath) throws IOException {
BufferedWriter out = Files.newBufferedWriter(filePath);
try (CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
.withHeader(snapshot_headers.toArray(new String[0])))) {
for (int i = 0; i < this.snapshotSizes.length; i++) {
Object[] toPrint = new Object[snapshotSizes[i].length+1];
toPrint[0] = i;
for (int j = 0; j < snapshotSizes[i].length; j++) {
toPrint[j+1] = snapshotSizes[i][j];
}
printer.printRecord(toPrint);
}
}
}
}
}
|
package org.postgresql.util;
import org.postgresql.PGEnvironment;
import org.postgresql.PGProperty;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class PGPropertyServiceParser {
private static final Logger LOGGER = Logger.getLogger(PGPropertyServiceParser.class.getName());
private final String serviceName;
private boolean ignoreIfOpenFails = true;
private PGPropertyServiceParser(String serviceName) {
this.serviceName = serviceName;
}
/**
* Read pg_service.conf resource
*
* @param serviceName service name to search for
* @return key value pairs
*/
public static @Nullable Properties getServiceProperties(String serviceName) {
PGPropertyServiceParser pgPropertyServiceParser = new PGPropertyServiceParser(serviceName);
return pgPropertyServiceParser.findServiceDescription();
}
private @Nullable Properties findServiceDescription() {
String resourceName = findPgServiceConfResourceName();
if (resourceName == null) {
return null;
}
Properties result = null;
try (InputStream inputStream = openInputStream(resourceName)) {
result = parseInputStream(inputStream);
} catch (IOException e) {
Level level = ignoreIfOpenFails ? Level.FINE : Level.WARNING;
LOGGER.log(level, "Failed to handle resource [{0}] with error [{1}]", new Object[]{resourceName, e.getMessage()});
}
return result;
}
// open URL or File
private InputStream openInputStream(String resourceName) throws IOException {
try {
URL url = new URL(resourceName);
return url.openStream();
} catch ( MalformedURLException ex ) {
// try file
File file = new File(resourceName);
return new FileInputStream(file);
}
}
// choose resource where to search for service description
private @Nullable String findPgServiceConfResourceName() {
// default file name
String pgServceConfFileDefaultName = PGEnvironment.PGSERVICEFILE.getDefaultValue();
// if there is value, use it - 1st priority
{
String propertyName = PGEnvironment.ORG_POSTGRESQL_PGSERVICEFILE.getName();
String resourceName = System.getProperty(propertyName);
if (resourceName != null && !resourceName.trim().isEmpty()) {
this.ignoreIfOpenFails = false;
LOGGER.log(Level.FINE, "Value [{0}] selected from property [{1}]",
new Object[]{resourceName, propertyName});
return resourceName;
}
}
// if there is value, use it - 2nd priority
{
String envVariableName = PGEnvironment.PGSERVICEFILE.getName();
String resourceName = System.getenv().get(envVariableName);
if (resourceName != null && !resourceName.trim().isEmpty()) {
this.ignoreIfOpenFails = false;
LOGGER.log(Level.FINE, "Value [{0}] selected from environment variable [{1}]",
new Object[]{resourceName, envVariableName});
return resourceName;
}
}
// if file in user home is readable, use it, otherwise continue - 3rd priority
{
String resourceName = OSUtil.getUserConfigRootDirectory();
if (OSUtil.isWindows()) {
resourceName += "postgresql" + File.separator;
}
resourceName += ".";
resourceName += pgServceConfFileDefaultName;
if (new File(resourceName).canRead()) {
LOGGER.log(Level.FINE, "Value [{0}] selected because file exist in user home directory", new Object[]{resourceName});
return resourceName;
}
}
// if there is value, use it - 4th priority
{
String envVariableName = PGEnvironment.PGSYSCONFDIR.getName();
String pgSysconfDir = System.getenv().get(envVariableName);
if (pgSysconfDir != null && !pgSysconfDir.trim().isEmpty()) {
String resourceName = pgSysconfDir + File.separator + pgServceConfFileDefaultName;
LOGGER.log(Level.FINE, "Value [{0}] selected using environment variable [{1}]", new Object[]{resourceName, envVariableName});
return resourceName;
}
}
// otherwise null
LOGGER.log(Level.FINE, "Value for resource [{0}] not found", pgServceConfFileDefaultName);
return null;
}
/*
# Requirements for stream handling (have to match with libpq behaviour)
#
# space around line is removed
# Line: " host=my-host "
# equal to : "host=my-host"
# keys are case sensitive
# Line: "host=my-host"
# not equal to : "HOST=my-host"
# keys are limited with values described in enum PGEnvironment field name
# key is invalid: "my-host=my-host"
# unexpected keys produce error
# Example: "my-host=my-host"
# Example: "HOST=my-host"
# space before equal sign becomes part of key
# Line: "host =my-host"
# key equals: "host "
# space after equal sign becomes part of value
# Line: "host= my-host"
# key equals: " my-host"
# in case of duplicate section - first entry counts
# Line: "[service-one]"
# Line: "host=host-one"
# Line: "[service-two]"
# Line: "host=host-two"
# --> section-one is selected
# in case of duplicate key - first entry counts
# Line: "[service-one]"
# Line: "host=host-one"
# Line: "host=host-two"
# --> host-one is selected
# service name is case sensitive
# Line: "[service-one]"
# Line: "[service-ONE]"
# --> these are unique service names
# whatever is between brackets is considered as service name (including space)
# Line: "[ service-ONE]"
# Line: "[service-ONE ]"
# Line: "[service ONE]"
# --> these are unique service names
*/
private @Nullable Properties parseInputStream(InputStream inputStream) throws IOException {
// build set of allowed keys
Set<String> allowedServiceKeys = Arrays.stream(PGProperty.values())
.map(PGProperty::getName)
.map(PGPropertyUtil::translatePGPropertyToPGService)
.collect(Collectors.toSet());
Properties result = new Properties();
boolean isFound = false;
try (
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(reader)) {
String originalLine;
String line;
int lineNumber = 0;
while ((originalLine = br.readLine()) != null) {
lineNumber++;
// remove spaces around it
line = originalLine.trim();
// skip if empty line or starts with comment sign
if (line.isEmpty() || line.startsWith("
continue;
}
// find first equal sign
int indexOfEqualSign = line.indexOf("=");
// is it section start?
if (line.startsWith("[") && line.endsWith("]")) {
// stop processing if section with correct name was found already
if (isFound) {
break;
}
// get name of section
String sectionName = line.substring(1, line.length() - 1);
// if match then mark it as section is found
if (serviceName.equals(sectionName)) {
isFound = true;
}
} else if (!isFound) {
// skip further processing until section is found
continue;
} else if (indexOfEqualSign > 1) {
// get key and value
String key = line.substring(0, indexOfEqualSign);
String value = line.substring(indexOfEqualSign + 1);
// check key against set of allowed keys
if (!allowedServiceKeys.contains(key)) {
// log list of allowed keys
String allowedValuesCommaSeparated =
allowedServiceKeys.stream().sorted().collect(Collectors.joining(","));
LOGGER.log(Level.SEVERE, "Got invalid key: line number [{0}], value [{1}], allowed "
+ "values [{2}]",
new Object[]{lineNumber, originalLine, allowedValuesCommaSeparated});
// stop processing because of invalid key
return null;
}
// ignore line if value is missing
if (!value.isEmpty()) {
// ignore line having duplicate key, otherwise store key-value pair
result.putIfAbsent(PGPropertyUtil.translatePGServiceToPGProperty(key), value);
}
} else {
// if not equal sign then stop processing because of invalid syntax
LOGGER.log(Level.WARNING, "Not valid line: line number [{0}], value [{1}]",
new Object[]{lineNumber, originalLine});
return null;
}
}
}
// null means failure - service is not found
return isFound ? result : null;
}
}
|
package jenkins.plugins.git;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.FilePath;
import hudson.model.*;
import hudson.model.labels.LabelAtom;
import hudson.plugins.git.GitTool;
import hudson.slaves.DumbSlave;
import hudson.tools.*;
import hudson.util.StreamTaskListener;
import jenkins.model.Jenkins;
import jenkins.plugins.git.traits.BranchDiscoveryTrait;
import jenkins.scm.api.trait.SCMSourceTrait;
import org.jenkinsci.plugins.gitclient.JGitApacheTool;
import org.jenkinsci.plugins.gitclient.JGitTool;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.io.FileMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
/**
* The test aims to functionally validate "estimation of size" and "git implementation recommendation" from a
* cached directory and from plugin extensions.
*/
public class GitToolChooserTest {
@Rule
public JenkinsRule jenkins = new JenkinsRule();
@Rule
public GitSampleRepoRule sampleRepo = new GitSampleRepoRule();
static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
private CredentialsStore store = null;
@Before
public void enableSystemCredentialsProvider() {
SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) {
if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
store = s;
break;
}
}
assertThat("The system credentials provider is enabled", store, notNullValue());
}
/*
This test checks the GitToolChooser in a scenario where repo size>5M, user's choice is `jgit`.
In the event of having no node-specific installations, GitToolChooser will choose to return the default installation.
*/
@Issue("JENKINS-63519")
@Test
public void testResolveGitTool() throws IOException, InterruptedException {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitTool JTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, JTool);
GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL,true);
assertThat(r.getGitTool(), containsString(isWindows() ? "git.exe" : "git"));
}
/*
This test checks the GitToolChooser in a scenario where repo size>5M, user's choice is `jgit`.
There is no specific agent(node=null). In this case agent = Jenkins.get().
In the event of running the GitToolChooser on the agent, it should correctly predict the git installation for
that specific agent.
*/
@Issue("JENKINS-63519")
@Test
public void testResolveGitToolWithJenkins() throws IOException, InterruptedException {
if (isWindows()) { // Runs on Unix only
/* Do not distract warnings system by using assumeThat to skip tests */
return;
}
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
TestToolInstaller inst = new TestToolInstaller("master", "echo Hello", "updated/git");
GitTool t = new GitTool("myGit", "default/git", Collections.singletonList(
new InstallSourceProperty(Collections.singletonList(inst))));
GitTool tool = new GitTool("my-git", "git", Collections.<ToolProperty<?>>emptyList());
GitTool JTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, JTool, t);
GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, null, TaskListener.NULL,true);
assertThat(r.getGitTool(), containsString("updated/git"));
}
/*
This test checks the GitToolChooser in a scenario where repo size>5M, user's choice is `jgit`.
There is an agent labeled -> `agent-windows`
In the event of running the GitToolChooser on the agent, it should correctly predict the git installation for
that specific agent.
*/
@Issue("JENKINS-63519")
@Test
public void testResolutionGitToolOnAgent() throws Exception {
if (isWindows()) { // Runs on Unix only
/* Do not distract warnings system by using assumeThat to skip tests */
return;
}
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
LabelAtom label = new LabelAtom("agent-windows");
DumbSlave agent = jenkins.createOnlineSlave(label);
agent.setMode(Node.Mode.NORMAL);
agent.setLabelString("agent-windows");
TestToolInstaller inst = new TestToolInstaller("master", "echo Hello", "myGit/git");
GitTool toolOnMaster = new GitTool("myGit", "default/git", Collections.singletonList(
new InstallSourceProperty(Collections.singletonList(inst))));
TestToolInstaller instonAgent = new TestToolInstaller("agent-windows", "echo Hello", "my-git/git");
GitTool toolOnAgent = new GitTool("my-git", "git", Collections.singletonList(new InstallSourceProperty(Collections.singletonList(instonAgent))));
GitTool JTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(toolOnMaster, toolOnAgent, JTool);
agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnMaster.getName(), toolOnMaster.getHome())));
agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), toolOnAgent.getName(), toolOnAgent.getHome())));
agent.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class), JTool.getName(), null)));
GitToolChooser r = new GitToolChooser(remote, context, credentialsId, JTool, agent, TaskListener.NULL,true);
assertThat(r.getGitTool(), containsString("my-git/git"));
}
/*
In the event of having no cache but extension APIs in the ExtensionList, the estimator should recommend a tool
instead of recommending no git implementation.
*/
@Test
public void testSizeEstimationWithNoGitCache() throws Exception {
sampleRepo.init();
GitSCMSource instance = new GitSCMSource("https://github.com/rishabhBudhouliya/git-plugin.git");
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
//Since no installation is provided, the gitExe will be git
GitTool rTool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser repoSizeEstimator = new GitToolChooser(instance.getRemote(), list.get(0), "github", rTool, null, TaskListener.NULL, true);
String tool = repoSizeEstimator.getGitTool();
// The class get a size < 5M from APIs and wants to recommend `jgit` but will return NONE instead
// as `jgit` is not enabled by the user
assertThat(tool, is("NONE"));
// If size were reported as 0, should return NONE
assertThat(repoSizeEstimator.determineSwitchOnSize(0L, rTool), is("NONE"));
}
/*
In the case of having a cached .git repository, the estimator class should estimate the size of the local checked
out repository and ultimately provide a suggestion on the base of decided heuristic.
*/
@Test
public void testSizeEstimationWithGitCache() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// With JGit, we don't ask the name and home of the tool
GitTool tool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
// Add a JGit tool to the Jenkins instance to let the estimator find and recommend "jgit"
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool);
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
GitToolChooser repoSizeEstimator = new GitToolChooser(source.getRemote(), list.get(0), "github", tool, null,TaskListener.NULL,true);
/*
Since the size of repository is 21.785 KiBs, the estimator should suggest "jgit" as an implementation
*/
assertThat(repoSizeEstimator.getGitTool(), containsString("jgit"));
}
/*
In the event of having an extension which returns the size of repository as 10000 KiB, the estimator should
recommend "git" as the optimal implementation from the heuristics
*/
@Test
public void testSizeEstimationWithAPIForGit() throws Exception {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed and git is present in the machine
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), containsString("git"));
}
/*
In the event of having an extension which returns the size of repository as 500 KiB, the estimator should
recommend "jgit" as the optimal implementation from the heuristics
*/
@Test
public void testSizeEstimationWithAPIForJGit() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
// With JGit, we don't ask the name and home of the tool
GitTool tool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool);
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), containsString("jgit"));
}
/*
In the event of having an extension which is not applicable to the remote URL provided by the git plugin,
the estimator recommends no git implementation
*/
@Test
public void testSizeEstimationWithBitbucketAPIs() throws Exception {
String remote = "https://bitbucket.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed by user and git is present in the machine
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool,null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is("NONE"));
}
/*
In the event of having an extension which is applicable to the remote URL but throws an exception due to some
reason from the implemented git provider plugin, the estimator handles the exception by silently logging an
"INFO" message and returns no recommendation.
*/
@Test
public void testSizeEstimationWithException() throws Exception {
String remote = "https://bitbucket.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed by user and git is present in the machine
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool,null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is("NONE"));
}
/*
In case of having no user credentials, the git plugin expects the `implementers` of the extension point to handle
and try querying for size of repo, if it throws an exception we catch it and recommend "NONE", i.e, no recommendation.
*/
@Test
public void testSizeEstimationWithNoCredentials() throws Exception {
sampleRepo.init();
buildAProject(sampleRepo, true);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed by user and git is present in the machine
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(sampleRepo.toString(), list.get(0), null, tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is("NONE"));
}
/*
Tests related to git tool resolution
Scenario 1: Size of repo is < 5 MiB, "jgit" should be recommended
*/
@Test
public void testGitToolChooserWithCustomGitTool() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool);
GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true);
//According to size of repo, "jgit" should be recommended but it is not installed by the user
//Hence, in this case GitToolChooser should return a NONE
assertThat(gitToolChooser.getGitTool(), is("NONE"));
}
@Test
public void testGitToolChooserWithBothGitAndJGit() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitTool jgitTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool);
GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true);
assertThat(gitToolChooser.getGitTool(), is("jgit"));
}
/*
According to the size of repo, GitToolChooser will recommend "jgit" even if "jgitapache" is present
*/
@Test
public void testGitToolChooserWithAllTools() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", "/usr/bin/git", Collections.<ToolProperty<?>>emptyList());
GitTool jgitTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
GitTool jGitApacheTool = new JGitApacheTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool, jGitApacheTool);
GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, tool, null, TaskListener.NULL,true);
assertThat(gitToolChooser.getGitTool(), is("jgit"));
}
/*
If the user has chosen `jgitapache` and the system contains "cli git" and "jgitapache", GitToolChooser should
recommend `jgitapache`
*/
@Test
public void testGitToolChooserWithJGitApache() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", "/usr/bin/git", Collections.<ToolProperty<?>>emptyList());
GitTool jGitApacheTool = new JGitApacheTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jGitApacheTool);
GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL,true);
assertThat(gitToolChooser.getGitTool(), is("jgitapache"));
}
/*
According to the size of repo, GitToolChooser will recommend "jgitapache" since that is user's configured choice
*/
@Test
public void testGitToolChooserWithJGitApacheAndGit() throws Exception {
String remote = "https://github.com/rishabhBudhouliya/git-plugin.git";
Item context = Mockito.mock(Item.class);
String credentialsId = null;
// With JGit, we don't ask the name and home of the tool
GitTool jGitApacheTool = new JGitApacheTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(jGitApacheTool);
GitToolChooser gitToolChooser = new GitToolChooser(remote, context, credentialsId, jGitApacheTool, null, TaskListener.NULL,true);
assertThat(gitToolChooser.getGitTool(), is("jgitapache"));
}
/*
Tests related to git tool resolution
Scenario 2: Size of repo is > 5 MiB, "git" should be recommended
*/
@Test
public void testGitToolChooserWithDefaultTool() throws Exception {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed and git is present in the machine
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), containsString("git"));
}
@Test
public void testGitToolChooserWithOnlyJGit() throws Exception {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
// With JGit, we don't ask the name and home of the tool
GitTool jGitTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(jGitTool);
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed and git is present in the machine
String gitExe = jGitTool.getGitExe();
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", jGitTool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is("jgit")); // Since git is not available, we suggest `jgit` which doesn't make any difference
}
@Test
public void testGitToolChooserWithCustomGitTool_2() throws Exception {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool);
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed and git is present in the machine
String gitExe = tool.getGitExe();
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is(isWindows() ? "git.exe" : "git"));
}
@Test
public void testGitToolChooserWithAllTools_2() throws Exception {
String remote = "https://gitlab.com/rishabhBudhouliya/git-plugin.git";
sampleRepo.init();
store.addCredentials(Domain.global(), createCredential(CredentialsScope.GLOBAL, "github"));
store.save();
// With JGit, we don't ask the name and home of the tool
GitTool tool = new GitTool("my-git", isWindows() ? "git.exe" : "git", Collections.<ToolProperty<?>>emptyList());
GitTool jgitTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
GitTool jGitApacheTool = new JGitApacheTool(Collections.<ToolProperty<?>>emptyList());
jenkins.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(tool, jgitTool, jGitApacheTool);
buildAProject(sampleRepo, false);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Assuming no tool is installed and git is present in the machine
String gitExe = tool.getGitExe();
GitToolChooser sizeEstimator = new GitToolChooser(remote, list.get(0), "github", tool, null, TaskListener.NULL,true);
assertThat(sizeEstimator.getGitTool(), is(isWindows() ? "git.exe" : "git"));
}
@Test
@Issue("JENKINS-63541")
public void getCacheDirCreatesNoDirectory() throws Exception {
// Generate a unique repository name and compute expected cache directory
String remoteName = "https://github.com/jenkinsci/git-plugin-" + java.util.UUID.randomUUID().toString() + ".git";
String cacheEntry = AbstractGitSCMSource.getCacheEntry(remoteName);
File expectedCacheDir = new File(new File(jenkins.jenkins.getRootDir(), "caches"), cacheEntry);
// Directory should not exist
assertThat(expectedCacheDir, is(not(anExistingFileOrDirectory())));
// Getting the cache directory will not create an empty directory
File nullCacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry, false);
assertThat(nullCacheDir, is(nullValue()));
assertThat(expectedCacheDir, is(not(anExistingFileOrDirectory())));
// Getting the cache directory will create an empty directory
File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry, true);
assertThat(cacheDir, is(anExistingDirectory()));
assertThat(expectedCacheDir, is(anExistingDirectory()));
}
/* Do not throw null pointer excception if remote configuration is empty. */
@Test
@Issue("JENKINS-63572")
public void testSizeEstimationWithNoRemoteConfig() throws Exception {
sampleRepo.init();
failAProject(sampleRepo);
List<TopLevelItem> list = jenkins.jenkins.getItems();
// Use JGit as the git tool for this NPE check
GitTool jgitTool = new JGitTool(Collections.<ToolProperty<?>>emptyList());
GitToolChooser sizeEstimator = new GitToolChooser(sampleRepo.toString(), list.get(0), null, jgitTool, null, TaskListener.NULL, true);
assertThat(sizeEstimator.getGitTool(), is("NONE"));
}
/*
A test extension implemented to clone the behavior of a plugin extending the capability of providing the size of
repo from a remote URL of "Github".
*/
@TestExtension
public static class TestExtensionGithub extends GitToolChooser.RepositorySizeAPI {
@Override
public boolean isApplicableTo(String remote, Item context, String credentialsId) {
return remote.contains("github");
}
@Override
public Long getSizeOfRepository(String remote, Item context, String credentialsId) {
return (long) 500;
}
}
/*
A test extension implemented to clone the behavior of a plugin extending the capability of providing the size of
repo from a remote URL of "GitLab".
*/
@TestExtension
public static class TestExtensionGitlab extends GitToolChooser.RepositorySizeAPI {
@Override
public boolean isApplicableTo(String remote, Item context, String credentialsId) {
return remote.contains("gitlab");
}
@Override
public Long getSizeOfRepository(String remote, Item context, String credentialsId) {
return (long) 10000;
}
}
/*
A test extension implemented to clone the behavior of a plugin extending the capability of providing the size of
repo from a remote URL of "BitBucket".
*/
@TestExtension
public static class TestExtensionBit extends GitToolChooser.RepositorySizeAPI {
@Override
public boolean isApplicableTo(String remote, Item context, String credentialsId) {
return remote.contains("bit");
}
@Override
public Long getSizeOfRepository(String remote, Item context, String credentialsId) throws IOException {
throw new IOException();
}
}
private static class TestToolInstaller extends CommandInstaller {
private boolean invoked;
public TestToolInstaller(String label, String command, String toolHome) {
super(label, command, toolHome);
}
public boolean isInvoked() {
return invoked;
}
@Override
public FilePath performInstallation(ToolInstallation toolInstallation, Node node, TaskListener taskListener) throws IOException, InterruptedException {
taskListener.error("Hello, world!");
invoked = true;
return super.performInstallation(toolInstallation, node, taskListener);
}
}
private void buildAProject(GitSampleRepoRule sampleRepo, boolean noCredentials) throws Exception {
WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"node {\n"
+ " checkout(\n"
+ " [$class: 'GitSCM', \n"
+ " userRemoteConfigs: [[credentialsId: 'github', url: $/" + sampleRepo + "/$]]]\n"
+ " )"
+ "}", true));
WorkflowRun b = jenkins.assertBuildStatusSuccess(p.scheduleBuild2(0));
if (!noCredentials) {
jenkins.waitForMessage("using credential github", b);
}
}
/* Attempt to perform a checkout without defining a remote repository. Expected to fail, but should not report NPE */
private void failAProject(GitSampleRepoRule sampleRepo) throws Exception {
WorkflowJob p = jenkins.jenkins.createProject(WorkflowJob.class, "intentionally-failing-job-without-remote-config");
p.setDefinition(new CpsFlowDefinition("node {\n"
+ " checkout(\n"
+ " [$class: 'GitSCM']\n"
+ " )\n"
+ "}", true));
WorkflowRun b = jenkins.assertBuildStatus(hudson.model.Result.FAILURE, p.scheduleBuild2(0));
jenkins.waitForMessage("Couldn't find any revision to build", b);
}
private StandardCredentials createCredential(CredentialsScope scope, String id) {
return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, "username", "password");
}
/** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */
private boolean isWindows() {
return File.pathSeparatorChar==';';
}
}
|
package lt.vilnius.tvarkau.api;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import lt.vilnius.tvarkau.BuildConfig;
import lt.vilnius.tvarkau.network.TokenAuthenticator;
import lt.vilnius.tvarkau.network.TokenInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class LegacyApiModule {
public static final String API_BASE_URL = "http:
@Provides
@Singleton
public OkHttpClient provideOkHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder
.addNetworkInterceptor(interceptor)
.addNetworkInterceptor(new StethoInterceptor());
}
return builder
.authenticator(new TokenAuthenticator())
.addInterceptor(new TokenInterceptor())
.connectTimeout(7, TimeUnit.SECONDS)
.addNetworkInterceptor(chain -> {
Request.Builder requestBuilder = chain.request().newBuilder();
requestBuilder.header("Content-Type", "application/json");
return chain.proceed(requestBuilder.build());
})
.build();
}
@Provides
@Singleton
public Retrofit provideRetrofit(OkHttpClient okHttpClient) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer())
.serializeNulls()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
return new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
@Provides
@Singleton
public LegacyApiService provideProblemService(Retrofit retrofit) {
return retrofit.create(LegacyApiService.class);
}
public static class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDateTime.parse(json.getAsString(), formatter);
}
@Override
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.format(formatter));
}
}
}
|
package org.apache.commons.lang.exception;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a>
* @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
* @author <a href="mailto:knielsen@apache.org">Kasper Nielsen</a>
* @author <a href="mailto:steven@caswell.name">Steven Caswell</a>
* @version $Id: NestableDelegate.java,v 1.7 2002/08/25 19:02:49 dlr Exp $
*/
public class NestableDelegate
{
/**
* Constructor error message.
*/
private static final String MUST_BE_THROWABLE =
"The Nestable implementation passed to the NestableDelegate(Nestable) "
+ "constructor must extend java.lang.Throwable";
/**
* Holds the reference to the exception or error that caused this
* exception to be thrown.
*/
private Throwable cause = null;
/**
* Constructs a new <code>NestableDelegate</code> instance to manage the
* specified <code>Nestable</code>.
*
* @param cause the Nestable implementation (<i>must</i> extend
* {@link java.lang.Throwable})
*/
NestableDelegate(Nestable cause) // package
{
if (cause instanceof Throwable)
{
this.cause = (Throwable) cause;
}
else
{
throw new IllegalArgumentException(MUST_BE_THROWABLE);
}
}
/**
* Returns the error message of the <code>Throwable</code> in the chain
* of <code>Throwable</code>s at the specified index, numbererd from 0.
*
* @param index the index of the <code>Throwable</code> in the chain of
* <code>Throwable</code>s
* @return the error message, or null if the <code>Throwable</code> at the
* specified index in the chain does not contain a message
* @throws IndexOutOfBoundsException if the <code>index</code> argument is
* negative or not less than the count of <code>Throwable</code>s in the
* chain
*/
String getMessage(int index)
{
Throwable t = this.getThrowable(index);
if(Nestable.class.isInstance(t))
{
return ((Nestable) t).getMessage(0);
}
else
{
return t.getMessage();
}
}
/**
* Returns the full message contained by the <code>Nestable</code>
* and any nested <code>Throwable</code>s.
*
* @param baseMsg the base message to use when creating the full
* message. Should be generally be called via
* <code>nestableHelper.getMessage(super.getMessage())</code>,
* where <code>super</code> is an instance of {@link
* java.lang.Throwable}.
* @return The concatenated message for this and all nested
* <code>Throwable</code>s
*/
String getMessage(String baseMsg) // package
{
StringBuffer msg = new StringBuffer();
if (baseMsg != null)
{
msg.append(baseMsg);
}
Throwable nestedCause = ExceptionUtils.getCause(this.cause);
if (nestedCause != null)
{
String causeMsg = nestedCause.getMessage();
if (causeMsg != null)
{
if (baseMsg != null)
{
msg.append(": ");
}
msg.append(causeMsg);
}
}
return (msg.length() > 0 ? msg.toString() : null);
}
/**
* Returns the error message of this and any nested <code>Throwable</code>s
* in an array of Strings, one element for each message. Any
* <code>Throwable</code> not containing a message is represented in the
* array by a null. This has the effect of cause the length of the returned
* array to be equal to the result of the {@link #getThrowableCount()}
* operation.
*
* @return the error messages
*/
String[] getMessages() // package
{
Throwable[] throwables = this.getThrowables();
String[] msgs = new String[throwables.length];
for(int i = 0; i < throwables.length; i++)
{
msgs[i] = (Nestable.class.isInstance(throwables[i]) ?
((Nestable) throwables[i]).getMessage(0) :
throwables[i].getMessage());
}
return msgs;
}
/**
* Returns the <code>Throwable</code> in the chain of
* <code>Throwable</code>s at the specified index, numbererd from 0.
*
* @param index the index, numbered from 0, of the <code>Throwable</code> in
* the chain of <code>Throwable</code>s
* @return the <code>Throwable</code>
* @throws IndexOutOfBoundsException if the <code>index</code> argument is
* negative or not less than the count of <code>Throwable</code>s in the
* chain
*/
Throwable getThrowable(int index)
{
if(index == 0)
{
return this.cause;
}
Throwable[] throwables = this.getThrowables();
return throwables[index];
}
/**
* Returns the number of <code>Throwable</code>s contained in the
* <code>Nestable</code> contained by this delegate.
*
* @return the throwable count
*/
int getThrowableCount() // package
{
return ExceptionUtils.getThrowableCount(this.cause);
}
/**
* Returns this delegate's <code>Nestable</code> and any nested
* <code>Throwable</code>s in an array of <code>Throwable</code>s, one
* element for each <code>Throwable</code>.
*
* @return the <code>Throwable</code>s
*/
Throwable[] getThrowables() // package
{
return ExceptionUtils.getThrowables(this.cause);
}
/**
* Returns the index, numbered from 0, of the first <code>Throwable</code>
* that matches the specified type in the chain of <code>Throwable</code>s
* held in this delegate's <code>Nestable</code> with an index greater than
* or equal to the specified index, or -1 if the type is not found.
*
* @param type <code>Class</code> to be found
* @param fromIndex the index, numbered from 0, of the starting position in
* the chain to be searched
* @return index of the first occurrence of the type in the chain, or -1 if
* the type is not found
* @throws IndexOutOfBoundsException if the <code>fromIndex</code> argument
* is negative or not less than the count of <code>Throwable</code>s in the
* chain
*/
int indexOfThrowable(Class type, int fromIndex) // package
{
return ExceptionUtils.indexOfThrowable(this.cause, type, fromIndex);
}
/**
* Prints the stack trace of this exception the the standar error
* stream.
*/
public void printStackTrace()
{
printStackTrace(System.err);
}
/**
* Prints the stack trace of this exception to the specified
* stream.
*
* @param out <code>PrintStream</code> to use for output.
* @see #printStackTrace(PrintWriter)
*/
public void printStackTrace(PrintStream out)
{
synchronized (out)
{
PrintWriter pw = new PrintWriter(out, false);
printStackTrace(pw);
// Flush the PrintWriter before it's GC'ed.
pw.flush();
}
}
/**
* Prints the stack trace of this exception to the specified
* writer.
*
* @param out <code>PrintWriter</code> to use for output.
*/
public void printStackTrace(PrintWriter out)
{
synchronized (out)
{
String[] st = getStackFrames(this.cause);
Throwable nestedCause = ExceptionUtils.getCause(this.cause);
if (nestedCause != null)
{
if (nestedCause instanceof Nestable)
{
// Recurse until a non-Nestable is encountered.
((Nestable) nestedCause).printStackTrace(out);
}
else
{
String[] nst = getStackFrames(nestedCause);
for (int i = 0; i < nst.length; i++)
{
out.println(nst[i]);
}
}
out.print("rethrown as ");
}
// Output desired frames from stack trace.
for (int i = 0; i < st.length; i++)
{
out.println(st[i]);
}
}
}
/**
* Captures the stack trace associated with the specified
* <code>Throwable</code> object, decomposing it into a list of
* stack frames.
*
* @param t The <code>Throwable</code>.
* @return An array of strings describing each stack frame.
*/
private String[] getStackFrames(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
// Avoid infinite loop between decompose() and printStackTrace().
if (t instanceof Nestable)
{
((Nestable) t).printPartialStackTrace(pw);
}
else
{
t.printStackTrace(pw);
}
return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
}
}
|
package net.sf.farrago.test;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import java.util.regex.*;
import junit.extensions.*;
import junit.framework.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.core.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.db.*;
import net.sf.farrago.fem.med.*;
import net.sf.farrago.fem.security.*;
import net.sf.farrago.jdbc.*;
import net.sf.farrago.jdbc.engine.*;
import net.sf.farrago.session.*;
import net.sf.farrago.trace.*;
import net.sf.farrago.util.*;
import net.sf.farrago.release.FarragoReleaseProperties;
import org.eigenbase.jmi.JmiObjUtil;
import org.eigenbase.sql.*;
import org.eigenbase.test.*;
import org.eigenbase.util.*;
import org.eigenbase.util.property.*;
import sqlline.SqlLine;
/**
* FarragoTestCase is a common base for Farrago JUnit tests. Subclasses must
* implement the suite() method in order to get a database connection correctly
* initialized. See FarragoQueryTest for an example.
*
* <p>For SQL tests, FarragoTestCase writes the output from sqlline to a file
* called <code><<i>testname</i>>.log</code>, and compares that output
* with a reference log file <code><<i>testname</i>>.ref</code>.
*
* <p>It is also possible to have additional logfiles, for tests which generate
* output to files. FarragoTestCase scans the input .sql file for lines of the
* form
* <blockquote><code>##COMPARE <file>.log</code></blockquote>
* and for each such command, it compares file.log with file.ref.
*
* @author John V. Sichi
* @version $Id$
*/
public abstract class FarragoTestCase
extends ResultSetTestCase
{
/**
* Logger to use for test tracing.
*/
protected static final Logger tracer = FarragoTrace.getTestTracer();
/**
* JDBC connection to Farrago database.
*/
protected static Connection connection;
/**
* Repos for test object definitions.
*/
protected static FarragoRepos repos;
/**
* Flag used to allow individual test methods to be called from IntelliJ.
*/
private static boolean individualTest;
/**
* Saved copy of Farrago configuration parameters.
*/
private static SortedMap<String, Object> savedFarragoConfig;
/**
* Saved copy of Fennel configuration parameters.
*/
private static SortedMap<String, Object> savedFennelConfig;
private static Thread shutdownHook;
/**
* Connection counter for distinguishing connections during debug.
*
* @see #newConnection
*/
private static int connCounter = 0;
static {
// If required system properties aren't set yet, attempt to set them
// based on environment variables. This allows tests to work with less
// fuss in IDE's such as Eclipse which make it difficult to set
// properties globally.
StringProperty homeDir = FarragoProperties.instance().homeDir;
StringProperty traceConfigFile =
FarragoProperties.instance().traceConfigFile;
if (homeDir.get() == null) {
String eigenHome = System.getenv("EIGEN_HOME");
if (eigenHome != null) {
homeDir.set(new File(eigenHome, "farrago").getAbsolutePath());
if (traceConfigFile.get() == null) {
traceConfigFile.set(
new File(
new File(
homeDir.get(),
"trace"),
"FarragoTrace.properties").getAbsolutePath());
}
}
}
}
/**
* PreparedStatement for processing queries.
*/
protected PreparedStatement preparedStmt;
/**
* Statement for processing queries.
*/
protected Statement stmt;
/**
* An owner for any heavyweight allocations.
*/
protected FarragoCompoundAllocation allocOwner;
/**
* Creates a new FarragoTestCase object.
*
* @param testName .
*
* @throws Exception .
*/
protected FarragoTestCase(String testName)
throws Exception
{
super(testName);
}
// override DiffTestCase
protected File getTestlogRoot()
throws Exception
{
return getTestlogRootStatic();
}
/**
* Implementation for { @link DiffTestCase#getTestlogRoot } which uses
* 'testlog' directory under Farrago home.
*
* @return the root under which testlogs should be written
*/
public static File getTestlogRootStatic()
{
String homeDir = FarragoProperties.instance().homeDir.get(true);
return new File(homeDir, "testlog");
}
/**
* One-time setup routine.
*
* @throws Exception .
*/
public static void staticSetUp()
throws Exception
{
if (shutdownHook == null) {
shutdownHook = new ShutdownThread();
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
if (connection == null) {
connection = newConnection();
if (connection instanceof FarragoJdbcEngineConnection) {
repos = getSession().getRepos();
saveParameters();
}
} else {
// cycle connections to discard any leftover session state; but do
// it crab-wise so that repos doesn't get shut down in the middle
Connection newConnection = newConnection();
connection.close();
connection = newConnection;
}
runCleanup();
}
protected static void runCleanup()
throws Exception
{
// See CleanupFactory for an example of adding custom cleanup.
Cleanup cleanup = CleanupFactory.getFactory().newCleanup("cleanup");
boolean endSession = false;
try {
cleanup.setUp();
if (connection instanceof FarragoJdbcEngineConnection) {
getSession().getRepos().beginReposSession();
endSession = true;
}
cleanup.execute(); // let overrides see this call!
} finally {
if (endSession) {
getSession().getRepos().endReposSession();
}
// NOTE: bypass staticTearDown
cleanup.tearDownImpl();
}
}
/**
* One-time tear-down routine.
*
* @throws Exception .
*/
public static void staticTearDown()
throws Exception
{
if (!FarragoDbSingleton.isReferenced()) {
// some kind of forced shutdown already happened; pop out
return;
}
if (repos != null) {
restoreParameters();
}
rollbackIfSupported();
}
/**
* @return FarragoSession for this test
*/
protected static FarragoSession getSession()
{
assert (connection != null);
FarragoJdbcEngineConnection farragoConnection =
(FarragoJdbcEngineConnection) connection;
return farragoConnection.getSession();
}
private static void rollbackIfSupported()
throws SQLException
{
if (connection == null) {
return;
}
if (connection.getMetaData().supportsTransactions()) {
connection.rollback();
}
}
private static Connection newConnection()
throws Exception
{
FarragoAbstractJdbcDriver driver = newJdbcEngineDriver();
String uri = getJdbcUri(driver);
Properties props = new Properties();
props.put("user", FarragoCatalogInit.SA_USER_NAME);
props.put("password", "mumble");
Connection newConnection = driver.connect(uri, props);
if (newConnection.getMetaData().supportsTransactions()) {
newConnection.setAutoCommit(false);
}
return newConnection;
}
public static void forceShutdown()
throws Exception
{
repos = null;
rollbackIfSupported();
if (connection != null) {
connection.close();
connection = null;
}
// This method shouldn't be called except by the "last one out". So
// if other sessions are still hanging around, that's bad; fail
// tests so some unlucky person will have to track them down.
// Hint:
/*
grep -n -F "`echo pinReference && echo disconnectSession`" \
FarragoTrace.log | more
*/
if (FarragoDbSingleton.isReferenced()) {
String msg = "Leaked test sessions detected, aborting!";
System.err.println(msg);
tracer.severe(msg);
Runtime.getRuntime().halt(1);
}
}
/**
* Saves system parameters.
*/
protected static void saveParameters()
{
saveParameters(repos);
}
/**
* Restores system parameters to state saved by saveParameters().
*/
protected static void restoreParameters()
{
restoreParameters(repos);
}
protected static void saveParameters(FarragoRepos repos)
{
FarragoReposTxnContext reposTxn = repos.newTxnContext(true);
try {
reposTxn.beginReadTxn();
savedFarragoConfig =
JmiObjUtil.getAttributeValues(repos.getCurrentConfig());
savedFennelConfig =
JmiObjUtil.getAttributeValues(
repos.getCurrentConfig().getFennelConfig());
// NOTE jvs 15-Mar-2007: special case for these parameters
// which doesn't take effect until restart anyway;
// let the change be permanent (test must know what it is doing)
savedFarragoConfig.remove("serverRmiRegistryPort");
savedFarragoConfig.remove("serverSingleListenerPort");
savedFarragoConfig.remove("connectionTimeoutMillis");
savedFennelConfig.remove("resourceDir");
savedFennelConfig.remove("deviceSchedulerType");
} finally {
reposTxn.commit();
}
}
protected static void restoreParameters(FarragoRepos repos)
{
FarragoReposTxnContext reposTxn = repos.newTxnContext(true);
try {
reposTxn.beginWriteTxn();
JmiObjUtil.setAttributeValues(
repos.getCurrentConfig(),
savedFarragoConfig);
JmiObjUtil.setAttributeValues(
repos.getCurrentConfig().getFennelConfig(),
savedFennelConfig);
} finally {
reposTxn.commit();
}
}
// NOTE: Repos open/close is slow and causes sporadic problems when done
// in quick succession, so only do it once for the entire test suite
// instead of the Junit-recommended once per test case.
/**
* Generic implementation of suite() to be called by subclasses.
*
* @param clazz the subclass being wrapped
*
* @return a JUnit test suite which will take care of initialization of
* per-testcase members
*/
public static Test wrappedSuite(Class<? extends TestCase> clazz)
{
TestSuite suite = new TestSuite(clazz);
return wrappedSuite(suite);
}
/**
* Generic implementation of suite() to be called by subclasses.
*
* <p>If the {@link SaffronProperties#testEverything} property is false, and
* the {@link SaffronProperties#testName} property is set, then returns a
* suite containing only the tests whose names match.
*
* @param suite the suite being wrapped
*
* @return a JUnit test suite which will take care of initialization of
* per-testcase members
*/
public static Test wrappedSuite(TestSuite suite)
{
// Filter out tests whose names match "saffron.test.Name".
final SaffronProperties saffronProps = SaffronProperties.instance();
if (!saffronProps.testEverything.get()) {
final String testNamePattern = saffronProps.testName.get();
if (testNamePattern != null) {
Pattern testPattern = Pattern.compile(testNamePattern);
suite = EigenbaseTestCase.copySuite(suite, testPattern);
}
}
TestSetup wrapper =
new TestSetup(suite) {
protected void setUp()
throws Exception
{
staticSetUp();
}
protected void tearDown()
throws Exception
{
staticTearDown();
}
};
return wrapper;
}
// implement TestCase
protected void setUp()
throws Exception
{
allocOwner = new FarragoCompoundAllocation();
if (connection == null) {
assert (!individualTest) : "You forgot to implement suite()";
individualTest = true;
staticSetUp();
}
tracer.info(
"Entering test case "
+ getClass().getName() + "." + getName());
super.setUp();
stmt = connection.createStatement();
if (connection instanceof FarragoJdbcEngineConnection) {
// discard any cached query plans (can't call
// sys_boot.mgmt.flush_code_cache because it may not exist yet,
// plus it's slow)
FarragoObjectCache codeCache =
((FarragoDbSession) getSession()).getDatabase().getCodeCache();
long savedBytesMax = codeCache.getBytesMax();
codeCache.setMaxBytes(0);
codeCache.setMaxBytes(savedBytesMax);
}
resultSet = null;
}
// implement TestCase
protected void tearDown()
throws Exception
{
tearDownImpl();
if (individualTest) {
staticTearDown();
}
}
protected void tearDownImpl()
throws Exception
{
try {
if (resultSet != null) {
resultSet.close();
resultSet = null;
}
if (preparedStmt != null) {
preparedStmt.close();
preparedStmt = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
rollbackIfSupported();
allocOwner.closeAllocation();
allocOwner = null;
} finally {
tracer.info(
"Leaving test case "
+ getClass().getName() + "." + getName());
if (tracer.isLoggable(Level.FINE)) {
Runtime rt = Runtime.getRuntime();
rt.gc();
rt.gc();
long heapSize = rt.totalMemory() - rt.freeMemory();
tracer.fine("JVM heap size = " + heapSize);
}
super.tearDown();
}
}
/**
* Retrieves a new instance of the FarragoJdbcEngineDriver configured for
* this test.
*
* @return an instance of FarragoJdbcEngineDriver (or a subclass)
*
* @throws Exception
*/
protected static FarragoAbstractJdbcDriver newJdbcEngineDriver()
throws Exception
{
String driverName =
FarragoProperties.instance().testJdbcDriverClass.get();
if (driverName == null) {
return new FarragoJdbcEngineDriver();
}
Class<?> clazz = Class.forName(driverName);
return (FarragoAbstractJdbcDriver) clazz.newInstance();
}
protected static String getJdbcUri(FarragoAbstractJdbcDriver driver)
throws Exception
{
final StringBuilder sb = new StringBuilder();
sb.append(driver.getUrlPrefix());
if (driver.acceptsUrlWithHostPort()) {
// append host:port specification for client drivers
// Default to "localhost", but could also get real hostname with
// java.net.InetAddress.getLocalHost().getHostName().
// Supplying RMI port allows client-driver tests to be run against
// systems which use a non-default RMI port.
sb.append("//localhost");
int rmiRegistryPort =
FarragoReleaseProperties.instance().jdbcUrlPortDefault.get();
sb.append(":").append(rmiRegistryPort);
}
// create sessionName with connection counter to help
// distinguish connections during debugging
sb.append(";sessionName=FarragoTestCase:");
sb.append(++connCounter);
return sb.toString();
}
protected void runSqlLineTest(String sqlFile)
throws Exception
{
runSqlLineTest(sqlFile, shouldDiff());
}
protected void runSqlLineTest(
String sqlFile, boolean shouldDiff)
throws Exception
{
tracer.finer("runSqlLineTest: Starting " + sqlFile);
FarragoAbstractJdbcDriver driver = newJdbcEngineDriver();
String uri = getJdbcUri(driver);
assert (sqlFile.endsWith(".sql")) :
"\"" + sqlFile + "\" does not end with .sql";
File sqlFileSansExt =
new File(sqlFile.substring(0, sqlFile.length() - 4));
String driverName = driver.getClass().getName();
String [] args =
new String[] {
"-u", uri, "-d",
driverName, "-n",
FarragoCatalogInit.SA_USER_NAME,
"--force=true", "--silent=true",
"--maxWidth=1024"
};
PrintStream savedOut = System.out;
PrintStream savedErr = System.err;
// get contents of file
String sqlFileContents = fileContents(new File(sqlFile));
// read from the specified file
InputStream inputStream = new FileInputStream(sqlFile);
// to make sure the connection is closed properly, append the
// !quit command
String quitCommand = "\n!quit\n";
ByteArrayInputStream quitStream =
new ByteArrayInputStream(quitCommand.getBytes());
SequenceInputStream sequenceStream =
new SequenceInputStream(inputStream, quitStream);
try {
OutputStream outputStream = openTestLogOutputStream(sqlFileSansExt);
FilterOutputStream filterStream =
new ReplacingOutputStream(
outputStream,
"(0: jdbc(:[^:>]+)+:(//.*:[0123456789]+)?|(\\. )*\\.?)>",
">");
PrintStream printStream = new PrintStream(filterStream);
System.setOut(printStream);
System.setErr(printStream);
// tell SqlLine not to exit (this boolean is active-low)
System.setProperty("sqlline.system.exit", "true");
SqlLine.mainWithInputRedirection(args, sequenceStream);
printStream.close();
if (shouldDiff) {
addDiffMask("\\$" + "Id: .*$");
diffTestLog();
// Execute any '##COMPARE <filename>' commands in the .sql file
int k;
while ((k = sqlFileContents.indexOf("##COMPARE ")) > 0) {
sqlFileContents = sqlFileContents.substring(k);
int n = sqlFileContents.indexOf(TestUtil.NL);
String logFile =
sqlFileContents.substring("##COMPARE ".length(), n);
if (!logFile.endsWith(".log")) {
throw new AssertionError(
"Filename argument to '##COMPARE' must end " +
"in '.log': " + logFile);
}
String refFile =
logFile.substring(
0,
logFile.length() - ".log".length()) + ".ref";
diffFile(new File(logFile), new File(refFile));
}
}
} finally {
System.setOut(savedOut);
System.setErr(savedErr);
inputStream.close();
}
tracer.finer("runSqlLineTest: Completed " + sqlFile);
}
protected boolean shouldDiff()
{
return true;
}
// override DiffTestCase
protected void setRefFileDiffMasks()
{
super.setRefFileDiffMasks();
// physical quantities such as row size may vary according to
// architecture
addDiffMask(".*Row size.*exceeds maximum.*");
}
private static class ShutdownThread
extends Thread
{
public void run()
{
try {
forceShutdown();
} catch (Exception ex) {
// TODO: trace
}
}
}
/**
* CleanupFactory is a factory for Cleanup objects. Test cases overriding
* FarragoTestCase can provide custom test cleanup by overriding
* CleanupFactory. This is normally done only for extension projects that
* have additional repository objects that require special cleanup. Most
* individual test cases can simply use the setUp/tearDown facility built
* into JUnit. The alternate CleanupFactory should override <code>
* newCleanup(String)</code> to return an extension of Cleanup that provides
* custom cleanup. The extension project test case should provide static
* helper methods to wrap the Test objects returned by FarragoTestCase's
* static <code>wrappedSuite</code> methods with code that sets and resets
* the CleanupFactory. In other words:
*
* <pre>
* public abstract class ExtensionTestCase extends FarragoTestCase
* {
* public static Test wrappedExtensionSuite(Class clazz)
* {
* TestSuite suite = new TestSuite(clazz);
* return wrappedExtensionSuite(suite);
* }
*
* public static Test wrappedExtensionSuite(TestSuite suite)
* {
* Test farragoSuite = FarragoTestCase.wrappedSuite(suite);
*
* TestSetup wrapper =
* new TestSetup(farragoSuite) {
* protected void setUp() throws Exception
* {
* CleanupFactory.setFactory(
* new ExtensionCleanupFactory());
* }
*
* protected void tearDown() throws Exception
* {
* CleanupFactory.resetFactory();
* }
* };
* return wrapper;
* }
* }
* </pre>
*/
public static class CleanupFactory
{
private static final CleanupFactory defaultFactory =
new CleanupFactory();
private static CleanupFactory factory = defaultFactory;
public static synchronized void setFactory(CleanupFactory altFactory)
{
factory = altFactory;
}
public static synchronized void resetFactory()
{
factory = defaultFactory;
}
public static synchronized CleanupFactory getFactory()
{
return factory;
}
public Cleanup newCleanup(String name)
throws Exception
{
return new Cleanup(name);
}
}
/**
* Helper for staticSetUp.
*/
public static class Cleanup
extends FarragoTestCase
{
public Cleanup(String name)
throws Exception
{
super(name);
}
protected FarragoRepos getRepos()
{
return repos;
}
protected Statement getStmt()
{
return stmt;
}
public void execute()
throws Exception
{
restoreCleanupParameters();
dropSchemas();
dropDataWrappers();
dropDataServers();
dropAuthIds();
}
public void saveCleanupParameters()
{
if (getRepos() != null) {
saveParameters(getRepos());
}
}
public void restoreCleanupParameters()
{
if (getRepos() != null) {
restoreParameters(getRepos());
}
}
/**
* Decides whether schema should be preserved as a global fixture.
* Extension project test case can override this method to bless
* additional schemas or use attributes other than the name to make the
* determination.
*
* @param schema schema to check
*
* @return true iff schema should be preserved as fixture
*/
protected boolean isBlessedSchema(CwmSchema schema)
{
String name = schema.getName();
return isBlessedSchema(name);
}
protected boolean isBlessedSchema(String name)
{
tracer.finer("checking name: " + name);
return name.equals("SALES")
|| name.equals("SQLJ")
|| name.equals("INFORMATION_SCHEMA")
|| name.startsWith("SYS_");
}
/**
* Decides whether server should be preserved as a global fixture.
* Extension project test case can override this method to bless
* additional servers or use attributes other than the name to make the
* determination.
*
* @param server server to check
*
* @return true iff schema should be preserved as fixture
*/
protected boolean isBlessedServer(FemDataServer server)
{
return isBlessedServer(server.getName());
}
protected boolean isBlessedServer(String name)
{
tracer.finer("checking name: " + name);
return name.equals("HSQLDB_DEMO")
|| name.startsWith("SYS_");
}
/**
* Decides whether wrapper should be preserved as a global fixture.
* Extension project test case can override this method to bless
* additional schemas or use attributes other than the name to make the
* determination.
*
* @param wrapper wrapper to check
*
* @return true iff wrapper should be preserved as fixture
*/
protected boolean isBlessedWrapper(FemDataWrapper wrapper)
{
return isBlessedWrapper(wrapper.getName());
}
protected boolean isBlessedWrapper(String name)
{
tracer.finer("checking name: " + name);
return name.startsWith("SYS_");
}
/**
* Decides whether authId should be preserved as a global fixture.
* Extension project test case can override this method to bless
* additional authIds or use attributes other than the name to make the
* determination.
*
* @param authId authorization ID to check
*
* @return true iff authId should be preserved as fixture
*/
protected boolean isBlessedAuthId(FemAuthId authId)
{
return isBlessedAuthId(authId.getName());
}
protected boolean isBlessedAuthId(String name)
{
tracer.finest("checking name: " + name);
return name.equals(FarragoCatalogInit.SYSTEM_USER_NAME)
|| name.equals(FarragoCatalogInit.PUBLIC_ROLE_NAME)
|| name.equals(FarragoCatalogInit.SA_USER_NAME);
}
protected void dropSchemas() throws Exception
{
List<String> list = new ArrayList<String>();
tracer.fine("Dropping Schemas.");
// NOTE: don't use DatabaseMetaData.getSchemas since it doesn't
// work when Fennel is disabled. Also note that the
// repository is not available when using a Client JDBC driver.
final FarragoRepos repos = getRepos();
if (repos != null) {
for (
CwmModelElement obj
: repos.getSelfAsCatalog().getOwnedElement())
{
if (!(obj instanceof CwmSchema)) {
continue;
}
CwmSchema schema = (CwmSchema) obj;
String schemaName = schema.getName();
if (!isBlessedSchema(schema)) {
list.add(schemaName);
}
}
} else if (connection != null) {
ResultSet schemas = connection.getMetaData().getSchemas();
while(schemas.next()) {
String name = schemas.getString(1);
if (!isBlessedSchema(name))
{
list.add(name);
}
}
}
tracer.finer("Schema name list has " + list.size() + " entries");
for (String name : list) {
String dropStmt = "drop schema "
+ SqlUtil.eigenbaseDialect.quoteIdentifier(name)
+ " cascade";
tracer.finer(dropStmt);
getStmt().execute(dropStmt);
}
}
private void dropDataWrappers()
throws Exception
{
tracer.fine("Dropping DataWrappers.");
List<String> list = new ArrayList<String>();
final FarragoRepos repos = getRepos();
if (repos != null) {
for (
FemDataWrapper wrapper
: repos.allOfClass(FemDataWrapper.class))
{
if (isBlessedWrapper(wrapper)) {
continue;
}
list.add(wrapper.isForeign() ? "foreign" : "local");
list.add(wrapper.getName());
}
} else if (stmt != null) {
if (stmt.execute("select \"name\",\"foreign\" from sys_fem.med.\"DataWrapper\"")) {
ResultSet rset = stmt.getResultSet();
while (rset.next()) {
String name = rset.getString(1);
if (isBlessedWrapper(name)) {
continue;
}
String foreignFlag = rset.getString(2);
list.add(foreignFlag.equals("true") ? "foreign" : "local");
list.add(name);
}
}
}
tracer.finer("Datawrapper name list has " + list.size() + " entries");
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String wrapperType = iter.next();
String name = iter.next();
String sql = "drop " + wrapperType + " data wrapper "
+ SqlUtil.eigenbaseDialect.quoteIdentifier(name)
+ " cascade";
tracer.finer(sql);
getStmt().execute(sql);
}
}
// NOTE jvs 21-May-2006: Dropping data wrappers cascades to server, so
// this isn't strictly necessary. But it's convenient for test authors
// so that they can use the prefab wrapper definitions and still have
// servers dropped.
private void dropDataServers()
throws Exception
{
tracer.fine("Dropping DataServers.");
List<String> list = new ArrayList<String>();
final FarragoRepos repos = getRepos();
if (repos != null) {
for (
FemDataServer server
: repos.allOfClass(FemDataServer.class))
{
if (isBlessedServer(server)) {
continue;
}
list.add(server.getName());
}
} else if (stmt != null) {
if (stmt.execute("select \"name\" from sys_fem.med.\"DataServer\"")) {
ResultSet rset = stmt.getResultSet();
while (rset.next()) {
String name = rset.getString(1);
if (isBlessedServer(name)) {
continue;
}
list.add(name);
}
}
}
tracer.finer("Dataserver name list has " + list.size() + " entries");
for (String name : list) {
String sql = "drop server "
+ SqlUtil.eigenbaseDialect.quoteIdentifier(name)
+ " cascade";
tracer.finer(sql);
getStmt().execute(sql);
}
}
private void dropAuthIds()
throws Exception
{
tracer.fine("Dropping AuthIds.");
List<String> list = new ArrayList<String>();
final FarragoRepos repos = getRepos();
if (repos != null) {
for (FemAuthId authId : repos.allOfType(FemAuthId.class)) {
if (isBlessedAuthId(authId)) {
continue;
}
list.add(
((authId instanceof FemRole) ? "ROLE" : "USER")
+ " "
+ SqlUtil.eigenbaseDialect.quoteIdentifier(
authId.getName()));
}
} else if (stmt != null) {
if (stmt.execute("select \"name\",\"mofClassName\" from sys_fem.\"Security\".\"AuthId\"")) {
ResultSet rset = stmt.getResultSet();
while (rset.next()) {
String name = rset.getString(1);
String className = rset.getString(2);
if (isBlessedAuthId(name)) {
continue;
}
list.add(className + " " + name);
}
}
}
tracer.finer("AuthId name list has " + list.size() + " entries");
for (String name : list) {
String sql = "drop " + name;
tracer.finer(sql);
getStmt().execute(sql);
}
}
}
/**
* Stream which applies regular expression replacement to its contents.
*
* <p>Lame implementation which buffers its input and applies replacement
* only when {@link #close} is called.
*/
private static class ReplacingOutputStream
extends FilterOutputStream
{
private final OutputStream outputStream;
private final String seekPattern;
private final String replace;
public ReplacingOutputStream(
OutputStream outputStream,
String seekPattern,
String replace)
{
super(new ByteArrayOutputStream());
this.outputStream = outputStream;
this.seekPattern = seekPattern;
this.replace = replace;
}
public void close()
throws IOException
{
super.close();
final String s = ((ByteArrayOutputStream) this.out).toString();
final String s2 = s.replaceAll(seekPattern, replace);
outputStream.write(s2.getBytes());
outputStream.close();
}
}
}
// End FarragoTestCase.java
|
package me.lemire.integercompression;
import java.util.Arrays;
import java.util.Random;
import junit.framework.Assert;
import me.lemire.integercompression.synth.ClusteredDataGenerator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Just some basic sanity tests.
*
* @author Daniel Lemire
*/
public class BasicTest
{
/**
* Verify bitpacking.
*/
@SuppressWarnings("static-method")
@Test
public void verifyBitPacking() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt(1 << bit);
}
BitPacking.fastpack(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
assertArrayEquals(uncompressed, data);
}
}
}
/**
* Verify bitpacking without mask.
*/
@SuppressWarnings("static-method")
@Test
public void verifyWithoutMask() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt(1 << bit);
}
BitPacking.fastpackwithoutmask(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
assertArrayEquals(uncompressed, data);
}
}
}
/**
* Verify bitpacking with exception.
*/
@SuppressWarnings("static-method")
@Test
public void verifyWithExceptions() {
final int N = 32;
final int TIMES = 1000;
Random r = new Random();
int[] data = new int[N];
int[] compressed = new int[N];
int[] uncompressed = new int[N];
for (int bit = 0; bit < 31; ++bit) {
for (int t = 0; t < TIMES; ++t) {
for (int k = 0; k < N; ++k) {
data[k] = r.nextInt();
}
BitPacking.fastpack(data, 0, compressed, 0, bit);
BitPacking.fastunpack(compressed, 0, uncompressed, 0, bit);
for (int k = 0; k < N; ++k) {
if ((data[k] & ((1 << bit) - 1)) != uncompressed[k]) {
// TODO: use Assert
System.err.println("ERROR: detected a problem, dump debugging info:");
for (int k2 = 0; k2 < N; ++k2) {
System.err.println((data[k] & ((1 << bit) - 1)) + " " + uncompressed[k]);
}
System.err.println(compressed[0]);
throw new RuntimeException("bug " + bit);
}
}
}
}
}
/**
* check that the codecs can be inverted.
*/
@SuppressWarnings("static-method")
@Test
public void basictest() {
test(5, 10);
test(5, 14);
test(2, 18);
}
/**
* check that there is no spurious output.
*/
@SuppressWarnings("static-method")
@Test
public void spuriousouttest() {
testSpurious(new IntegratedBinaryPacking());
testSpurious(new BinaryPacking());
testSpurious(new NewPFD());
testSpurious(new NewPFDS9());
testSpurious(new NewPFDS16());
testSpurious(new OptPFD());
testSpurious(new OptPFDS9());
testSpurious(new OptPFDS16());
testSpurious(new FastPFOR());
}
/**
* check that an empty array generates an empty array
* after compression.
*/
@SuppressWarnings("static-method")
@Test
public void zeroinzerouttest() {
testZeroInZeroOut(new IntegratedBinaryPacking());
testZeroInZeroOut(new IntegratedVariableByte());
testZeroInZeroOut(new BinaryPacking());
testZeroInZeroOut(new NewPFD());
testZeroInZeroOut(new NewPFDS9());
testZeroInZeroOut(new NewPFDS16());
testZeroInZeroOut(new OptPFD());
testZeroInZeroOut(new OptPFDS9());
testZeroInZeroOut(new OptPFDS16());
testZeroInZeroOut(new FastPFOR());
testZeroInZeroOut(new VariableByte());
testZeroInZeroOut(new Composition(new IntegratedBinaryPacking(), new VariableByte()));
testZeroInZeroOut(new Composition(new BinaryPacking(), new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFD(), new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFDS9(), new VariableByte()));
testZeroInZeroOut(new Composition(new NewPFDS16(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFD(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFDS9(), new VariableByte()));
testZeroInZeroOut(new Composition(new OptPFDS16(), new VariableByte()));
testZeroInZeroOut(new Composition(new FastPFOR(), new VariableByte()));
testZeroInZeroOut(new IntegratedComposition(new IntegratedBinaryPacking(), new IntegratedVariableByte()));
}
private static void testSpurious(IntegerCODEC c) {
int[] x = new int[1024];
int[] y = new int[0];
IntWrapper i0 = new IntWrapper(0);
IntWrapper i1 = new IntWrapper(0);
for (int inlength = 0; inlength < 128; ++inlength) {
c.compress(x, i0, inlength, y, i1);
assertEquals(0, i1.intValue());
}
}
private static void testZeroInZeroOut(IntegerCODEC c) {
int[] x = new int[0];
int[] y = new int[0];
IntWrapper i0 = new IntWrapper(0);
IntWrapper i1 = new IntWrapper(0);
c.compress(x, i0, 0, y, i1);
assertEquals(0, i1.intValue());
int[] out = new int[0];
IntWrapper outpos = new IntWrapper(0);
c.uncompress(y, i1, 0, out, outpos);
assertEquals(0, outpos.intValue());
}
private static void test(int N, int nbr) {
ClusteredDataGenerator cdg = new ClusteredDataGenerator();
for (int sparsity = 1; sparsity < 31 - nbr; sparsity += 4) {
int[][] data = new int[N][];
int Max = (1 << (nbr + sparsity));
for (int k = 0; k < N; ++k) {
data[k] = cdg.generateClustered((1 << nbr), Max);
}
testCodec(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()), data, Max);
testCodec(new JustCopy(), data, Max);
testCodec(new VariableByte(), data, Max);
testCodec(new IntegratedVariableByte(), data, Max);
testCodec(new Composition(new BinaryPacking(), new VariableByte()),
data, Max);
testCodec(new Composition(new NewPFD(), new VariableByte()), data,
Max);
testCodec(new Composition(new NewPFDS9(), new VariableByte()),
data, Max);
testCodec(new Composition(new NewPFDS16(), new VariableByte()),
data, Max);
testCodec(new Composition(new OptPFD(), new VariableByte()), data,
Max);
testCodec(new Composition(new OptPFDS9(), new VariableByte()),
data, Max);
testCodec(new Composition(new OptPFDS16(), new VariableByte()),
data, Max);
testCodec(new Composition(new FastPFOR(), new VariableByte()),
data, Max);
testCodec(new Simple9(), data, Max);
}
}
private static void testCodec(IntegerCODEC c, int[][] data, int Max) {
int N = data.length;
int maxlength = 0;
for (int k = 0; k < N; ++k) {
if (data[k].length > maxlength)
maxlength = data[k].length;
}
int[] buffer = new int[maxlength + 1024];
int[] dataout = new int[4 * maxlength + 1024];
/* 4x + 1024 to account for the possibility of some negative compression */
IntWrapper inpos = new IntWrapper();
IntWrapper outpos = new IntWrapper();
for (int k = 0; k < N; ++k) {
int[] backupdata = Arrays.copyOf(data[k], data[k].length);
inpos.set(1);
outpos.set(0);
if (!(c instanceof IntegratedIntegerCODEC)) {
Delta.delta(backupdata);
}
c.compress(backupdata, inpos, backupdata.length - inpos.get(),
dataout, outpos);
final int thiscompsize = outpos.get() + 1;
inpos.set(0);
outpos.set(1);
buffer[0] = backupdata[0];
c.uncompress(dataout, inpos, thiscompsize - 1, buffer, outpos);
if (!(c instanceof IntegratedIntegerCODEC))
Delta.fastinverseDelta(buffer);
if (outpos.get() != data[k].length)
throw new RuntimeException("we have a bug (diff length) " + c
+ " expected " + data[k].length + " got "
+ outpos.get());
for (int m = 0; m < outpos.get(); ++m)
if (buffer[m] != data[k][m]) {
throw new RuntimeException(
"we have a bug (actual difference), expected "
+ data[k][m] + " found " + buffer[m]
+ " at " + m);
}
}
}
/**
* Test for unsorted array.
*/
@SuppressWarnings("static-method")
@Test
public void testUnsortedExample() {
testUnsorted(new VariableByte());
testUnsorted(new IntegratedVariableByte());
testUnsorted(new Composition(new BinaryPacking(), new VariableByte()));
testUnsorted(new Composition(new NewPFD(), new VariableByte()));
testUnsorted(new Composition(new NewPFDS9(), new VariableByte()));
testUnsorted(new Composition(new NewPFDS16(), new VariableByte()));
testUnsorted(new Composition(new OptPFD(), new VariableByte()));
testUnsorted(new Composition(new OptPFDS9(), new VariableByte()));
testUnsorted(new Composition(new OptPFDS16(), new VariableByte()));
testUnsorted(new Composition(new FastPFOR(), new VariableByte()));
testUnsorted(new IntegratedComposition(new IntegratedBinaryPacking(),
new IntegratedVariableByte()));
testUnsorted(new Composition(new IntegratedBinaryPacking(), new VariableByte()));
}
public void testUnsorted(IntegerCODEC codec)
{
int[] lengths = {133,1333333};
for (int N : lengths ) {
int[] data = new int[N];
// initialize the data (most will be small
for (int k = 0; k < N; k += 1)
data[k] = 3;
// throw some larger values
for (int k = 0; k < N; k += 5)
data[k] = 100;
for (int k = 0; k < N; k += 533)
data[k] = 10000;
data[5] = -311;
// could need more compressing
int[] compressed = new int[(int) Math.ceil(N * 1.01) + 1024];
IntWrapper inputoffset = new IntWrapper(0);
IntWrapper outputoffset = new IntWrapper(0);
codec.compress(data, inputoffset, data.length,
compressed, outputoffset);
// we can repack the data: (optional)
compressed = Arrays.copyOf(compressed,
outputoffset.intValue());
int[] recovered = new int[N];
IntWrapper recoffset = new IntWrapper(0);
codec.uncompress(compressed, new IntWrapper(0),
compressed.length, recovered, recoffset);
Assert.assertTrue(Arrays.equals(data, recovered));
}
}
}
|
package liquibase.util;
import java.util.*;
import java.util.regex.Pattern;
/**
* Various utility methods for working with strings.
*/
public class StringUtils {
private static final Pattern upperCasePattern = Pattern.compile(".*[A-Z].*");
private static final Pattern lowerCasePattern = Pattern.compile(".*[a-z].*");
public static String trimToEmpty(String string) {
if (string == null) {
return "";
}
return string.trim();
}
public static String trimToNull(String string) {
if (string == null) {
return null;
}
String returnString = string.trim();
if (returnString.length() == 0) {
return null;
} else {
return returnString;
}
}
/**
* Removes any comments from multiple line SQL using {@link #stripComments(String)}
* and then extracts each individual statement using {@link #splitSQL(String, String)}.
*
* @param multiLineSQL A String containing all the SQL statements
* @param stripComments If true then comments will be stripped, if false then they will be left in the code
*/
public static String[] processMutliLineSQL(String multiLineSQL, boolean stripComments, boolean splitStatements, String endDelimiter) {
StringClauses parsed = SqlParser.parse(multiLineSQL, true, !stripComments);
List<String> returnArray = new ArrayList<String>();
StringBuilder currentString = new StringBuilder();
String previousPiece = null;
boolean previousDelimiter = false;
for (Object piece : parsed.toArray(true)) {
if (splitStatements && piece instanceof String && isDelimiter((String) piece, previousPiece, endDelimiter)) {
String trimmedString = StringUtils.trimToNull(currentString.toString());
if (trimmedString != null) {
returnArray.add(trimmedString);
}
currentString = new StringBuilder();
previousDelimiter = true;
} else {
if (!previousDelimiter || StringUtils.trimToNull((String) piece) != null) { //don't include whitespace after a delimiter
if (!currentString.equals("") || StringUtils.trimToNull((String) piece) != null) { //don't include whitespace before the statement
currentString.append(piece);
}
}
previousDelimiter = false;
}
previousPiece = (String) piece;
}
String trimmedString = StringUtils.trimToNull(currentString.toString());
if (trimmedString != null) {
returnArray.add(trimmedString);
}
return returnArray.toArray(new String[returnArray.size()]);
}
protected static boolean isDelimiter(String piece, String previousPiece, String endDelimiter) {
if (endDelimiter == null) {
return piece.equals(";") || ((piece.equalsIgnoreCase("go") || piece.equalsIgnoreCase("/")) && (previousPiece == null || previousPiece.endsWith("\n")));
} else {
if (endDelimiter.length() == 1) {
return piece.toLowerCase().equalsIgnoreCase(endDelimiter.toLowerCase());
} else {
return piece.toLowerCase().matches(endDelimiter.toLowerCase()) || (previousPiece+piece).toLowerCase().matches(endDelimiter.toLowerCase());
}
}
}
/**
* Splits a (possible) multi-line SQL statement along ;'s and "go"'s.
*/
public static String[] splitSQL(String multiLineSQL, String endDelimiter) {
return processMutliLineSQL(multiLineSQL, false, true, endDelimiter);
}
* any comments that are between \/**\/ or anything that matches
* SP--SP<text>\n (to support the ANSI standard commenting of --
* at the end of a line).
*
* @return The String without the comments in
*/
public static String stripComments(String multiLineSQL) {
return SqlParser.parse(multiLineSQL, true, false).toString().trim();
}
public static String join(Object[] array, String delimiter, StringUtilsFormatter formatter) {
if (array == null) {
return null;
}
return join(Arrays.asList(array), delimiter, formatter);
}
public static String join(String[] array, String delimiter) {
return join(Arrays.asList(array), delimiter);
}
public static String join(Collection<String> collection, String delimiter) {
return join(collection, delimiter, new ToStringFormatter());
}
public static String join(Collection collection, String delimiter, StringUtilsFormatter formatter) {
if (collection == null) {
return null;
}
if (collection.size() == 0) {
return "";
}
StringBuffer buffer = new StringBuffer();
for (Object val : collection) {
buffer.append(formatter.toString(val)).append(delimiter);
}
String returnString = buffer.toString();
return returnString.substring(0, returnString.length() - delimiter.length());
}
public static String join(Collection collection, String delimiter, StringUtilsFormatter formatter, boolean sorted) {
if (sorted) {
TreeSet<String> sortedSet = new TreeSet<String>();
for (Object obj : collection) {
sortedSet.add(formatter.toString(obj));
}
return join(sortedSet, delimiter);
}
return join(collection, delimiter, formatter);
}
public static String join(Collection<String> collection, String delimiter, boolean sorted) {
if (sorted) {
return join(new TreeSet<String>(collection), delimiter);
} else {
return join(collection, delimiter);
}
}
public static String join(Map map, String delimiter) {
return join(map, delimiter, new ToStringFormatter());
}
public static String join(Map map, String delimiter, StringUtilsFormatter formatter) {
List<String> list = new ArrayList<String>();
for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
list.add(entry.getKey().toString()+"="+formatter.toString(entry.getValue()));
}
return join(list, delimiter);
}
public static List<String> splitAndTrim(String s, String regex) {
if (s == null) {
return null;
}
List<String> returnList = new ArrayList<String>();
for (String string : s.split(regex)) {
returnList.add(string.trim());
}
return returnList;
}
public static String repeat(String string, int times) {
String returnString = "";
for (int i=0; i<times; i++) {
returnString += string;
}
return returnString;
}
public static String join(Integer[] array, String delimiter) {
if (array == null) {
return null;
}
int[] ints = new int[array.length];
for (int i=0; i < ints.length; i++)
{
ints[i] = array[i];
}
return StringUtils.join(ints, delimiter);
}
public static String join(int[] array, String delimiter) {
if (array == null) {
return null;
}
if (array.length == 0) {
return "";
}
StringBuffer buffer = new StringBuffer();
for (int val : array) {
buffer.append(val).append(delimiter);
}
String returnString = buffer.toString();
return returnString.substring(0, returnString.length() - delimiter.length());
}
public static String indent(String string) {
return indent(string, 4);
}
public static String indent(String string, int padding) {
String pad = StringUtils.repeat(" ", padding);
return pad+(string.replaceAll("\n", "\n" + pad));
}
public static String lowerCaseFirst(String string) {
return string.substring(0, 1).toLowerCase()+string.substring(1);
}
public static String upperCaseFirst(String string) {
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
public static boolean hasUpperCase(String string) {
return upperCasePattern.matcher(string).matches();
}
public static boolean hasLowerCase(String string) {
return lowerCasePattern.matcher(string).matches();
}
public static String standardizeLineEndings(String string) {
if (string == null) {
return null;
}
return string.replace("\r\n", "\n").replace("\r", "\n");
}
public static boolean isAscii(String string) {
if (string == null) {
return true;
}
for (char c : string.toCharArray()) {
if (!isAscii(c)) {
return false;
}
}
return true;
}
public static boolean isAscii(char ch) {
return ch < 128;
}
public static String escapeHtml(String str) {
StringBuilder out = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c > 0x7F) {
out.append("&
out.append(Integer.toString(c, 10));
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
public static String pad(String value, int length) {
value = StringUtils.trimToEmpty(value);
if (value.length() >= length) {
return value;
}
return value + StringUtils.repeat(" ", length - value.length());
}
/**
* Null-safe check if string is empty.
*
* @param value String to be checked
* @return true if String is null or empty
*/
public static boolean isEmpty(String value) {
return value == null || value.length() == 0;
}
/**
* Null-safe check if string is not empty
*
* @param value String to be checked
* @return true if string is not null and not empty (length > 0)
*/
public static boolean isNotEmpty(String value) {
return !isEmpty(value);
}
/**
* Checks if <code>value</code> starts with <code>startsWith</code>.
* @param value
* @param startsWith
* @return true if <code>value</code> starts with <code>startsWith</code>, otherwise false. If any of arguments is null returns false
*/
public static boolean startsWith(String value, String startsWith) {
if(value == null || startsWith == null){
return false;
}
return value.startsWith(startsWith);
}
public static boolean isWhitespace(CharSequence string) {
if (string == null) {
return true;
}
return StringUtils.trimToNull(string.toString()) == null;
}
public static interface StringUtilsFormatter<Type> {
public String toString(Type obj);
}
public static class ToStringFormatter implements StringUtilsFormatter {
@Override
public String toString(Object obj) {
if (obj == null) {
return null;
}
return obj.toString();
}
}
public static String limitSize(String string, int maxLength) {
if (string.length() > maxLength) {
return string.substring(0, maxLength - 3) + "...";
}
return string;
}
}
|
package me.pagarme.transaction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import me.pagarme.AntifraudMetadataPojo;
import me.pagarme.BaseTest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.JsonObject;
import me.pagar.model.Address;
import me.pagar.model.BankAccount;
import me.pagar.model.Customer;
import me.pagar.model.PagarMeException;
import me.pagar.model.Phone;
import me.pagar.model.Recipient;
import me.pagar.model.SplitRule;
import me.pagar.model.Transaction;
import me.pagar.model.Transaction.CaptureMethod;
import me.pagar.util.JSONUtils;
import me.pagarme.factory.RecipientFactory;
import me.pagarme.factory.CustomerFactory;
import me.pagarme.factory.TransactionFactory;
import me.pagarme.helper.TestEndpoints;
import org.joda.time.DateTime;
public class TransactionTest extends BaseTest {
private RecipientFactory recipientFactory = new RecipientFactory();
private CustomerFactory customerFactory = new CustomerFactory();
private TransactionFactory transactionFactory = new TransactionFactory();
private TestEndpoints testEndpoints = new TestEndpoints();
private static Integer AMOUNT = 100;
private static Integer PAID_AMOUNT_PARTIAL = 50;
@Before
public void setUp() {
super.setUp();
transaction = new Transaction();
}
@Test
public void testCreatedDateExistence() throws PagarMeException{
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.save();
Assert.assertNotNull(transaction.getCreatedAt());
Assert.assertNotNull(transaction.getUpdatedAt());
}
@Test
public void testCreateAndCaptureTransactionWithSoftDescriptor() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setSoftDescriptor("API Test");
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getSoftDescriptor(), "API Test");
}
@Test
public void testCreateAndCaptureTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndCaptureTransactionMetaData() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.save();
Transaction foundTransaction = new Transaction().find(transaction.getId());
Assert.assertEquals(foundTransaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(foundTransaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(foundTransaction.getMetadata().get("metadata1"), "value1");
Assert.assertEquals(foundTransaction.getMetadata().get("metadata2"), "value2");
}
@SuppressWarnings("unchecked")
@Test
public void testCreateAndCaptureTransactionAntifraudMetaDataMap() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
Map<String, Object> antifraudMetadata = new HashMap<String, Object>();
antifraudMetadata.put("antifraudMetadata1", "value1");
antifraudMetadata.put("antifraudMetadata2", "value2");
transaction.setAntifraudMetadata(antifraudMetadata);
transaction.save();
JsonObject json = JSONUtils.treeToJson(transaction.getAntifraudMetadata());
Map<String, Object> antifraudMetadataRes = JSONUtils.getAsObject(json, HashMap.class);
Assert.assertEquals(antifraudMetadataRes.get("antifraudMetadata1"), "value1");
Assert.assertEquals(antifraudMetadataRes.get("antifraudMetadata2"), "value2");
}
@Test
public void testCreateAndCaptureTransactionAntifraudMetaDataPojo() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
AntifraudMetadataPojo antifraudMetadata = new AntifraudMetadataPojo();
antifraudMetadata.setName("Philip J. Fry");
transaction.setAntifraudMetadata(antifraudMetadata);
transaction.save();
JsonObject json = JSONUtils.treeToJson(transaction.getAntifraudMetadata());
AntifraudMetadataPojo antifraudMetadataRes = JSONUtils.getAsObject(json, AntifraudMetadataPojo.class);
Assert.assertEquals(antifraudMetadataRes.getName(), "Philip J. Fry");
}
@Test
public void testCreateAndCaptureTransactionMetaDataInCapture() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.save();
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndAuthorizedTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
}
@Test
public void testTransactionCreatePostbackUrl() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setPostbackUrl("http://pagar.me");
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PROCESSING);
}
@Test
public void testTransactionAuthAndCaptureCaptureTotalValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testTransactionCanBeMadeString() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.toString();
}
@Test
public void testTransactionCanBeMadeJSON() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(50);
transaction.toJson();
}
@Test
public void testTransactionAuthAndCaptureCapturePartialValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testTransactionAuthAndCaptureRefoundPartialValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
transaction.save();
transaction.refund(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), AMOUNT);
Assert.assertEquals(transaction.getRefundedAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testBoletoTransactionAuthAndCaptureRefund() throws Throwable {
Transaction transaction = transactionFactory.createBoletoTransaction();
transaction.setCapture(true);
transaction.setAmount(10000);
transaction.save();
transaction = testEndpoints.payBoleto(transaction);
Transaction transaction2 = transactionFactory.createBoletoTransaction();
transaction2.setCapture(true);
transaction2.setAmount(10000);
transaction2.save();
transaction2 = testEndpoints.payBoleto(transaction2);
BankAccount bankAccount = (BankAccount)new BankAccount().findCollection(1, 0).toArray()[0];
transaction.refund(bankAccount);
Assert.assertEquals(Transaction.Status.PENDING_REFUND, transaction.getStatus());
}
@Test
public void testTransactionAuthAndCaptureRefoundTotalValue() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
transaction.save();
transaction.refund(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.REFUNDED);
Assert.assertEquals(transaction.getRefundedAmount(), AMOUNT);
}
@Test
public void testCreateAndAuthorizedTransactionWithBoleto() throws Throwable {
transaction = transactionFactory.createBoletoTransaction();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
}
@Test
public void testCreateTransactionWithBoleto() throws Throwable {
transaction = transactionFactory.createBoletoTransaction();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
Assert.assertEquals(transaction.getBoletoUrl(), "https://pagar.me");
Assert.assertNotNull(transaction.getBoletoBarcode());
}
@Test
public void testBoletoExpirationDate() throws Throwable{
transaction = transactionFactory.createBoletoTransaction();
transaction.setBoletoExpirationDate(DateTime.now().plusDays(4));
transaction.save();
Transaction foundTransaction = new Transaction().find(transaction.getId());
Assert.assertEquals(DateTime.now().plusDays(4).withTime(3, 0, 0, 0), foundTransaction.getBoletoExpirationDate());
}
@Test
public void testFindTransactionById() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.save();
Integer transactionId = transaction.getId();
transaction = transaction.find(transactionId);
Assert.assertEquals(transaction.getId(), transactionId);
}
@Test
public void testCreatingCustomerTransactionThroughTheTransaction() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
Customer customer = this.customerCommon();
Address address = this.addressCommon();
Phone phone = this.phoneCommon();
customer.setAddress(address);
customer.setPhone(phone);
transaction.setCustomer(customer);
transaction.save();
Customer transactionCustomer = transaction.getCustomer();
Assert.assertEquals(transactionCustomer.getName(), "lucas santos");
Assert.assertEquals(transactionCustomer.getDocumentNumber(), "15317529506");
Assert.assertEquals(transactionCustomer.getEmail(), "testelibjava@pagar.me");
Address transactionAddress = transactionCustomer.getAddress();
Assert.assertEquals(transactionAddress.getStreet(), "Rua Piraju");
Assert.assertEquals(transactionAddress.getStreetNumber(), "218");
Assert.assertEquals(transactionAddress.getComplementary(), "ao lado da consigáz");
Assert.assertEquals(transactionAddress.getNeighborhood(), "Interlagos");
Phone transactionPhone = transactionCustomer.getPhone();
Assert.assertEquals(transactionPhone.getDdd(), "11");
Assert.assertEquals(transactionPhone.getNumber(), "55284132");
}
@Test
public void testCaptureFalseWithSplitTransaction() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(false);
transaction.setAmount(10000);
Customer customer = customerFactory.create();
transaction.setCustomer(customer);
transaction.save();
Collection<SplitRule> splitRules = new ArrayList<SplitRule>();
Recipient recipient1 = recipientFactory.create();
recipient1.save();
SplitRule splitRule = new SplitRule();
splitRule.setRecipientId(recipient1.getId());
splitRule.setPercentage(50);
splitRule.setLiable(true);
splitRule.setChargeProcessingFee(true);
splitRules.add(splitRule);
Recipient recipient2 = recipientFactory.create();
SplitRule splitRule2 = new SplitRule();
recipient2.save();
splitRule2.setRecipientId(recipient2.getId());
splitRule2.setPercentage(50);
splitRule2.setLiable(true);
splitRule2.setChargeProcessingFee(true);
splitRules.add(splitRule2);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.setSplitRules(splitRules);
transaction.capture(transaction.getAmount());
Transaction foundTransaction = new Transaction().find(transaction.getId());
Collection<SplitRule> foundSplitRules = foundTransaction.getSplitRules();
Assert.assertEquals(splitRules.size(), foundSplitRules.size());
}
@Test
public void testSplitTransaction() throws Throwable {
transaction = transactionFactory.createCreditCardTransactionWithoutPinMode();
transaction.setCapture(true);
transaction.setAmount(10000);
Collection<SplitRule> splitRules = new ArrayList<SplitRule>();
Recipient recipient1 = recipientFactory.create();
recipient1.save();
SplitRule splitRule = new SplitRule();
splitRule.setRecipientId(recipient1.getId());
splitRule.setPercentage(50);
splitRule.setLiable(true);
splitRule.setChargeProcessingFee(true);
splitRules.add(splitRule);
Recipient recipient2 = recipientFactory.create();
SplitRule splitRule2 = new SplitRule();
recipient2.save();
splitRule2.setRecipientId(recipient2.getId());
splitRule2.setPercentage(50);
splitRule2.setLiable(true);
splitRule2.setChargeProcessingFee(true);
splitRules.add(splitRule2);
transaction.setSplitRules(splitRules);
transaction.save();
Transaction foundTransaction = new Transaction().find(transaction.getId());
Collection<SplitRule> foundSplitRules = foundTransaction.getSplitRules();
Assert.assertEquals(splitRules.size(), foundSplitRules.size());
}
// private String getRecipientId(Boolean documentNumber) {
// int bankAccountId = this.getBankAccountId(documentNumber);
// recipient.setTransferInterval(Recipient.TransferInterval.WEEKLY);
// recipient.setTransferDay(TRANSFER_DAY);
// recipient.setTransferEnabled(TRANSFER_ENABLE);
// recipient.setBankAccountId(bankAccountId);
// try {
// recipient.save();
// return recipient.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
// /**
// *
// * @return
// */
// private Integer getBankAccountId(Boolean documentNumber) {
// System.out.print("Hello " + documentNumber);
// if (documentNumber == true) {
// bankAccount = new BankAccount();
// bankAccount.setAgencia(AGENCIA);
// bankAccount.setAgenciaDv(AGENCIA_DV);
// bankAccount.setConta(CONTA);
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber(DOCUMENT_NUMBER);
// } else {
// bankAccount = new BankAccount();
// System.out.print("Hello " + bankAccount.getConta());
// bankAccount.setAgencia("0173");
// bankAccount.setAgenciaDv("1");
// bankAccount.setConta("506725");
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber("55278368128");
// try {
// bankAccount.save();
// return bankAccount.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
}
|
/*
* Cliente de chat IRC-style
* Trabajo grupal de Computadores
*
* Clase UserOut
*
* Autores:
* - Lucas Alvarez
* - Oscar de Arriba
* - Estefania Gonzalez
*/
package es.uniovi.UO217138;
import java.util.StringTokenizer;
/*
* Clase UserOut
*
* Se encarga de procesar las respuestas almacenadas en
* el buffer de respuestas y mostrar al usuario la
* informacin pertinente.
*/
public class UserOut extends Thread {
private ChatIRC hiloPadre;
private BufferFifo bufferResponses;
/*
* Constructor de la clase UserOut
*/
public UserOut (BufferFifo bufferResponses, ChatIRC principal) {
this.hiloPadre = principal;
this.bufferResponses = bufferResponses;
}
/*
* Funcin de ejecucin del Thread
*/
public void run() {
Message message;
while(true) {
message = new Message();
try {
// Intentar obtener una respuesta del buffer
message = this.bufferResponses.get();
} catch(InterruptedException e) {
e.printStackTrace();
}
String[] args = message.getArgs();
switch(message.getType()){
case Message.TYPE_MSG:
//paquete del tipo mensaje
if (message.getPacket() == Message.PKT_INF) {
//mensaje del servidor
System.out.println(args[1]+"|"+args[0]+">"+args[2]);
}
if (message.getPacket() == Message.PKT_ERR) {
// error delservidor
System.out.println("ERROR(tipo: mensaje): "+args[0]);
}
break;
case Message.TYPE_JOIN:
//paquete del tipo unirse a sala
if (message.getPacket() == Message.PKT_INF) {
System.out.println("El usuario "+ args[0]+" se ha unido a la sala :"+args[1]);
//mensaje del servidor
}
if (message.getPacket() == Message.PKT_OK) {
//constestacion del servidor
System.out.println("Te has unido a la sala "+args[1]);
}
if (message.getPacket() == Message.PKT_ERR) {
// error delservidor
System.out.println("ERROR(tipo: unirse a sala): "+args[0]);
}
break;
case Message.TYPE_LEAVE:
//paquete del tipo abandornar sala
if (message.getPacket() == Message.PKT_INF) {
System.out.println("El usuario "+ args[0]+" ha abandonado la sala :"+args[1]);
//mensaje del servidor
}
if (message.getPacket() == Message.PKT_OK) {
System.out.println("Has abandonado la sala "+args[1]);
//constestacion del servidor
}
if (message.getPacket() == Message.PKT_ERR) {
// error delservidor
System.out.println("ERROR(tipo: abandonar sala): "+args[0]);
}
break;
case Message.TYPE_NICK:
//paquete del tipo cambio de nick
if (message.getPacket() == Message.PKT_INF) {
System.out.println("El usuario "+ args[0]+" ha cambiado su nick por "+args[1]);
//mensaje del servidor
}
if (message.getPacket() == Message.PKT_OK) {
System.out.println("Se a realizado satisfactoriamente el cambio de nick de "+ args[0]+" a "+args[1]);
//constestacion del servidor
}
if (message.getPacket() == Message.PKT_ERR) {
// error delservidor
System.out.println("ERROR(tipo: cambio de nick): "+args[0]);
}
break;
case Message.TYPE_QUIT:
//paquete del tipo fon de conexion
if (message.getPacket() == Message.PKT_INF) {
System.out.println("El usuario "+ args[0]+" se ha deconectado");
//mensaje del servidor
}
if (message.getPacket() == Message.PKT_OK) {
System.out.println("Tu ("+ args[0]+") has finalizado la conexion");
//constestacion del servidor
}
if (message.getPacket() == Message.PKT_ERR) {
System.out.println("ERROR(tipo: desconexion): "+args[0]);
// error delservidor
}
break;
case Message.TYPE_LIST:
//paquete del tipo list de salas
if (message.getPacket() == Message.PKT_OK) {
StringTokenizer st= new StringTokenizer(args[0],";");
System.out.println("Las siguientes salas estan disponibles: ");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
//constestacion del servidor
}
if (message.getPacket() == Message.PKT_ERR) {
System.out.println("ERROR(tipo: lista de salas): "+args[0]);
// error delservidor
}
break;
case Message.TYPE_WHO:
//paquete del tipo usuarios en sala
if (message.getPacket() == Message.PKT_OK) {
StringTokenizer st= new StringTokenizer(args[1],";");
System.out.println("En la sala "+args[0]+ "se encuentran :");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
//constestacion del servidor
}
if (message.getPacket() == Message.PKT_ERR) {
System.out.println("ERROR(tipo: lista de usuarios en sala): "+args[0]);
// error delservidor
}
break;
case Message.TYPE_HELLO:
//paquete del tipo mensaje de bienvenida del server
if (message.getPacket() == Message.PKT_OK) {
System.out.println("Mensaje del servidor : "+args[0]);
//constestacion del servidor
}
break;
case Message.TYPE_MISC:
//paquete del tipo demas errores
if (message.getPacket() == Message.PKT_ERR) {
System.out.println("ERROR(tipo: no especifico): "+args[0]);
// error delservidor
}
break;
}
}
}
}
|
package octoteam.tahiti.performance;
import otcoteam.tahiti.performance.recorder.CountingRecorder;
import otcoteam.tahiti.performance.reporter.LogReporter;
import otcoteam.tahiti.performance.reporter.RollingFileReporter;
import org.junit.Test;
import static org.junit.Assert.*;
public class CountingRecorderTest {
public CountingRecorder testRecorder = new CountingRecorder("Login times");
@Test
public void testgetName(){
assertEquals("Login times",testRecorder.getName());
}
@Test
public void testgetReport(){
assertEquals("0",testRecorder.getReport());
}
@Test
public void testRecord(){
testRecorder.record();
assertEquals("1",testRecorder.getReport());
}
@Test
public void testRest(){
testRecorder.reset();
assertEquals("0",testRecorder.getReport());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.