answer stringlengths 17 10.2M |
|---|
package uk.ac.ebi.pride.archive.web.service.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import static uk.ac.ebi.pride.archive.web.service.interceptor.RateLimitServiceImpl.COUNT_EXPIRY_PERIOD_SECONDS;
/**
* This class rate limits all Web Service GET requests. This is according to the values set for
* MAX_REQUESTS_PER_PERIOD which is double the value set for RateLimitServiceImpl.COUNT_EXPIRY_PERIOD_SECONDS.
* The purpose is to limit the frequency individual users may query for information, primarily in relation
* to PSMs. Pagination alone does not solve such a problem.
*
* @author Tobias Ternent
*/
@Service
public class RateLimitInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(RateLimitInterceptor.class);
public static final int MAX_REQUESTS_PER_PERIOD = COUNT_EXPIRY_PERIOD_SECONDS * 2;
@Value("#{redisConfig['redis.host']}")
private String redisServer;
@Value("#{redisConfig['redis.port']}")
private String redisPort;
@Value("#{redisConfig['redis.password']}")
private String redisPassword;
private JedisPool jedisPool;
@Autowired
private RateLimitService rateLimitService;
/**
* This method is called before handling every single request.
* @param request the request sent to the Web Service.
* @param response the response sent back to the user.
* @param handler the handler object.
* @return true to process the request onwards as normal, false otherwise and the request is not processed at all.
* @throws Exception Any exception encountered attempting to limit the user's requests.
*/
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
boolean result = true;
if (jedisPool==null) {
jedisPool = new JedisPool(new JedisPoolConfig(), redisServer, Integer.parseInt(redisPort), 0, redisPassword);
}
if ("GET".equalsIgnoreCase(request.getMethod())) {
if (logger.isDebugEnabled()) {
debugRequestHeaders(request);
}
String address = request.getHeader("requestx-forwarded-for");
if (address == null || address.length() == 0 || "unknown".equalsIgnoreCase(address)) {
address = request.getHeader("x-cluster-client-ip");
}
if (address == null || address.length() == 0 || "unknown".equalsIgnoreCase(address)) {
address = request.getRemoteAddr();
}
int incrementUserGetCount = rateLimitService.incrementLimit("GET~" + address, jedisPool);
logger.debug("Current count for user: " + address + " is: " + incrementUserGetCount);
if (incrementUserGetCount >= MAX_REQUESTS_PER_PERIOD) {
response.sendError(429, "Rate limit exceeded: " + MAX_REQUESTS_PER_PERIOD + " requests per " + COUNT_EXPIRY_PERIOD_SECONDS + " seconds. Please wait " + COUNT_EXPIRY_PERIOD_SECONDS*2 + " seconds to try again.");
result = false;
logger.info("Throttled connections for user: " + address);
} else {
response.addIntHeader("Remaining request count", MAX_REQUESTS_PER_PERIOD - incrementUserGetCount);
}
}
return result;
}
/**
* This method outputs the HTTP request headers to the debug logger.
* @param request the HTTP request.
*/
private void debugRequestHeaders(HttpServletRequest request) {
logger.debug(request.getRemoteAddr() + ": Printing all headers...");
logger.debug("Throttled connections for user: " + request.getRemoteAddr());
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
logger.debug(request.getRemoteAddr() + ": Header name: " + headerName);
logger.debug(request.getRemoteAddr() + ": Header value: " + request.getHeader(headerName));
}
logger.debug("Finished printing all headers!");
}
} |
package org.spongepowered.common.mixin.core.entity.ai.goal;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityPredicate;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.goal.Goal;
import net.minecraft.entity.ai.goal.LookAtGoal;
import net.minecraft.util.EntityPredicates;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import java.util.List;
import javax.annotation.Nullable;
@SuppressWarnings({"unchecked", "rawtypes"})
@Mixin(LookAtGoal.class)
public abstract class LookAtGoalMixin extends Goal {
@Shadow protected Class watchedClass;
@Nullable
@Redirect(method = "shouldExecute",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/world/World;func_225318_b(Ljava/lang/Class;Lnet/minecraft/entity/EntityPredicate;Lnet/minecraft/entity/LivingEntity;DDDLnet/minecraft/util/math/AxisAlignedBB;)Lnet/minecraft/entity/LivingEntity;"))
private LivingEntity onFindNearestEntityWithinAABB(final World world, final Class clazz, final EntityPredicate predicate, final LivingEntity living,
final double x, final double y, final double z, final AxisAlignedBB aabb) {
LivingEntity entity1 = null;
double d0 = Double.MAX_VALUE;
for (final Entity foundEntity: (List<Entity>) world.getEntities(this.watchedClass, EntityPredicates.NOT_SPECTATING)) {
if (foundEntity.getBoundingBox().intersects(aabb) && foundEntity != living) {
final double d1 = living.getDistanceSq(foundEntity);
if (d1 <= d0)
{
entity1 = foundEntity;
d0 = d1;
}
}
}
return entity1;
}
} |
package de.terrestris.shogun2.service;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import de.terrestris.shogun2.dao.ApplicationDao;
import de.terrestris.shogun2.dao.LayoutDao;
import de.terrestris.shogun2.dao.ModuleDao;
import de.terrestris.shogun2.dao.RoleDao;
import de.terrestris.shogun2.dao.UserDao;
import de.terrestris.shogun2.dao.UserGroupDao;
import de.terrestris.shogun2.init.ContentInitializer;
import de.terrestris.shogun2.model.Application;
import de.terrestris.shogun2.model.Role;
import de.terrestris.shogun2.model.User;
import de.terrestris.shogun2.model.UserGroup;
import de.terrestris.shogun2.model.layout.Layout;
import de.terrestris.shogun2.model.module.Module;
@Service("initializationService")
@Transactional(value="transactionManager")
public class InitializationService {
/**
* The Logger
*/
private static final Logger LOG = Logger
.getLogger(InitializationService.class);
@Autowired
private RoleDao<Role> roleDao;
@Autowired
private UserDao<User> userDao;
@Autowired
private UserGroupDao<UserGroup> userGroupDao;
@Autowired
private LayoutDao<Layout> layoutDao;
@Autowired
private ModuleDao<Module> moduleDao;
@Autowired
private ApplicationDao<Application> applicationDao;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* Used to create a role.
*
* @param role
* @return
*/
public Role createRole(Role role) {
roleDao.saveOrUpdate(role);
LOG.trace("Created the role " + role);
return role;
}
/**
* Used to create a user.
*
* @param user
* @return
*/
public User createUser(User user) {
// encode the raw password using bcrypt
final String pwHash = passwordEncoder.encode(user.getPassword());
user.setPassword(pwHash);
userDao.saveOrUpdate(user);
LOG.trace("Created the user " + user);
return user;
}
/**
* Used to create a user.
*
* @param userGroup
* @return
*/
public UserGroup createUserGroup(UserGroup userGroup) {
userGroupDao.saveOrUpdate(userGroup);
LOG.trace("Created the user group " + userGroup);
return userGroup;
}
/**
* Used to create a layout.
*
* @param layout
*/
public Layout createLayout(Layout layout) {
layoutDao.saveOrUpdate(layout);
LOG.trace("Created the layout " + layout);
return layout;
}
/**
* Used to create a module.
*
* @param module
*/
public Module createModule(Module module) {
moduleDao.saveOrUpdate(module);
LOG.trace("Created the module " + module);
return module;
}
/**
* Used to create an application.
*
* @param application
* @return
*/
public Application createApplication(Application application) {
applicationDao.saveOrUpdate(application);
LOG.trace("Created the application " + application);
return application;
}
} |
package com.fasterxml.jackson.databind.jsontype;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestSubtypesExistingProperty extends BaseMapTest {
/**
* Polymorphic base class - existing property as simple property on subclasses
*/
@JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Apple.class, name = "apple") ,
@Type(value = Orange.class, name = "orange")
})
static abstract class Fruit {
public String name;
protected Fruit(String n) { name = n; }
}
@JsonTypeName("apple")
static class Apple extends Fruit
{
public int seedCount;
public String type;
private Apple() { super(null); type = "apple"; }
public Apple(String name, int b) {
super(name);
seedCount = b;
type = "apple";
}
}
@JsonTypeName("orange")
static class Orange extends Fruit
{
public String color;
public String type;
private Orange() { super(null); type = "orange"; }
public Orange(String name, String c) {
super(name);
color = c;
type = "orange";
}
}
static class FruitWrapper {
public Fruit fruit;
public FruitWrapper() {}
public FruitWrapper(Fruit f) { fruit = f; }
}
/**
* Polymorphic base class - existing property forced by abstract method
*/
@JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Dog.class, name = "doggie") ,
@Type(value = Cat.class, name = "kitty")
})
static abstract class Animal {
public String name;
protected Animal(String n) { name = n; }
public abstract String getType();
}
@JsonTypeName("doggie")
static class Dog extends Animal
{
public int boneCount;
private Dog() { super(null); }
public Dog(String name, int b) {
super(name);
boneCount = b;
}
@Override
public String getType() {
return "doggie";
}
}
@JsonTypeName("kitty")
static class Cat extends Animal
{
public String furColor;
private Cat() { super(null); }
public Cat(String name, String c) {
super(name);
furColor = c;
}
@Override
public String getType() {
return "kitty";
}
}
static class AnimalWrapper {
public Animal animal;
public AnimalWrapper() {}
public AnimalWrapper(Animal a) { animal = a; }
}
/**
* Polymorphic base class - existing property NOT forced by abstract method on base class
*/
@JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Accord.class, name = "accord") ,
@Type(value = Camry.class, name = "camry")
})
static abstract class Car {
public String name;
protected Car(String n) { name = n; }
}
@JsonTypeName("accord")
static class Accord extends Car
{
public int speakerCount;
private Accord() { super(null); }
public Accord(String name, int b) {
super(name);
speakerCount = b;
}
public String getType() {
return "accord";
}
}
@JsonTypeName("camry")
static class Camry extends Car
{
public String exteriorColor;
private Camry() { super(null); }
public Camry(String name, String c) {
super(name);
exteriorColor = c;
}
public String getType() {
return "camry";
}
}
static class CarWrapper {
public Car car;
public CarWrapper() {}
public CarWrapper(Car c) { car = c; }
}
private final ObjectMapper MAPPER = new ObjectMapper();
private static final Orange mandarin = new Orange("Mandarin Orange", "orange");
private static final String mandarinJson = "{\"name\":\"Mandarin Orange\",\"color\":\"orange\",\"type\":\"orange\"}";
private static final Apple pinguo = new Apple("Apple-A-Day", 16);
private static final String pinguoJson = "{\"name\":\"Apple-A-Day\",\"seedCount\":16,\"type\":\"apple\"}";
private static final FruitWrapper pinguoWrapper = new FruitWrapper(pinguo);
private static final String pinguoWrapperJson = "{\"fruit\":" + pinguoJson + "}";
private static final List<Fruit> fruitList = Arrays.asList(pinguo, mandarin);
private static final String fruitListJson = "[" + pinguoJson + "," + mandarinJson + "]";
private static final Cat beelzebub = new Cat("Beelzebub", "tabby");
private static final String beelzebubJson = "{\"name\":\"Beelzebub\",\"furColor\":\"tabby\",\"type\":\"kitty\"}";
private static final Dog rover = new Dog("Rover", 42);
private static final String roverJson = "{\"name\":\"Rover\",\"boneCount\":42,\"type\":\"doggie\"}";
private static final AnimalWrapper beelzebubWrapper = new AnimalWrapper(beelzebub);
private static final String beelzebubWrapperJson = "{\"animal\":" + beelzebubJson + "}";
private static final List<Animal> animalList = Arrays.asList(beelzebub, rover);
private static final String animalListJson = "[" + beelzebubJson + "," + roverJson + "]";
private static final Camry camry = new Camry("Sweet Ride", "candy-apple-red");
private static final String camryJson = "{\"name\":\"Sweet Ride\",\"exteriorColor\":\"candy-apple-red\",\"type\":\"camry\"}";
private static final Accord accord = new Accord("Road Rage", 6);
private static final String accordJson = "{\"name\":\"Road Rage\",\"speakerCount\":6,\"type\":\"accord\"}";
private static final CarWrapper camryWrapper = new CarWrapper(camry);
private static final String camryWrapperJson = "{\"car\":" + camryJson + "}";
private static final List<Car> carList = Arrays.asList(camry, accord);
private static final String carListJson = "[" + camryJson + "," + accordJson + "]";
/**
* Fruits - serialization tests for simple property on sub-classes
*/
public void testExistingPropertySerializationFruits() throws Exception
{
Map<String,Object> result = writeAndMap(MAPPER, pinguo);
assertEquals(3, result.size());
assertEquals(pinguo.name, result.get("name"));
assertEquals(pinguo.seedCount, result.get("seedCount"));
assertEquals(pinguo.type, result.get("type"));
result = writeAndMap(MAPPER, mandarin);
assertEquals(3, result.size());
assertEquals(mandarin.name, result.get("name"));
assertEquals(mandarin.color, result.get("color"));
assertEquals(mandarin.type, result.get("type"));
String pinguoSerialized = MAPPER.writeValueAsString(pinguo);
assertEquals(pinguoSerialized, pinguoJson);
String mandarinSerialized = MAPPER.writeValueAsString(mandarin);
assertEquals(mandarinSerialized, mandarinJson);
String fruitWrapperSerialized = MAPPER.writeValueAsString(pinguoWrapper);
assertEquals(fruitWrapperSerialized, pinguoWrapperJson);
String fruitListSerialized = MAPPER.writeValueAsString(fruitList);
assertEquals(fruitListSerialized, fruitListJson);
}
/**
* Fruits - deserialization tests for simple property on sub-classes
*/
public void testSimpleClassAsExistingPropertyDeserializationFruits() throws Exception
{
Fruit pinguoDeserialized = MAPPER.readValue(pinguoJson, Fruit.class);
assertTrue(pinguoDeserialized instanceof Apple);
assertSame(pinguoDeserialized.getClass(), Apple.class);
assertEquals(pinguo.name, pinguoDeserialized.name);
assertEquals(pinguo.seedCount, ((Apple) pinguoDeserialized).seedCount);
assertEquals(pinguo.type, ((Apple) pinguoDeserialized).type);
FruitWrapper pinguoWrapperDeserialized = MAPPER.readValue(pinguoWrapperJson, FruitWrapper.class);
Fruit pinguoExtracted = pinguoWrapperDeserialized.fruit;
assertTrue(pinguoExtracted instanceof Apple);
assertSame(pinguoExtracted.getClass(), Apple.class);
assertEquals(pinguo.name, pinguoExtracted.name);
assertEquals(pinguo.seedCount, ((Apple) pinguoExtracted).seedCount);
assertEquals(pinguo.type, ((Apple) pinguoExtracted).type);
@SuppressWarnings("unchecked")
List<Fruit> fruitListDeserialized = MAPPER.readValue(fruitListJson, List.class);
assertNotNull(fruitListDeserialized);
assertTrue(fruitListDeserialized.size() == 2);
Fruit apple = MAPPER.convertValue(fruitListDeserialized.get(0), Apple.class);
assertTrue(apple instanceof Apple);
assertSame(apple.getClass(), Apple.class);
Fruit orange = MAPPER.convertValue(fruitListDeserialized.get(1), Orange.class);
assertTrue(orange instanceof Orange);
assertSame(orange.getClass(), Orange.class);
}
/**
* Animals - serialization tests for abstract method in base class
*/
public void testExistingPropertySerializationAnimals() throws Exception
{
Map<String,Object> result = writeAndMap(MAPPER, beelzebub);
assertEquals(3, result.size());
assertEquals(beelzebub.name, result.get("name"));
assertEquals(beelzebub.furColor, result.get("furColor"));
assertEquals(beelzebub.getType(), result.get("type"));
result = writeAndMap(MAPPER, rover);
assertEquals(3, result.size());
assertEquals(rover.name, result.get("name"));
assertEquals(rover.boneCount, result.get("boneCount"));
assertEquals(rover.getType(), result.get("type"));
String beelzebubSerialized = MAPPER.writeValueAsString(beelzebub);
assertEquals(beelzebubSerialized, beelzebubJson);
String roverSerialized = MAPPER.writeValueAsString(rover);
assertEquals(roverSerialized, roverJson);
String animalWrapperSerialized = MAPPER.writeValueAsString(beelzebubWrapper);
assertEquals(animalWrapperSerialized, beelzebubWrapperJson);
String animalListSerialized = MAPPER.writeValueAsString(animalList);
assertEquals(animalListSerialized, animalListJson);
}
/**
* Animals - deserialization tests for abstract method in base class
*/
public void testSimpleClassAsExistingPropertyDeserializationAnimals() throws Exception
{
Animal beelzebubDeserialized = MAPPER.readValue(beelzebubJson, Animal.class);
assertTrue(beelzebubDeserialized instanceof Cat);
assertSame(beelzebubDeserialized.getClass(), Cat.class);
assertEquals(beelzebub.name, beelzebubDeserialized.name);
assertEquals(beelzebub.furColor, ((Cat) beelzebubDeserialized).furColor);
assertEquals(beelzebub.getType(), beelzebubDeserialized.getType());
AnimalWrapper beelzebubWrapperDeserialized = MAPPER.readValue(beelzebubWrapperJson, AnimalWrapper.class);
Animal beelzebubExtracted = beelzebubWrapperDeserialized.animal;
assertTrue(beelzebubExtracted instanceof Cat);
assertSame(beelzebubExtracted.getClass(), Cat.class);
assertEquals(beelzebub.name, beelzebubExtracted.name);
assertEquals(beelzebub.furColor, ((Cat) beelzebubExtracted).furColor);
assertEquals(beelzebub.getType(), beelzebubExtracted.getType());
@SuppressWarnings("unchecked")
List<Animal> animalListDeserialized = MAPPER.readValue(animalListJson, List.class);
assertNotNull(animalListDeserialized);
assertTrue(animalListDeserialized.size() == 2);
Animal cat = MAPPER.convertValue(animalListDeserialized.get(0), Animal.class);
assertTrue(cat instanceof Cat);
assertSame(cat.getClass(), Cat.class);
Animal dog = MAPPER.convertValue(animalListDeserialized.get(1), Animal.class);
assertTrue(dog instanceof Dog);
assertSame(dog.getClass(), Dog.class);
}
/**
* Cars - serialization tests for no abstract method or type variable in base class
*/
public void testExistingPropertySerializationCars() throws Exception
{
Map<String,Object> result = writeAndMap(MAPPER, camry);
assertEquals(3, result.size());
assertEquals(camry.name, result.get("name"));
assertEquals(camry.exteriorColor, result.get("exteriorColor"));
assertEquals(camry.getType(), result.get("type"));
result = writeAndMap(MAPPER, accord);
assertEquals(3, result.size());
assertEquals(accord.name, result.get("name"));
assertEquals(accord.speakerCount, result.get("speakerCount"));
assertEquals(accord.getType(), result.get("type"));
String camrySerialized = MAPPER.writeValueAsString(camry);
assertEquals(camrySerialized, camryJson);
String accordSerialized = MAPPER.writeValueAsString(accord);
assertEquals(accordSerialized, accordJson);
String carWrapperSerialized = MAPPER.writeValueAsString(camryWrapper);
assertEquals(carWrapperSerialized, camryWrapperJson);
String carListSerialized = MAPPER.writeValueAsString(carList);
assertEquals(carListSerialized, carListJson);
}
/**
* Cars - deserialization tests for no abstract method or type variable in base class
*/
public void testSimpleClassAsExistingPropertyDeserializationCars() throws Exception
{
Car camryDeserialized = MAPPER.readValue(camryJson, Camry.class);
assertTrue(camryDeserialized instanceof Camry);
assertSame(camryDeserialized.getClass(), Camry.class);
assertEquals(camry.name, camryDeserialized.name);
assertEquals(camry.exteriorColor, ((Camry) camryDeserialized).exteriorColor);
assertEquals(camry.getType(), ((Camry) camryDeserialized).getType());
CarWrapper camryWrapperDeserialized = MAPPER.readValue(camryWrapperJson, CarWrapper.class);
Car camryExtracted = camryWrapperDeserialized.car;
assertTrue(camryExtracted instanceof Camry);
assertSame(camryExtracted.getClass(), Camry.class);
assertEquals(camry.name, camryExtracted.name);
assertEquals(camry.exteriorColor, ((Camry) camryExtracted).exteriorColor);
assertEquals(camry.getType(), ((Camry) camryExtracted).getType());
@SuppressWarnings("unchecked")
List<Car> carListDeserialized = MAPPER.readValue(carListJson, List.class);
assertNotNull(carListDeserialized);
assertTrue(carListDeserialized.size() == 2);
Car camry = MAPPER.convertValue(carListDeserialized.get(0), Car.class);
assertTrue(camry instanceof Camry);
assertSame(camry.getClass(), Camry.class);
Car accord = MAPPER.convertValue(carListDeserialized.get(1), Car.class);
assertTrue(accord instanceof Accord);
assertSame(accord.getClass(), Accord.class);
}
} |
package edu.northwestern.bioinformatics.studycalendar.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import static org.easymock.classextension.EasyMock.*;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import javax.servlet.http.HttpServletRequest;
/**
* @author Rhett Sutphin
*/
public class NewStudyControllerTest extends ControllerTestCase {
private NewStudyController controller;
private NewStudyCommand command;
private Study study;
private StudyDao studyDao;
protected void setUp() throws Exception {
super.setUp();
request.setMethod("GET");
studyDao = registerMockFor(StudyDao.class);
study = new Study();
command = new TestCommand();
controller = new TestController();
controller.setStudyDao(studyDao);
}
public void testReferenceData() throws Exception {
Map<String, Object> refdata = controller.referenceData(request);
assertEquals("Wrong action name", "New", refdata.get("action"));
}
public void testViewOnGet() throws Exception {
ModelAndView mv = controller.handleRequest(request, response);
assertEquals("editStudy", mv.getViewName());
}
public void testViewOnGoodSubmit() throws Exception {
study.setId(14);
request.setMethod("POST");
request.addParameter("studyName", "Study of things and stuff");
ModelAndView mv = controller.handleRequest(request, response);
assertEquals("redirectToCalendarTemplate", mv.getViewName());
}
public void testIdInModelOnGoodSubmit() throws Exception {
study.setId(14);
studyDao.save(study);
replayMocks();
request.addParameter("studyName", "Study of other things");
request.addParameter("epochNames[0]", "Eocene");
request.addParameter("arms[0]", "false");
Map<String, Object> model = controller.onSubmit(command, new BindException(command, "command")).getModel();
verifyMocks();
assertEquals("New study's ID not in model", study.getId(), model.get("id"));
assertEquals("Something besides the id in the model: " + model, 1, model.size());
}
// The binding tests test bind on GET for simplicity; bind on POST should be the same.
public void testBindHasArms() throws Exception {
request.addParameter("arms[0]", "true");
request.addParameter("arms[1]", "false");
request.addParameter("arms[2]", "true");
controller.handleRequest(request, response);
assertTrue(command.getArms().get(0));
assertFalse(command.getArms().get(1));
assertTrue(command.getArms().get(2));
}
public void testBindStudyName() throws Exception {
String studyName = "This study right here";
request.addParameter("studyName", studyName);
controller.handleRequest(request, response);
assertEquals(studyName, command.getStudyName());
}
public void testBindEpochNames() throws Exception {
List<String> names = Arrays.asList("Eocene", "Holocene");
request.addParameter("epochNames[0]", names.get(0));
request.addParameter("epochNames[1]", names.get(1));
controller.handleRequest(request, response);
assertEquals(2, command.getEpochNames().size());
assertEquals(names.get(0), command.getEpochNames().get(0));
assertEquals(names.get(1), command.getEpochNames().get(1));
}
public void testBindArmNames() throws Exception {
List<String> names = Arrays.asList("The arm", "An arm");
request.addParameter("armNames[1][0]", names.get(0));
request.addParameter("armNames[1][1]", names.get(1));
controller.handleRequest(request, response);
List<List<String>> actualArmNames = command.getArmNames();
assertEquals(0, actualArmNames.get(0).size());
assertEquals(2, actualArmNames.get(1).size());
Object s = actualArmNames.get(1).get(0);
assertEquals(names.get(0), s);
assertEquals(names.get(1), actualArmNames.get(1).get(1));
}
private class TestController extends NewStudyController {
protected Object formBackingObject(HttpServletRequest request) throws Exception {
return command;
}
}
private class TestCommand extends NewStudyCommand {
public Study createStudy() {
return study;
}
}
} |
package org.apache.wicket.osgi;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.wicket.util.string.Strings;
import org.junit.Assert;
import org.junit.Test;
public class OsgiClashingPackagesTest extends Assert
{
@Test
public void collectProjectPackages() throws IOException
{
char pathSeparator = System.getProperty("path.separator").charAt(0);
String classpath = System.getProperty("java.class.path");
String[] dependencies = Strings.split(classpath, pathSeparator);
// packageName -> projects containing a package with this name
Map<String, List<Project>> projectBuckets = new HashMap<String, List<Project>>();
for (String dependency : dependencies)
{
// process only wicket-xyz.jar
if (dependency.contains("wicket-") && dependency.endsWith(".jar"))
{
JarFile jarFile = new JarFile(dependency);
try
{
String projectName = Strings.afterLast(dependency, '/');
Project project = new Project(projectName, jarFile);
project.addTo(projectBuckets);
} finally {
jarFile.close();
}
}
}
Set<Entry<String, List<Project>>> entrySet = projectBuckets.entrySet();
for (Entry<String, List<Project>> entry : entrySet) {
List<Project> projects = entry.getValue();
if (projects.size() > 1) {
fail(entry);
}
}
}
private void fail(Entry<String, List<Project>> entry) {
StringBuilder builder = new StringBuilder();
String packageName = entry.getKey();
builder.append("Package '").append(packageName).append("' has files in two or more modules: ");
for (Project conflict : entry.getValue()) {
builder.append(conflict.getName()).append(", ");
}
try
{
builder.append("\nResources:\n");
Enumeration<URL> resources = getClass().getClassLoader().getResources(packageName);
while (resources.hasMoreElements())
{
URL resource = resources.nextElement();
builder.append("\n\t").append(resource.toExternalForm());
}
} catch (IOException e)
{
e.printStackTrace();
}
fail(builder.toString());
}
private static class Project {
// a set with all package names in a dependency
private final Set<String> packagesWithContent = new TreeSet<String>();
// the name of the dependency
private final String name;
public Project(String name, JarFile jarFile) {
this.name = name;
collectPackageNames(jarFile);
}
/**
* Adds this project to as a value in the global map that contains 'packageName -> List[Project]'
* @param projectBuckets
* the global map
*/
public void addTo(Map<String, List<Project>> projectBuckets) {
for (String packageWithContent : packagesWithContent) {
if (!projectBuckets.containsKey(packageWithContent)) {
projectBuckets.put(packageWithContent, new ArrayList<OsgiClashingPackagesTest.Project>());
}
projectBuckets.get(packageWithContent).add(this);
}
}
/**
* Collects the names of all packages in this JarFile
* @param jarFile
* the jar file to analyze
*/
private void collectPackageNames(final JarFile jarFile)
{
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String entryName = jarEntry.getName();
if (shouldCollect(entryName))
{
String packageName = Strings.beforeLast(entryName, '/');
packagesWithContent.add(packageName);
}
}
}
public String getName() {
return name;
}
@Override
public String toString()
{
return "Project{" +
"name='" + name + '\'' +
'}';
}
private boolean shouldCollect(final String entryName)
{
if (
// all modules have META-INF {MANIFEST.MF, Maven stuff, ..}
entryName.startsWith("META-INF/") ||
// ignore Wicket's IInitializer conf files
(entryName.startsWith("wicket") && entryName.endsWith(".properties"))
)
{
return false;
}
return true;
}
}
} |
package jolie.net;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import jolie.Interpreter;
import jolie.lang.Constants;
import jolie.lang.NativeType;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.http.Method;
import jolie.net.http.MultiPartFormDataParser;
import jolie.net.ports.Interface;
import jolie.net.protocols.CommProtocol;
import jolie.runtime.ByteArray;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.OperationTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import jolie.util.LocationParser;
import jolie.xml.XmlUtils;
import jolie.js.JsUtils;
import joliex.gwt.client.JolieService;
import joliex.gwt.server.JolieGWTConverter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* HTTP protocol implementation
* @author Fabrizio Montesi
* 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes
*/
public class HttpProtocol extends CommProtocol
{
private static final int DEFAULT_STATUS_CODE = 200;
private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303;
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; // default content type per RFC 2616#7.2.1
private static final String DEFAULT_FORMAT = "xml";
private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >();
private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >();
static {
locationRequiredStatusCodes.add( 301 );
locationRequiredStatusCodes.add( 302 );
locationRequiredStatusCodes.add( 303 );
locationRequiredStatusCodes.add( 307 );
locationRequiredStatusCodes.add( 308 );
}
static {
// Initialise the HTTP Status code map.
statusCodeDescriptions.put( 100,"Continue" );
statusCodeDescriptions.put( 101,"Switching Protocols" );
statusCodeDescriptions.put( 102,"Processing" );
statusCodeDescriptions.put( 200,"OK" );
statusCodeDescriptions.put( 201,"Created" );
statusCodeDescriptions.put( 202,"Accepted" );
statusCodeDescriptions.put( 203,"Non-Authoritative Information" );
statusCodeDescriptions.put( 204,"No Content" );
statusCodeDescriptions.put( 205,"Reset Content" );
statusCodeDescriptions.put( 206,"Partial Content" );
statusCodeDescriptions.put( 207,"Multi-Status" );
statusCodeDescriptions.put( 208,"Already Reported" );
statusCodeDescriptions.put( 226,"IM Used" );
statusCodeDescriptions.put( 300,"Multiple Choices" );
statusCodeDescriptions.put( 301,"Moved Permanently" );
statusCodeDescriptions.put( 302,"Found" );
statusCodeDescriptions.put( 303,"See Other" );
statusCodeDescriptions.put( 304,"Not Modified" );
statusCodeDescriptions.put( 305,"Use Proxy" );
statusCodeDescriptions.put( 306,"Reserved" );
statusCodeDescriptions.put( 307,"Temporary Redirect" );
statusCodeDescriptions.put( 308,"Permanent Redirect" );
statusCodeDescriptions.put( 400,"Bad Request" );
statusCodeDescriptions.put( 401,"Unauthorized" );
statusCodeDescriptions.put( 402,"Payment Required" );
statusCodeDescriptions.put( 403,"Forbidden" );
statusCodeDescriptions.put( 404,"Not Found" );
statusCodeDescriptions.put( 405,"Method Not Allowed" );
statusCodeDescriptions.put( 406,"Not Acceptable" );
statusCodeDescriptions.put( 407,"Proxy Authentication Required" );
statusCodeDescriptions.put( 408,"Request Timeout" );
statusCodeDescriptions.put( 409,"Conflict" );
statusCodeDescriptions.put( 410,"Gone" );
statusCodeDescriptions.put( 411,"Length Required" );
statusCodeDescriptions.put( 412,"Precondition Failed" );
statusCodeDescriptions.put( 413,"Request Entity Too Large" );
statusCodeDescriptions.put( 414,"Request-URI Too Long" );
statusCodeDescriptions.put( 415,"Unsupported Media Type" );
statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" );
statusCodeDescriptions.put( 417,"Expectation Failed" );
statusCodeDescriptions.put( 422,"Unprocessable Entity" );
statusCodeDescriptions.put( 423,"Locked" );
statusCodeDescriptions.put( 424,"Failed Dependency" );
statusCodeDescriptions.put( 426,"Upgrade Required" );
statusCodeDescriptions.put( 427,"Unassigned" );
statusCodeDescriptions.put( 428,"Precondition Required" );
statusCodeDescriptions.put( 429,"Too Many Requests" );
statusCodeDescriptions.put( 430,"Unassigned" );
statusCodeDescriptions.put( 431,"Request Header Fields Too Large" );
statusCodeDescriptions.put( 500,"Internal Server Error" );
statusCodeDescriptions.put( 501,"Not Implemented" );
statusCodeDescriptions.put( 502,"Bad Gateway" );
statusCodeDescriptions.put( 503,"Service Unavailable" );
statusCodeDescriptions.put( 504,"Gateway Timeout" );
statusCodeDescriptions.put( 505,"HTTP Version Not Supported" );
statusCodeDescriptions.put( 507,"Insufficient Storage" );
statusCodeDescriptions.put( 508,"Loop Detected" );
statusCodeDescriptions.put( 509,"Unassigned" );
statusCodeDescriptions.put( 510,"Not Extended" );
statusCodeDescriptions.put( 511,"Network Authentication Required" );
}
private static class Parameters {
private static final String KEEP_ALIVE = "keepAlive";
private static final String DEBUG = "debug";
private static final String COOKIES = "cookies";
private static final String METHOD = "method";
private static final String ALIAS = "alias";
private static final String MULTIPART_HEADERS = "multipartHeaders";
private static final String CONCURRENT = "concurrent";
private static final String USER_AGENT = "userAgent";
private static final String HOST = "host";
private static final String HEADERS = "headers";
private static final String ADD_HEADERS = "addHeader";
private static final String STATUS_CODE = "statusCode";
private static final String REDIRECT = "redirect";
private static final String DEFAULT_OPERATION = "default";
private static final String COMPRESSION = "compression";
private static final String COMPRESSION_TYPES = "compressionTypes";
private static final String REQUEST_COMPRESSION = "requestCompression";
private static final String FORMAT = "format";
private static final String JSON_ENCODING = "json_encoding";
private static final String CHARSET = "charset";
private static final String CONTENT_TYPE = "contentType";
private static final String CONTENT_TRANSFER_ENCODING = "contentTransferEncoding";
private static final String CONTENT_DISPOSITION = "contentDisposition";
private static final String DROP_URI_PATH = "dropURIPath";
private static class MultiPartHeaders {
private static final String FILENAME = "filename";
}
}
private static class Headers {
private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID";
}
private String inputId = null;
private final Transformer transformer;
private final DocumentBuilderFactory docBuilderFactory;
private final DocumentBuilder docBuilder;
private final URI uri;
private final boolean inInputPort;
private MultiPartFormDataParser multiPartFormDataParser = null;
public String name()
{
return "http";
}
public boolean isThreadSafe()
{
return checkBooleanParameter( Parameters.CONCURRENT );
}
public HttpProtocol(
VariablePath configurationPath,
URI uri,
boolean inInputPort,
TransformerFactory transformerFactory,
DocumentBuilderFactory docBuilderFactory,
DocumentBuilder docBuilder
)
throws TransformerConfigurationException
{
super( configurationPath );
this.uri = uri;
this.inInputPort = inInputPort;
this.transformer = transformerFactory.newTransformer();
this.docBuilderFactory = docBuilderFactory;
this.docBuilder = docBuilder;
transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
}
private void valueToDocument(
Value value,
Node node,
Document doc
)
{
node.appendChild( doc.createTextNode( value.strValue() ) );
Element currentElement;
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
currentElement = doc.createElement( entry.getKey() );
node.appendChild( currentElement );
Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
currentElement.setAttribute(
attrEntry.getKey(),
attrEntry.getValue().first().strValue()
);
}
}
valueToDocument( val, currentElement, doc );
}
}
}
}
public String getMultipartHeaderForPart( String operationName, String partName )
{
if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) {
Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS );
if ( v.hasChildren( partName ) ) {
v = v.getFirstChild( partName );
if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) {
v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME );
return v.strValue();
}
}
}
return null;
}
private final static String BOUNDARY = "----Jol13H77p77Bound4r155";
private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
String domain;
StringBuilder cookieSB = new StringBuilder();
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "";
if ( domain.isEmpty() || hostname.endsWith( domain ) ) {
cookieSB
.append( entry.getKey() )
.append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( ";" );
}
}
}
if ( cookieSB.length() > 0 ) {
headerBuilder
.append( "Cookie: " )
.append( cookieSB )
.append( HttpUtils.CRLF );
}
}
}
private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder )
{
Value cookieParam = null;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) {
cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookieParam = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookieParam != null ) {
Value cookieConfig;
for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) {
cookieConfig = entry.getValue().first();
if ( message.value().hasChildren( cookieConfig.strValue() ) ) {
headerBuilder
.append( "Set-Cookie: " )
.append( entry.getKey() ).append( '=' )
.append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() )
.append( "; expires=" )
.append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" )
.append( "; domain=" )
.append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" )
.append( "; path=" )
.append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" );
if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) {
headerBuilder.append( "; secure" );
}
headerBuilder.append( HttpUtils.CRLF );
}
}
}
}
private String encoding = null;
private String responseFormat = null;
private boolean headRequest = false;
private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( value.children().isEmpty() == false ) {
headerBuilder.append( '?' );
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
for( Value v : entry.getValue() ) {
headerBuilder
.append( entry.getKey() )
.append( '=' )
.append( URLEncoder.encode( v.strValue(), charset ) )
.append( '&' );
}
}
}
}
private void send_appendJsonQueryString( CommMessage message, String charset, StringBuilder headerBuilder )
throws IOException
{
if ( message.value().hasChildren() == false ) {
headerBuilder.append( "?=" );
JsUtils.valueToJsonString( message.value(), getSendType( message ), headerBuilder );
}
}
private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder )
throws IOException
{
int offset = 0;
ArrayList<String> aliasKeys = new ArrayList<String>();
String currStrValue;
String currKey;
StringBuilder result = new StringBuilder( alias );
Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias );
while( m.find() ) {
if ( m.group( 1 ) == null ) { // We have to use URLEncoder
currKey = alias.substring( m.start() + 2, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = URLEncoder.encode( value.strValue(), charset );
} else {
currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset );
aliasKeys.add( currKey );
}
} else { // We have to insert the string raw
currKey = alias.substring( m.start() + 3, m.end() - 1 );
if ( "$".equals( currKey ) ) {
currStrValue = value.strValue();
} else {
currStrValue = value.getFirstChild( currKey ).strValue();
aliasKeys.add( currKey );
}
}
result.replace(
m.start() + offset, m.end() + offset,
currStrValue
);
offset += currStrValue.length() - 3 - currKey.length();
}
// removing used keys
for( int k = 0; k < aliasKeys.size(); k++ ) {
value.children().remove( aliasKeys.get( k ) );
}
headerBuilder.append( result );
}
private String send_getFormat()
{
String format = DEFAULT_FORMAT;
if ( inInputPort && responseFormat != null ) {
format = responseFormat;
responseFormat = null;
} else if ( hasParameter( Parameters.FORMAT ) ) {
format = getStringParameter( Parameters.FORMAT );
}
return format;
}
private static class EncodedContent {
private ByteArray content = null;
private String contentType = DEFAULT_CONTENT_TYPE;
private String contentDisposition = "";
}
private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format )
throws IOException
{
EncodedContent ret = new EncodedContent();
if ( inInputPort == false && method == Method.GET ) {
// We are building a GET request
return ret;
}
if ( "xml".equals( format ) ) {
ret.contentType = "text/xml";
Document doc = docBuilder.newDocument();
Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") );
doc.appendChild( root );
if ( message.isFault() ) {
Element faultElement = doc.createElement( message.fault().faultName() );
root.appendChild( faultElement );
valueToDocument( message.fault().value(), faultElement, doc );
} else {
valueToDocument( message.value(), root, doc );
}
Source src = new DOMSource( doc );
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
Result dest = new StreamResult( tmpStream );
try {
transformer.transform( src, dest );
} catch( TransformerException e ) {
throw new IOException( e );
}
ret.content = new ByteArray( tmpStream.toString().getBytes( charset ) );
} else if ( "binary".equals( format ) ) {
if ( message.value().isByteArray() ) {
ret.content = (ByteArray) message.value().valueObject();
ret.contentType = "application/octet-stream";
}
} else if ( "html".equals( format ) ) {
ret.contentType = "text/html";
if ( message.isFault() ) {
StringBuilder builder = new StringBuilder();
builder.append( "<html><head><title>" );
builder.append( message.fault().faultName() );
builder.append( "</title></head><body>" );
builder.append( message.fault().value().strValue() );
builder.append( "</body></html>" );
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
}
} else if ( "multipart/form-data".equals( format ) ) {
ret.contentType = "multipart/form-data; boundary=" + BOUNDARY;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
StringBuilder builder = new StringBuilder();
for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
builder.append( "--" ).append( BOUNDARY ).append( HttpUtils.CRLF );
builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' );
boolean isBinary = false;
if ( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) {
Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS );
if ( specOpParam.hasChildren( "partName" ) ) {
ValueVector partNames = specOpParam.getChildren( "partName" );
for( int p = 0; p < partNames.size(); p++ ) {
if ( partNames.get( p ).hasChildren( "part" ) ) {
if ( partNames.get( p ).getFirstChild( "part" ).strValue().equals( entry.getKey() ) ) {
isBinary = true;
if ( partNames.get( p ).hasChildren( "filename" ) ) {
builder.append( "; filename=\"" ).append( partNames.get( p ).getFirstChild( "filename" ).strValue() ).append( "\"" );
}
if ( partNames.get( p ).hasChildren( "contentType" ) ) {
builder.append( HttpUtils.CRLF ).append( "Content-Type:" ).append( partNames.get( p ).getFirstChild( "contentType" ).strValue() );
}
}
}
}
}
}
builder.append( HttpUtils.CRLF ).append( HttpUtils.CRLF );
if ( isBinary ) {
bStream.write( builder.toString().getBytes( charset ) );
bStream.write( entry.getValue().first().byteArrayValue().getBytes() );
builder.delete( 0, builder.length() - 1 );
builder.append( HttpUtils.CRLF );
} else {
builder.append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF );
}
}
}
builder.append( "--" + BOUNDARY + "--" );
bStream.write( builder.toString().getBytes( charset ));
ret.content = new ByteArray( bStream.toByteArray() );
} else if ( "x-www-form-urlencoded".equals( format ) ) {
ret.contentType = "application/x-www-form-urlencoded";
Iterator< Entry< String, ValueVector > > it =
message.value().children().entrySet().iterator();
StringBuilder builder = new StringBuilder();
if ( message.isFault() ) {
builder.append( "faultName=" );
builder.append( URLEncoder.encode( message.fault().faultName(), HttpUtils.URL_DECODER_ENC ) );
builder.append( "&data=" );
builder.append( URLEncoder.encode( message.fault().value().strValue(), HttpUtils.URL_DECODER_ENC ) );
} else {
Entry< String, ValueVector > entry;
while( it.hasNext() ) {
entry = it.next();
builder.append( entry.getKey() )
.append( "=" )
.append( URLEncoder.encode( entry.getValue().first().strValue(), HttpUtils.URL_DECODER_ENC ) );
if ( it.hasNext() ) {
builder.append( '&' );
}
}
}
ret.content = new ByteArray( builder.toString().getBytes( charset ) );
} else if ( "text/x-gwt-rpc".equals( format ) ) {
ret.contentType = "text/x-gwt-rpc";
try {
if ( message.isFault() ) {
ret.content = new ByteArray(
RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset )
);
} else {
joliex.gwt.client.Value v = new joliex.gwt.client.Value();
JolieGWTConverter.jolieToGwtValue( message.value(), v );
ret.content = new ByteArray(
RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset )
);
}
} catch( SerializationException e ) {
throw new IOException( e );
}
} else if ( "json".equals( format ) ) {
ret.contentType = "application/json";
StringBuilder jsonStringBuilder = new StringBuilder();
if ( message.isFault() ) {
Value error = message.value().getFirstChild( "error" );
error.getFirstChild( "code" ).setValue( -32000 );
error.getFirstChild( "message" ).setValue( message.fault().faultName() );
error.getChildren( "data" ).set( 0, message.fault().value() );
}
JsUtils.valueToJsonString( message.value(), getSendType( message ), jsonStringBuilder );
ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) );
} else if ( "raw".equals( format ) ) {
if ( message.isFault() ) {
ret.content = new ByteArray( message.fault().value().strValue().getBytes( charset ) );
} else {
ret.content = new ByteArray( message.value().strValue().getBytes( charset ) );
}
}
return ret;
}
private boolean isLocationNeeded( int statusCode )
{
return locationRequiredStatusCodes.contains( statusCode );
}
private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder )
{
int statusCode = DEFAULT_STATUS_CODE;
String statusDescription = null;
if( hasParameter( Parameters.STATUS_CODE ) ) {
statusCode = getIntParameter( Parameters.STATUS_CODE );
if ( !statusCodeDescriptions.containsKey( statusCode ) ) {
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which is not in the HTTP specifications."
);
statusDescription = "Internal Server Error";
} else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) {
// if statusCode is a redirection code, location parameter is needed
Interpreter.getInstance().logWarning( "HTTP protocol for operation " +
message.operationName() +
" is sending a message with status code " +
statusCode +
", which expects a redirect parameter but the latter is not set."
);
}
} else if ( hasParameter( Parameters.REDIRECT ) ) {
statusCode = DEFAULT_REDIRECTION_STATUS_CODE;
}
if ( statusDescription == null ) {
statusDescription = statusCodeDescriptions.get( statusCode );
}
headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + HttpUtils.CRLF );
// if redirect has been set, the redirect location parameter is set
if ( hasParameter( Parameters.REDIRECT ) ) {
headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + HttpUtils.CRLF );
}
send_appendSetCookieHeader( message, headerBuilder );
headerBuilder.append( "Server: Jolie" ).append( HttpUtils.CRLF );
StringBuilder cacheControlHeader = new StringBuilder();
if ( hasParameter( "cacheControl" ) ) {
Value cacheControl = getParameterFirstValue( "cacheControl" );
if ( cacheControl.hasChildren( "maxAge" ) ) {
cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() );
}
}
if ( cacheControlHeader.length() > 0 ) {
headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( HttpUtils.CRLF );
}
}
private void send_appendRequestMethod( Method method, StringBuilder headerBuilder )
{
headerBuilder.append( method.id() );
}
private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
if ( uri.getPath() == null || uri.getPath().isEmpty() || checkBooleanParameter( Parameters.DROP_URI_PATH, false ) ) {
headerBuilder.append( '/' );
} else {
if ( uri.getPath().charAt( 0 ) != '/' ) {
headerBuilder.append( '/' );
}
headerBuilder.append( uri.getPath() );
}
if ( hasOperationSpecificParameter( message.operationName(), Parameters.ALIAS ) ) {
String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS );
send_appendParsedAlias( alias, message.value(), charset, headerBuilder );
} else {
headerBuilder.append( message.operationName() );
}
if ( method == Method.GET ) {
boolean jsonFormat = false;
if ( getParameterFirstValue( Parameters.METHOD ).hasChildren( "queryFormat" ) ) {
if ( getParameterFirstValue( Parameters.METHOD ).getFirstChild( "queryFormat" ).strValue().equals( "json" ) ) {
jsonFormat = true;
send_appendJsonQueryString( message, charset, headerBuilder );
}
}
if ( !jsonFormat ) {
send_appendQuerystring( message.value(), charset, headerBuilder );
}
}
}
private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder )
{
if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) {
Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() );
//String realm = v.getFirstChild( "realm" ).strValue();
String userpass =
v.getFirstChild( "userid" ).strValue() + ":" +
v.getFirstChild( "password" ).strValue();
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
userpass = encoder.encode( userpass.getBytes() );
headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( HttpUtils.CRLF );
}
}
private void send_appendHeader( CommMessage message, StringBuilder headerBuilder )
{
Value v = getParameterFirstValue( Parameters.ADD_HEADERS );
if ( v != null ) {
if ( v.hasChildren("header") ) {
for( Value head : v.getChildren("header") ) {
String header =
head.strValue() + ": " +
head.getFirstChild( "value" ).strValue();
headerBuilder.append( header ).append( HttpUtils.CRLF );
}
}
}
}
private Method send_getRequestMethod( CommMessage message )
throws IOException
{
Method method =
hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ?
Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() )
: hasParameter( Parameters.METHOD ) ?
Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() )
:
Method.POST;
return method;
}
private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset )
throws IOException
{
send_appendRequestMethod( method, headerBuilder );
headerBuilder.append( ' ' );
send_appendRequestPath( message, method, headerBuilder, charset );
headerBuilder.append( " HTTP/1.1" + HttpUtils.CRLF );
headerBuilder.append( "Host: " + uri.getHost() + HttpUtils.CRLF );
send_appendCookies( message, uri.getHost(), headerBuilder );
send_appendAuthorizationHeader( message, headerBuilder );
if ( checkBooleanParameter( Parameters.COMPRESSION, true ) ) {
String requestCompression = getStringParameter( Parameters.REQUEST_COMPRESSION );
if ( requestCompression.equals( "gzip" ) || requestCompression.equals( "deflate" ) ) {
encoding = requestCompression;
headerBuilder.append( "Accept-Encoding: " + encoding + HttpUtils.CRLF );
} else {
headerBuilder.append( "Accept-Encoding: gzip, deflate" + HttpUtils.CRLF );
}
}
send_appendHeader( message, headerBuilder );
}
private void send_appendGenericHeaders(
CommMessage message,
EncodedContent encodedContent,
String charset,
StringBuilder headerBuilder
)
throws IOException
{
if ( checkBooleanParameter( Parameters.KEEP_ALIVE, true ) == false || channel().toBeClosed() ) {
channel().setToBeClosed( true );
headerBuilder.append( "Connection: close" + HttpUtils.CRLF );
}
if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) {
headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( HttpUtils.CRLF );
}
if ( encodedContent.content != null ) {
String contentType = getStringParameter( Parameters.CONTENT_TYPE );
if ( contentType.length() > 0 ) {
encodedContent.contentType = contentType;
}
encodedContent.contentType = encodedContent.contentType.toLowerCase();
headerBuilder.append( "Content-Type: " + encodedContent.contentType );
if ( charset != null ) {
headerBuilder.append( "; charset=" + charset.toLowerCase() );
}
headerBuilder.append( HttpUtils.CRLF );
String transferEncoding = getStringParameter( Parameters.CONTENT_TRANSFER_ENCODING );
if ( transferEncoding.length() > 0 ) {
headerBuilder.append( "Content-Transfer-Encoding: " + transferEncoding + HttpUtils.CRLF );
}
String contentDisposition = getStringParameter( Parameters.CONTENT_DISPOSITION );
if ( contentDisposition.length() > 0 ) {
encodedContent.contentDisposition = contentDisposition;
headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + HttpUtils.CRLF );
}
boolean compression = encoding != null && checkBooleanParameter( Parameters.COMPRESSION, true );
String compressionTypes = getStringParameter(
Parameters.COMPRESSION_TYPES,
"text/html text/css text/plain text/xml text/x-js application/json application/javascript"
).toLowerCase();
if ( compression && !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) {
compression = false;
}
if ( compression ) {
encodedContent.content = HttpUtils.encode( encoding, encodedContent.content, headerBuilder );
}
headerBuilder.append( "Content-Length: " + (encodedContent.content.size()) + HttpUtils.CRLF ); //headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + HttpUtils.CRLF );
} else {
headerBuilder.append( "Content-Length: 0" + HttpUtils.CRLF );
}
}
private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent, String charset )
throws IOException
{
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Sending:\n" );
debugSB.append( header );
if (
getParameterVector( Parameters.DEBUG ).first().getFirstChild( "showContent" ).intValue() > 0
&& encodedContent.content != null
) {
debugSB.append( encodedContent.content.toString( charset ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
}
private void send_internal( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
Method method = send_getRequestMethod( message );
String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET ), null );
String format = send_getFormat();
EncodedContent encodedContent = send_encodeContent( message, method, charset, format );
StringBuilder headerBuilder = new StringBuilder();
if ( inInputPort ) {
// We're responding to a request
send_appendResponseHeaders( message, headerBuilder );
} else {
// We're sending a notification or a solicit
send_appendRequestHeaders( message, method, headerBuilder, charset );
}
send_appendGenericHeaders( message, encodedContent, charset, headerBuilder );
headerBuilder.append( HttpUtils.CRLF );
send_logDebugInfo( headerBuilder, encodedContent, charset );
inputId = message.operationName();
ostream.write( headerBuilder.toString().getBytes( charset ) );
if ( encodedContent.content != null && !headRequest ) {
ostream.write( encodedContent.content.getBytes() );
}
headRequest = false;
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
try {
send_internal( ostream, message, istream );
} catch ( IOException e ) {
if ( inInputPort ) {
HttpUtils.errorGenerator( ostream, e );
}
throw e;
}
}
private void parseXML( HttpMessage message, Value value, String charset )
throws IOException
{
try {
if ( message.size() > 0 ) {
DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
src.setEncoding( charset );
Document doc = builder.parse( src );
XmlUtils.documentToValue( doc, value );
}
} catch( ParserConfigurationException pce ) {
throw new IOException( pce );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private static void parseJson( HttpMessage message, Value value, boolean strictEncoding, String charset )
throws IOException
{
JsUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ), charset ), value, strictEncoding );
}
private static void parseForm( HttpMessage message, Value value, String charset )
throws IOException
{
String line = new String( message.content(), charset );
String[] pair;
for( String item : line.split( "&" ) ) {
pair = item.split( "=", 2 );
if ( pair.length != 2 ) {
throw new IOException( "Item " + item + " not in x-www-form-urlencoded" );
}
value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], HttpUtils.URL_DECODER_ENC ) );
}
}
private void parseMultiPartFormData( HttpMessage message, Value value, String charset )
throws IOException
{
multiPartFormDataParser = new MultiPartFormDataParser( message, value, charset );
multiPartFormDataParser.parse();
}
private static String parseGWTRPC( HttpMessage message, Value value, String charset )
throws IOException
{
RPCRequest request = RPC.decodeRequest( new String( message.content(), charset ) );
String operationName = (String)request.getParameters()[0];
joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1];
JolieGWTConverter.gwtToJolieValue( requestValue, value );
return operationName;
}
private void recv_checkForSetCookie( HttpMessage message, Value value )
throws IOException
{
if ( hasParameter( Parameters.COOKIES ) ) {
String type;
Value cookies = getParameterFirstValue( Parameters.COOKIES );
Value cookieConfig;
Value v;
for( HttpMessage.Cookie cookie : message.setCookies() ) {
if ( cookies.hasChildren( cookie.name() ) ) {
cookieConfig = cookies.getFirstChild( cookie.name() );
if ( cookieConfig.isString() ) {
v = value.getFirstChild( cookieConfig.strValue() );
type =
cookieConfig.hasChildren( "type" ) ?
cookieConfig.getFirstChild( "type" ).strValue()
:
"string";
recv_assignCookieValue( cookie.value(), v, type );
}
}
/*currValue = Value.create();
currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() );
currValue.getNewChild( "path" ).setValue( cookie.path() );
currValue.getNewChild( "name" ).setValue( cookie.name() );
currValue.getNewChild( "value" ).setValue( cookie.value() );
currValue.getNewChild( "domain" ).setValue( cookie.domain() );
currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) );
cookieVec.add( currValue );*/
}
}
}
private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword )
throws IOException
{
NativeType type = NativeType.fromString( typeKeyword );
if ( NativeType.INT == type ) {
try {
value.setValue( new Integer( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.LONG == type ) {
try {
value.setValue( new Long( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.STRING == type ) {
value.setValue( cookieValue );
} else if ( NativeType.DOUBLE == type ) {
try {
value.setValue( new Double( cookieValue ) );
} catch( NumberFormatException e ) {
throw new IOException( e );
}
} else if ( NativeType.BOOL == type ) {
value.setValue( Boolean.valueOf( cookieValue ) );
} else {
value.setValue( cookieValue );
}
}
private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value cookies = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) {
cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES );
} else if ( hasParameter( Parameters.COOKIES ) ) {
cookies = getParameterFirstValue( Parameters.COOKIES );
}
if ( cookies != null ) {
Value v;
String type;
for( Entry< String, String > entry : message.cookies().entrySet() ) {
if ( cookies.hasChildren( entry.getKey() ) ) {
Value cookieConfig = cookies.getFirstChild( entry.getKey() );
if ( cookieConfig.isString() ) {
v = decodedMessage.value.getFirstChild( cookieConfig.strValue() );
if ( cookieConfig.hasChildren( "type" ) ) {
type = cookieConfig.getFirstChild( "type" ).strValue();
} else {
type = "string";
}
recv_assignCookieValue( entry.getValue(), v, type );
}
}
}
}
}
private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
Value headers = null;
if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) {
headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS );
} else if ( hasParameter( Parameters.HEADERS ) ) {
headers = getParameterFirstValue( Parameters.HEADERS );
}
if ( headers != null ) {
for( String headerName : headers.children().keySet() ) {
String headerAlias = headers.getFirstChild( headerName ).strValue();
headerName = headerName.replace( "_", "-" );
decodedMessage.value.getFirstChild( headerAlias ).setValue( message.getPropertyOrEmptyString( headerName ) );
}
}
}
private static void recv_parseQueryString( HttpMessage message, Value value )
{
Map< String, Integer > indexes = new HashMap< String, Integer >();
String queryString = message.requestPath() == null ? "" : message.requestPath();
String[] kv = queryString.split( "\\?" );
Integer index;
if ( kv.length > 1 ) {
queryString = kv[1];
String[] params = queryString.split( "&" );
for( String param : params ) {
kv = param.split( "=", 2 );
if ( kv.length > 1 ) {
index = indexes.get( kv[0] );
if ( index == null ) {
index = 0;
indexes.put( kv[0], index );
}
value.getChildren( kv[0] ).get( index ).setValue( kv[1] );
indexes.put( kv[0], index + 1 );
}
}
}
}
/*
* Prints debug information about a received message
*/
private void recv_logDebugInfo( HttpMessage message, String charset )
throws IOException
{
StringBuilder debugSB = new StringBuilder();
debugSB.append( "[HTTP debug] Receiving:\n" );
debugSB.append( "HTTP Code: " + message.statusCode() + "\n" );
debugSB.append( "Resource: " + message.requestPath() + "\n" );
debugSB.append( "--> Header properties\n" );
for( Entry< String, String > entry : message.properties() ) {
debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' );
}
for( HttpMessage.Cookie cookie : message.setCookies() ) {
debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' );
}
for( Entry< String, String > entry : message.cookies().entrySet() ) {
debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' );
}
if (
getParameterFirstValue( Parameters.DEBUG ).getFirstChild( "showContent" ).intValue() > 0
&& message.size() > 0
) {
debugSB.append( "--> Message content\n" );
debugSB.append( new String( message.content(), charset ) );
}
Interpreter.getInstance().logInfo( debugSB.toString() );
}
private void recv_parseRequestFormat( HttpMessage message, String type )
throws IOException
{
responseFormat = null;
if ( "text/xml".equals( type ) ) {
responseFormat = "xml";
} else if ( "text/x-gwt-rpc".equals( type ) ) {
responseFormat = "text/x-gwt-rpc";
} else if ( "application/json".equals( type ) ) {
responseFormat = "json";
}
}
private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String type, String charset )
throws IOException
{
if ( "text/html".equals( type ) ) {
decodedMessage.value.setValue( new String( message.content(), charset ) );
} else if ( "application/x-www-form-urlencoded".equals( type ) ) {
parseForm( message, decodedMessage.value, charset );
} else if ( "text/xml".equals( type ) || type.contains( "xml" ) ) {
parseXML( message, decodedMessage.value, charset );
} else if ( "text/x-gwt-rpc".equals( type ) ) {
decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value, charset );
} else if ( "multipart/form-data".equals( type ) ) {
parseMultiPartFormData( message, decodedMessage.value, charset );
} else if (
"application/octet-stream".equals( type ) || type.startsWith( "image/" )
|| "application/zip".equals( type )
) {
decodedMessage.value.setValue( new ByteArray( message.content() ) );
} else if ( "application/json".equals( type ) || type.contains( "json" ) ) {
boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" );
parseJson( message, decodedMessage.value, strictEncoding, charset );
} else {
decodedMessage.value.setValue( new String( message.content(), charset ) );
}
}
private String getDefaultOperation( HttpMessage.Type t )
{
if ( hasParameter( Parameters.DEFAULT_OPERATION ) ) {
Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION );
String method = HttpUtils.httpMessageTypeToString( t );
if ( method == null || dParam.hasChildren( method ) == false ) {
return dParam.strValue();
} else {
return dParam.getFirstChild( method ).strValue();
}
}
return null;
}
private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage )
{
if ( decodedMessage.operationName == null ) {
String requestPath = message.requestPath().split( "\\?" )[0];
decodedMessage.operationName = requestPath;
Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName );
if ( m.find() ) {
int resourceStart = m.end();
if ( m.find() ) {
decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() );
decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() );
}
}
}
if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) {
String defaultOpId = getDefaultOperation( message.type() );
if ( defaultOpId != null ) {
Value body = decodedMessage.value;
decodedMessage.value = Value.create();
decodedMessage.value.getChildren( "data" ).add( body );
decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName );
if ( message.userAgent() != null ) {
decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
Value cookies = decodedMessage.value.getFirstChild( "cookies" );
for( Entry< String, String > cookie : message.cookies().entrySet() ) {
cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() );
}
decodedMessage.operationName = defaultOpId;
}
}
}
private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage )
{
if ( multiPartFormDataParser != null ) {
String target;
for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) {
if ( entry.getValue().filename() != null ) {
target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() );
if ( target != null ) {
decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() );
}
}
}
multiPartFormDataParser = null;
}
}
private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage )
throws IOException
{
recv_checkForCookies( message, decodedMessage );
recv_checkForGenericHeader( message, decodedMessage );
recv_checkForMultiPartHeaders( decodedMessage );
if (
message.userAgent() != null &&
hasParameter( Parameters.USER_AGENT )
) {
getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() );
}
if ( getParameterVector( Parameters.HOST ) != null ) {
getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) );
}
}
private static class DecodedMessage {
private String operationName = null;
private Value value = Value.create();
private String resourcePath = "/";
private long id = CommMessage.GENERIC_ID;
}
private void recv_checkForStatusCode( HttpMessage message )
{
if ( hasParameter( Parameters.STATUS_CODE ) ) {
getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() );
}
}
private CommMessage recv_internal( InputStream istream, OutputStream ostream )
throws IOException
{
HttpMessage message = new HttpParser( istream ).parse();
String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET ), message );
CommMessage retVal = null;
DecodedMessage decodedMessage = new DecodedMessage();
HttpUtils.recv_checkForChannelClosing( message, channel() );
if ( checkBooleanParameter( Parameters.DEBUG ) ) {
recv_logDebugInfo( message, charset );
}
recv_checkForStatusCode( message );
encoding = message.getProperty( "accept-encoding" );
String contentType = DEFAULT_CONTENT_TYPE;
if ( message.getProperty( "content-type" ) != null ) {
contentType = message.getProperty( "content-type" ).split( ";" )[0].toLowerCase();
}
recv_parseRequestFormat( message, contentType );
if ( message.size() > 0 ) {
recv_parseMessage( message, decodedMessage, contentType, charset );
}
headRequest = inInputPort && message.isHead();
if ( checkBooleanParameter( Parameters.CONCURRENT ) ) {
String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID );
if ( messageId != null ) {
try {
decodedMessage.id = Long.parseLong( messageId );
} catch( NumberFormatException e ) {}
}
}
if ( message.isResponse() ) {
recv_checkForSetCookie( message, decodedMessage.value );
retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null );
} else if ( message.isError() == false ) {
if ( message.isGet() ) {
recv_parseQueryString( message, decodedMessage.value );
}
recv_checkReceivingOperation( message, decodedMessage );
recv_checkForMessageProperties( message, decodedMessage );
retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null );
}
if ( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null
&& (channel().parentPort().getInterface().containsOperation( retVal.operationName() )
|| channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null) ) {
try {
// The message is for this service
boolean hasInput = false;
OneWayTypeDescription oneWayTypeDescription = null;
if ( channel().parentInputPort() != null ) {
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asOneWayTypeDescription();
hasInput = true;
}
}
if ( !hasInput ) {
Interface iface = channel().parentPort().getInterface();
oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() );
}
if ( oneWayTypeDescription != null ) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast( retVal.value() );
} else {
hasInput = false;
RequestResponseTypeDescription rrTypeDescription = null;
if ( channel().parentInputPort() != null ) {
if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) {
rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asRequestResponseTypeDescription();
hasInput = true;
}
}
if ( !hasInput ) {
Interface iface = channel().parentPort().getInterface();
rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() );
}
if ( retVal.isFault() ) {
Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() );
if ( faultType != null ) {
faultType.cast( retVal.value() );
}
} else {
if ( message.isResponse() ) {
rrTypeDescription.responseType().cast( retVal.value() );
} else {
rrTypeDescription.requestType().cast( retVal.value() );
}
}
}
} catch( TypeCastingException e ) {
// TODO: do something here?
}
}
return retVal;
}
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
try {
return recv_internal( istream, ostream );
} catch ( IOException e ) {
if ( inInputPort && channel().isOpen() ) {
HttpUtils.errorGenerator( ostream, e );
}
throw e;
}
}
private Type getSendType( CommMessage message )
throws IOException
{
Type ret = null;
if ( channel().parentPort() == null ) {
throw new IOException( "Could not retrieve communication port for HTTP protocol" );
}
OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH );
if ( opDesc == null ) {
return null;
}
if ( opDesc.asOneWayTypeDescription() != null ) {
if ( message.isFault() ) {
ret = Type.UNDEFINED;
} else {
OneWayTypeDescription ow = opDesc.asOneWayTypeDescription();
ret = ow.requestType();
}
} else if ( opDesc.asRequestResponseTypeDescription() != null ) {
RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription();
if ( message.isFault() ) {
ret = rr.getFaultType( message.fault().faultName() );
if ( ret == null ) {
ret = Type.UNDEFINED;
}
} else {
ret = ( inInputPort ) ? rr.responseType() : rr.requestType();
}
}
return ret;
}
} |
package jolie.net;
import com.ibm.wsdl.extensions.schema.SchemaImpl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.Detail;
import javax.xml.soap.DetailEntry;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import jolie.lang.Constants;
import jolie.Interpreter;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import jolie.runtime.VariablePath;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.sun.xml.xsom.XSAttributeDecl;
import com.sun.xml.xsom.XSAttributeUse;
import com.sun.xml.xsom.XSComplexType;
import com.sun.xml.xsom.XSContentType;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSModelGroup;
import com.sun.xml.xsom.XSModelGroupDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.XSTerm;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.parser.XSOMParser;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.Service;
import javax.wsdl.Types;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import jolie.net.http.HttpMessage;
import jolie.net.http.HttpParser;
import jolie.net.http.HttpUtils;
import jolie.net.ports.Interface;
import jolie.net.protocols.SequentialCommProtocol;
import jolie.net.soap.WSDLCache;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.runtime.typing.TypeCastingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
/** Implements the SOAP over HTTP protocol.
*
* @author Fabrizio Montesi
*
* 2006 - Fabrizio Montesi, Mauro Silvagni: first write.
* 2007 - Fabrizio Montesi: rewritten from scratch, exploiting new JOLIE capabilities.
* 2008 - Fabrizio Montesi: initial support for schemas.
* 2008 - Claudio Guidi: initial support for WS-Addressing.
* 2010 - Fabrizio Montesi: initial support for WSDL documents.
*
*/
public class SoapProtocol extends SequentialCommProtocol
{
private String inputId = null;
private final Interpreter interpreter;
private final MessageFactory messageFactory;
private XSSchemaSet schemaSet = null;
private URI uri = null;
private Definition wsdlDefinition = null;
private Port wsdlPort = null;
private final TransformerFactory transformerFactory;
private final Map< String, String > namespacePrefixMap = new HashMap< String, String > ();
private boolean received = false;
private final static String CRLF = new String( new char[] { 13, 10 } );
public String name()
{
return "soap";
}
public SoapProtocol( VariablePath configurationPath, URI uri, Interpreter interpreter )
throws SOAPException
{
super( configurationPath );
this.uri = uri;
this.transformerFactory = TransformerFactory.newInstance();
this.interpreter = interpreter;
this.messageFactory = MessageFactory.newInstance( SOAPConstants.SOAP_1_1_PROTOCOL );
}
private void parseSchemaElement( Definition definition, Element element, XSOMParser schemaParser )
throws IOException
{
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty( "indent", "yes" );
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult( sw );
DOMSource source = new DOMSource( element );
transformer.transform( source, result );
InputSource schemaSource = new InputSource( new StringReader( sw.toString() ) );
schemaSource.setSystemId( definition.getDocumentBaseURI() );
schemaParser.parse( schemaSource );
} catch( TransformerConfigurationException e ) {
throw new IOException( e );
} catch( TransformerException e ) {
throw new IOException( e );
} catch( SAXException e ) {
throw new IOException( e );
}
}
private void parseWSDLTypes( XSOMParser schemaParser )
throws IOException
{
Definition definition = getWSDLDefinition();
if ( definition != null ) {
Types types = definition.getTypes();
if ( types != null ) {
List< ExtensibilityElement > list = types.getExtensibilityElements();
for( ExtensibilityElement element : list ) {
if ( element instanceof SchemaImpl ) {
Element schemaElement = ((SchemaImpl)element).getElement();
Map< String, String > namespaces = definition.getNamespaces();
for( Entry< String, String > entry : namespaces.entrySet() ) {
if ( entry.getKey().equals( "xmlns" ) || entry.getKey().trim().isEmpty() ) {
continue;
}
if ( schemaElement.getAttribute( "xmlns:" + entry.getKey() ).isEmpty() ) {
schemaElement.setAttribute( "xmlns:" + entry.getKey(), entry.getValue() );
}
}
parseSchemaElement( definition, schemaElement, schemaParser );
}
}
}
}
}
private XSSchemaSet getSchemaSet()
throws IOException, SAXException
{
if ( schemaSet == null ) {
XSOMParser schemaParser = new XSOMParser();
ValueVector vec = getParameterVector( "schema" );
if ( vec.size() > 0 ) {
for( Value v : vec ) {
schemaParser.parse( new File( v.strValue() ) );
}
}
parseWSDLTypes( schemaParser );
schemaSet = schemaParser.getResult();
String nsPrefix = "jolie";
int i = 1;
for( XSSchema schema : schemaSet.getSchemas() ) {
if ( !schema.getTargetNamespace().equals( XMLConstants.W3C_XML_SCHEMA_NS_URI ) ) {
namespacePrefixMap.put( schema.getTargetNamespace(), nsPrefix + i++ );
}
}
}
return schemaSet;
}
private boolean convertAttributes()
{
boolean ret = false;
if ( hasParameter( "convertAttributes" ) ) {
ret = checkBooleanParameter( "convertAttributes" );
}
return ret;
}
private void initNamespacePrefixes( SOAPElement element )
throws SOAPException
{
for( Entry< String, String > entry : namespacePrefixMap.entrySet() ) {
element.addNamespaceDeclaration( entry.getValue(), entry.getKey() );
}
}
private void valueToSOAPElement(
Value value,
SOAPElement element,
SOAPEnvelope soapEnvelope
)
throws SOAPException
{
String type = "any";
if ( value.isDefined() ) {
if ( value.isInt() ) {
type = "int";
} else if ( value.isString() ) {
type = "string";
} else if ( value.isDouble() ) {
type = "double";
}
element.addAttribute( soapEnvelope.createName( "type", "xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI ), "xsd:" + type );
element.addTextNode( value.strValue() );
}
if ( convertAttributes() ) {
Map< String, ValueVector > attrs = getAttributesOrNull( value );
if ( attrs != null ) {
for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) {
element.addAttribute(
soapEnvelope.createName( attrEntry.getKey() ),
attrEntry.getValue().first().strValue()
);
}
}
}
for( Entry< String, ValueVector > entry : value.children().entrySet() ) {
if ( !entry.getKey().startsWith( "@" ) ) {
for( Value val : entry.getValue() ) {
valueToSOAPElement(
val,
element.addChildElement( entry.getKey() ),
soapEnvelope
);
}
}
}
}
private static Map< String, ValueVector > getAttributesOrNull( Value value )
{
Map< String, ValueVector > ret = null;
ValueVector vec = value.children().get( Constants.Predefined.ATTRIBUTES.token().content() );
if ( vec != null && vec.size() > 0 )
ret = vec.first().children();
if ( ret == null )
ret = new HashMap< String, ValueVector >();
return ret;
}
private static Value getAttributeOrNull( Value value, String attrName )
{
Value ret = null;
Map< String, ValueVector > attrs = getAttributesOrNull( value );
if ( attrs != null ) {
ValueVector vec = attrs.get( attrName );
if ( vec != null && vec.size() > 0 )
ret = vec.first();
}
return ret;
}
private static Value getAttribute( Value value, String attrName )
{
return value.getChildren( Constants.Predefined.ATTRIBUTES.token().content() ).first()
.getChildren( attrName ).first();
}
private String getPrefixOrNull( XSAttributeDecl decl )
{
if ( decl.getOwnerSchema().attributeFormDefault() )
return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() );
return null;
}
private String getPrefixOrNull( XSElementDecl decl )
{
if ( decl.getOwnerSchema().elementFormDefault() )
return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() );
return null;
}
private String getPrefix( XSElementDecl decl )
{
return namespacePrefixMap.get( decl.getOwnerSchema().getTargetNamespace() );
}
private void valueToTypedSOAP(
Value value,
XSElementDecl xsDecl,
SOAPElement element,
SOAPEnvelope envelope,
boolean first // Ugly fix! This should be removed as soon as another option arises.
)
throws SOAPException
{
XSType type = xsDecl.getType();
if ( type.isSimpleType() ) {
element.addTextNode( value.strValue() );
} else if ( type.isComplexType() ) {
String name;
Value currValue;
XSComplexType complexT = type.asComplexType();
// Iterate over attributes
Collection< ? extends XSAttributeUse > attributeUses = complexT.getAttributeUses();
for( XSAttributeUse attrUse : attributeUses ) {
name = attrUse.getDecl().getName();
if ( (currValue=getAttributeOrNull( value, name )) != null ) {
QName attrName = envelope.createQName( name, getPrefixOrNull( attrUse.getDecl() ) );
element.addAttribute( attrName, currValue.strValue() );
}
}
XSParticle particle;
XSContentType contentT;
contentT = complexT.getContentType();
if ( contentT.asSimpleType() != null ) {
element.addTextNode( value.strValue() );
} else if ( (particle=contentT.asParticle()) != null ) {
XSTerm term = particle.getTerm();
// XSElementDecl elementDecl;
XSModelGroupDecl modelGroupDecl;
XSModelGroup modelGroup = null;
//int size = value.children().size();
//if ( particle.getMinOccurs()
// It's a simple element, repeated some times
/*if ( (elementDecl=term.asElementDecl()) != null ) {
} else */if ( (modelGroupDecl=term.asModelGroupDecl()) != null ) {
modelGroup = modelGroupDecl.getModelGroup();
} else if ( term.isModelGroup() )
modelGroup = term.asModelGroup();
if ( modelGroup != null ) {
XSModelGroup.Compositor compositor = modelGroup.getCompositor();
if ( compositor.equals( XSModelGroup.SEQUENCE ) ) {
XSParticle[] children = modelGroup.getChildren();
XSTerm currTerm;
XSElementDecl currElementDecl;
Value v;
ValueVector vec;
String prefix;
for( int i = 0; i < children.length; i++ ) {
currTerm = children[i].getTerm();
if ( currTerm.isElementDecl() ) {
currElementDecl = currTerm.asElementDecl();
name = currElementDecl.getName();
prefix = ( first ) ? getPrefix( currElementDecl ) : getPrefixOrNull( currElementDecl );
SOAPElement childElement = null;
if ( (vec=value.children().get( name )) != null ) {
int k = 0;
while( vec.size() > 0 && (children[i].getMaxOccurs() > k || children[i].getMaxOccurs() == XSParticle.UNBOUNDED ) ) {
if ( prefix == null ) {
childElement = element.addChildElement( name );
} else {
childElement = element.addChildElement( name, prefix );
}
v = vec.remove( 0 );
valueToTypedSOAP(
v,
currElementDecl,
childElement,
envelope,
false );
k++;
}
} else if ( children[i].getMinOccurs() > 0 ) {
// TODO improve this error message.
throw new SOAPException( "Invalid variable structure: expected " + name );
}
}
}
}
}
}
}
}
private Definition getWSDLDefinition()
throws IOException
{
if ( wsdlDefinition == null && hasParameter( "wsdl" ) ) {
String wsdlUrl = getStringParameter( "wsdl" );
try {
wsdlDefinition = WSDLCache.getInstance().get( wsdlUrl );
} catch( WSDLException e ) {
throw new IOException( e );
}
}
return wsdlDefinition;
}
private String getSoapActionForOperation( String operationName )
throws IOException
{
String soapAction = null;
Port port = getWSDLPort();
if ( port != null ) {
BindingOperation bindingOperation = port.getBinding().getBindingOperation( operationName, null, null );
for( ExtensibilityElement element : (List< ExtensibilityElement >)bindingOperation.getExtensibilityElements() ) {
if ( element instanceof SOAPOperation ) {
soapAction = ((SOAPOperation)element).getSoapActionURI();
}
}
}
if ( soapAction == null ) {
soapAction = getStringParameter( "namespace" ) + "/" + operationName;
}
return soapAction;
}
private Port getWSDLPort()
throws IOException
{
Port port = wsdlPort;
if ( port == null && hasParameter( "wsdl" ) && getParameterFirstValue( "wsdl" ).hasChildren( "port" ) ) {
String portName = getParameterFirstValue( "wsdl" ).getFirstChild( "port" ).strValue();
Definition definition = getWSDLDefinition();
if ( definition != null ) {
Map< QName, Service > services = definition.getServices();
Iterator< Entry< QName, Service > > it = services.entrySet().iterator();
while( port == null && it.hasNext() ) {
port = it.next().getValue().getPort( portName );
}
}
if ( port != null ) {
wsdlPort = port;
}
}
return port;
}
private String getOutputMessageRootElementName( String operationName )
throws IOException
{
String elementName = operationName + (( received ) ? "Response" : "");
Port port = getWSDLPort();
if ( port != null ) {
try {
Operation operation = port.getBinding().getPortType().getOperation( operationName, null, null );
Part part = null;
if ( received ) {
// We are sending a response
part = ((Entry<String,Part>) operation.getOutput().getMessage().getParts().entrySet().iterator().next()).getValue();
} else {
// We are sending a request
part = ((Entry<String,Part>) operation.getInput().getMessage().getParts().entrySet().iterator().next()).getValue();
}
elementName = part.getElementName().getLocalPart();
} catch( Exception e ) {}
}
return elementName;
}
private String getOutputMessageNamespace( String operationName )
throws IOException
{
String messageNamespace = "";
Port port = getWSDLPort();
if ( port == null ) {
if ( hasParameter( "namespace" ) ) {
messageNamespace = getStringParameter( "namespace" );
}
} else {
Operation operation = port.getBinding().getPortType().getOperation( operationName, null, null );
if ( operation != null ) {
Map< String, Part > parts = operation.getOutput().getMessage().getParts();
if ( parts.size() > 0 ) {
Part part = parts.entrySet().iterator().next().getValue();
if ( part.getElementName() == null ) {
messageNamespace = operation.getOutput().getMessage().getQName().getNamespaceURI();
} else {
messageNamespace = part.getElementName().getNamespaceURI();
}
}
}
}
return messageNamespace;
}
public void send( OutputStream ostream, CommMessage message, InputStream istream )
throws IOException
{
try {
inputId = message.operationName();
String messageNamespace = getOutputMessageNamespace( message.operationName() );
if ( received ) {
// We're responding to a request
inputId += "Response";
}
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
if ( checkBooleanParameter( "wsAddressing" ) ) {
SOAPHeader soapHeader = soapEnvelope.getHeader();
// WS-Addressing namespace
soapHeader.addNamespaceDeclaration( "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
// Message ID
Name messageIdName = soapEnvelope.createName( "MessageID", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
SOAPHeaderElement messageIdElement = soapHeader.addHeaderElement(messageIdName);
if ( received ) {
// TODO: remove this after we implement a mechanism for being sure message.id() is the one received before.
messageIdElement.setValue( "uuid:1" );
} else {
messageIdElement.setValue( "uuid:" + message.id() );
}
// Action element
Name actionName = soapEnvelope.createName( "Action", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
SOAPHeaderElement actionElement = soapHeader.addHeaderElement( actionName );
/* TODO: the action element could be specified within the parameter.
* Perhaps wsAddressing.action ?
* We could also allow for giving a prefix or a suffix to the operation name,
* like wsAddressing.action.prefix, wsAddressing.action.suffix
*/
actionElement.setValue( message.operationName() );
// From element
Name fromName = soapEnvelope.createName( "From", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
SOAPHeaderElement fromElement = soapHeader.addHeaderElement( fromName );
Name addressName = soapEnvelope.createName( "Address", "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
SOAPElement addressElement = fromElement.addChildElement( addressName );
addressElement.setValue( "http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous" );
// To element
}
if ( message.isFault() ) {
FaultException f = message.fault();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultCode( soapEnvelope.createQName( "Server", soapEnvelope.getPrefix() ) );
soapFault.setFaultString( f.getMessage() );
Detail detail = soapFault.addDetail();
DetailEntry de = detail.addDetailEntry( soapEnvelope.createName( f.faultName(), null, messageNamespace ) );
valueToSOAPElement( f.value(), de, soapEnvelope );
} else {
XSSchemaSet sSet = getSchemaSet();
XSElementDecl elementDecl;
String messageRootElementName = getOutputMessageRootElementName( message.operationName() );
if ( sSet == null ||
(elementDecl=sSet.getElementDecl( messageNamespace, messageRootElementName )) == null
) {
Name operationName = null;
if ( messageNamespace.isEmpty() ) {
operationName = soapEnvelope.createName( messageRootElementName );
} else {
operationName = soapEnvelope.createName( messageRootElementName, "jolieMessage", messageNamespace );
}
SOAPBodyElement opBody = soapBody.addBodyElement( operationName );
valueToSOAPElement( message.value(), opBody, soapEnvelope );
} else {
initNamespacePrefixes( soapEnvelope );
boolean wrapped = true;
Value vStyle = getParameterVector( "style" ).first();
if ( "document".equals( vStyle.strValue() ) ) {
wrapped = ( vStyle.getChildren( "wrapped" ).first().intValue() > 0 );
}
SOAPElement opBody = soapBody;
if ( wrapped ) {
opBody = soapBody.addBodyElement(
soapEnvelope.createName( messageRootElementName, namespacePrefixMap.get( elementDecl.getOwnerSchema().getTargetNamespace() ), null )
);
}
valueToTypedSOAP( message.value(), elementDecl, opBody, soapEnvelope, !wrapped );
}
}
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
soapMessage.writeTo( tmpStream );
String soapString = CRLF + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
new String( tmpStream.toByteArray() );
String messageString = "";
String soapAction = null;
if ( received ) {
// We're responding to a request
messageString += "HTTP/1.1 200 OK" + CRLF;
received = false;
} else {
// We're sending a notification or a solicit
String path = uri.getPath(); // TODO: fix this to consider resourcePaths
if ( path == null || path.length() == 0 ) {
path = "*";
}
messageString += "POST " + path + " HTTP/1.1" + CRLF;
messageString += "Host: " + uri.getHost() + CRLF;
/*soapAction =
"SOAPAction: \"" + messageNamespace + "/" + message.operationName() + '\"' + CRLF;*/
soapAction = "SOAPAction: \"" + getSoapActionForOperation( message.operationName() ) + '\"' + CRLF;
}
if ( getParameterVector( "keepAlive" ).first().intValue() != 1 ) {
channel().setToBeClosed( true );
messageString += "Connection: close" + CRLF;
}
//messageString += "Content-Type: application/soap+xml; charset=\"utf-8\"\n";
messageString += "Content-Type: text/xml; charset=\"utf-8\"" + CRLF;
messageString += "Content-Length: " + soapString.length() + CRLF;
if ( soapAction != null ) {
messageString += soapAction;
}
messageString += soapString + CRLF;
if ( getParameterVector( "debug" ).first().intValue() > 0 ) {
interpreter.logInfo( "[SOAP debug] Sending:\n" + tmpStream.toString() );
}
inputId = message.operationName();
Writer writer = new OutputStreamWriter( ostream );
writer.write( messageString );
writer.flush();
} catch( SOAPException se ) {
throw new IOException( se );
} catch( SAXException saxe ) {
throw new IOException( saxe );
}
}
private void xmlNodeToValue( Value value, Node node )
{
String type = "xsd:string";
Node currNode;
// Set attributes
NamedNodeMap attributes = node.getAttributes();
if ( attributes != null ) {
for( int i = 0; i < attributes.getLength(); i++ ) {
currNode = attributes.item( i );
if ( "type".equals( currNode.getNodeName() ) == false && convertAttributes() ) {
getAttribute( value, currNode.getNodeName() ).setValue( currNode.getNodeValue() );
} else {
type = currNode.getNodeValue();
}
}
}
// Set children
NodeList list = node.getChildNodes();
Value childValue;
for( int i = 0; i < list.getLength(); i++ ) {
currNode = list.item( i );
switch( currNode.getNodeType() ) {
case Node.ELEMENT_NODE:
childValue = value.getNewChild( currNode.getLocalName() );
xmlNodeToValue( childValue, currNode );
break;
case Node.TEXT_NODE:
value.setValue( currNode.getNodeValue() );
break;
}
}
if ( "xsd:int".equals( type ) ) {
value.setValue( value.intValue() );
} else if ( "xsd:double".equals( type ) ) {
value.setValue( value.doubleValue() );
}
}
private static Element getFirstElement( Node node )
{
NodeList nodes = node.getChildNodes();
for( int i = 0; i < nodes.getLength(); i++ ) {
if ( nodes.item( i ).getNodeType() == Node.ELEMENT_NODE ) {
return (Element)nodes.item( i );
}
}
return null;
}
/*private Schema getRecvMessageValidationSchema()
throws IOException
{
List< Source > sources = new ArrayList< Source >();
Definition definition = getWSDLDefinition();
if ( definition != null ) {
Types types = definition.getTypes();
if ( types != null ) {
List< ExtensibilityElement > list = types.getExtensibilityElements();
for( ExtensibilityElement element : list ) {
if ( element instanceof SchemaImpl ) {
sources.add( new DOMSource( ((SchemaImpl)element).getElement() ) );
}
}
}
}
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI );
try {
return schemaFactory.newSchema( sources.toArray( new Source[sources.size()] ) );
} catch( SAXException e ) {
throw new IOException( e );
}
}*/
public CommMessage recv( InputStream istream, OutputStream ostream )
throws IOException
{
HttpParser parser = new HttpParser( istream );
HttpMessage message = parser.parse();
HttpUtils.recv_checkForChannelClosing( message, channel() );
CommMessage retVal = null;
String messageId = message.getPropertyOrEmptyString( "soapaction" );
FaultException fault = null;
Value value = Value.create();
try {
if ( message.content() != null && message.content().length > 0 ) {
SOAPMessage soapMessage = messageFactory.createMessage();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
/*Schema messageSchema = getRecvMessageValidationSchema();
if ( messageSchema != null ) {
factory.setIgnoringElementContentWhitespace( true );
factory.setSchema( messageSchema );
}*/
factory.setNamespaceAware( true );
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) );
Document doc = builder.parse( src );
DOMSource dom = new DOMSource( doc );
soapMessage.getSOAPPart().setContent( dom );
if ( getParameterVector( "debug" ).first().intValue() > 0 ) {
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
soapMessage.writeTo( tmpStream );
interpreter.logInfo( "[SOAP debug] Receiving:\n" + tmpStream.toString() );
}
SOAPFault soapFault = soapMessage.getSOAPBody().getFault();
if ( soapFault == null ) {
Element soapValueElement = getFirstElement( soapMessage.getSOAPBody() );
messageId = soapValueElement.getLocalName();
xmlNodeToValue( value, soapValueElement );
ValueVector schemaPaths = getParameterVector( "schema" );
if ( schemaPaths.size() > 0 ) {
List< Source > sources = new LinkedList< Source >();
Value schemaPath;
for( int i = 0; i < schemaPaths.size(); i++ ) {
schemaPath = schemaPaths.get( i );
if ( schemaPath.getChildren( "validate" ).first().intValue() > 0 )
sources.add( new StreamSource( new File( schemaPaths.get( i ).strValue() ) ) );
}
if ( !sources.isEmpty() ) {
Schema schema =
SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI )
.newSchema( sources.toArray( new Source[0] ) );
schema.newValidator().validate( new DOMSource( soapMessage.getSOAPBody().getFirstChild() ) );
}
}
} else {
String faultName = "UnknownFault";
Value faultValue = Value.create();
Detail d = soapFault.getDetail();
if ( d != null ) {
Node n = d.getFirstChild();
if ( n != null ) {
faultName = n.getLocalName();
xmlNodeToValue(
faultValue, n
);
} else {
faultValue.setValue( soapFault.getFaultString() );
}
}
fault = new FaultException( faultName, faultValue );
}
}
String resourcePath = recv_getResourcePath( message );
if ( message.isResponse() ) {
if ( fault != null && message.httpCode() == 500 ) {
fault = new FaultException( "InternalServerError", "" );
}
retVal = new CommMessage( CommMessage.GENERIC_ID, inputId, resourcePath, value, fault );
} else if ( !message.isError() ) {
if ( messageId.isEmpty() ) {
throw new IOException( "Received SOAP Message without a specified operation" );
}
retVal = new CommMessage( CommMessage.GENERIC_ID, messageId, resourcePath, value, fault );
}
} catch( SOAPException e ) {
throw new IOException( e );
} catch( ParserConfigurationException e ) {
throw new IOException( e );
} catch( SAXException e ) {
//TODO support resourcePath
retVal = new CommMessage( CommMessage.GENERIC_ID, messageId, "/", value, new FaultException( "TypeMismatch", e ) );
}
received = true;
if ( "/".equals( retVal.resourcePath() )
&& channel().parentPort().getInterface().containsOperation( retVal.operationName() ) ) {
try {
// The message is for this service
Interface iface = channel().parentPort().getInterface();
OneWayTypeDescription oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() );
if ( oneWayTypeDescription != null && message.isResponse() == false ) {
// We are receiving a One-Way message
oneWayTypeDescription.requestType().cast( retVal.value() );
} else {
RequestResponseTypeDescription rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() );
if ( retVal.isFault() ) {
Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() );
if ( faultType != null ) {
faultType.cast( retVal.value() );
}
} else {
if ( message.isResponse() ) {
rrTypeDescription.responseType().cast( retVal.value() );
} else {
rrTypeDescription.requestType().cast( retVal.value() );
}
}
}
} catch( TypeCastingException e ) {
// TODO: do something here?
}
}
return retVal;
}
private String recv_getResourcePath( HttpMessage message )
{
String ret = "/";
if ( checkBooleanParameter( "interpretResource" ) ) {
ret = message.requestPath();
}
return ret;
}
} |
package jlibs.nio.filters;
import jlibs.nio.Input;
import jlibs.nio.InputFilter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Santhosh Kumar Tekuri
*/
public class LimitInput extends InputFilter{
private long limit;
public LimitInput(Input peer, long limit){
super(peer);
this.limit = limit;
}
@Override
protected boolean readReady(){
return false;
}
@Override
public long available(){
return peer.available();
}
@Override
public long read(ByteBuffer[] dsts, int offset, int length) throws IOException{
if(peer.available()>limit)
throw InputLimitExceeded.INSTANCE;
long read = peer.read(dsts, offset, length);
if(read>0){
if(read>limit)
throw InputLimitExceeded.INSTANCE;
limit -= read;
}
return read;
}
@Override
public int read(ByteBuffer dst) throws IOException{
if(peer.available()>limit)
throw InputLimitExceeded.INSTANCE;
int read = peer.read(dst);
if(read>0){
if(read>limit)
throw InputLimitExceeded.INSTANCE;
limit -= read;
}
return read;
}
@Override
public long transferTo(long position, long count, FileChannel target) throws IOException{
long transferred = peer.transferTo(position, count, target);
if(transferred>limit)
throw InputLimitExceeded.INSTANCE;
limit -= transferred;
return transferred;
}
@Override
public boolean eof(){
return peer.eof();
}
} |
package com.ajaybhatia.mausam;
import java.io.IOException;
import java.text.DecimalFormat;
import net.aksingh.java.api.owm.CurrentWeatherData;
import net.aksingh.java.api.owm.CurrentWeatherData.Main;
import net.aksingh.java.api.owm.OpenWeatherMap;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class SecondActivity extends Activity {
private String city;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
city = intent.getStringExtra(MainActivity.CITY);
WeatherTask task = new WeatherTask();
task.execute(new String[]{city});
}
private class WeatherTask extends AsyncTask<String, Void, Main> {
protected Main doInBackground(String... params) {
Main main = null;
try {
OpenWeatherMap owm = new OpenWeatherMap("");
CurrentWeatherData cwd = owm.currentWeatherByCityName(params[0]);
main = cwd.getMainData_Object();
} catch (IOException | JSONException ex) {}
return main;
}
@Override
protected void onPostExecute(Main result) {
super.onPostExecute(result);
TextView tvCity = (TextView)findViewById(R.id.tvCityResult);
TextView tvTemp = (TextView)findViewById(R.id.tvTempResult);
tvCity.setText(city);
tvTemp.setText(String.valueOf(toCelcius(result.getMaxTemperature())) + (char)0x00B0 + "C");
}
}
private float toCelcius(float fahrenheit) {
DecimalFormat df = new DecimalFormat("0.00");
return Float.parseFloat(df.format((fahrenheit - 32) * 5.0f/9.0f));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package com.cellwars.client;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ClientConnection {
private Socket client;
private DataOutputStream out;
private DataInputStream in;
public boolean connect(String ip) {
try {
client = new Socket(ip, 3000);
OutputStream outToServer = client.getOutputStream();
out = new DataOutputStream(outToServer);
InputStream inFromServer = client.getInputStream();
in = new DataInputStream(inFromServer);
return true;
} catch (IOException e) {
return false;
}
}
public void sendMessage(String ... message) throws IOException {
String joinedMessage = Stream.of(message)
.collect(Collectors.joining(":"));
out.writeUTF(joinedMessage);
}
public String getMessage() throws IOException {
return in.readUTF();
}
} |
package com.ecyrd.jspwiki.plugin;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.providers.ProviderException;
import org.apache.log4j.Category;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Builds an index of all pages.
* <P>Parameters</P>
* <UL>
* <LI>itemsPerLine: How many items should be allowed per line before break.
* <LI>include: Include only these pages.
* <LI>exclude: Exclude with this pattern.
* </UL>
*
* @author Alain Ravet
* @author Janne Jalkanen
* @since 1.9.9
*/
public class IndexPlugin implements WikiPlugin
{
protected static Category log = Category.getInstance(IndexPlugin.class);
public static final String INITIALS_COLOR = "red" ;
private static final int DEFAULT_ITEMS_PER_LINE = 4 ;
private static final String PARAM_ITEMS_PER_LINE = "itemsPerLine";
private static final String PARAM_INCLUDE = "include";
private static final String PARAM_EXCLUDE = "exclude";
private int m_currentNofPagesOnLine = 0;
private int m_itemsPerLine;
protected String m_previousPageFirstLetter = "";
protected StringWriter m_bodyPart = new StringWriter();
protected StringWriter m_headerPart = new StringWriter();
private Pattern m_includePattern;
private Pattern m_excludePattern;
public String execute( WikiContext i_context , Map i_params )
throws PluginException
{
// Parse arguments and create patterns.
PatternCompiler compiler = new GlobCompiler();
m_itemsPerLine = TextUtil.parseIntParameter( (String) i_params.get(PARAM_ITEMS_PER_LINE),
DEFAULT_ITEMS_PER_LINE );
try
{
String ptrn = (String) i_params.get(PARAM_INCLUDE);
if( ptrn == null ) ptrn = "*";
m_includePattern = compiler.compile(ptrn);
ptrn = (String) i_params.get(PARAM_EXCLUDE);
if( ptrn == null ) ptrn = "";
m_excludePattern = compiler.compile(ptrn);
}
catch( MalformedPatternException e )
{
throw new PluginException("Illegal pattern detected."); // FIXME, make a proper error.
}
// Get pages, then sort.
final Collection allPages = getAllPagesSortedByName( i_context );
final TranslatorReader linkProcessor = new TranslatorReader( i_context,
new java.io.StringReader ( "" ) );
// Build the page.
buildIndexPageHeaderAndBody( allPages, linkProcessor );
return m_headerPart.toString()
+ "<br>"
+ m_bodyPart.toString();
}
private void buildIndexPageHeaderAndBody ( final Collection i_allPages ,
final TranslatorReader i_linkProcessor )
{
PatternMatcher matcher = new Perl5Matcher();
for( Iterator i = i_allPages.iterator (); i.hasNext ();)
{
WikiPage curPage = (WikiPage) i.next();
if( matcher.matches( curPage.getName(), m_includePattern ) )
{
if( !matcher.matches( curPage.getName(), m_excludePattern ) )
{
++m_currentNofPagesOnLine;
String pageNameFirstLetter = curPage.getName().substring(0,1).toUpperCase();
boolean sameFirstLetterAsPreviousPage = m_previousPageFirstLetter.equals(pageNameFirstLetter);
if( !sameFirstLetterAsPreviousPage )
{
addLetterToIndexHeader( pageNameFirstLetter );
addLetterHeaderWithLine( pageNameFirstLetter );
m_currentNofPagesOnLine = 1;
m_previousPageFirstLetter = pageNameFirstLetter;
}
addPageToIndex( curPage, i_linkProcessor );
breakLineIfTooLong();
}
}
} // for
}
/**
* Gets all pages, then sorts them.
*/
static Collection getAllPagesSortedByName( WikiContext i_context )
{
final WikiEngine engine = i_context.getEngine();
final PageManager pageManager = engine.getPageManager();
if( pageManager == null )
return null;
Collection result = new TreeSet( new Comparator() {
public int compare( Object o1, Object o2 )
{
if( o1 == null || o2 == null ) { return 0; }
WikiPage page1 = (WikiPage)o1,
page2 = (WikiPage)o2;
return page1.getName().compareTo( page2.getName() );
}
});
try
{
Collection allPages = pageManager.getAllPages();
result.addAll( allPages );
}
catch( ProviderException e )
{
log.fatal("PageProvider is unable to list pages: ", e);
}
return result;
}
private void addLetterToIndexHeader( final String i_firstLetter )
{
final boolean noLetterYetInTheIndex = ! "".equals(m_previousPageFirstLetter);
if( noLetterYetInTheIndex )
{
m_headerPart.write(" - " );
}
m_headerPart.write("<A href=\"#" + i_firstLetter + "\">" + i_firstLetter + "</A>" );
}
// FIXME: Should really use <SPAN> instead of <FONT>.
private void addLetterHeaderWithLine( final String i_firstLetter )
{
m_bodyPart.write("<br /><br />" +
"<A name=\"" + i_firstLetter + "\">" +
"<font color="+INITIALS_COLOR+">"+i_firstLetter+"</A></font>" +
"<hr>" );
}
protected void addPageToIndex( WikiPage i_curPage, final TranslatorReader i_linkProcessor )
{
final boolean notFirstPageOnLine = 2 <= m_currentNofPagesOnLine;
if( notFirstPageOnLine )
{
m_bodyPart.write(", ");
}
m_bodyPart.write( i_linkProcessor.makeLink( TranslatorReader.READ,
i_curPage.getName(),
i_curPage.getName () ));
}
protected void breakLineIfTooLong()
{
final boolean limitReached = (m_itemsPerLine == m_currentNofPagesOnLine);
if( limitReached )
{
m_bodyPart.write( "<br />" );
m_currentNofPagesOnLine = 0;
}
}
} |
package com.fedorvlasov.lazylist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.Stack;
import java.util.WeakHashMap;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
fileCache=new FileCache(context);
}
final int stub_id=R.drawable.stub;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
PhotosQueue photosQueue=new PhotosQueue();
public void stopThread()
{
photoLoaderThread.interrupt();
}
//stores list of photos to download
class PhotosQueue
{
private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
//removes all instances of this ImageView
public void Clean(ImageView image)
{
for(int j=0 ;j<photosToLoad.size();){
if(photosToLoad.get(j).imageView==image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while(true)
{
//thread waits until there are any images to load in the queue
if(photosQueue.photosToLoad.size()==0)
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.wait();
}
if(photosQueue.photosToLoad.size()!=0)
{
PhotoToLoad photoToLoad;
synchronized(photosQueue.photosToLoad){
photoToLoad=photosQueue.photosToLoad.pop();
}
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
String tag=imageViews.get(photoToLoad.imageView);
if(tag!=null && tag.equals(photoToLoad.url)){
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if(Thread.interrupted())
break;
}
} catch (InterruptedException e) {
//allow thread to exit
}
}
}
PhotosLoader photoLoaderThread=new PhotosLoader();
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
public void run()
{
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
} |
package com.googlecode.totallylazy;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipSource implements Sources {
final ZipInputStream in;
private ZipSource(InputStream inputStream) {
in = inputStream instanceof ZipInputStream ? Unchecked.<ZipInputStream>cast(inputStream) : new ZipInputStream(inputStream);
}
public static ZipSource zipSource(InputStream inputStream) {
return new ZipSource(inputStream);
}
@Override
public Sequence<Source> sources() {
return Zip.entries(in).map(new Function1<ZipEntry, Source>() {
@Override
public Source call(ZipEntry zipEntry) throws Exception {
return new Source(zipEntry.getName(), new Date(zipEntry.getTime()), new IgnoreCloseInputStream());
}
});
}
@Override
public void close() throws IOException {
in.close();
}
private class IgnoreCloseInputStream extends InputStream {
@Override
public int read() throws IOException {
return in.read();
}
@Override
public int read(byte[] b) throws IOException {
return in.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
}
} |
package com.jme.intersection;
import com.jme.math.Ray;
import com.jme.math.Vector3f;
import com.jme.scene.BoundingBox;
/**
* <code>Intersection</code> provides functional methods for calculating the
* intersection of some objects. All the methods are static to allow for quick
* and easy calls.
* @author Mark Powell
* @version $Id: IntersectionBox.java,v 1.4 2004-03-23 16:06:18 mojomonkey Exp $
*/
public class IntersectionBox {
/**
* EPSILON represents the error buffer used to denote a hit.
*/
public static final double EPSILON = 1e-12;
/**
*
* <code>intersection</code> determines if a ray has intersected a box.
* @param ray the ray to test.
* @param box the box to test.
* @return true if they intersect, false otherwise.
*/
public static boolean intersection(Ray ray, BoundingBox box) {
Vector3f diff = ray.origin.subtract(box.center);
// convert ray to box coordinates
Vector3f kOrigin = new Vector3f(diff.x, diff.y, diff.z);
Vector3f kDirection = new Vector3f(ray.direction.x, ray.direction.y, ray.direction.z);
float[] fT = new float[2];
fT[0] = 0f;
fT[1] = Float.POSITIVE_INFINITY;
float[] extents = { box.xExtent, box.yExtent, box.zExtent };
boolean bIntersects = findIntersection(kOrigin,kDirection,extents,fT);
return bIntersects;
}
/**
*
* <code>intersection</code> compares two static spheres for intersection.
* If any part of the two spheres touch, true is returned, otherwise false
* will return.
* @param box1 the first box to test.
* @param box2 the second box to test.
* @return true if the spheres are intersecting, false otherwise.
*/
public static boolean intersection(
BoundingBox box1,
BoundingBox box2) {
if (box1.center.x + box1.xExtent < box2.center.x - box2.xExtent ||
box1.center.x - box1.xExtent > box2.center.x + box2.xExtent)
return false;
else if (box1.center.y + box1.yExtent < box2.center.y - box2.yExtent ||
box1.center.y - box1.yExtent > box2.center.y + box2.yExtent)
return false;
else if (box1.center.z + box1.zExtent < box2.center.z - box2.zExtent ||
box1.center.z - box1.zExtent > box2.center.z + box2.zExtent)
return false;
else
return true;
}
private static boolean clip(float fDenom, float fNumer, float[] rfT)
{
// Return value is 'true' if line segment intersects the current test
// plane. Otherwise 'false' is returned in which case the line segment
// is entirely clipped.
if ( fDenom > 0.0f ) {
if ( fNumer > fDenom*rfT[1] )
return false;
if ( fNumer > fDenom*rfT[0] )
rfT[0] = fNumer/fDenom;
return true;
} else if ( fDenom < 0.0f ) {
if ( fNumer > fDenom*rfT[0] )
return false;
if ( fNumer > fDenom*rfT[1] )
rfT[1] = fNumer/fDenom;
return true;
} else {
return fNumer <= 0.0;
}
}
private static boolean findIntersection(Vector3f rkOrigin, Vector3f rkDirection, float[] afExtent, float[] rfT) {
float fSaveT0 = rfT[0], fSaveT1 = rfT[1];
boolean bNotEntirelyClipped =
clip(+rkDirection.x,-rkOrigin.x-afExtent[0],rfT) &&
clip(-rkDirection.x,+rkOrigin.x-afExtent[0],rfT) &&
clip(+rkDirection.y,-rkOrigin.y-afExtent[1],rfT) &&
clip(-rkDirection.y,+rkOrigin.y-afExtent[1],rfT) &&
clip(+rkDirection.z,-rkOrigin.z-afExtent[2],rfT) &&
clip(-rkDirection.z,+rkOrigin.z-afExtent[2],rfT);
return bNotEntirelyClipped && ( rfT[0] != fSaveT0 || rfT[1] != fSaveT1 );
}
} |
package com.relteq.sirius.simulator;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
/** Load, manipulate, and run scenarios.
* <p>
* A scenario is a collection of,
* <ul>
* <li> networks (nodes, links, sensors, and signals), </li>
* <li> network connections, </li>
* <li> initial conditions, </li>
* <li> weaving factor profiles, </li>
* <li> split ratio profiles, </li>
* <li> downstream boundary conditions, </li>
* <li> events, </li>
* <li> controllers, </li>
* <li> fundamental diagram profiles, </li>
* <li> path segments, </li>
* <li> decision points, </li>
* <li> routes, </li>
* <li> background demand profiles, and </li>
* <li> OD demand profiles. </li>
* </ul>
* @author Gabriel Gomes
* @version VERSION NUMBER
*/
public final class Scenario extends com.relteq.sirius.jaxb.Scenario {
/** @y.exclude */ protected Clock clock;
/** @y.exclude */ protected String configfilename;
/** @y.exclude */ protected Random random = new Random();
/** @y.exclude */ protected Scenario.UncertaintyType uncertaintyModel;
/** @y.exclude */ protected int numVehicleTypes; // number of vehicle types
/** @y.exclude */ protected boolean global_control_on; // global control switch
/** @y.exclude */ protected double global_demand_knob; // scale factor for all demands
/** @y.exclude */ protected double simdtinseconds; // [sec] simulation time step
/** @y.exclude */ protected double simdtinhours; // [hr] simulation time step
/** @y.exclude */ protected boolean scenariolocked=false; // true when the simulation is running
/** @y.exclude */ protected ControllerSet controllerset = new ControllerSet();
/** @y.exclude */ protected EventSet eventset = new EventSet(); // holds time sorted list of events
/** @y.exclude */ protected static enum ModeType { normal,
warmupFromZero ,
warmupFromIC };
/** @y.exclude */ protected static enum UncertaintyType { uniform,
gaussian }
/** @y.exclude */ protected int numEnsemble;
// protected constructor
/** @y.exclude */
protected Scenario(){}
// populate / reset / validate / update
/** populate methods copy data from the jaxb state to extended objects.
* They do not throw exceptions or report mistakes. Data errors should be
* circumvented and left for the validation to report.
* @throws SiriusException
* @y.exclude
*/
protected void populate() throws SiriusException {
// network list
if(getNetworkList()!=null)
for( com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork() )
((Network) network).populate(this);
// split ratio profile set (must follow network)
if(getSplitRatioProfileSet()!=null)
((SplitRatioProfileSet) getSplitRatioProfileSet()).populate(this);
// boundary capacities (must follow network)
if(getDownstreamBoundaryCapacitySet()!=null)
for( com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile() )
((CapacityProfile) capacityProfile).populate(this);
if(getDemandProfileSet()!=null)
((DemandProfileSet) getDemandProfileSet()).populate(this);
// fundamental diagram profiles
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile) fd).populate(this);
// initial density profile
if(getInitialDensityProfile()!=null)
((InitialDensityProfile) getInitialDensityProfile()).populate(this);
// initialize controllers and events
controllerset.populate(this);
eventset.populate(this);
}
/** Prepare scenario for simulation:
* set the state of the scenario to the initial condition
* sample profiles
* open output files
* @return success A boolean indicating whether the scenario was successfuly reset.
* @throws SiriusException
* @y.exclude
*/
protected boolean reset(Scenario.ModeType simulationMode) throws SiriusException {
// reset the clock
clock.reset();
// reset network
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
((Network)network).reset(simulationMode);
// reset demand profiles
if(getDemandProfileSet()!=null)
((DemandProfileSet)getDemandProfileSet()).reset();
// reset fundamental diagrams
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile)fd).reset();
// reset controllers
global_control_on = true;
controllerset.reset();
// reset events
eventset.reset();
return true;
}
/**
* @throws SiriusException
* @y.exclude
*/
protected void update() throws SiriusException {
// sample profiles .............................
if(getDownstreamBoundaryCapacitySet()!=null)
for(com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile())
((CapacityProfile) capacityProfile).update();
if(getDemandProfileSet()!=null)
((DemandProfileSet)getDemandProfileSet()).update();
if(getSplitRatioProfileSet()!=null)
((SplitRatioProfileSet) getSplitRatioProfileSet()).update();
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fdProfile : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile) fdProfile).update();
// update controllers
if(global_control_on)
controllerset.update();
// update events
eventset.update();
// update the network state......................
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
((Network) network).update();
}
// protected interface
/** Retrieve a network with a given id.
* @param id The string id of the network
* @return The corresponding network if it exists, <code>null</code> otherwise.
*
*/
protected Network getNetworkWithId(String id){
if(getNetworkList()==null)
return null;
if(getNetworkList().getNetwork()==null)
return null;
if(id==null && getNetworkList().getNetwork().size()>1)
return null;
if(id==null && getNetworkList().getNetwork().size()==1)
return (Network) getNetworkList().getNetwork().get(0);
id.replaceAll("\\s","");
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork()){
if(network.getId().equals(id))
return (Network) network;
}
return null;
}
// excluded from API
/** @y.exclude */
public Integer [] getVehicleTypeIndices(com.relteq.sirius.jaxb.VehicleTypeOrder vtypeorder){
Integer [] vehicletypeindex;
// single vehicle types in setting and no vtypeorder, return 0
if(vtypeorder==null && numVehicleTypes==1){
vehicletypeindex = new Integer[numVehicleTypes];
vehicletypeindex[0]=0;
return vehicletypeindex;
}
// multiple vehicle types in setting and no vtypeorder, return 0...n
if(vtypeorder==null && numVehicleTypes>1){
vehicletypeindex = new Integer[numVehicleTypes];
for(int i=0;i<numVehicleTypes;i++)
vehicletypeindex[i] = i;
return vehicletypeindex;
}
// vtypeorder is not null
int numTypesInOrder = vtypeorder.getVehicleType().size();
int i,j;
vehicletypeindex = new Integer[numTypesInOrder];
for(i=0;i<numTypesInOrder;i++)
vehicletypeindex[i] = -1;
if(getSettings()==null)
return vehicletypeindex;
if(getSettings().getVehicleTypes()==null)
return vehicletypeindex;
for(i=0;i<numTypesInOrder;i++){
String vtordername = vtypeorder.getVehicleType().get(i).getName();
List<com.relteq.sirius.jaxb.VehicleType> settingsname = getSettings().getVehicleTypes().getVehicleType();
for(j=0;j<settingsname.size();j++){
if(settingsname.get(j).getName().equals(vtordername)){
vehicletypeindex[i] = j;
break;
}
}
}
return vehicletypeindex;
}
/** @y.exclude */
public boolean validate() {
// validate network
if( getNetworkList()!=null)
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
if(!((Network)network).validate()){
SiriusErrorLog.addErrorMessage("Network validation failure.");
return false;
}
// NOTE: DO THIS ONLY IF IT IS USED. IE DO IT IN THE RUN WITH CORRECT FUNDAMENTAL DIAGRAMS
// validate initial density profile
// if(getInitialDensityProfile()!=null)
// if(!((_InitialDensityProfile) getInitialDensityProfile()).validate()){
// SiriusErrorLog.addErrorMessage("InitialDensityProfile validation failure.");
// return false;
// validate capacity profiles
if(getDownstreamBoundaryCapacitySet()!=null)
for(com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile())
if(!((CapacityProfile)capacityProfile).validate()){
SiriusErrorLog.addErrorMessage("DownstreamBoundaryCapacitySet validation failure.");
return false;
}
// validate demand profiles
if(getDemandProfileSet()!=null)
if(!((DemandProfileSet)getDemandProfileSet()).validate()){
SiriusErrorLog.addErrorMessage("DemandProfileSet validation failure.");
return false;
}
// validate split ratio profiles
if(getSplitRatioProfileSet()!=null)
if(!((SplitRatioProfileSet)getSplitRatioProfileSet()).validate()){
SiriusErrorLog.addErrorMessage("SplitRatioProfileSet validation failure.");
return false;
}
// validate fundamental diagram profiles
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
if(!((FundamentalDiagramProfile)fd).validate()){
SiriusErrorLog.addErrorMessage("FundamentalDiagramProfileSet validation failure.");
return false;
}
// validate controllers
if(!controllerset.validate())
return false;
return true;
}
// API
/** Run the scenario <code>numRepetitions</code> times, save output to text files.
*
* <p> The scenario is reset and run multiple times in sequence. All
* probabilistic quantities are re-sampled between runs. Output files are
* created with a common prefix with the index of the simulation appended to
* the file name.
*
* @param timestart
* @param timeend
* @param outdt
* @param numRepetitions The integer number of simulations to run.
* @param owr_props the output writer properties
* @throws SiriusException
*/
public void run(Double timestart,Double timeend,double outdt,int numRepetitions,Properties owr_props) throws SiriusException{
RunParameters param = new RunParameters(timestart, timeend, outdt, simdtinseconds);
numEnsemble = 1;
run_internal(param,numRepetitions,true,false,owr_props);
}
/** Run the scenario once, return the state trajectory.
* <p> The scenario is reset and run once.
* @return An object with the history of densities and flows for all links in the scenario.
* @throws SiriusException
*/
public SiriusStateTrajectory run(Double timestart,Double timeend,double outdt) throws SiriusException{
RunParameters param = new RunParameters(timestart,timeend,outdt,simdtinseconds);
numEnsemble = 1;
return run_internal(param,1,false,true,null);
}
/** Advance the simulation <i>nsec</i> seconds.
*
* <p> Move the simulation forward <i>nsec</i> seconds and stops.
* Returns <code>true</code> if the operation completes succesfully. Returns <code>false</code>
* if the end of the simulation is reached.
* @param nsec Number of seconds to advance.
* @throws SiriusException
*/
public boolean advanceNSeconds(double nsec) throws SiriusException{
if(!scenariolocked)
throw new SiriusException("Run not initialized. Use initialize_run() first.");
if(!SiriusMath.isintegermultipleof(nsec,simdtinseconds))
throw new SiriusException("nsec (" + nsec + ") must be an interger multiple of simulation dt (" + simdtinseconds + ").");
int nsteps = SiriusMath.round(nsec/simdtinseconds);
return advanceNSteps_internal(ModeType.normal,nsteps,false,false,null,null,-1);
}
/** Save the scenario to XML.
*
* @param filename The name of the configuration file.
* @throws SiriusException
*/
public void saveToXML(String filename) throws SiriusException{
try {
JAXBContext context = JAXBContext.newInstance("com.relteq.sirius.jaxb");
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(this,new FileOutputStream(filename));
} catch( JAXBException je ) {
throw new SiriusException(je.getMessage());
} catch (FileNotFoundException e) {
throw new SiriusException(e.getMessage());
}
}
/** Current simulation time in seconds.
* @return Simulation time in seconds after midnight.
*/
public double getTimeInSeconds() {
if(clock==null)
return Double.NaN;
return clock.getT();
}
/** Time elapsed since the beginning of the simulation in seconds.
* @return Simulation time in seconds after start time.
*/
public double getTimeElapsedInSeconds() {
if(clock==null)
return Double.NaN;
return clock.getTElapsed();
}
/** Current simulation time step.
* @return Integer number of time steps since the start of the simulation.
*/
public int getCurrentTimeStep() {
if(clock==null)
return 0;
return clock.getCurrentstep();
}
/** Total number of time steps that will be simulated, regardless of the simulation mode.
* @return Integer number of time steps to simulate.
*/
public int getTotalTimeStepsToSimulate(){
return clock.getTotalSteps();
}
/** Number of vehicle types included in the scenario.
* @return Integer number of vehicle types
*/
public int getNumVehicleTypes() {
return numVehicleTypes;
}
/** Vehicle type names.
* @return Array of strings with the names of the vehicles types.
*/
public String [] getVehicleTypeNames(){
String [] vehtypenames = new String [numVehicleTypes];
if(getSettings()==null || getSettings().getVehicleTypes()==null)
vehtypenames[0] = Defaults.vehicleType;
else
for(int i=0;i<getSettings().getVehicleTypes().getVehicleType().size();i++)
vehtypenames[i] = getSettings().getVehicleTypes().getVehicleType().get(i).getName();
return vehtypenames;
}
/** Vehicle type weights.
* @return Array of doubles with the weights of the vehicles types.
*/
public Double [] getVehicleTypeWeights(){
Double [] vehtypeweights = new Double [numVehicleTypes];
if(getSettings()==null || getSettings().getVehicleTypes()==null)
vehtypeweights[0] = 1d;
else
for(int i=0;i<getSettings().getVehicleTypes().getVehicleType().size();i++)
vehtypeweights[i] = getSettings().getVehicleTypes().getVehicleType().get(i).getWeight().doubleValue();
return vehtypeweights;
}
/** Vehicle type index from name
* @return integer index of the vehicle type.
*/
public int getVehicleTypeIndex(String name){
String [] vehicleTypeNames = getVehicleTypeNames();
if(vehicleTypeNames==null)
return 0;
if(vehicleTypeNames.length<=1)
return 0;
for(int i=0;i<vehicleTypeNames.length;i++)
if(vehicleTypeNames[i].equals(name))
return i;
return -1;
}
/** Size of the simulation time step in seconds.
* @return Simulation time step in seconds.
*/
public double getSimDtInSeconds() {
return simdtinseconds;
}
/** Size of the simulation time step in hours.
* @return Simulation time step in hours.
*/
public double getSimDtInHours() {
return simdtinhours;
}
/** Start time of the simulation.
* @return Start time in seconds.
*/
public double getTimeStart() {
if(clock==null)
return Double.NaN;
else
return this.clock.getStartTime();
}
/** End time of the simulation.
* @return End time in seconds.
* @return XXX
*/
public double getTimeEnd() {
if(clock==null)
return Double.NaN;
else
return this.clock.getEndTime();
}
/** Get a reference to a controller by its id.
* @param id Id of the controller.
* @return A reference to the controller if it exists, <code>null</code> otherwise.
*/
public Controller getControllerWithId(String id){
if(controllerset==null)
return null;
for(Controller c : controllerset.get_Controllers()){
if(c.id.equals(id))
return c;
}
return null;
}
/** Get a reference to an event by its id.
* @param id Id of the event.
* @return A reference to the event if it exists, <code>null</code> otherwise.
*/
public Event getEventWithId(String id){
if(eventset==null)
return null;
for(Event e : eventset.sortedevents){
if(e.getId().equals(id))
return e;
}
return null;
}
/** Get a reference to a node by its composite id.
*
* @param network_id String id of the network containing the node.
* @param id String id of the node.
* @return Reference to the node if it exists, <code>null</code> otherwise
*/
public Node getNodeWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getNodeWithId(id);
else
return null;
else
return network.getNodeWithId(id);
}
/** Get a reference to a link by its composite id.
*
* @param network_id String id of the network containing the link.
* @param id String id of the link.
* @return Reference to the link if it exists, <code>null</code> otherwise
*/
public Link getLinkWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getLinkWithId(id);
else
return null;
else
return network.getLinkWithId(id);
}
/** Get a reference to a sensor by its composite id.
*
* @param network_id String id of the network containing the sensor.
* @param id String id of the sensor.
* @return Reference to the sensor if it exists, <code>null</code> otherwise
*/
public Sensor getSensorWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSensorWithId(id);
else
return null;
else
return network.getSensorWithId(id);
}
/** Get a reference to a signal by its composite id.
*
* @param network_id String id of the network containing the signal.
* @param id String id of the signal.
* @return Reference to the signal if it exists, <code>null</code> otherwise
*/
public Signal getSignalWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSignalWithId(id);
else
return null;
else
return network.getSignalWithId(id);
}
/** Get a reference to a signal by the composite id of its node.
*
* @param network_id String id of the network containing the signal.
* @param node_id String id of the node under the signal.
* @return Reference to the signal if it exists, <code>null</code> otherwise
*/
public Signal getSignalForNodeId(String network_id,String node_id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSignalWithNodeId(node_id);
else
return null;
else
return network.getSignalWithNodeId(node_id);
}
/** Add a controller to the scenario.
*
* <p>Controllers can only be added if a) the scenario is not currently running, and
* b) the controller is valid.
* @param C The controller
* @return <code>true</code> if the controller was successfully added, <code>false</code> otherwise.
*/
public boolean addController(Controller C){
if(scenariolocked)
return false;
if(C==null)
return false;
if(C.myType==null)
return false;
// validate
if(!C.validate())
return false;
// add
controllerset.controllers.add(C);
return true;
}
/** Add an event to the scenario.
*
* <p>Events are not added if the scenario is running. This method does not validate the event.
* @param E The event
* @return <code>true</code> if the event was successfully added, <code>false</code> otherwise.
*/
public boolean addEvent(Event E){
if(scenariolocked)
return false;
if(E==null)
return false;
if(E.myType==null)
return false;
// add event to list
eventset.addEvent(E);
return true;
}
/** Add a sensor to the scenario.
*
* <p>Sensors can only be added if a) the scenario is not currently running, and
* b) the sensor is valid.
* @param S The sensor
* @return <code>true</code> if the sensor was successfully added, <code>false</code> otherwise.
*/
public boolean addSensor(Sensor S){
if(S==null)
return false;
if(S.myType==null)
return false;
if(S.myLink==null)
return false;
if(S.myLink.myNetwork==null)
return false;
// validate
if(!S.validate())
return false;
// add sensor to list
S.myLink.myNetwork.getSensorList().getSensor().add(S);
return true;
}
/** Get the initial density state for the network with given id.
* @param network_id String id of the network
* @return A two-dimensional array of doubles where the first dimension is the
* link index (ordered as in {@link Network#getListOfLinks}) and the second is the vehicle type
* (ordered as in {@link Scenario#getVehicleTypeNames})
*/
public double [][] getInitialDensityForNetwork(String network_id){
Network network = getNetworkWithId(network_id);
if(network==null)
return null;
double [][] density = new double [network.getLinkList().getLink().size()][getNumVehicleTypes()];
InitialDensityProfile initprofile = (InitialDensityProfile) getInitialDensityProfile();
int i,j;
for(i=0;i<network.getLinkList().getLink().size();i++){
if(initprofile==null){
for(j=0;j<numVehicleTypes;j++)
density[i][j] = 0d;
}
else{
com.relteq.sirius.jaxb.Link link = network.getLinkList().getLink().get(i);
Double [] init_density = initprofile.getDensityForLinkIdInVeh(link.getId(),network.getId());
for(j=0;j<numVehicleTypes;j++)
density[i][j] = init_density[j];
}
}
return density;
}
/** Get the current density state for the network with given id.
* @param network_id String id of the network
* @return A two-dimensional array of doubles where the first dimension is the
* link index (ordered as in {@link Network#getListOfLinks}) and the second is the vehicle type
* (ordered as in {@link Scenario#getVehicleTypeNames})
*/
public double [][] getDensityForNetwork(String network_id,int ensemble){
Network network = getNetworkWithId(network_id);
if(network==null)
return null;
double [][] density = new double [network.getLinkList().getLink().size()][getNumVehicleTypes()];
int i,j;
for(i=0;i<network.getLinkList().getLink().size();i++){
Link link = (Link) network.getLinkList().getLink().get(i);
Double [] linkdensity = link.getDensityInVeh(ensemble);
for(j=0;j<numVehicleTypes;j++)
density[i][j] = linkdensity[j];
}
return density;
}
/** Initialize the run before using {@link Scenario#advanceNSeconds(double)}
*
* <p>This method performs certain necessary initialization tasks on the scenario. In particular
* it locks the scenario so that elements may not be added mid-run. It also resets the scenario
* rolling back all profiles and clocks.
* @param numEnsemble Number of simulations to run in parallel
*/
public void initialize_run(int numEnsemble) throws SiriusException{
scenariolocked = false;
this.numEnsemble = numEnsemble;
// check that no controllers are used
if(global_control_on && numEnsemble>1 && getControllerSet()!=null){
if(!getControllerSet().getController().isEmpty()){
System.out.println("Warning! This scenario has controllers. " +
"Currently ensemble runs work only with control turned off. " +
"Deactivting control and continuing");
global_control_on = false;
}
}
double time_ic;
if(getInitialDensityProfile()!=null)
time_ic = ((InitialDensityProfile)getInitialDensityProfile()).timestamp;
else
time_ic = 0.0;
double timestart = time_ic; // start at the initial condition time
Scenario.ModeType simulationMode = Scenario.ModeType.normal;
if(numEnsemble<=0)
throw new SiriusException("Number of ensemble runs must be at least 1.");
// create the clock
clock = new Clock(timestart,Double.POSITIVE_INFINITY,simdtinseconds);
// reset the simulation
if(!reset(simulationMode))
throw new SiriusException("Reset failed.");
// lock the scenario
scenariolocked = true;
}
// private
private SiriusStateTrajectory run_internal(RunParameters param,int numRepetitions,boolean writefiles,boolean returnstate,Properties owr_props) throws SiriusException{
if(returnstate && numRepetitions>1)
throw new SiriusException("run with multiple repetitions and returning state not allowed.");
SiriusStateTrajectory state = null;
// create the clock
clock = new Clock(param.timestart,param.timeend,simdtinseconds);
// lock the scenario
scenariolocked = true;
// loop through simulation runs ............................
for(int i=0;i<numRepetitions;i++){
OutputWriterIF outputwriter = null;
if (writefiles && param.simulationMode.compareTo(Scenario.ModeType.normal)==0) {
outputwriter = OutputWriterFactory.getWriter(this, owr_props);
outputwriter.setRunId(i);
outputwriter.open();
}
try{
// allocate state
if(returnstate)
state = new SiriusStateTrajectory(this,param.outsteps);
// reset the simulation
if(!reset(param.simulationMode))
throw new SiriusException("Reset failed.");
// advance to end of simulation
while( advanceNSteps_internal(param.simulationMode,1,writefiles,returnstate,outputwriter,state,param.outsteps) ){
}
} finally {
if (null != outputwriter) outputwriter.close();
}
}
scenariolocked = false;
return state;
}
// advance the simulation by n steps.
// parameters....
// n: number of steps to advance.
// doreset: call scenario reset if true
// writefiles: write result to text files if true
// returnstate: recored and return the state trajectory if true
// outputwriter: output writing class
// state: state trajectory container
// returns....
// true if scenario advanced n steps without error
// false if scenario reached t_end without error before completing n steps
// throws
// SiriusException for all errors
private boolean advanceNSteps_internal(Scenario.ModeType simulationMode,int n,boolean writefiles,boolean returnstate,OutputWriterIF outputwriter,SiriusStateTrajectory state,int outsteps) throws SiriusException{
// advance n steps
for(int k=0;k<n;k++){
// export initial condition
if(simulationMode.compareTo(ModeType.normal)==0 && outsteps>0 )
if( clock.getCurrentstep()==0 )
recordstate(writefiles,returnstate,outputwriter,state,false,outsteps);
// update scenario
update();
// update time (before write to output)
clock.advance();
if(simulationMode.compareTo(ModeType.normal)==0 && outsteps>0 )
if( clock.getCurrentstep()%outsteps == 0 )
recordstate(writefiles,returnstate,outputwriter,state,true,outsteps);
if(clock.expired())
return false;
}
return true;
}
private void recordstate(boolean writefiles,boolean returnstate,OutputWriterIF outputwriter,SiriusStateTrajectory state,boolean exportflows,int outsteps) throws SiriusException {
if(writefiles)
outputwriter.recordstate(clock.getT(),exportflows,outsteps);
if(returnstate)
state.recordstate(clock.getCurrentstep(),clock.getT(),exportflows,outsteps);
}
private class RunParameters{
public double timestart; // [sec] start of the simulation
public double timeend; // [sec] end of the simulation
public int outsteps; // [-] number of simulation steps per output step
public Scenario.ModeType simulationMode;
// input parameter outdt [sec] output sampling time
public RunParameters(double tstart,double tend,double outdt,double simdtinseconds) throws SiriusException{
// check timestart < timeend
if(tstart>=tend)
throw new SiriusException("Empty simulation period.");
// check that outdt is a multiple of simdt
if(!SiriusMath.isintegermultipleof(outdt,simdtinseconds))
throw new SiriusException("outdt (" + outdt + ") must be an interger multiple of simulation dt (" + simdtinseconds + ").");
this.timestart = tstart;
this.timeend = tend;
this.outsteps = SiriusMath.round(outdt/simdtinseconds);
// Simulation mode is normal <=> start time == initial profile time stamp
simulationMode = null;
double time_ic;
if(getInitialDensityProfile()!=null)
time_ic = ((InitialDensityProfile)getInitialDensityProfile()).timestamp;
else
time_ic = 0.0;
if(SiriusMath.equals(timestart,time_ic)){
simulationMode = Scenario.ModeType.normal;
}
else{
// it is a warmup. we need to decide on start and end times
timeend = timestart;
if(time_ic<timestart){ // go from ic to timestart
timestart = time_ic;
simulationMode = Scenario.ModeType.warmupFromIC;
}
else{ // start at earliest demand profile
timestart = Double.POSITIVE_INFINITY;
if(getDemandProfileSet()!=null)
for(com.relteq.sirius.jaxb.DemandProfile D : getDemandProfileSet().getDemandProfile())
timestart = Math.min(timestart,D.getStartTime().doubleValue());
else
timestart = 0.0;
simulationMode = Scenario.ModeType.warmupFromZero;
}
}
if( timeend < timestart )
timeend = timestart;
}
}
/** Get configuration file name */
public String getConfigFilename() {
return configfilename;
}
} |
package com.timepath.hl2.hudeditor;
import com.timepath.hl2.io.swing.VGUICanvas;
import apple.OSXAdapter;
import com.timepath.Utils;
import com.timepath.hl2.gameinfo.ExternalConsole;
import com.timepath.hl2.gameinfo.ExternalScoreboard;
import com.timepath.hl2.io.VTF;
import com.timepath.hl2.io.test.MDLTest;
import com.timepath.hl2.io.test.VBFTest;
import com.timepath.hl2.io.test.VCCDTest;
import com.timepath.hl2.io.test.VTFTest;
import com.timepath.hl2.io.util.Element;
import com.timepath.hl2.io.util.Property;
import com.timepath.plaf.OS;
import com.timepath.plaf.linux.Ayatana;
import com.timepath.plaf.linux.GtkFixer;
import com.timepath.plaf.mac.Application;
import com.timepath.plaf.mac.Application.AboutEvent;
import com.timepath.plaf.mac.Application.AboutHandler;
import com.timepath.plaf.mac.Application.PreferencesEvent;
import com.timepath.plaf.mac.Application.PreferencesHandler;
import com.timepath.plaf.mac.Application.QuitEvent;
import com.timepath.plaf.mac.Application.QuitHandler;
import com.timepath.plaf.mac.Application.QuitResponse;
import com.timepath.plaf.x.filechooser.BaseFileChooser;
import com.timepath.plaf.x.filechooser.NativeFileChooser;
import com.timepath.steam.SteamUtils;
import com.timepath.steam.io.GCF;
import com.timepath.steam.io.GCF.GCFDirectoryEntry;
import com.timepath.steam.io.RES;
import com.timepath.steam.io.VDF;
import com.timepath.steam.io.test.ArchiveTest;
import com.timepath.steam.io.test.DataTest;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetContext;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
/**
*
* @author timepath
*/
@SuppressWarnings("serial")
public class HUDEditor extends javax.swing.JFrame {
private static final Logger LOG = Logger.getLogger(HUDEditor.class.getName());
//<editor-fold defaultstate="collapsed" desc="Variables">
private final EditorMenuBar jmb;
private final DefaultMutableTreeNode fileSystemRoot;
private final ProjectTree fileTree;
private final PropertyTable propTable;
private static VGUICanvas canvas;
private boolean updating;
private File lastLoaded;
private JSpinner spinnerWidth;
private JSpinner spinnerHeight;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Updates">
private BufferedReader getPage(String s) throws IOException {
URL u = new URL(s);
URLConnection c = u.openConnection();
// HttpURLConnection c = (HttpURLConnection) u.openConnection();
LOG.log(Level.INFO, "{0} size: {1}", new Object[]{s, c.getContentLength()});
InputStream is = c.getInputStream();
return new BufferedReader(new InputStreamReader(is));
}
private String currentVersion() throws IOException {
BufferedReader r = getPage("https://dl.dropbox.com/u/42745598/tf/HUD%20Editor/TF2%20HUD%20Editor.jar.current");
String l = r.readLine();
r.close();
return l;
}
private String checksum() throws IOException {
BufferedReader r = getPage("https://dl.dropbox.com/u/42745598/tf/HUD%20Editor/TF2%20HUD%20Editor.jar.MD5");
String l = r.readLine();
r.close();
return l;
}
private String changelog() throws IOException {
BufferedReader r = getPage("https://dl.dropbox.com/u/42745598/tf/HUD%20Editor/TF2%20HUD%20Editor.jar.changes");
String text = "";
String grep = null;
if(Main.myVer != 0) {
grep = "" + Main.myVer;
}
String line;
while((line = r.readLine()) != null) {
if(grep != null && line.contains(grep)) {
text += line.replace(grep, "<b><u>" + grep + "</u></b>");
} else {
text += line;
}
}
r.close();
return text;
}
private static boolean checked;
private void checkForUpdates(final boolean force) {
new Thread() {
int retries = 3;
private String calculateTime(long diffInSeconds) {
StringBuilder sb = new StringBuilder();
long sec = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
long min = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
long hrs = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
long days = (diffInSeconds = (diffInSeconds / 24)) >= 30 ? diffInSeconds % 30 : diffInSeconds;
//<editor-fold defaultstate="collapsed" desc="approximate months/years">
// long months = (diffInSeconds = (diffInSeconds / 30)) >= 12 ? diffInSeconds % 12 : diffInSeconds;
// long years = (diffInSeconds = (diffInSeconds / 12));
// if(years > 0) {
// if(years == 1) {
// sb.append("a year");
// } else {
// sb.append(years + " years");
// if(years <= 6 && months > 0) {
// if(months == 1) {
// sb.append(" and a month");
// } else {
// sb.append(" and " + months + " months");
// } else if(months > 0) {
// if(months == 1) {
// sb.append("a month");
// } else {
// sb.append(months + " months");
// if(months <= 6 && days > 0) {
// if(days == 1) {
// sb.append(" and a day");
// } else {
// sb.append(" and " + days + " days");
// } else
//</editor-fold>
if(days > 0) {
if(days == 1) {
sb.append("a day");
} else {
sb.append(days).append(" days");
}
if(days <= 3 && hrs > 0) {
if(hrs == 1) {
sb.append(" and an hour");
} else {
sb.append(" and ").append(hrs).append(" hours");
}
}
} else if(hrs > 0) {
if(hrs == 1) {
sb.append("an hour");
} else {
sb.append(hrs).append(" hours");
}
if(min > 1) {
sb.append(" and ").append(min).append(" minutes");
}
} else if(min > 0) {
if(min == 1) {
sb.append("a minute");
} else {
sb.append(min).append(" minutes");
}
if(sec > 1) {
sb.append(" and ").append(sec).append(" seconds");
}
} else {
if(sec <= 1) {
sb.append("about a second");
} else {
sb.append("about ").append(sec).append(" seconds");
}
}
sb.append(" ago");
return sb.toString();
}
private void doCheckForUpdates() {
try {
String current = currentVersion();
final long lastUpdate = Long.parseLong(current);
boolean equal = lastUpdate == Main.myVer;
LOG.log(Level.INFO, "{0} ={1}= {2}", new Object[]{lastUpdate, equal ? "" : "/", Main.myVer});
if(Main.myVer != 0 && Main.myVer >= lastUpdate && !force) {
return;
}
String text = changelog();
final JEditorPane pane = new JEditorPane("text/html", text);
Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
pane.setPreferredSize(new Dimension(s.width / 4, s.height / 2));
pane.setEditable(false);
pane.setOpaque(false);
pane.setBackground(new Color(0, 0, 0, 0));
pane.addHyperlinkListener(linkListener);
JScrollPane window = new JScrollPane(pane);
window.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
final JLabel lastUpdated = new JLabel();
new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lastUpdated.setText(calculateTime((System.currentTimeMillis() / 1000) - lastUpdate));
}
}).start();
if((Main.myVer == 0 || lastUpdate > Main.myVer)) {
// updateButton.setEnabled(true);
int returnCode = JOptionPane.showConfirmDialog(HUDEditor.this, new JComponent[]{new JLabel("Would you like to update to the latest version?"), new JLabel(), window, lastUpdated}, "A new update is available", JOptionPane.YES_NO_OPTION);
if(returnCode == JOptionPane.YES_OPTION) {
String md5 = checksum();
final File downloaded = new File(Utils.workingDirectory(HUDEditor.class), "update.tmp");
for(int attempt = 1;; attempt++) {
LOG.log(Level.INFO, "Checking for {0}", downloaded);
if(!downloaded.exists()) {
long startTime = System.currentTimeMillis();
LOG.info("Connecting to Dropbox...");
URL latest = new URL("https://dl.dropbox.com/u/42745598/tf/HUD%20Editor/TF2%20HUD%20Editor.jar");
URLConnection editor = latest.openConnection();
JProgressBar pb = new JProgressBar(0, editor.getContentLength());
pb.setPreferredSize(new Dimension(175, 20));
pb.setStringPainted(true);
pb.setValue(0);
// JLabel label = new JLabel("Update Progress: ");
// JPanel center_panel = new JPanel();
// center_panel.add(label);
// center_panel.add(pb);
// statusBar.remove(updateButton);
status.add(pb);
status.revalidate();
InputStream in = latest.openStream();
// Utils.workingDirectory(EditorFrame.class)
updating = true;
LOG.info("Downloading JAR file in 150KB blocks at a time.\n");
FileOutputStream writer = new FileOutputStream(downloaded);
byte[] buffer = new byte[153600]; // 150KB
int totalBytesRead = 0;
int bytesRead;
while((bytesRead = in.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
totalBytesRead += bytesRead;
pb.setValue(totalBytesRead);
}
long endTime = System.currentTimeMillis();
LOG.log(Level.INFO, "Done. {0} kilobytes downloaded ({1} seconds).\n", new Object[]{new Integer(totalBytesRead / 1000).toString(), new Long((endTime - startTime) / 1000).toString()});
writer.close();
in.close();
// dialog.dispose();
status.remove(pb);
} else {
LOG.info("Exists");
}
LOG.info("Checking MD5...");
if(!Utils.takeMD5(Utils.loadFile(downloaded)).equalsIgnoreCase(md5)) {
LOG.warning("Corrupt or old download");
} else {
LOG.info("MD5 matches");
break;
}
if(attempt == retries) {
LOG.warning("Update failed");
return;
}
}
info("Restart to apply update to " + Utils.currentFile(Main.class));
updating = false;
}
} else if(force) {
JOptionPane.showMessageDialog(HUDEditor.this, new JComponent[]{new JLabel("You have the latest version."), new JLabel(""), window, lastUpdated}, "Info", JOptionPane.INFORMATION_MESSAGE);
}
} catch(NoSuchAlgorithmException ex) {
} catch(IOException ex) {
retries
if(retries > 0) {
doCheckForUpdates();
} else {
LOG.log(Level.SEVERE, null, ex);
updating = false;
}
}
}
@Override
public void run() {
doCheckForUpdates();
checked = true;
}
}.start();
}
//</editor-fold>
public void preferences() {
jDialog1.setVisible(true);
}
public void about() {
String latestThread = "http:
String aboutText = "<html><h2>This is a What You See Is What You Get HUD Editor for TF2.</h2>";
aboutText += "<p>You can graphically edit TF2 HUDs with it!<br>";
aboutText += "<p>It was written by <a href=\"http:
aboutText += "<p>Source available on <a href=\"http://code.google.com/p/tf2-hud-editor/\">Google code</a></p>";
aboutText += "<p>I have an <a href=\"http://code.google.com/feeds/p/tf2-hud-editor/hgchanges/basic\">Atom feed</a> set up listing source commits</p>";
aboutText += "<p>Please leave feedback or suggestions on <a href=\"" + latestThread + "\">the latest update thread</a></p>";
aboutText += "<p>Logging to <a href=\"" + Main.logFile.toURI() + "\">" + Main.logFile + "</a></p>";
if(Main.myVer != 0) {
long time = Main.myVer;
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
aboutText += "<p>Build date: " + df.format(new Date(time * 1000)) + " (" + time + ")</p>";
}
aboutText += "</html>";
JEditorPane pane = new JEditorPane("text/html", aboutText);
pane.setEditable(false);
pane.setOpaque(false);
pane.setBackground(new Color(0, 0, 0, 0));
pane.addHyperlinkListener(linkListener);
info(pane, "About");
}
private void locateUserDirectory() {
FilenameFilter dirFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
};
JComboBox dropDown = new JComboBox(); // <String>
File steamappsFolder = SteamUtils.getSteamApps();
File[] userFolders = steamappsFolder.listFiles(dirFilter);
if(userFolders == null) {
error("SteamApps is empty!", "Empty SteamApps directory");
return;
}
for(int i = 0; i < userFolders.length; i++) {
if(userFolders[i].getName().equalsIgnoreCase("common") || userFolders[i].getName().equalsIgnoreCase("sourcemods")) {
continue;
}
File[] gameFolders = userFolders[i].listFiles(dirFilter);
for(int j = 0; j < gameFolders.length; j++) {
if(gameFolders[j].getName().equalsIgnoreCase("Team Fortress 2")) {
dropDown.addItem(userFolders[i].getName());
break;
}
}
}
if(dropDown.getItemCount() == 0) {
error("No users have TF2 installed!", "TF2 not found");
return;
}
if(dropDown.getItemCount() > 1) {
JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
dialogPanel.add(new JLabel("Please choose for which user you want to install the HUD"));
dialogPanel.add(dropDown);
JOptionPane.showMessageDialog(this, dialogPanel, "Select user", JOptionPane.QUESTION_MESSAGE);
}
File installDir = new File(steamappsFolder, dropDown.getSelectedItem() + "/Team Fortress 2/tf");
if(installDir.isDirectory() && installDir.exists()) {
info("Install path: " + installDir, "Install path");
}
}
/**
* Start in the home directory
* System.getProperty("user.home")
* linux = ~
* windows = %userprofile%
* mac = ?
*/
private void locateHudDirectory() {
new Thread() {
@Override
public void run() {
try {
final File[] selection = new NativeFileChooser().setParent(HUDEditor.this).setTitle(Main.getString("LoadHudDir")).setDirectory(lastLoaded != null ? lastLoaded.getPath() : null).setFileMode(BaseFileChooser.FileMode.DIRECTORIES_ONLY).choose();
if(selection != null) {
new Thread() {
@Override
public void run() {
load(selection[0]);
}
}.start();
} else {
}
} catch(IOException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
private void locateZippedHud() {
}
//<editor-fold defaultstate="collapsed" desc="Messages">
private void error(Object msg) {
error(msg, Main.getString("Error"));
}
private void error(Object msg, String title) {
LOG.log(Level.SEVERE, "{0}:{1}", new Object[]{title, msg});
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
private void warn(Object msg) {
error(msg, Main.getString("Warning"));
}
private void warn(Object msg, String title) {
LOG.log(Level.WARNING, "{0}:{1}", new Object[]{title, msg});
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.WARNING_MESSAGE);
}
private void info(Object msg) {
info(msg, Main.getString("Info"));
}
private void info(Object msg, String title) {
LOG.log(Level.INFO, "{0}:{1}", new Object[]{title, msg});
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.INFORMATION_MESSAGE);
}
//</editor-fold>
private void changeResolution() {
//<editor-fold defaultstate="collapsed" desc="Number filter">
// private static class NumericDocumentFilter extends DocumentFilter {
// @Override
// public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
// if(stringContainsOnlyDigits(string)) {
// super.insertString(fb, offset, string, attr);
// @Override
// public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
// super.remove(fb, offset, length);
// @Override
// public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
// if(stringContainsOnlyDigits(text)) {
// super.replace(fb, offset, length, text, attrs);
// private boolean stringContainsOnlyDigits(String text) {
// for (int i = 0; i < text.length(); i++) {
// if (!Character.isDigit(text.charAt(i))) {
// return false;
// return true;
//</editor-fold>
// spinnerWidth = new JSpinner(new SpinnerNumberModel(canvas.screen.width, 640, 7680, 1)); // WHUXGA
spinnerWidth.setEnabled(false);
// NumberEditor jsWidth = (NumberEditor) spinnerWidth.getEditor();
// final Document jsWidthDoc = jsWidth.getTextField().getDocument();
// if(jsWidthDoc instanceof PlainDocument) {
// AbstractDocument docWidth = new PlainDocument() {
// @Override
// public void setDocumentFilter(DocumentFilter filter) {
// if(filter instanceof NumericDocumentFilter) {
// super.setDocumentFilter(filter);
// docWidth.setDocumentFilter(new NumericDocumentFilter());
// jsWidth.getTextField().setDocument(docWidth);
// spinnerHeight = new JSpinner(new SpinnerNumberModel(canvas.screen.height, 480, 4800, 1)); // WHUXGA
spinnerHeight.setEnabled(false);
// NumberEditor jsHeight = (NumberEditor) spinnerHeight.getEditor();
// final Document jsHeightDoc = jsHeight.getTextField().getDocument();
// if(jsHeightDoc instanceof PlainDocument) {
// AbstractDocument docHeight = new PlainDocument() {
// @Override
// public void setDocumentFilter(DocumentFilter filter) {
// if (filter instanceof NumericDocumentFilter) {
// super.setDocumentFilter(filter);
// docHeight.setDocumentFilter(new NumericDocumentFilter());
// jsHeight.getTextField().setDocument(docHeight);
final JComboBox dropDown = new JComboBox(); // <String>
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = env.getScreenDevices();
ArrayList<String> listItems = new ArrayList<String>();
for(int i = 0; i < devices.length; i++) {
DisplayMode[] resolutions = devices[i].getDisplayModes(); // TF2 has different resolutions
for(int j = 0; j < resolutions.length; j++) {
String item = resolutions[j].getWidth() + "x" + resolutions[j].getHeight(); // TODO: Work out aspect ratios
if(!listItems.contains(item)) {
listItems.add(item);
}
}
}
dropDown.addItem("Custom");
for(int i = 0; i < listItems.size(); i++) {
dropDown.addItem(listItems.get(i));
}
dropDown.setSelectedIndex(1);
dropDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String item = dropDown.getSelectedItem().toString();
boolean isRes = item.contains("x");
spinnerWidth.setEnabled(!isRes);
spinnerHeight.setEnabled(!isRes);
if(isRes) {
String[] xy = item.split("x");
spinnerWidth.setValue(Integer.parseInt(xy[0]));
spinnerHeight.setValue(Integer.parseInt(xy[1]));
}
}
});
Object[] message = {"Presets: ", dropDown, "Width: ", spinnerWidth, "Height: ", spinnerHeight};
final JOptionPane optionPane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null);
final JDialog dialog = optionPane.createDialog(this, "Change resolution...");
dialog.setContentPane(optionPane);
dialog.pack();
dialog.setVisible(true);
if(optionPane.getValue() != null) {
int value = ((Integer) optionPane.getValue()).intValue();
if(value == JOptionPane.YES_OPTION) {
canvas.setPreferredSize(new Dimension(Integer.parseInt(spinnerWidth.getValue().toString()), Integer.parseInt(spinnerHeight.getValue().toString())));
}
}
}
//<editor-fold defaultstate="collapsed" desc="Overrides">
@Override
public void setJMenuBar(JMenuBar menubar) {
LOG.log(Level.INFO, "Setting menubar for {0}", OS.get());
super.setJMenuBar(menubar);
if(OS.isMac()) {
try {
//<editor-fold defaultstate="collapsed" desc="Deprecated">
OSXAdapter.setQuitHandler(this, getClass().getDeclaredMethod("quit", (Class[]) null));
OSXAdapter.setAboutHandler(this, getClass().getDeclaredMethod("about", (Class[]) null));
OSXAdapter.setPreferencesHandler(this, getClass().getDeclaredMethod("preferences", (Class[]) null));
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Unimplemented">
Application app = Application.getApplication();
app.setAboutHandler(new AboutHandler() {
public void handleAbout(AboutEvent e) {
about();
}
});
app.setPreferencesHandler(new PreferencesHandler() {
public void handlePreferences(PreferencesEvent e) {
preferences();
}
});
app.setQuitHandler(new QuitHandler() {
public void handleQuitRequestWith(QuitEvent qe, QuitResponse qr) {
quit();
}
});
URL url = getClass().getResource("/com/timepath/hl2/hudeditor/resources/Icon.png");
Image icon = Toolkit.getDefaultToolkit().getImage(url);
app.setDockIconImage(icon);
//</editor-fold>
} catch(Exception e) {
LOG.severe(e.toString());
}
} else if(OS.isLinux()) {
if(!Ayatana.installMenu((JFrame) this, menubar)) {
LOG.log(Level.WARNING, "AyatanaDesktop failed to load for {0}", System.getenv("XDG_CURRENT_DESKTOP"));
}
}
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
this.createBufferStrategy(2);
track("ProgramLoad");
if(Main.myVer != 0 && Main.prefs.getBoolean("autoupdate", true) && !checked) {
this.checkForUpdates(false);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Actions">
// private void close() {
// canvas.removeAllElements();
// fileSystemRoot.removeAllChildren();
// fileSystemRoot.setUserObject(null);
// DefaultTreeModel model1 = (DefaultTreeModel) fileTree.getModel();
// model1.reload();
// fileTree.setSelectionRow(0);
// propTable.clear();
private void load(final File root) {
if(root == null) {
return;
}
if(!root.exists()) {
error(new MessageFormat(Main.getString("FileAccessError")).format(new Object[]{root}));
}
setLastLoaded(root);
LOG.log(Level.INFO, "You have selected: {0}", root.getAbsolutePath());
if(root.getName().endsWith(".zip")) {
try {
ZipInputStream zin = new ZipInputStream(new FileInputStream(root));
ZipEntry entry;
while((entry = zin.getNextEntry()) != null) {
LOG.log(Level.INFO, "{0}", entry.getName());
zin.closeEntry();
}
zin.close();
} catch(IOException e) {
}
return;
}
if(root.isDirectory()) {
File[] folders = root.listFiles();
boolean valid = true; // TODO: find resource and scripts if there is a parent directory
for(int i = 0; i < folders.length; i++) {
if(folders[i].isDirectory() && ("resource".equalsIgnoreCase(folders[i].getName()) || "scripts".equalsIgnoreCase(folders[i].getName()))) {
valid = true;
break;
}
}
if(!valid) {
error("Selection not valid. Please choose a folder containing \'resources\' or \'scripts\'.");
locateHudDirectory();
return;
}
// close();
new Thread(new Runnable() {
public void run() {
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
HUDEditor.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final DefaultMutableTreeNode project = new DefaultMutableTreeNode();
project.setUserObject(root.getName());
connectNodes(fileSystemRoot, project);
DefaultTreeModel model = (DefaultTreeModel) fileTree.getModel();
model.reload();
final long start = System.currentTimeMillis();
recurseDirectoryToNode(root, project);
LOG.log(Level.INFO, "Loaded hud - took {0}ms", (System.currentTimeMillis() - start));
fileTree.expandPath(new TreePath(project.getPath()));
fileTree.setSelectionRow(fileSystemRoot.getIndex(project));
fileTree.requestFocusInWindow();
HUDEditor.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}).start();
}
}
private void connectNodes(final DefaultMutableTreeNode parent, final DefaultMutableTreeNode child) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// parent.add(child);
DefaultTreeModel model = (DefaultTreeModel) fileTree.getModel();
synchronized(model) {
model.insertNodeInto(child, parent, parent.getChildCount());
}
}
});
} catch(InterruptedException ex) {
Logger.getLogger(SteamUtils.class.getName()).log(Level.SEVERE, null, ex);
} catch(InvocationTargetException ex) {
Logger.getLogger(SteamUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void recurseDirectoryToNode(File root, final DefaultMutableTreeNode parent) {
final String[] blacklist = {".mp3", ".exe", ".sh", ".dll", ".dylib", ".so",
".ttf", ".bik", ".mov", ".cfg", ".cache", ".manifest",
".frag", ".vert", ".tga", ".png", ".html", ".wav",
".ico", ".uifont", ".xml", ".css", ".dic", ".conf",
".pak", ".py", ".flt", ".mix", ".asi", ".checksum",
".xz", ".log", ".doc", ".webm", ".jpg", ".psd", ".avi",
".zip", ".bin"};
final File[] fileList = root.listFiles();
final Thread[] threads = new Thread[fileList.length];
if(fileList.length == 0) {
return;
}
Arrays.sort(fileList, Utils.ALPHA_COMPARATOR);
for(int i = 0; i < fileList.length; i++) {
final File f = fileList[i];
final DefaultMutableTreeNode child = new DefaultMutableTreeNode();
child.setUserObject(f); // Unknown = File
if(f.isDirectory()) {
//<editor-fold defaultstate="collapsed" desc="Validate">
if(f.getName().toLowerCase().equals("common")
|| f.getName().toLowerCase().equals("downloading")
|| f.getName().toLowerCase().equals("temp")
|| f.getName().toLowerCase().equals("sourcemods")) {
continue;
}
if(f.listFiles().length == 0) {
continue;
}
//</editor-fold>
connectNodes(parent, child);
recurseDirectoryToNode(f, child);
} else {
//<editor-fold defaultstate="collapsed" desc="Validate">
boolean flag = false;
for(int j = 0; j < blacklist.length; j++) {
if(f.getName().endsWith(blacklist[j])) {
flag = true;
break;
}
}
if(flag) {
continue;
}
//</editor-fold>
connectNodes(parent, child);
threads[i] = new Thread(new Runnable() {
public void run() {
if(f.getName().endsWith(".txt")
|| f.getName().endsWith(".vdf")
|| f.getName().endsWith(".pop")
|| f.getName().endsWith(".layout")
|| f.getName().endsWith(".menu")
|| f.getName().endsWith(".styles")) {
VDF.analyze(f, child);
} else if(f.getName().endsWith(".res")) {
RES.analyze(f, child);
} else if(f.getName().endsWith(".vmt")) {
// VDF.analyze(f, child);
} else if(f.getName().endsWith(".vtf")) {
VTF v = null;
try {
v = VTF.load(new FileInputStream(f));
} catch(IOException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
}
if(v != null) {
child.setUserObject(v);
}
} else if(f.getName().endsWith(".gcf")) {
try {
GCF g = new GCF(f);
child.setUserObject(g);
g.analyze(child);
} catch(IOException ex) {
Logger.getLogger(SteamUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
threads[i].start();
}
}
for(int i = 0; i < threads.length; i++) {
try {
if(threads[i] != null) {
threads[i].join();
}
} catch(InterruptedException ex) {
Logger.getLogger(SteamUtils.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void quit() {
if(!updating) {
LOG.info("Closing...");
this.dispose();
if(OS.isMac()) {
// JFrame f = new JFrame();
// f.setUndecorated(true);
// f.setJMenuBar(this.getJMenuBar());
// f.setLocation(-Integer.MAX_VALUE, -Integer.MAX_VALUE); // Hacky - should just use the OSX Application calls...
// f.setVisible(true);
} else {
// System.exit(0);
}
}
}
private void setLastLoaded(File root) {
jmb.reloadItem.setEnabled(root != null);
if(root == null || !root.exists()) {
return;
}
lastLoaded = root;
Main.prefs.put("lastLoaded", root.getPath());
}
private HyperlinkListener linkListener = new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent he) {
if(he.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
if(Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(he.getURL().toURI());
} catch(Exception e) {
error(e);
}
} else {
warn("Unable to follow link");
}
}
}
};
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Interface">
/**
* Creates new form EditorFrame
*/
public HUDEditor() {
HUDEditor.lookAndFeel();
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
quit();
}
});
this.setIconImage(new ImageIcon(getClass().getResource("/com/timepath/hl2/hudeditor/resources/Icon.png")).getImage());
this.setTitle(Main.getString("Title"));
this.getRootPane().putClientProperty("apple.awt.brushMetalLook", Boolean.TRUE); // Mac tweak
boolean buggyWM = true;
//<editor-fold defaultstate="collapsed" desc="Menu fix for window managers that don't set position on resize">
if(OS.isLinux() && buggyWM) {
this.addComponentListener(new ComponentAdapter() {
private boolean moved;
private Point real = new Point();
private boolean updateReal = true;
/**
* When maximizing windows on linux under gnome-shell and possibly others, the
* JMenuBar
* menus appear not to work. This is because the position of the
* window never updates. This is an attempt to make them usable again.
*/
@Override
public void componentResized(ComponentEvent e) {
Rectangle b = HUDEditor.this.getBounds();
Rectangle s = HUDEditor.this.getGraphicsConfiguration().getBounds();
if(moved) {
moved = false;
return;
}
if(updateReal) {
real.x = b.x;
real.y = b.y;
}
updateReal = true;
b.x = real.x;
b.y = real.y;
if(b.x + b.width > s.width) {
b.x -= ((b.x + b.width) - s.width);
updateReal = false;
}
if(b.y + b.height > s.height) {
b.y = 0;
updateReal = false;
}
HUDEditor.this.setBounds(b);
}
@Override
public void componentMoved(ComponentEvent e) {
Rectangle b = HUDEditor.this.getBounds();
moved = true;
real.x = b.x;
real.y = b.y;
}
});
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Drag+drop">
this.setDropTarget(new DropTarget() {
@Override
public void drop(DropTargetDropEvent e) {
try {
DropTargetContext context = e.getDropTargetContext();
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
Transferable t = e.getTransferable();
if(OS.isLinux()) {
DataFlavor nixFileDataFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
String data = (String) t.getTransferData(nixFileDataFlavor);
for(StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();) {
String token = st.nextToken().trim();
if(token.startsWith("#") || token.length() == 0) {
// comment line, by RFC 2483
continue;
}
try {
File file = new File(new URI(token));
load(file);
} catch(Exception ex) {
}
}
} else {
Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
if(data instanceof List) {
for(Iterator<?> it = ((List<?>) data).iterator(); it.hasNext();) {
Object o = it.next();
if(o instanceof File) {
load((File) o);
}
}
}
}
context.dropComplete(true);
} catch(ClassNotFoundException ex) {
LOG.log(Level.SEVERE, null, ex);
} catch(InvalidDnDOperationException ex) {
LOG.log(Level.SEVERE, null, ex);
} catch(UnsupportedFlavorException ex) {
LOG.log(Level.SEVERE, null, ex);
} catch(IOException ex) {
LOG.log(Level.SEVERE, null, ex);
} finally {
e.dropComplete(true);
repaint();
}
}
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Dimensions">
GraphicsConfiguration gc = this.getGraphicsConfiguration();
Rectangle screenBounds = gc.getBounds();
Insets screenInsets = this.getToolkit().getScreenInsets(gc);
Dimension workspace = new Dimension(screenBounds.width - screenInsets.left - screenInsets.right, screenBounds.height - screenInsets.top - screenInsets.bottom);
DisplayMode d = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();
this.setMinimumSize(new Dimension(Math.max(workspace.width / 2, 640), Math.max(3 * workspace.height / 4, 480)));
this.setPreferredSize(new Dimension((int) (workspace.getWidth() / 1.5), (int) (workspace.getHeight() / 1.5)));
this.setLocation((d.getWidth() / 2) - (this.getPreferredSize().width / 2), (d.getHeight() / 2) - (this.getPreferredSize().height / 2));
this.setLocationRelativeTo(null);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Menubar">
jmb = new EditorMenuBar();
this.setJMenuBar(jmb);
String str = Main.prefs.get("lastLoaded", null);
if(str != null) {
this.setLastLoaded(new File(str));
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Base">
initComponents();
jCheckBox1.setSelected(Main.prefs.getBoolean("autoupdate", true));
tools.setWindow(this);
tools.putClientProperty("Quaqua.ToolBar.style", "title");
status.putClientProperty("Quaqua.ToolBar.style", "bottom");
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Tree">
fileSystemRoot = new DefaultMutableTreeNode("root");
fileTree = new ProjectTree(fileSystemRoot);
JScrollPane fileTreePane = new JScrollPane(fileTree);
// fileTreePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sideSplit.setTopComponent(fileTreePane);
fileTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent();
if(node == null) {
return;
}
propTable.clear();
DefaultTableModel model = (DefaultTableModel) propTable.getModel();
Object nodeInfo = node.getUserObject();
if(nodeInfo instanceof Element) {
Element element = (Element) nodeInfo;
canvas.load(element);
loadProps(element);
} else if(nodeInfo instanceof VTF) {
VTF v = (VTF) nodeInfo;
for(int i = Math.max(v.mipCount - 8, 0); i < Math.max(v.mipCount - 5, v.mipCount); i++) {
try {
ImageIcon img = new ImageIcon(v.getImage(i));
model.insertRow(model.getRowCount(), new Object[]{"mip[" + i + "]", img, ""});
} catch(IOException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
model.insertRow(model.getRowCount(), new Object[]{"version", v.version, ""});
model.insertRow(model.getRowCount(), new Object[]{"headerSize", v.headerSize, ""});
model.insertRow(model.getRowCount(), new Object[]{"width", v.width, ""});
model.insertRow(model.getRowCount(), new Object[]{"height", v.height, ""});
model.insertRow(model.getRowCount(), new Object[]{"flags", v.flags, ""});
model.insertRow(model.getRowCount(), new Object[]{"frameFirst", v.frameFirst, ""});
model.insertRow(model.getRowCount(), new Object[]{"reflectivity", v.reflectivity, ""});
model.insertRow(model.getRowCount(), new Object[]{"bumpScale", v.bumpScale, ""});
model.insertRow(model.getRowCount(), new Object[]{"format", v.format, ""});
model.insertRow(model.getRowCount(), new Object[]{"mipCount", v.mipCount, ""});
model.insertRow(model.getRowCount(), new Object[]{"thumbFormat", v.thumbFormat, ""});
model.insertRow(model.getRowCount(), new Object[]{"thumbWidth", v.thumbWidth, ""});
model.insertRow(model.getRowCount(), new Object[]{"thumbHeight", v.thumbHeight, ""});
model.insertRow(model.getRowCount(), new Object[]{"depth", v.depth, ""});
} else if(nodeInfo instanceof GCF) {
GCF g = (GCF) nodeInfo;
Object[][] rows = {
// {"headerVersion", g.header.headerVersion, g.header.getClass().getSimpleName()},
// {"cacheType", g.header.cacheType},
// {"formatVersion", g.header.formatVersion},
{"applicationID", g.header.applicationID, g.header.getClass().getSimpleName()},
{"applicationVersion", g.header.applicationVersion},
{"isMounted", g.header.isMounted},
// {"dummy0", g.header.dummy0},
{"fileSize", g.header.fileSize},
// {"clusterSize", g.header.clusterSize},
{"clusterCount", g.header.clusterCount},
{"checksum", g.header.checksum + " vs " + g.header.check()},
{"blockCount", g.blockAllocationTableHeader.blockCount, g.blockAllocationTableHeader.getClass().getSimpleName()},
{"blocksUsed", g.blockAllocationTableHeader.blocksUsed},
{"lastBlockUsed", g.blockAllocationTableHeader.lastBlockUsed},
// {"dummy0", g.blockAllocationTableHeader.dummy0},
// {"dummy1", g.blockAllocationTableHeader.dummy1},
// {"dummy2", g.blockAllocationTableHeader.dummy2},
// {"dummy3", g.blockAllocationTableHeader.dummy3},
{"checksum", g.blockAllocationTableHeader.checksum + " vs " + g.blockAllocationTableHeader.check()},
{"clusterCount", g.fragMap.clusterCount, g.fragMap.getClass().getSimpleName()},
{"firstUnusedEntry", g.fragMap.firstUnusedEntry},
// {"isLongTerminator", g.fragMap.isLongTerminator},
{"checksum", g.fragMap.checksum + " vs " + g.fragMap.check()},
// {"headerVersion", g.manifestHeader.headerVersion, g.manifestHeader.getClass().getSimpleName()},
// {"applicationID", g.manifestHeader.applicationID},
// {"applicationVersion", g.manifestHeader.applicationVersion},
{"nodeCount", g.manifestHeader.nodeCount, g.manifestHeader.getClass().getSimpleName()},
{"fileCount", g.manifestHeader.fileCount},
// {"compressionBlockSize", g.manifestHeader.compressionBlockSize},
{"binarySize", g.manifestHeader.binarySize},
{"nameSize", g.manifestHeader.nameSize},
{"hashTableKeyCount", g.manifestHeader.hashTableKeyCount},
{"minimumFootprintCount", g.manifestHeader.minimumFootprintCount},
{"userConfigCount", g.manifestHeader.userConfigCount},
{"bitmask", g.manifestHeader.bitmask},
{"fingerprint", (((long) (g.manifestHeader.fingerprint)) & 0xFFFFFFFF)},
{"checksum", g.manifestHeader.checksum + " vs " + g.manifestHeader.check()},
// {"headerVersion", g.directoryMapHeader.headerVersion, g.directoryMapHeader.getClass().getSimpleName()},
// {"dummy0", g.directoryMapHeader.dummy0},
// {"headerVersion", g.checksumHeader.headerVersion, g.checksumHeader.getClass().getSimpleName()},
{"checksumSize", g.checksumHeader.checksumSize, g.checksumHeader.getClass().getSimpleName()},
// {"formatCode", g.checksumMapHeader.formatCode, g.checksumMapHeader.getClass().getSimpleName()},
// {"dummy0", g.checksumMapHeader.dummy0},
{"itemCount", g.checksumMapHeader.itemCount, g.checksumMapHeader.getClass().getSimpleName()},
{"checksumCount", g.checksumMapHeader.checksumCount},
// {"gcfRevision", g.dataBlockHeader.gcfRevision, g.dataBlockHeader.getClass().getSimpleName()},
{"blockCount", g.dataBlockHeader.blockCount, g.dataBlockHeader.getClass().getSimpleName()},
// {"blockSize", g.dataBlockHeader.blockSize},
{"firstBlockOffset", g.dataBlockHeader.firstBlockOffset},
{"blocksUsed", g.dataBlockHeader.blocksUsed},
{"checksum", g.dataBlockHeader.checksum + " vs " + g.dataBlockHeader.check()}};
for(int i = 0; i < rows.length; i++) {
model.insertRow(model.getRowCount(), rows[i]);
}
} else if(nodeInfo instanceof GCFDirectoryEntry) {
GCFDirectoryEntry d = (GCFDirectoryEntry) nodeInfo;
model.insertRow(model.getRowCount(), new Object[]{"index", d.index, ""});
model.insertRow(model.getRowCount(), new Object[]{"itemSize", d.itemSize, ""});
model.insertRow(model.getRowCount(), new Object[]{"attributes", d.attributes, ""});
}
}
});
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Table">
propTable = new PropertyTable();
JScrollPane propTablePane = new JScrollPane(propTable);
sideSplit.setBottomComponent(propTablePane);
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Canvas">
canvas = new VGUICanvas() {
@Override
public void placed() {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent();
if(node == null) {
return;
}
Object nodeInfo = node.getUserObject();
if(nodeInfo instanceof Element) {
Element element = (Element) nodeInfo;
loadProps(element);
}
}
};
canvas.setBackgroundImage(getClass().getResource("/com/timepath/hl2/hudeditor/resources/Badlands1.png"));
JScrollPane canvasPane = new JScrollPane(canvas);
// canvasPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
canvasPane.getVerticalScrollBar().setBlockIncrement(30);
canvasPane.getVerticalScrollBar().setUnitIncrement(20);
// canvasPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
canvasPane.getHorizontalScrollBar().setBlockIncrement(30);
canvasPane.getHorizontalScrollBar().setUnitIncrement(20);
tabbedContent.add(Main.getString("Canvas"), canvasPane);
canvas.requestFocusInWindow();
//</editor-fold>
}
private void loadProps(final Element element) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
propTable.clear();
DefaultTableModel model = (DefaultTableModel) propTable.getModel();
if(!element.getProps().isEmpty()) {
element.validateDisplay();
for(int i = 0; i < element.getProps().size(); i++) {
Property entry = element.getProps().get(i);
if(entry.getKey().equals("\\n")) {
continue;
}
model.addRow(new Object[]{entry.getKey(), entry.getValue(), entry.getInfo()});
}
model.fireTableDataChanged();
propTable.repaint();
}
}
});
}
public static void restart(File file) throws URISyntaxException, IOException {
final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
if(!file.getName().endsWith(".jar")) {
return;
}
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(file.getPath());
final ProcessBuilder process = new ProcessBuilder(command);
process.start();
System.exit(0);
}
/**
* TODO: wrap this class in a launcher, rather than explicitly restarting
*/
public static void restart() throws URISyntaxException, IOException {
restart(new File(HUDEditor.class.getProtectionDomain().getCodeSource().getLocation().toURI()));
}
/**
* Sets the look and feel
*/
private static void lookAndFeel() {
LOG.log(Level.INFO, "L&F: {0} | {1}", new Object[]{System.getProperty("swing.defaultlaf"), Main.prefs.get("theme", null)});
UIManager.installLookAndFeel("Quaqua", "ch.randelshofer.quaqua.QuaquaLookAndFeel");
UIManager.installLookAndFeel("GTK extended", "org.gtk.laf.extended.GTKLookAndFeelExtended");
if(System.getProperty("swing.defaultlaf") == null && Main.prefs.get("theme", null) == null) { // Do not override user specified theme
boolean nimbus = false;
//<editor-fold defaultstate="collapsed" desc="Attempt to apply nimbus">
if(nimbus) {
try {
for(UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
return;
}
}
} catch(Exception ex) {
LOG.log(Level.WARNING, null, ex);
}
}
//</editor-fold>
boolean metal = false;
//<editor-fold defaultstate="collapsed" desc="Fall back to metal">
if(metal) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
return;
} catch(ClassNotFoundException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InstantiationException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(UnsupportedLookAndFeelException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Fall back to native">
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(ClassNotFoundException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(InstantiationException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(UnsupportedLookAndFeelException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
}
//</editor-fold>
} else {
String theme = System.getProperty("swing.defaultlaf");
if(theme == null) {
theme = Main.prefs.get("theme", null);
}
try {
UIManager.setLookAndFeel(theme);
} catch(InstantiationException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(UnsupportedLookAndFeelException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(ClassNotFoundException ex) {
// Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
LOG.warning("Unable to load user L&F");
}
}
//<editor-fold defaultstate="collapsed" desc="Improve native LaF">
if(UIManager.getLookAndFeel()
.isNativeLookAndFeel()) {
try {
LOG.log(Level.INFO, "Adding swing enhancements for {0}", new Object[]{OS.get()});
if(OS.isMac()) {
UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel"); // Apply quaqua if available
} else if(OS.isLinux()) {
if(UIManager.getLookAndFeel().getClass().getName().equals("com.sun.java.swing.plaf.gtk.GTKLookAndFeel")) {
GtkFixer.installGtkPopupBugWorkaround(); // Apply clearlooks java menu fix if applicable
UIManager.setLookAndFeel("org.gtk.laf.extended.GTKLookAndFeelExtended");
}
}
LOG.info("All swing enhancements installed");
} catch(InstantiationException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(IllegalAccessException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(UnsupportedLookAndFeelException ex) {
Logger.getLogger(HUDEditor.class.getName()).log(Level.SEVERE, null, ex);
} catch(ClassNotFoundException ex) {
// Logger.getLogger(EditorFrame.class.getName()).log(Level.INFO, null, ex);
LOG.warning("Unable to load enhanced L&F");
}
}
//</editor-fold>
}
private void track(String state) {
// LOG.log(Level.INFO, "Tracking {0}", state);
// if(Main.myVer == null) {
// return;
// String appID = "UA-35189411-2";
// String title = "TF2 HUD Editor";
// com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker track = new com.boxysystems.jgoogleanalytics.JGoogleAnalyticsTracker(title, "1", appID);
// com.boxysystems.jgoogleanalytics.FocusPoint focusPoint = new com.boxysystems.jgoogleanalytics.FocusPoint(state);
// track.trackAsynchronously(focusPoint);
// com.dmurph.tracking.AnalyticsConfigData config = new com.dmurph.tracking.AnalyticsConfigData(appID);
// com.dmurph.tracking.JGoogleAnalyticsTracker tracker = new com.dmurph.tracking.JGoogleAnalyticsTracker(config, com.dmurph.tracking.JGoogleAnalyticsTracker.GoogleAnalyticsVersion.V_4_7_2);
// tracker.setEnabled(true);
// tracker.trackPageView(state, title, "");
// EasyTracker.getInstance().activityStart(this);
}
private class EditorMenuBar extends JMenuBar {
private JMenuItem newItem;
private JMenuItem openItem;
private JMenuItem openZippedItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
private JMenuItem reloadItem;
private JMenuItem closeItem;
private JMenuItem exitItem;
private JMenuItem undoItem;
private JMenuItem redoItem;
private JMenuItem cutItem;
private JMenuItem copyItem;
private JMenuItem pasteItem;
private JMenuItem deleteItem;
private JMenuItem selectAllItem;
private JMenuItem preferencesItem;
private JMenuItem locateUserItem;
private JMenuItem resolutionItem;
private JMenuItem previewItem;
private JMenuItem updateItem;
private JMenuItem aboutItem;
private JMenuItem vtfItem;
private JMenuItem captionItem;
private JMenuItem vdfItem;
private JMenuItem gcfItem;
private JMenuItem bitmapItem;
private int state = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
EditorMenuBar() {
super();
//<editor-fold defaultstate="collapsed" desc="File">
JMenu fileMenu = new JMenu(Main.getString("File"));
fileMenu.setMnemonic(KeyEvent.VK_F);
this.add(fileMenu);
newItem = new JMenuItem(new CustomAction(Main.getString("New"), null, KeyEvent.VK_N,
KeyStroke.getKeyStroke(KeyEvent.VK_N, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
newItem.setEnabled(false);
fileMenu.add(newItem);
openItem = new JMenuItem(new CustomAction("Open", null, KeyEvent.VK_O,
KeyStroke.getKeyStroke(KeyEvent.VK_O, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
locateHudDirectory();
}
});
fileMenu.add(openItem);
openZippedItem = new JMenuItem(new CustomAction("OpenArchive", null, KeyEvent.VK_Z,
KeyStroke.getKeyStroke(KeyEvent.VK_O, state + ActionEvent.SHIFT_MASK)) {
@Override
public void actionPerformed(ActionEvent ae) {
locateZippedHud();
}
});
openZippedItem.setEnabled(false);
fileMenu.add(openZippedItem);
fileMenu.addSeparator();
closeItem = new JMenuItem(new CustomAction("Close", null, KeyEvent.VK_C,
KeyStroke.getKeyStroke(KeyEvent.VK_W, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
// close();
}
});
if(OS.isMac()) {
fileMenu.add(closeItem);
}
saveItem = new JMenuItem(new CustomAction("Save", null, KeyEvent.VK_S,
KeyStroke.getKeyStroke(KeyEvent.VK_S, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
if(canvas.getElements().size() > 0) {
info(canvas.getElements().get(canvas.getElements().size() - 1).save());
}
}
});
saveItem.setEnabled(false);
fileMenu.add(saveItem);
saveAsItem = new JMenuItem(new CustomAction("Save As...", null, KeyEvent.VK_A,
KeyStroke.getKeyStroke(KeyEvent.VK_S, state + ActionEvent.SHIFT_MASK)) {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
saveAsItem.setEnabled(false);
fileMenu.add(saveAsItem);
reloadItem = new JMenuItem(new CustomAction("Revert", null, KeyEvent.VK_R,
KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)) {
@Override
public void actionPerformed(ActionEvent ae) {
new Thread() {
@Override
public void run() {
load(lastLoaded);
}
}.start();
}
});
reloadItem.setEnabled(false);
fileMenu.add(reloadItem);
if(!OS.isMac()) {
fileMenu.addSeparator();
fileMenu.add(closeItem);
exitItem = new JMenuItem(new CustomAction("Exit", null, KeyEvent.VK_X,
KeyStroke.getKeyStroke(KeyEvent.VK_Q, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
quit();
}
});
fileMenu.add(exitItem);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Edit">
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
this.add(editMenu);
undoItem = new JMenuItem(new CustomAction("Undo", null, KeyEvent.VK_U,
KeyStroke.getKeyStroke(KeyEvent.VK_Z, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
undoItem.setEnabled(false);
editMenu.add(undoItem);
redoItem = new JMenuItem(new CustomAction("Redo", null, KeyEvent.VK_R,
KeyStroke.getKeyStroke(KeyEvent.VK_Y, state)) { // TODO: ctrl + shift + z
@Override
public void actionPerformed(ActionEvent ae) {
}
});
redoItem.setEnabled(false);
editMenu.add(redoItem);
editMenu.addSeparator();
cutItem = new JMenuItem(new CustomAction("Cut", null, KeyEvent.VK_T,
KeyStroke.getKeyStroke(KeyEvent.VK_X, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
cutItem.setEnabled(false);
editMenu.add(cutItem);
copyItem = new JMenuItem(new CustomAction("Copy", null, KeyEvent.VK_C,
KeyStroke.getKeyStroke(KeyEvent.VK_C, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
copyItem.setEnabled(false);
editMenu.add(copyItem);
pasteItem = new JMenuItem(new CustomAction("Paste", null, KeyEvent.VK_P,
KeyStroke.getKeyStroke(KeyEvent.VK_V, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
}
});
pasteItem.setEnabled(false);
editMenu.add(pasteItem);
deleteItem = new JMenuItem(new CustomAction("Delete", null, KeyEvent.VK_D,
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)) {
@Override
public void actionPerformed(ActionEvent ae) {
canvas.removeElements(canvas.getSelected());
}
});
editMenu.add(deleteItem);
editMenu.addSeparator();
selectAllItem = new JMenuItem(new CustomAction("Select All", null, KeyEvent.VK_A,
KeyStroke.getKeyStroke(KeyEvent.VK_A, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
for(int i = 0; i < canvas.getElements().size(); i++) {
canvas.select(canvas.getElements().get(i));
}
}
});
editMenu.add(selectAllItem);
editMenu.addSeparator();
if(!OS.isMac()) {
preferencesItem = new JMenuItem(new CustomAction("Preferences", null, KeyEvent.VK_E, null) {
@Override
public void actionPerformed(ActionEvent ae) {
preferences();
}
});
editMenu.add(preferencesItem);
}
locateUserItem = new JMenuItem(new CustomAction("Select user folder", null, KeyEvent.VK_S, null) {
@Override
public void actionPerformed(ActionEvent ae) {
locateUserDirectory();
}
});
editMenu.add(locateUserItem);
//</editor-fold>
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
this.add(viewMenu);
resolutionItem = new JMenuItem(new CustomAction("Change Resolution", null, KeyEvent.VK_R,
KeyStroke.getKeyStroke(KeyEvent.VK_R, state)) {
@Override
public void actionPerformed(ActionEvent ae) {
changeResolution();
}
});
resolutionItem.setEnabled(false);
viewMenu.add(resolutionItem);
previewItem = new JMenuItem(new CustomAction("Full Screen Preview", null, KeyEvent.VK_F,
KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0)) {
private boolean fullscreen;
@Override
public void actionPerformed(ActionEvent ae) {
HUDEditor.this.dispose();
HUDEditor.this.setUndecorated(!fullscreen);
HUDEditor.this.setExtendedState(fullscreen ? JFrame.NORMAL : JFrame.MAXIMIZED_BOTH);
HUDEditor.this.setVisible(true);
HUDEditor.this.setJMenuBar(jmb);
HUDEditor.this.pack();
HUDEditor.this.toFront();
fullscreen = !fullscreen;
}
});
viewMenu.add(previewItem);
viewMenu.addSeparator();
//<editor-fold defaultstate="collapsed" desc="Views">
JMenuItem viewItem1 = new JMenuItem("Main Menu");
viewItem1.setEnabled(false);
viewMenu.add(viewItem1);
JMenuItem viewItem2 = new JMenuItem("In-game (Health and ammo)");
viewItem2.setEnabled(false);
viewMenu.add(viewItem2);
JMenuItem viewItem3 = new JMenuItem("Scoreboard");
viewItem3.setEnabled(false);
viewMenu.add(viewItem3);
JMenuItem viewItem4 = new JMenuItem("CTF HUD");
viewItem4.setEnabled(false);
viewMenu.add(viewItem4);
//</editor-fold>
extras();
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
this.add(helpMenu);
updateItem = new JMenuItem(new CustomAction("Updates", null, KeyEvent.VK_U, null) {
@Override
public void actionPerformed(ActionEvent ae) {
HUDEditor.this.checkForUpdates(true);
}
});
updateItem.setEnabled(Main.myVer != 0); // XXX
updateItem.setEnabled(true);
helpMenu.add(updateItem);
if(!OS.isMac()) {
aboutItem = new JMenuItem(new CustomAction("About", null, KeyEvent.VK_A, null) {
@Override
public void actionPerformed(ActionEvent ae) {
about();
}
});
helpMenu.add(aboutItem);
}
}
private void extras() {
JMenu extrasMenu = new JMenu("Extras");
extrasMenu.setMnemonic(KeyEvent.VK_X);
this.add(extrasMenu);
vtfItem = new JMenuItem(new CustomAction("VTF Viewer", null, KeyEvent.VK_T, null) {
@Override
public void actionPerformed(ActionEvent ae) {
VTFTest.main("");
}
});
extrasMenu.add(vtfItem);
captionItem = new JMenuItem(new CustomAction("Caption Editor", null, KeyEvent.VK_C, null) {
@Override
public void actionPerformed(ActionEvent ae) {
VCCDTest.main("");
}
});
extrasMenu.add(captionItem);
vdfItem = new JMenuItem(new CustomAction("VDF Viewer", null, KeyEvent.VK_D, null) {
@Override
public void actionPerformed(ActionEvent ae) {
DataTest.main("");
}
});
extrasMenu.add(vdfItem);
gcfItem = new JMenuItem(new CustomAction("Archive Explorer", null, KeyEvent.VK_E, null) {
@Override
public void actionPerformed(ActionEvent ae) {
ArchiveTest.main("");
}
});
extrasMenu.add(gcfItem);
bitmapItem = new JMenuItem(new CustomAction("Bitmap Font Glyph Editor", null, KeyEvent.VK_G, null) {
@Override
public void actionPerformed(ActionEvent ae) {
VBFTest.main("");
}
});
extrasMenu.add(bitmapItem);
JMenuItem i1 = new JMenuItem(new CustomAction("External Console", null, KeyEvent.VK_X, null) {
@Override
public void actionPerformed(ActionEvent ae) {
ExternalConsole.main("");
}
});
extrasMenu.add(i1);
JMenuItem i2 = new JMenuItem(new CustomAction("External Scoreboard", null, KeyEvent.VK_S, null) {
@Override
public void actionPerformed(ActionEvent ae) {
ExternalScoreboard.main("");
}
});
extrasMenu.add(i2);
JMenuItem i3 = new JMenuItem(new CustomAction("Model viewer", null, KeyEvent.VK_M, null) {
@Override
public void actionPerformed(ActionEvent ae) {
MDLTest.main("");
}
});
extrasMenu.add(i3);
}
}
private class CustomAction extends AbstractAction {
private CustomAction(String string, Icon icon, int mnemonic, KeyStroke shortcut) {
super(Main.getString(string), icon);
this.putValue(Action.MNEMONIC_KEY, mnemonic);
this.putValue(Action.ACCELERATOR_KEY, shortcut);
}
public void actionPerformed(ActionEvent ae) {
}
}
//<editor-fold defaultstate="collapsed" desc="Generated Code">
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jDialog1 = new javax.swing.JDialog(this);
jLabel1 = new javax.swing.JLabel();
themeSelector1 = new com.timepath.swing.ThemeSelector();
jLabel2 = new javax.swing.JLabel();
jCheckBox1 = new javax.swing.JCheckBox();
tools = new com.timepath.swing.BlendedToolBar();
rootSplit = new javax.swing.JSplitPane();
sideSplit = new javax.swing.JSplitPane();
tabbedContent = new javax.swing.JTabbedPane();
status = new com.timepath.swing.StatusBar();
jDialog1.setTitle("Preferences");
jDialog1.setMinimumSize(new java.awt.Dimension(400, 300));
jDialog1.setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL);
jDialog1.getContentPane().setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Theme:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
jDialog1.getContentPane().add(jLabel1, gridBagConstraints);
themeSelector1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
themeSelector1PropertyChange(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
jDialog1.getContentPane().add(themeSelector1, gridBagConstraints);
jLabel2.setText("Auto update:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
jDialog1.getContentPane().add(jLabel2, gridBagConstraints);
jCheckBox1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
jCheckBox1PropertyChange(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
jDialog1.getContentPane().add(jCheckBox1, gridBagConstraints);
getContentPane().add(tools, java.awt.BorderLayout.PAGE_START);
rootSplit.setDividerLocation(180);
rootSplit.setContinuousLayout(true);
rootSplit.setOneTouchExpandable(true);
sideSplit.setBorder(null);
sideSplit.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
sideSplit.setResizeWeight(0.5);
sideSplit.setContinuousLayout(true);
sideSplit.setOneTouchExpandable(true);
rootSplit.setLeftComponent(sideSplit);
rootSplit.setRightComponent(tabbedContent);
getContentPane().add(rootSplit, java.awt.BorderLayout.CENTER);
getContentPane().add(status, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jCheckBox1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCheckBox1PropertyChange
Main.prefs.putBoolean("autoupdate", jCheckBox1.isSelected());
}//GEN-LAST:event_jCheckBox1PropertyChange
private void themeSelector1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_themeSelector1PropertyChange
Main.prefs.put("theme", UIManager.getLookAndFeel().getClass().getName());
}//GEN-LAST:event_themeSelector1PropertyChange
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JDialog jDialog1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JSplitPane rootSplit;
private javax.swing.JSplitPane sideSplit;
private com.timepath.swing.StatusBar status;
private javax.swing.JTabbedPane tabbedContent;
private com.timepath.swing.ThemeSelector themeSelector1;
private com.timepath.swing.BlendedToolBar tools;
// End of variables declaration//GEN-END:variables
//</editor-fold>
//</editor-fold>
} |
package jlibs.wadl.cli.model;
import jlibs.core.net.URLUtil;
import jlibs.wadl.cli.Util;
import jlibs.wadl.model.*;
import javax.xml.bind.JAXBContext;
import java.util.HashSet;
import java.util.List;
/**
* @author Santhosh Kumar T
*/
public class WADLReader{
private Application app;
private HashSet<Object> inlined = new HashSet<Object>();
public Application read(String systemID) throws Exception{
if(systemID.startsWith("~/"))
systemID = Util.toFile(systemID).getAbsolutePath();
JAXBContext jc = JAXBContext.newInstance(Application.class.getPackage().getName());
app = (Application)jc.createUnmarshaller().unmarshal(URLUtil.toURL(systemID));
inline();
return app;
}
private void inline(){
for(Object item: app.getResourceTypeOrMethodOrRepresentation()){
if(item instanceof Method)
inline((Method)item);
}
for(Object item: app.getResourceTypeOrMethodOrRepresentation()){
if(item instanceof ResourceType)
inline((ResourceType)item);
}
for(Resources resources: app.getResources()){
for(Resource resource: resources.getResource())
inline(resource);
}
}
public void inline(List<Representation> representations){
for(int i=0; i<representations.size(); i++){
Representation representation = representations.get(i);
if(representation.getHref()!=null)
representations.set(i, getRepresentation(representation.getHref()));
}
}
public void inline(Method method){
if(!inlined.add(method))
return;
if(method.getRequest()!=null)
inline(method.getRequest().getRepresentation());
for(Response response: method.getResponse())
inline(response.getRepresentation());
}
public void inline(ResourceType rt){
if(!inlined.add(rt))
return;
for(int i=0; i<rt.getMethodOrResource().size(); i++){
Object item = rt.getMethodOrResource().get(i);
if(item instanceof Method){
Method method = (Method)item;
if(method.getHref()!=null)
rt.getMethodOrResource().set(i, getMethod(method.getHref()));
}else if(item instanceof Resource)
inline((Resource)item);
}
}
public void inline(Resource resource){
if(!inlined.add(resource))
return;
for(String type: resource.getType()){
ResourceType rt = getResourceType(type);
if(rt!=null){
inline(rt);
resource.getMethodOrResource().addAll(rt.getMethodOrResource());
}
}
for(int i=0; i<resource.getMethodOrResource().size(); i++){
Object item = resource.getMethodOrResource().get(i);
if(item instanceof Method){
Method method = (Method)item;
if(method.getHref()!=null)
resource.getMethodOrResource().set(i, getMethod(method.getHref()));
}else if(item instanceof Resource)
inline((Resource)item);
}
}
private ResourceType getResourceType(String ref){
ref = ref.substring(1);
for(Object item: app.getResourceTypeOrMethodOrRepresentation()){
if(item instanceof ResourceType){
ResourceType rt = (ResourceType)item;
if(rt.getId().equals(ref))
return rt;
}
}
throw new RuntimeException("cannot find resourceType with id: "+ref);
}
private Method getMethod(String ref){
ref = ref.substring(1);
for(Object item: app.getResourceTypeOrMethodOrRepresentation()){
if(item instanceof Method){
Method method = (Method)item;
if(method.getId().equals(ref))
return method;
}
}
throw new RuntimeException("cannot find method with id: "+ref);
}
private Representation getRepresentation(String ref){
ref = ref.substring(1);
for(Object item: app.getResourceTypeOrMethodOrRepresentation()){
if(item instanceof Representation){
Representation rep = (Representation)item;
if(rep.getId().equals(ref))
return rep;
}
}
throw new RuntimeException("cannot find representation with id: "+ref);
}
} |
package com.tzapps.tzpalette.ui;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ShareActionProvider;
import android.widget.Toast;
import com.tzapps.common.ui.OnFragmentStatusChangedListener;
import com.tzapps.common.utils.ActivityUtils;
import com.tzapps.common.utils.BitmapUtils;
import com.tzapps.common.utils.MediaHelper;
import com.tzapps.common.utils.StringUtils;
import com.tzapps.tzpalette.R;
import com.tzapps.tzpalette.data.PaletteData;
import com.tzapps.tzpalette.data.PaletteDataHelper;
import com.tzapps.tzpalette.ui.PaletteItemOptionsDialogFragment.OnClickPaletteItemOptionListener;
import com.tzapps.tzpalette.ui.PaletteListFragment.OnClickPaletteItemListener;
public class MainActivity extends Activity implements OnFragmentStatusChangedListener,
OnClickPaletteItemOptionListener, OnClickPaletteItemListener
{
private final static String TAG = "MainActivity";
private final static String FOLDER_HOME = "tzpalette";
/** Called when the user clicks the TakePicture button */
static final int TAKE_PHOTE_RESULT = 1;
/** Called when the user clicks the LoadPicture button */
static final int LOAD_PICTURE_RESULT = 2;
public final static String PALETTE_CARD_DATA_ID = "com.tzapps.tzpalette.PaletteCardDataId";
private static final String TZPALETTE_FILE_PREFIX = "MyPalette";
ProgressDialog mDialog;
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
String mCurrentPhotoPath;
PaletteData mCurrentPalette;
PaletteDataHelper mDataHelper;
ShareActionProvider mShareActionProvider;
CaptureFragment mCaptureFrag;
PaletteListFragment mPaletteListFragment;
CaptureFragment fragment3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ActivityUtils.forceToShowOverflowOptionsOnActoinBar(this);
mDataHelper = PaletteDataHelper.getInstance(this);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(actionBar.newTab().setText("Capture"), CaptureFragment.class, null);
mTabsAdapter.addTab(actionBar.newTab().setText("My Palettes"), PaletteListFragment.class,
null);
// mTabsAdapter.addTab(actionBar.newTab().setText("About"), CaptureFragment.class, null);
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null)
{
if (type.startsWith("image/"))
handleSendImage(intent);
}
}
private void handleSendImage(Intent intent)
{
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null)
handlePicture(imageUri);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
if (mCurrentPalette != null)
outState.putParcelable("currentPaletteData", mCurrentPalette);
if (mCurrentPhotoPath != null)
outState.putString("currentPhotoPath", mCurrentPhotoPath);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mTabsAdapter.setSelectedTab(savedInstanceState.getInt("tab", 0));
mCurrentPalette = savedInstanceState.getParcelable("currentPaletteData");
mCurrentPhotoPath = savedInstanceState.getString("currentPhotoPath");
udpateCaptureVeiw();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.capture_view_actions, menu);
/*
* TODO adjust menu items dynamically based on: 1. the current tab 2. whether a palette data
* exists
*/
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.action_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// TODO adjust the share item contents based on the palette data
return super.onCreateOptionsMenu(menu);
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent)
{
if (mShareActionProvider != null)
{
mShareActionProvider.setShareIntent(shareIntent);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle presses on the action bar items
switch (item.getItemId())
{
case R.id.action_share:
sharePalette(item.getActionView());
return true;
case R.id.action_export:
exportPalette(item.getActionView());
return true;
case R.id.action_takePhoto:
takePhoto(item.getActionView());
return true;
case R.id.action_loadPicture:
loadPicture(item.getActionView());
return true;
case R.id.action_settings:
openSettings();
// sharePalette(item.getActionView());
return true;
case R.id.action_about:
//mTabsAdapter.setSelectedTab(2);
return true;
case R.id.action_save:
savePalette(item.getActionView());
return true;
case R.id.action_clear:
clearCaptureView(item.getActionView());
return true;
case R.id.action_analysis:
analysisPicture(item.getActionView());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings()
{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
@Override
public void onPaletteItemOptionClicked(int position, long dataId, PaletteItemOption option)
{
assert (mPaletteListFragment != null);
PaletteData data = mPaletteListFragment.getItem(position);
if (data == null)
return;
switch (option)
{
case Rename:
Log.d(TAG, "Rename palatte item(position=" + position + " , id=" + dataId + ")");
showRenameDialog(position, dataId);
break;
case Delete:
Log.d(TAG, "Delete palatte item(position=" + position + " , id=" + dataId + ")");
mPaletteListFragment.remove(data);
mDataHelper.delete(data);
break;
case View:
Log.d(TAG, "View palette item (position=" + position + " , id=" + dataId + ")");
openPaletteCardView(dataId);
break;
}
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.palette_item_options:
long dataId = (Long) view.getTag(R.id.TAG_PALETTE_DATA_ID);
int itemPosition = (Integer) view.getTag(R.id.TAG_PALETTE_ITEM_POSITION);
PaletteData data = mPaletteListFragment.getItem(itemPosition);
Log.d(TAG, "Show options on palette data + " + data);
PaletteItemOptionsDialogFragment optionDialogFrag =
PaletteItemOptionsDialogFragment.newInstance(data.getTitle(), itemPosition, dataId);
optionDialogFrag.show(getFragmentManager(), "dialog");
break;
}
}
@Override
public void onPaletteItemClick(int position, long dataId, PaletteData data)
{
// TODO view the palette data
Log.i(TAG, "palette data " + data.getId() + " clicked");
openPaletteCardView(dataId);
}
private void openPaletteCardView(long dataId)
{
Intent intent = new Intent(this, PaletteCardActivity.class);
intent.putExtra(PALETTE_CARD_DATA_ID, dataId);
startActivity(intent);
}
@Override
public void onPaletteItemLongClick(int position, long dataId, PaletteData data)
{
Log.i(TAG, "palette data " + data.getId() + " long clicked");
PaletteItemOptionsDialogFragment optionDialogFrag =
PaletteItemOptionsDialogFragment.newInstance(data.getTitle(), position, dataId);
optionDialogFrag.show(getFragmentManager(), "dialog");
}
private void updatePaletteDataTitle(int position, long dataId, String title)
{
assert (mPaletteListFragment != null);
PaletteData data = mPaletteListFragment.getItem(position);
if (data == null)
return;
data.setTitle(title);
mDataHelper.update(data, /* updateThumb */false);
mPaletteListFragment.refresh();
}
private void showRenameDialog(final int position, final long dataId)
{
assert (mPaletteListFragment != null);
PaletteData data = mPaletteListFragment.getItem(position);
if (data == null)
return;
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
input.setText(data.getTitle());
input.setSingleLine(true);
input.setSelectAllOnFocus(true);
alert.setTitle(R.string.action_rename)
.setView(input)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
String text = input.getText().toString();
updatePaletteDataTitle(position, dataId, text);
}
})
.setNegativeButton("Cancel", null);
final AlertDialog dialog = alert.create();
input.setOnFocusChangeListener(new OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
}
);
dialog.show();
}
private void sharePalette(View view)
{
if (mCurrentPalette == null)
return;
View paletteCard = (View) findViewById(R.id.frame_palette_card);
Bitmap bitmap = BitmapUtils.getBitmapFromView(paletteCard);
assert (bitmap != null);
// TODO make the share function work rather than just a trial version
String name = FOLDER_HOME + File.separator + "share";
File file = BitmapUtils.saveBitmapToSDCard(bitmap, name);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("image/jpeg");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.putExtra(Intent.EXTRA_TEXT, "My Palette");
startActivity(Intent.createChooser(sendIntent, "share"));
}
private void exportPalette(View view)
{
if (mCurrentPalette == null)
return;
View paletteCard = (View) findViewById(R.id.frame_palette_card);
Bitmap bitmap = BitmapUtils.getBitmapFromView(paletteCard);
assert (bitmap != null);
String title = mCurrentPalette.getTitle();
if (title == null)
title = getResources().getString(R.string.palette_title_default);
BitmapUtils.saveBitmapToSDCard(bitmap, FOLDER_HOME + File.separator + title);
Toast.makeText(this, "Palette <" + title + "> has been exported", Toast.LENGTH_SHORT)
.show();
}
/** refresh capture view fragment in main activity with persisted mPaletteData */
private void udpateCaptureVeiw()
{
if (mCaptureFrag == null || mCurrentPalette == null)
return;
Bitmap bitmap = null;
String imagePath = mCurrentPalette.getImageUrl();
Uri imageUri = imagePath == null ? null : Uri.parse(imagePath);
bitmap = BitmapUtils.getBitmapFromUri(this, imageUri);
if (bitmap != null)
{
int orientation;
/*
* This is a quick fix on picture orientation for the picture taken
* from the camera, as it will be always rotated to landscape
* incorrectly even if we take it in portrait mode...
*/
orientation = MediaHelper.getPictureOrientation(this, imageUri);
bitmap = BitmapUtils.getRotatedBitmap(bitmap, orientation);
mCaptureFrag.updateImageView(bitmap);
}
mCaptureFrag.updateColors(mCurrentPalette.getColors());
}
@Override
public void onFragmentViewCreated(Fragment fragment)
{
if (fragment instanceof CaptureFragment)
{
mCaptureFrag = (CaptureFragment) fragment;
udpateCaptureVeiw();
}
if (fragment instanceof PaletteListFragment)
{
mPaletteListFragment = (PaletteListFragment) fragment;
mPaletteListFragment.addAll(mDataHelper.getAllData());
}
}
private File getAlbumDir()
{
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
FOLDER_HOME);
if (!storageDir.isDirectory())
storageDir.mkdirs();
return storageDir;
}
private File createImageFile() throws IOException
{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = TZPALETTE_FILE_PREFIX + "_" + timeStamp;
File image = File.createTempFile(imageFileName, ".jpg", getAlbumDir());
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
/** Called when the user performs the Take Photo action */
public void takePhoto(View view)
{
Log.d(TAG, "take a photo");
if (ActivityUtils.isIntentAvailable(getBaseContext(), MediaStore.ACTION_IMAGE_CAPTURE))
{
try
{
File file = createImageFile();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, TAKE_PHOTE_RESULT);
}
catch (IOException e)
{
Log.e(TAG, "take a photo failed");
}
}
else
{
Log.e(TAG, "no camera found");
}
}
/** Called when the user performs the Load Picture action */
public void loadPicture(View view)
{
Log.d(TAG, "load a picture");
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
/** Called when the user performs the Analysis action */
/** Called when the user performs the Clear action */
/** Called when the user performs the Save action */
mDataHelper.update(mCurrentPalette, /*updateThumb*/false);
/* invoke the system's media scanner to add the photo to
* the Media Provider's database
*/
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(selectedImage);
sendBroadcast(mediaScanIntent);
handlePicture(selectedImage);
}
}
break;
case LOAD_PICTURE_RESULT:
if (resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
if (selectedImage != null)
handlePicture(selectedImage);
}
break;
default:
break;
}
}
private String getPictureTilteFromUri(Uri uri)
{
String filename = null;
String scheme = uri.getScheme();
if (scheme.equals("file"))
{
filename = uri.getLastPathSegment();
}
else if (scheme.equals("content"))
{
String[] proj = {MediaStore.Images.Media.TITLE};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
if (cursor != null && cursor.getCount() != 0)
{
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
cursor.moveToFirst();
filename = cursor.getString(columnIndex);
}
cursor.close();
}
//TODO: sometimes we cannot parse and get image file name correctly
if (StringUtils.isEmpty(filename))
filename = getResources().getString(R.string.palette_title_default);
return filename;
}
private void handlePicture(Uri selectedImage)
{
assert(selectedImage != null);
Bitmap bitmap = BitmapUtils.getBitmapFromUri(this, selectedImage);
assert (bitmap != null);
mCurrentPalette = new PaletteData();
if (bitmap != null)
{
int orientation;
/*
* This is a quick fix on picture orientation for the picture taken
* from the camera, as it will be always rotated to landscape
* incorrectly even if we take it in portrait mode...
*/
orientation = MediaHelper.getPictureOrientation(this, selectedImage);
bitmap = BitmapUtils.getRotatedBitmap(bitmap, orientation);
mCurrentPalette.setThumb(bitmap);
}
//TODO something is still wrong on file title fetching logic
mCurrentPalette.setTitle(getPictureTilteFromUri(selectedImage));
mCurrentPalette.setImageUrl(selectedImage.toString());
udpateCaptureVeiw();
// start to analysis the picture immediately after loading it
new PaletteDataAnalysisTask().execute(mCurrentPalette);
}
private void startAnalysis()
{
if (mDialog == null)
mDialog = new ProgressDialog(this);
mDialog.setMessage(getResources().getText(R.string.analysis_picture_in_process));
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();
}
private void stopAnalysis()
{
mDialog.hide();
}
/**
* This is a helper class used to do the palette data analysis process asynchronously
*/
private class PaletteDataAnalysisTask extends AsyncTask<PaletteData, Void, PaletteData>
{
protected void onPreExecute()
{
super.onPreExecute();
startAnalysis();
}
/*
* The system calls this to perform work in a worker thread and delivers it the parameters
* given to AsyncTask.execute()
*/
protected PaletteData doInBackground(PaletteData... dataArray)
{
PaletteData data = dataArray[0];
mDataHelper.analysis(data, /* reset */true);
return data;
}
/*
* The system calls this to perform work in the UI thread and delivers the result from
* doInBackground()
*/
protected void onPostExecute(PaletteData result)
{
stopAnalysis();
if (mCaptureFrag != null)
mCaptureFrag.updateColors(result.getColors());
}
}
/**
* This is a helper class that implements the management of tabs and all details of connecting a
* ViewPager with associated TabHost. It relies on a trick. Normally a tab host has a simple API
* for supplying a View or Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host 0dp high (it is not shown)
* and the TabsAdapter supplies its own dummy view to show as the tab content. It listens to
* changes in tabs, and takes care of switch to the correct paged in the ViewPager whenever the
* selected tab changes.
*/
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener
{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo
{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args)
{
clss = _class;
args = _args;
}
}
public TabsAdapter(Activity activity, ViewPager pager)
{
super(activity.getFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void setSelectedTab(int position)
{
mActionBar.setSelectedNavigationItem(position);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args)
{
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount()
{
return mTabs.size();
}
@Override
public Fragment getItem(int position)
{
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
@Override
public void onPageSelected(int position)
{
mActionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{}
@Override
public void onPageScrollStateChanged(int state)
{}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{}
}
} |
package cx2x.xcodeml.xelement;
import cx2x.xcodeml.exception.IllegalTransformationException;
import org.w3c.dom.Element;
import java.util.ArrayList;
import java.util.List;
import cx2x.xcodeml.helper.*;
/**
* The XbasicType represents the basicType (3.3) element in XcodeML intermediate
* representation.
*
* Elements: (kind?, (len | (arrayIndex | indexRange)+)?, coShape?)
* - Optional:
* - kind (Xkind)
* - len (Xlength)
* - arrayIndex (XarrayIndex)
* - indexRange (XindexRange)
* - coShape TODO not needed for the moment
* Attributes:
* - Required: type (text), ref (text)
* - Optional: is_public (bool), is_private (bool), is_pointer (bool),
* is_target (bool), is_external (bool),is_intrinsic (bool),
* is_optional (bool), is_save (bool), is_parameter (bool),
* is_allocatable (bool), intent (text: in, out, inout)
*
* The type attribute is defined in the Xtype base class.
*
* @author clementval
*/
public class XbasicType extends Xtype implements Xclonable<XbasicType> {
private boolean _isArray = false;
// Optional elements
private List<Xindex> _dimensions = null;
private Xkind _kind = null;
private Xlength _length = null;
// XbasicType required attributes (type is declared in Xtype)
private String _ref;
// XbasicType optional attributes
private boolean _is_public = false;
private boolean _is_private = false;
private boolean _is_pointer = false;
private boolean _is_target = false;
private boolean _is_external = false;
private boolean _is_intrinsic = false;
private boolean _is_optional = false;
private boolean _is_save = false;
private boolean _is_parameter = false;
private boolean _is_allocatable = false;
private Xintent _intent = null;
/**
* Xelement standard ctor. Pass the base element to the base class and read
* inner information (elements and attributes).
* @param baseElement The root element of the Xelement
*/
public XbasicType(Element baseElement){
super(baseElement);
readBasicTypeInformation();
}
/**
* Read inner element information.
*/
private void readBasicTypeInformation(){
readRequiredAttributes();
readOptionalAttributes();
_dimensions = XelementHelper.findIndexes(this);
// is array ?
if (_dimensions.size() > 0){
_isArray = true;
}
// has length ?
_length = XelementHelper.findLen(this, false);
// has kind ?
_kind = XelementHelper.findKind(this, false);
}
/**
* Read all required attributes.
*/
private void readRequiredAttributes() {
// Attribute type is read in Xtype
_ref = XelementHelper.getAttributeValue(this, XelementName.ATTR_REF);
}
/**
* Read all optional attributes
*/
private void readOptionalAttributes() {
_is_public = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_PUBLIC);
_is_private = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_PRIVATE);
_is_pointer = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_POINTER);
_is_target = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_TARGET);
_is_external = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_EXTERNAL);
_is_intrinsic = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_INTRINSIC);
_is_optional = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_OPTIONAL);
_is_save = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_SAVE);
_is_parameter = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_PARAMETER);
_is_allocatable = XelementHelper.getBooleanAttributeValue(this,
XelementName.ATTR_IS_ALLOCATABLE);
String intentValue = XelementHelper.getAttributeValue(this,
XelementName.ATTR_INTENT);
_intent = Xintent.fromString(intentValue);
}
/**
* Get the indexRange object for the given dimension.
* @param index The position of the dimension. For the first dimension, index
* is 0, for the second is 1 and so on.
* @return A XindexRange object representing the index range of a specific
* dimension.
*/
public Xindex getDimensions(int index){
if(index >= _dimensions.size() || index < 0){
return null;
}
return _dimensions.get(index);
}
/**
* Check whether the type is an array type.
* @return True if the type is an array type. False otherwise.
*/
public boolean isArray(){
return _isArray;
}
/**
* Check whether the type has a length element.
* @return True if the type has a length element. False otherwise.
*/
public boolean hasLength(){
return _length != null;
}
/**
* Get the len element.
* @return Len element. Null if the basic type has no len element.
*/
public Xlength getLength(){
return _length;
}
/**
* Check whether the type has a kind element.
* @return True if the type has a kind element. False otherwise.
*/
public boolean hasKind(){
return _kind != null;
}
/**
* Get the kind element.
* @return Kind element. Null if the basic type has no kind element.
*/
public Xkind getKind(){
return _kind;
}
/**
* Get the array dimensions.
* @return The dimensions of the array type.
*/
public int getDimensions(){
return _dimensions.size();
}
/**
* Get ref attribute value.
* @return The ref attribute value as String.
*/
public String getRef(){
return _ref;
}
/**
* Set the value of ref attribute.
* @param value New value of ref attribute.
*/
public void setRef(String value){
if(baseElement != null){
baseElement.setAttribute(XelementName.ATTR_REF, value);
}
}
/**
* Check whether the type is public.
* @return True if the type is public. False otherwise.
*/
public boolean isPublic() {
return _is_public;
}
/**
* Check whether the type is private.
* @return True if the type is private. False otherwise.
*/
public boolean isPrivate() {
return _is_private;
}
/**
* Check whether the type is a pointer.
* @return True if the type is a pointer. False otherwise.
*/
public boolean isPointer() {
return _is_pointer;
}
/**
* Check whether the type is a target.
* @return True if the type is a target. False otherwise.
*/
public boolean isTarget() {
return _is_target;
}
/**
* Check whether the type is external.
* @return True if the type is external. False otherwise.
*/
public boolean isExternal() {
return _is_external;
}
/**
* Check whether the type is intrinsic.
* @return True if the type is intrinsic. False otherwise.
*/
public boolean isIntrinsic() {
return _is_intrinsic;
}
/**
* Check whether the type is optional.
* @return True if the type is optional. False otherwise.
*/
public boolean isOptional(){
return _is_optional;
}
/**
* Check whether the type is save.
* @return True if the type is save. False otherwise.
*/
public boolean isSave() {
return _is_save;
}
/**
* Check whether the type is a parameter.
* @return True if the type is a parameter. False otherwise.
*/
public boolean isParameter() {
return _is_parameter;
}
/**
* Check whether the type is allocatable.
* @return True if the type is allocatable. False otherwise.
*/
public boolean isAllocatable() {
return _is_allocatable;
}
/**
* Check whether the type has an intent.
* @return True if the type has an intent. False otherwise.
*/
public boolean hasIntent(){
return _intent != null;
}
/**
* Get the intent of the type.
* @return Intent. Null if the type has no intent.
*/
public Xintent getIntent(){
return _intent;
}
/**
* Set the intent of the type.
* @param value Intent value to be set.
*/
public void setIntent(Xintent value){
if(value != null) {
baseElement.setAttribute(XelementName.ATTR_INTENT, value.toString());
}
_intent = value;
}
/**
* Remove intent attribute from the element.
*/
public void removeIntent(){
if(hasIntent()) {
baseElement.removeAttribute(XelementName.ATTR_INTENT);
_intent = null;
}
}
/**
* Remove is_allocatable attribute from the element.
*/
public void removeAllocatable(){
if(isAllocatable()){
baseElement.removeAttribute(XelementName.ATTR_IS_ALLOCATABLE);
_is_allocatable = false;
}
}
/**
* Remove all dimension from the type
*/
public void resetDimension(){
for(Xindex idx : _dimensions){
idx.delete();
}
_dimensions.clear();
_isArray = false;
}
/**
* Remove the dimensions not in the given list. Dimension index starts at 1.
* @param keptDimensions List of dimension index to be kept.
*/
public void removeDimension(List<Integer> keptDimensions){
List<Xindex> keptDim = new ArrayList<>();
for(int i = 0; i < _dimensions.size(); i++){
if(keptDimensions.contains(i+1)){
keptDim.add(_dimensions.get(i));
} else {
_dimensions.get(i).delete();
}
}
if(keptDim.size() == 0){
_isArray = false;
}
_dimensions = keptDim;
}
/**
* Add a dimension to the basic type.
* @param index Index element to add as the new dimension.
* @param position Position compared to already existing element.
*/
public void addDimension(Xindex index, int position){
if(_dimensions.size() == 0){
this.appendToChildren(index, false);
_isArray = true;
} else {
if(position == _dimensions.size() - 1){ // Add at the end
Xindex last = _dimensions.get(_dimensions.size()-1);
XelementHelper.insertAfter(last, index);
_dimensions.add(index);
} else {
Xindex crtPos = _dimensions.get(position);
XelementHelper.insertBefore(crtPos, index);
_dimensions.add(position, index);
}
}
}
@Override
public XbasicType cloneObject() {
Element element = (Element)cloneNode();
return new XbasicType(element);
}
public static XbasicType create(String type, String ref, Xintent intent,
XcodeProgram xcodeml)
throws IllegalTransformationException
{
XbasicType bt = XelementHelper.createEmpty(XbasicType.class, xcodeml);
bt.setType(type);
if(ref != null) {
bt.setRef(ref);
}
if(intent != null) {
bt.setIntent(Xintent.IN);
}
return bt;
}
} |
package properties.competition;
import static structure.impl.other.Quantification.FORALL;
import properties.Property;
import properties.PropertyMaker;
import properties.papers.DaCapo;
import properties.papers.HasNextQEA;
import structure.intf.Assignment;
import structure.intf.Guard;
import structure.intf.QEA;
import creation.QEABuilder;
public class JavaMOP implements PropertyMaker {
@Override
public QEA make(Property property) {
switch (property) {
case JAVAMOP_ONE:
return makeOne();
case JAVAMOP_TWO:
return makeTwo();
case JAVAMOP_THREE:
return makeThree();
case JAVAMOP_FOUR:
return makeFour();
}
return null;
}
public QEA makeOne() {
// This is just the HasNext property we know and love
QEA qea = new HasNextQEA();
qea.setName("JAVAMOP_ONE");
return qea;
}
public QEA makeTwo() {
/*
* Note - this has a disjoint alphabet, we should implement this
* optimisation!
*/
QEABuilder q = new QEABuilder("JAVAMOP_TWO");
int LOCK = 1;
int UNLOCK = 2;
int thread = -1;
int lock = -2;
int count = 1;
q.addQuantification(FORALL, thread);
q.addQuantification(FORALL, lock);
q.addTransition(1, LOCK, new int[] { thread, lock },
Assignment.setVal(count, 1), 2);
q.addTransition(2, LOCK, new int[] { thread, lock },
Assignment.increment(count), 2);
q.addTransition(2, UNLOCK, new int[] { thread, lock },
Guard.isGreaterThanConstant(count, 1),
Assignment.decrement(count), 2);
q.addTransition(2, UNLOCK, new int[] { thread, lock },
Guard.isSemEqualToConstant(count, 1),
Assignment.setVal(count, 0), 1);
q.addFinalStates(1);
QEA qea = q.make();
qea.record_event_name("lock", LOCK);
qea.record_event_name("unlock", UNLOCK);
return qea;
}
public QEA makeThree() {
QEABuilder q = new QEABuilder("JAVAMOP_THREE");
int A = 1;
int B = 2;
int C = 3;
int a = 1;
int b = 2;
int c = 3;
// If we move away from state 1 they are no longer equal
q.addTransition(
1,
A,
Assignment.list(Assignment.incrementOrSet(a),
Assignment.ensure(b, 0),
Assignment.ensure(c, 0)), 2);
q.addTransition(
1,
B,
Assignment.list(Assignment.incrementOrSet(b),
Assignment.ensure(a, 0),
Assignment.ensure(c, 0)), 2);
q.addTransition(
1,
C,
Assignment.list(Assignment.incrementOrSet(c),
Assignment.ensure(a, 0),
Assignment.ensure(b, 0)), 2);
// If we are one less than the two others then we go to state 1
q.addTransition(
2,
A,
Guard.and(Guard.differenceEqualToVal(b, a, 1),
Guard.differenceEqualToVal(c, a, 1)),
Assignment.increment(a), 1);
q.addTransition(
2,
B,
Guard.and(Guard.differenceEqualToVal(a, b, 1),
Guard.differenceEqualToVal(c, b, 1)),
Assignment.increment(b), 1);
q.addTransition(
2,
C,
Guard.and(Guard.differenceEqualToVal(a, c, 1),
Guard.differenceEqualToVal(b, c, 1)),
Assignment.increment(c), 1);
// Otherwise we stay still and increment
q.addTransition(
2,
A,
Guard.or(Guard.differenceNotEqualToVal(b, a, 1),
Guard.differenceNotEqualToVal(c, a, 1)),
Assignment.increment(a), 2);
q.addTransition(
2,
B,
Guard.or(Guard.differenceNotEqualToVal(a, b, 1),
Guard.differenceNotEqualToVal(c, b, 1)),
Assignment.increment(b), 2);
q.addTransition(
2,
C,
Guard.or(Guard.differenceNotEqualToVal(a, c, 1),
Guard.differenceNotEqualToVal(b, c, 1)),
Assignment.increment(c), 2);
q.addFinalStates(1);
QEA qea = q.make();
qea.record_event_name("a", A);
qea.record_event_name("b", B);
qea.record_event_name("c", C);
return qea;
}
public QEA makeFour() {
QEA qea = DaCapo.makeUnsafeMapIter();
qea.setName("JAVAMOP_FOUR");
return qea;
}
} |
package io.spacedog.caremen;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.spacedog.admin.AdminJobs;
import io.spacedog.caremen.FareSettings.VehiculeFareSettings;
import io.spacedog.client.SpaceEnv;
import io.spacedog.client.SpaceRequest;
import io.spacedog.client.SpaceTarget;
import io.spacedog.sdk.SpaceData.SearchResults;
import io.spacedog.sdk.SpaceData.TermQuery;
import io.spacedog.sdk.SpaceDog;
import io.spacedog.utils.Check;
public class Billing {
DateTimeFormatter fullFormatter = DateTimeFormat.fullDateTime().withLocale(Locale.FRANCE);
DateTimeFormatter shortFormatter = DateTimeFormat.shortDateTime().withLocale(Locale.FRANCE);
public String charge() {
try {
SpaceEnv env = SpaceEnv.defaultEnv();
SpaceDog dog = SpaceDog.login(env.get("backend_id"), "cashier",
env.get("caremen_cashier_password"));
TermQuery query = new TermQuery();
query.type = "course";
query.size = 50;
query.terms = Lists.newArrayList("status", "completed");
SearchResults<Course> courses = dog.data().search(query, Course.class);
FareSettings fareSettings = dog.settings().get(FareSettings.class);
for (Course course : courses.objects()) {
try {
if (course.fare == null)
computeFare(dog, course, fareSettings);
if (course.payment.companyId == null)
chargeBill(dog, course);
course.status = "billed";
course.save();
} catch (Exception e) {
String url = env.target().url(dog.backendId(),
"/1/data/course/" + course.id());
AdminJobs.error(this, "Error billing course " + url, e);
}
}
} catch (Throwable t) {
return AdminJobs.error(this, t);
}
return "OK";
}
void computeFare(SpaceDog dog, Course course, FareSettings fareSettings) {
Check.notNull(course.requestedVehiculeType, "course.requestedVehiculeType");
Check.notNull(course.pickupTimestamp, "course.pickupTimestamp");
Check.notNull(course.dropoffTimestamp, "course.dropoffTimestamp");
Check.notNull(course.driver, "course.driver");
Check.notNull(course.driver.driverId, "course.driver.driverId");
Check.notNull(course.driver.vehicule, "course.driver.vehicule");
TermQuery query = new TermQuery();
query.type = "courselog";
query.size = 1000;
query.terms = Lists.newArrayList("courseId", course.id(),
"driverId", course.driver.driverId,
"status", Lists.newArrayList("in-progress", "completed"));
query.sort = "meta.createdAt";
query.ascendant = true;
SearchResults<CourseLog> logs = dog.data().search(query, CourseLog.class);
Check.isTrue(logs.total() <= 1000,
"too many course logs [%s] for course [%s]", logs.total(), course.id());
List<LatLng> points = Lists.newArrayList();
for (CourseLog log : logs.objects())
if (log.where != null)
points.add(log.where);
String type = course.requestedVehiculeType;
VehiculeFareSettings typeFareSettings = fareSettings.getFor(type);
Check.notNull(typeFareSettings.base, type + ".base");
Check.notNull(typeFareSettings.km, type + ".km");
Check.notNull(typeFareSettings.min, type + ".min");
Check.notNull(typeFareSettings.minimum, type + ".minimum");
course.distance = (long) SphericalUtil.computeLength(points);
course.time = course.dropoffTimestamp.getMillis()
- course.pickupTimestamp.getMillis();
course.fare = (typeFareSettings.km * course.distance / 1000)
+ (typeFareSettings.min * course.time / 60000)
+ typeFareSettings.base;
course.fare = Double.max(typeFareSettings.minimum, course.fare);
course.driver.gain = course.fare * fareSettings.driverShare;
course.save();
}
void chargeBill(SpaceDog dog, Course course) {
Check.notNull(course.payment, "course.payment");
Check.notNull(course.payment.stripe, "course.payment.stripe");
Check.notNull(course.payment.stripe.customerId, "course.payment.stripe.customerId");
Check.notNull(course.payment.stripe.cardId, "course.payment.stripe.cardId");
Check.notNull(course.to.address, "course.to.address");
String fullPickupDateTime = fullFormatter.print(course.pickupTimestamp);
String shortPickupDateTime = shortFormatter.print(course.pickupTimestamp);
Map<String, Object> params = Maps.newHashMap();
params.put("amount", (int) (course.fare * 100));
params.put("currency", "eur");
params.put("customer", course.payment.stripe.customerId);
params.put("source", course.payment.stripe.cardId);
params.put("description",
String.format("Course du [%s] à destination de [%s]",
fullPickupDateTime, course.to.address));
params.put("statement_descriptor",
String.format("Caremen %s", shortPickupDateTime));
ObjectNode payment = dog.stripe().charge(params);
course.payment.stripe.paymentId = payment.get("id").asText();
}
public static void main(String[] args) {
SpaceRequest.env().target(SpaceTarget.production);
System.setProperty("backend_id", "caredev");
new Billing().charge();
}
} |
package water.parser;
import water.*;
import water.api.ParseSetupV3;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OInternalParseException;
import water.exceptions.H2OParseException;
import water.exceptions.H2OParseSetupException;
import water.fvec.Frame;
import water.fvec.Vec;
import water.fvec.UploadFileVec;
import water.fvec.FileVec;
import water.fvec.ByteVec;
import water.util.Log;
import java.util.Arrays;
import java.util.HashSet;
/**
* Configuration and base guesser for a parse;
*/
public final class ParseSetup extends Iced {
public static final byte GUESS_SEP = -1;
public static final int NO_HEADER = -1;
public static final int GUESS_HEADER = 0;
public static final int HAS_HEADER = 1;
public static final int GUESS_COL_CNT = -1;
boolean _is_valid; // The initial parse is sane
long _invalid_lines; // Number of broken/invalid lines found
String[] _errors; // Errors in this parse setup
ParserType _parse_type; // CSV, XLS, XSLX, SVMLight, Auto, ARFF
byte _separator; // Field separator, usually comma ',' or TAB or space ' '
// Whether or not single-quotes quote a field. E.g. how do we parse:
// raw data: 123,'Mally,456,O'Mally
// singleQuotes==True ==> 2 columns: 123 and Mally,456,OMally
// singleQuotes==False ==> 4 columns: 123 and 'Mally and 456 and O'Mally
boolean _single_quotes;
int _check_header; // 1st row: 0: guess, +1 header, -1 data
int _number_columns; // Columns to parse
String[] _column_names;
byte[] _column_types; // Column types
String[][] _domains; // Domains for each column (null if numeric)
String[] _na_strings; // Strings for NA in a given column
String[][] _data; // First few rows of parsed/tokenized data
int _chunk_size = FileVec.DFLT_CHUNK_SIZE; // Optimal chunk size to be used store values
public ParseSetup(ParseSetup ps) {
this(ps._is_valid, ps._invalid_lines, ps._errors, ps._parse_type,
ps._separator, ps._single_quotes, ps._check_header, ps._number_columns,
ps._column_names, ps._column_types, ps._domains, ps._na_strings, ps._data, ps._chunk_size);
}
public ParseSetup(boolean isValid, long invalidLines, String[] errors, ParserType t, byte sep, boolean singleQuotes, int checkHeader, int ncols, String[] columnNames, byte[] ctypes, String[][] domains, String[] naStrings, String[][] data, int chunkSize) {
_is_valid = isValid;
_invalid_lines = invalidLines;
_errors = errors;
_parse_type = t;
_separator = sep;
_single_quotes = singleQuotes;
_check_header = checkHeader;
_number_columns = ncols;
_column_names = columnNames;
_column_types = ctypes;
_domains = domains;
_na_strings = naStrings;
_data = data;
_chunk_size = chunkSize;
}
/**
* Create a ParseSetup with parameters from the client.
*
* Typically used to guide sampling in the data
* to verify chosen settings, and fill in missing settings.
*
* @param ps Parse setup settings from client
*/
public ParseSetup(ParseSetupV3 ps) {
this(false, 0, null, ps.parse_type, ps.separator, ps.single_quotes,
ps.check_header, GUESS_COL_CNT, ps.column_names, strToColumnTypes(ps.column_types),
null, ps.na_strings, null, ps.chunk_size);
if(ps.parse_type == null) _parse_type = ParserType.AUTO;
if(ps.separator == 0) _separator = GUESS_SEP;
}
/**
* Create a ParseSetup with all parameters except chunk size.
*
* Typically used by file type parsers for returning final valid results
* _chunk_size will be set later using results from all files.
*/
public ParseSetup(boolean isValid, long invalidLines, String[] errors, ParserType t, byte sep, boolean singleQuotes, int checkHeader, int ncols, String[] columnNames, byte[] ctypes, String[][] domains, String[] naStrings, String[][] data) {
this(isValid, invalidLines, errors, t, sep, singleQuotes, checkHeader, ncols, columnNames, ctypes, domains, naStrings, data, FileVec.DFLT_CHUNK_SIZE);
}
/**
* Create a ParseSetup without any column information
*
* Typically used by file type parsers for returning final invalid results
*/
public ParseSetup(boolean isValid, long invalidLines, String[] errors, ParserType t, byte sep, boolean singleQuotes, int checkHeader, int ncols, String[][] data) {
this(isValid, invalidLines, errors, t, sep, singleQuotes, checkHeader, ncols, null, null, null, null, data, FileVec.DFLT_CHUNK_SIZE);
}
/**
* Create a default ParseSetup
*
* Used by Ray's schema magic
*/
public ParseSetup() {}
public String[] getColumnTypeStrings() {
String[] types = new String[_column_types.length];
for(int i=0; i< types.length; i++)
types[i] = Vec.TYPE_STR[_column_types[i]];
return types;
}
public static byte[] strToColumnTypes(String[] strs) {
if (strs == null) return null;
byte[] types = new byte[strs.length];
for(int i=0; i< types.length;i++) {
switch (strs[i].toLowerCase()) {
case "unknown": types[i] = Vec.T_BAD; break;
case "uuid": types[i] = Vec.T_UUID; break;
case "string": types[i] = Vec.T_STR; break;
case "numeric": types[i] = Vec.T_NUM; break;
case "enum": types[i] = Vec.T_ENUM; break;
case "time": types[i] = Vec.T_TIME; break;
default: types[i] = Vec.T_BAD;
// TODO throw an exception
Log.err("Column type "+ strs[i] + " is unknown.");
}
}
return types;
}
public Parser parser() {
switch(_parse_type) {
case CSV: return new CsvParser(this);
case XLS: return new XlsParser(this);
case SVMLight: return new SVMLightParser(this);
case ARFF: return new ARFFParser(this);
}
throw new H2OInternalParseException("Unknown file type. Parse cannot be completed.",
"Attempted to invoke a parser for ParseType:" + _parse_type +", which doesn't exist.");
}
// Set of duplicated column names
HashSet<String> checkDupColumnNames() {
HashSet<String> conflictingNames = new HashSet<>();
if( _column_names ==null ) return conflictingNames;
HashSet<String> uniqueNames = new HashSet<>();
for( String n : _column_names)
(uniqueNames.contains(n) ? conflictingNames : uniqueNames).add(n);
return conflictingNames;
}
@Override public String toString() {
if (_errors != null) {
StringBuilder sb = new StringBuilder();
for (String e : _errors) sb.append(e).append("\n");
return sb.toString();
}
return _parse_type.toString(_number_columns, _separator);
}
static boolean allStrings(String [] line){
ValueString str = new ValueString();
for( String s : line ) {
try {
Double.parseDouble(s);
return false; // Number in 1st row guesses: No Column Header
} catch (NumberFormatException e) { /*Pass - determining if number is possible*/ }
if( ParseTime.attemptTimeParse(str.setTo(s)) != Long.MIN_VALUE ) return false;
ParseTime.attemptUUIDParse0(str.setTo(s));
ParseTime.attemptUUIDParse1(str);
if( str.get_off() != -1 ) return false; // Valid UUID parse
}
return true;
}
// simple heuristic to determine if we have headers:
// return true iff the first line is all strings and second line has at least one number
static boolean hasHeader(String[] l1, String[] l2) {
return allStrings(l1) && !allStrings(l2);
}
/**
* Used by test harnesses for simple parsing of test data. Presumes
* auto-detection for file and separator types.
*
* @param fkeys Keys to input vectors to be parsed
* @param singleQuote single quotes quote fields
* @param checkHeader check for a header
* @return ParseSetup settings from looking at all files
*/
public static ParseSetup guessSetup(Key[] fkeys, boolean singleQuote, int checkHeader) {
return guessSetup(fkeys, new ParseSetup(false, 0, null, ParserType.AUTO, GUESS_SEP, singleQuote, checkHeader, GUESS_COL_CNT, null));
}
/**
* Discover the parse setup needed to correctly parse all files.
* This takes a ParseSetup as guidance. Each file is examined
* individually and then results merged. If a conflict exists
* between any results all files are re-examined using the
* best guess from the first examination.
*
* @param fkeys Keys to input vectors to be parsed
* @param userSetup Setup guidance from user
* @return ParseSetup settings from looking at all files
*/
public static ParseSetup guessSetup( Key[] fkeys, ParseSetup userSetup ) {
//Guess setup of each file and collect results
GuessSetupTsk t = new GuessSetupTsk(userSetup);
t.doAll(fkeys).getResult();
//check results
/* if (t._gblSetup._is_valid && (!t._failedSetup.isEmpty() || !t._conflicts.isEmpty())) {
// run guess setup once more, this time knowing the global setup to get rid of conflicts (turns them into failures) and bogus failures (i.e. single line files with unexpected separator)
GuessSetupTsk t2 = new GuessSetupTsk(t._gblSetup);
HashSet<Key> keySet = new HashSet<Key>(t._conflicts);
keySet.addAll(t._failedSetup);
Key[] keys2 = new Key[keySet.size()];
t2.doAll(keySet.toArray(keys2));
t._failedSetup = t2._failedSetup;
t._conflicts = t2._conflicts;
if(!gSetup._setup._header && t2._gblSetup._setup._header){
gSetup._setup._header = true;
gSetup._setup._column_names = t2._gblSetup._setup._column_names;
t._gblSetup._hdrFromFile = t2._gblSetup._hdrFromFile;
}*/
//Calc chunk-size
Iced ice = DKV.getGet(fkeys[0]);
if (ice instanceof Frame && ((Frame) ice).vec(0) instanceof UploadFileVec) {
t._gblSetup._chunk_size = FileVec.DFLT_CHUNK_SIZE;
} else {
t._gblSetup._chunk_size = FileVec.calcOptimalChunkSize(t._totalParseSize, t._gblSetup._number_columns);
}
// assert t._conflicts.isEmpty(); // we should not have any conflicts here, either we failed to find any valid global setup, or conflicts should've been converted into failures in the second pass
// if (!t._failedSetup.isEmpty()) {
// // TODO throw and exception ("Can not parse: Got incompatible files.", gSetup, t._failedSetup.keys);
// if (t._gblSetup == null || !t._gblSetup._is_valid) {
// //TODO throw an exception
return t._gblSetup;
}
/**
* Try to determine the ParseSetup on a file by file basis
* and merge results.
*/
public static class GuessSetupTsk extends MRTask<GuessSetupTsk> {
// Input
final ParseSetup _userSetup;
boolean _empty = true;
// Output
public ParseSetup _gblSetup;
//IcedArrayList<Key> _failedSetup;
//IcedArrayList<Key> _conflicts;
public long _totalParseSize;
/**
*
* @param userSetup ParseSetup to guide examination of files
*/
public GuessSetupTsk(ParseSetup userSetup) { _userSetup = userSetup; }
/**
* Runs once on each file to guess that file's ParseSetup
*/
@Override public void map(Key key) {
Iced ice = DKV.getGet(key);
if(ice == null) throw new H2OIllegalArgumentException("Missing data","Did not find any data under key " + key);
ByteVec bv = (ByteVec)(ice instanceof ByteVec ? ice : ((Frame)ice).vecs()[0]);
byte [] bits = ZipUtil.getFirstUnzippedBytes(bv);
// guess setup
if(bits.length > 0) {
_empty = false;
// _failedSetup = new IcedArrayList<Key>();
// _conflicts = new IcedArrayList<Key>();
try {
_gblSetup = guessSetup(bits, _userSetup);
} catch (H2OParseException pse) {
throw new H2OParseSetupException(key, pse);
}
// if (_gblSetup == null || !_gblSetup._is_valid)
// _failedSetup.add(key);
// else {
// _gblSetup._setupFromFile = key;
// if (_check_header && _gblSetup._setup._header)
// _gblSetup._hdrFromFile = key;
// get file size
float decompRatio = ZipUtil.decompressionRatio(bv);
if (decompRatio > 1.0)
_totalParseSize += bv.length() * decompRatio; // estimate file size
else // avoid numerical distortion of file size when not compressed
_totalParseSize += bv.length();
// report if multiple files exist in zip archive
if (ZipUtil.getFileCount(bv) > 1) {
if (_gblSetup._errors != null)
_gblSetup._errors = Arrays.copyOf(_gblSetup._errors, _gblSetup._errors.length + 1);
else
_gblSetup._errors = new String[1];
_gblSetup._errors[_gblSetup._errors.length - 1] = "Only single file zip " +
"archives are currently supported, only the first file has been parsed. " +
"Remaining files have been ignored.";
}
}
}
/**
* Merges ParseSetup results, conflicts, and errors from several files
*/
@Override
public void reduce(GuessSetupTsk other) {
if (other._empty) return;
if (_gblSetup == null) {
_empty = false;
_gblSetup = other._gblSetup;
assert (_gblSetup != null);
return;
}
ParseSetup setupA = _gblSetup, setupB = other._gblSetup;
if (setupA._is_valid && setupB._is_valid) {
_gblSetup._check_header = unifyCheckHeader(setupA._check_header, setupB._check_header);
_gblSetup._separator = unifyColumnSeparators(setupA._separator, setupB._separator);
_gblSetup._number_columns = unifyColumnCount(setupA._number_columns, setupB._number_columns);
_gblSetup._column_names = unifyColumnNames(setupA._column_names, setupB._column_names);
if (setupA._parse_type == ParserType.ARFF && setupB._parse_type == ParserType.CSV)
;// do nothing parse_type and col_types are already set correctly
else if (setupA._parse_type == ParserType.CSV && setupB._parse_type == ParserType.ARFF) {
_gblSetup._parse_type = ParserType.ARFF;
_gblSetup._column_types = setupB._column_types;
} else if (setupA._parse_type == setupB._parse_type) {
_gblSetup._column_types = unifyColumnTypes(setupA._column_types, setupB._column_types);
} else
throw new H2OParseSetupException("File type mismatch. Cannot parse files of type "
+ setupA._parse_type + " and " + setupB._parse_type + " as one dataset.");
} else { // one of the setups is invalid, fail
// TODO: Point out which file is problem
throw new H2OParseSetupException("Cannot determine parse parameters for file.");
}
if (_gblSetup._data.length < Parser.InspectDataOut.MAX_PREVIEW_LINES) {
int n = _gblSetup._data.length;
int m = Math.min(Parser.InspectDataOut.MAX_PREVIEW_LINES, n + other._gblSetup._data.length - 1);
_gblSetup._data = Arrays.copyOf(_gblSetup._data, m);
System.arraycopy(other._gblSetup._data, 1, _gblSetup._data, n, m - n);
}
_totalParseSize += other._totalParseSize;
}
private static int unifyCheckHeader(int chkHdrA, int chkHdrB){
if (chkHdrA == GUESS_HEADER || chkHdrB == GUESS_HEADER)
throw new H2OParseSetupException("Unable to determine header on a file. Not expected.");
if (chkHdrA == HAS_HEADER || chkHdrB == HAS_HEADER) return HAS_HEADER;
else return NO_HEADER;
}
private static byte unifyColumnSeparators(byte sepA, byte sepB) {
if( sepA == sepB) return sepA;
else if (sepA == GUESS_SEP) return sepB;
else if (sepB == GUESS_SEP) return sepA;
// TODO: Point out which file is problem
throw new H2OParseSetupException("Column separator mismatch. One file seems to use "
+ (char) sepA + " and the other uses " + (char) sepB + ".");
}
private static int unifyColumnCount(int cntA, int cntB) {
if (cntA == cntB) return cntA;
else if (cntA == 0) return cntB;
else if (cntB == 0) return cntA;
else { // files contain different numbers of columns
// TODO: Point out which file is problem
throw new H2OParseSetupException("Files conflict in number of columns. " + cntA
+ " vs. " + cntB + ".");
}
}
private static String[] unifyColumnNames(String[] namesA, String[] namesB){
if (namesA == null) return namesB;
else if (namesB == null) return namesA;
else {
for (int i = 0; i < namesA.length; i++) {
if (i > namesB.length || !namesA[i].equals(namesB[i])) {
// TODO improvement: if files match except for blanks, merge?
throw new H2OParseSetupException("Column names do not match between files.");
}
}
return namesA;
}
}
private static byte[] unifyColumnTypes(byte[] typesA, byte[] typesB){
if (typesA == null) return typesB;
else if (typesB == null) return typesA;
else {
for (int i = 0; i < typesA.length; i++) {
if (i > typesB.length || typesA[i] != typesB[i]) {
if (typesA[i] == Vec.T_BAD)
typesA[i] = typesB[i];
// TODO improvement: add file names
else throw new H2OParseSetupException("Column " + (i+1) + " type mismatched for at least two files. Got types: " + Vec.TYPE_STR[typesA[i]] + " and " + Vec.TYPE_STR[typesB[i]]);
}
}
return typesA;
}
}
}
/**
* Guess everything from a single pile-o-bits. Used in tests, or in initial
* parser inspections when the user has not told us anything about separators
* or headers.
*
* @param bits Initial bytes from a parse source
* @return ParseSetup settings from looking at all files
*/
public static ParseSetup guessSetup( byte[] bits, ParseSetup userSetup ) {
return guessSetup(bits, userSetup._parse_type, userSetup._separator, GUESS_COL_CNT, userSetup._single_quotes, userSetup._check_header, null, userSetup._column_types, null, null);
}
private static final ParserType guessFileTypeOrder[] = {ParserType.ARFF, ParserType.XLS,ParserType.XLSX,ParserType.SVMLight,ParserType.CSV};
public static ParseSetup guessSetup( byte[] bits, ParserType pType, byte sep, int ncols, boolean singleQuotes, int checkHeader, String[] columnNames, byte[] columnTypes, String[][] domains, String[] naStrings ) {
switch( pType ) {
case CSV: return CsvParser.guessSetup(bits, sep, ncols, singleQuotes, checkHeader, columnNames, columnTypes, naStrings);
case SVMLight: return SVMLightParser.guessSetup(bits);
case XLS: return XlsParser.guessSetup(bits);
case ARFF: return ARFFParser.guessSetup(bits, sep, singleQuotes, columnNames, naStrings);
case AUTO:
for( ParserType pTypeGuess : guessFileTypeOrder ) {
try {
ParseSetup ps = guessSetup(bits,pTypeGuess,sep,ncols,singleQuotes,checkHeader,columnNames,columnTypes, domains, naStrings);
if( ps != null && ps._is_valid) return ps;
} catch( Throwable ignore ) { /*ignore failed parse attempt*/ }
}
}
return new ParseSetup( false, 0, new String[]{"Cannot determine file type"}, pType, sep, singleQuotes, checkHeader, ncols, columnNames, null, domains, naStrings, null, FileVec.DFLT_CHUNK_SIZE);
}
public static String hex( String n ) {
// blahblahblah/myName.ext ==> myName
// blahblahblah/myName.csv.ext ==> myName
int sep = n.lastIndexOf(java.io.File.separatorChar);
if( sep > 0 ) n = n.substring(sep+1);
int dot = n.lastIndexOf('.');
if( dot > 0 ) n = n.substring(0, dot);
int dot2 = n.lastIndexOf('.');
if( dot2 > 0 ) n = n.substring(0, dot2);
// "2012_somedata" ==> "X2012_somedata"
if( !Character.isJavaIdentifierStart(n.charAt(0)) ) n = "X"+n;
// "human%Percent" ==> "human_Percent"
char[] cs = n.toCharArray();
for( int i=1; i<cs.length; i++ )
if( !Character.isJavaIdentifierPart(cs[i]) )
cs[i] = '_';
// "myName" ==> "myName.hex"
n = new String(cs);
int i = 0;
String res = n + ".hex";
Key k = Key.make(res);
// Renumber to handle dup names
while(DKV.get(k) != null)
k = Key.make(res = n + ++i + ".hex");
return res;
}
} // ParseSetup state class |
package water.rapids;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.*;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.fvec.Vec;
import water.parser.ParseDataset;
import water.parser.ParseSetup;
import water.util.ArrayUtils;
import java.io.File;
import java.util.Arrays;
public class RapidsTest extends TestUtil {
@BeforeClass public static void setup() { stall_till_cloudsize(1); }
@Test public void bigSlice() {
// check that large slices do something sane
String tree = "(rows a.hex [0:2147483647])";
checkTree(tree);
}
@Test public void test1() {
// Checking `hex + 5`
String tree = "(+ a.hex
checkTree(tree);
}
@Test public void test2() {
// Checking `hex + 5 + 10`
String tree = "(+ a.hex (+ #5 #10))";
checkTree(tree);
}
@Test public void test3() {
// Checking `hex + 5 - 1 * hex + 15 * (23 / hex)`
String tree = "(+ (- (+ a.hex #5) (* #1 a.hex)) (* #15 (/ #23 a.hex)))";
checkTree(tree);
}
@Test public void test4() {
//Checking `hex == 5`, <=, >=, <, >, !=
String tree = "(== a.hex
checkTree(tree);
tree = "(<= a.hex
checkTree(tree);
tree = "(>= a.hex #1.25132)";
checkTree(tree);
tree = "(< a.hex #112.341e-5)";
checkTree(tree);
tree = "(> a.hex #0.0123)";
checkTree(tree);
tree = "(!= a.hex
checkTree(tree);
}
@Test public void test4_throws() {
String tree = "(== a.hex (cols a.hex [1 2]))";
checkTree(tree,true);
}
@Test public void test5() {
// Checking `hex && hex`, ||, &, |
String tree = "(&& a.hex a.hex)";
checkTree(tree);
tree = "(|| a.hex a.hex)";
checkTree(tree);
tree = "(& a.hex a.hex)";
checkTree(tree);
tree = "(| a.hex a.hex)";
checkTree(tree);
}
@Test public void test6() {
// Checking `hex[,1]`
String tree = "(cols a.hex [0])";
checkTree(tree);
// Checking `hex[1,5]`
tree = "(rows (cols a.hex [0]) [5])";
checkTree(tree);
// Checking `hex[c(1:5,7,9),6]`
tree = "(cols (rows a.hex [0:4 6 7]) [0])";
checkTree(tree);
// Checking `hex[c(8,1,1,7),1]`
// No longer handle dup or out-of-order rows
tree = "(rows a.hex [2 7 8])";
checkTree(tree);
}
@Test public void testRowAssign() {
String tree;
// Assign column 3 over column 0
tree = "(:= a.hex (cols a.hex [3]) 0 [0:150])";
checkTree(tree);
// Assign 17 over column 0
tree = "(:= a.hex 17 [0] [0:150])";
checkTree(tree);
// Assign 17 over column 0, row 5
tree = "(:= a.hex 17 [0] [5])";
checkTree(tree);
// Append 17
tree = "(append a.hex 17 \"nnn\")";
checkTree(tree);
}
@Test public void testFun() {
// Compute 3*3; single variable defined in function body
String tree = "({var1 . (* var1 var1)} 3)";
checkTree(tree);
// Unknown var2
tree = "({var1 . (* var1 var2)} 3)";
checkTree(tree,true);
// Compute 3* a.hex[0,0]
tree = "({var1 . (* var1 (rows a.hex [0]))} 3)";
checkTree(tree);
// Some more horrible functions. Drop the passed function and return a 3
tree = "({fun . 3} {y . (* y y)})";
checkTree(tree);
// Apply a 3 to the passed function
tree = "({fun . (fun 3)} {y . (* y y)})";
checkTree(tree);
// Pass the squaring function thru the ID function
tree = "({fun . fun} {y . (* y y)})";
checkTree(tree);
// Pass the squaring function thru the twice-apply-3 function
tree = "({fun . (fun (fun 3))} {y . (* y y)})";
checkTree(tree);
// Pass the squaring function thru the twice-apply-x function
tree = "({fun x . (fun (fun x))} {y . (* y y)} 3)";
checkTree(tree);
// Pass the squaring function thru the twice-apply function
tree = " ({fun . {x . (fun (fun x))}} {y . (* y y)}) ";
checkTree(tree);
// Pass the squaring function thru the twice-apply function, and apply it
tree = "(({fun . {x . (fun (fun x))}} {y . (* y y)}) 3)";
checkTree(tree);
}
@Test public void testCBind() {
String tree = "(cbind 1 2)";
checkTree(tree);
tree = "(cbind 1 a.hex 2)";
checkTree(tree);
tree = "(cbind a.hex (cols a.hex 0) 2)";
checkTree(tree);
}
@Test public void testRBind() {
String tree = "(rbind 1 2)";
checkTree(tree);
//tree = "(rbind a.hex 1 2)";
//checkTree(tree);
}
@Test public void testApply() {
// Sum, reduction. 1 row result
String tree = "(apply a.hex 2 {x . (sum x)})";
checkTree(tree);
// Return ID column results. Shared data result.
tree = "(apply a.hex 2 {x . x})";
checkTree(tree);
// Return column results, new data result.
tree = "(apply a.hex 2 abs)";
checkTree(tree);
// Return two results
tree = "(apply a.hex 2 {x . (rbind (sumNA x) (sum x))})";
checkTree(tree);
}
@Test public void testRowApply() {
String tree = "(apply a.hex 1 sum)";
checkTree(tree);
tree = "(apply a.hex 1 max)";
checkTree(tree);
tree = "(apply a.hex 1 {x . (sum x)})";
checkTree(tree);
tree = "(apply a.hex 1 {x . (sum (* x x))})";
checkTree(tree);
// require lookup of 'y' outside the scope of the applied function.
// doubles all values.
tree = "({y . (apply a.hex 1 {x . (sum (* x y))})} 2)";
checkTree(tree);
}
@Test public void testMath() {
for( String s : new String[] {"abs", "cos", "sin", "acos", "ceiling", "floor", "cosh", "exp", "log", "sqrt", "tan", "tanh"} )
checkTree("("+s+" a.hex)");
}
@Test public void testVariance() {
// Checking variance: scalar
String tree = "({x . (var x x \"everything\")} (rows a.hex [0]))";
checkTree(tree);
tree = "({x . (var x x \"everything\")} a.hex)";
checkTree(tree);
tree = "(table (trunc (cols a.hex 1)))";
checkTree(tree);
tree = "(table (cols a.hex 1))";
checkTree(tree);
tree = "(table (cols a.hex 1) (cols a.hex 2))";
checkTree(tree);
}
private void checkTree(String tree) { checkTree(tree,false); }
private void checkTree(String tree, boolean expectThrow) {
//Frame r = frame(new double[][]{{-1},{1},{2},{3},{4},{5},{6},{254}});
//Key ahex = Key.make("a.hex");
//Frame fr = new Frame(ahex, null, new Vec[]{r.remove(0)});
//r.delete();
//DKV.put(ahex, fr);
Frame fr = parse_test_file(Key.make("a.hex"),"smalldata/iris/iris_wheader.csv");
fr.remove(4).remove();
try {
Val val = Exec.exec(tree);
Assert.assertFalse(expectThrow);
System.out.println(val.toString());
if( val instanceof ValFrame ) {
Frame fr2= ((ValFrame)val)._fr;
System.out.println(fr2.vec(0));
fr2.remove();
}
} catch( IllegalArgumentException iae ) {
if( !expectThrow ) throw iae;
} finally {
fr.delete();
}
}
@Test public void testCombo() {
Frame fr = parse_test_file(Key.make("a.hex"),"smalldata/iris/iris_wheader.csv");
String tree = "(tmp= py_2 (:= (tmp= py_1 (cbind a.hex (== (cols_py a.hex 4.0 ) \"Iris-setosa\" ) ) ) (as.factor (cols_py py_1 5.0 ) ) 5.0 [] ) )";
//String tree = "(:= (tmp= py_1 a.hex) (h2o.runif a.hex -1) 4 [])";
Val val = Exec.exec(tree);
if( val instanceof ValFrame ) {
Frame fr2= ((ValFrame)val)._fr;
System.out.println(fr2.vec(0));
fr2.remove();
}
fr.delete();
}
@Test public void testMerge() {
Frame l=null,r=null,f=null;
try {
l = ArrayUtils.frame("name" ,vec(ar("Cliff","Arno","Tomas","Spencer"),ari(0,1,2,3)));
l. add("age" ,vec(ar(">dirt" ,"middle","middle","young'n"),ari(0,1,2,3)));
l = new Frame(l);
DKV.put(l);
System.out.println(l);
r = ArrayUtils.frame("name" ,vec(ar("Arno","Tomas","Michael","Cliff"),ari(0,1,2,3)));
r. add("skill",vec(ar("science","linearmath","sparkling","hacker"),ari(0,1,2,3)));
r = new Frame(r);
DKV.put(r);
System.out.println(r);
String x = String.format("(merge %s %s #1 #0 [] [] \"auto\")",l._key,r._key);
Val res = Exec.exec(x);
f = res.getFrame();
System.out.println(f);
Vec names = f.vec(0);
Assert.assertEquals(names.factor(names.at8(0)),"Cliff");
Vec ages = f.vec(1);
Assert.assertEquals(ages .factor(ages .at8(0)),">dirt");
Vec skilz = f.vec(2);
Assert.assertEquals(skilz.factor(skilz.at8(0)),"hacker");
} finally {
if( f != null ) f.delete();
if( r != null ) r.delete();
if( l != null ) l.delete();
}
}
@Test public void testQuantile() {
Frame f = null;
try {
Frame fr = ArrayUtils.frame(ard(ard(1.223292e-02),
ard(1.635312e-25),
ard(1.601522e-11),
ard(8.452298e-10),
ard(2.643733e-10),
ard(2.671520e-06),
ard(1.165381e-06),
ard(7.193265e-10),
ard(3.383532e-04),
ard(2.561221e-05)));
double[] probs = new double[]{0.001, 0.005, .01, .02, .05, .10, .50, .8883, .90, .99};
String x = String.format("(quantile %s %s \"interpolate\")", fr._key, Arrays.toString(probs));
Val val = Exec.exec(x);
fr.delete();
f = val.getFrame();
Assert.assertEquals(2,f.numCols());
// Expected values computed as golden values from R's quantile call
double[] exp = ard(1.4413698000016206E-13, 7.206849000001562E-13, 1.4413698000001489E-12, 2.882739600000134E-12, 7.20684900000009E-12,
1.4413698000000017E-11, 5.831131148999999E-07, 3.3669567275300000E-04, 0.00152780988 , 0.011162408988 );
for( int i=0; i<exp.length; i++ )
Assert.assertTrue( "expected "+exp[i]+" got "+f.vec(1).at(i), water.util.MathUtils.compare(exp[i],f.vec(1).at(i),1e-6,1e-6) );
} finally {
if( f != null ) f.delete();
}
}
static void exec_str( String str, Session ses ) {
Val val = Exec.exec(str,ses);
switch( val.type() ) {
case Val.FRM:
Frame fr = val.getFrame();
System.out.println(fr);
checkSaneFrame();
break;
case Val.NUM:
System.out.println("num= "+val.getNum());
checkSaneFrame();
break;
case Val.STR:
System.out.println("str= "+val.getStr());
checkSaneFrame();
break;
default:
throw water.H2O.fail();
}
}
static void checkSaneFrame() { assert checkSaneFrame_impl(); }
static boolean checkSaneFrame_impl() {
for( Key k : H2O.localKeySet() ) {
Value val = Value.STORE_get(k);
if( val != null && val.isFrame() ) {
Frame fr = val.get();
Vec vecs[] = fr.vecs();
for( int i=0; i<vecs.length; i++ ) {
Vec v = vecs[i];
if( DKV.get(v._key) == null ) {
System.err.println("Frame "+fr._key+" in the DKV, is missing Vec "+v._key+", name="+fr._names[i]);
return false;
}
}
}
}
return true;
}
@Test public void testRowSlice() {
Session ses = new Session();
Frame fr = null;
try {
fr = parse_test_file(Key.make("a.hex"),"smalldata/airlines/AirlinesTrainMM.csv.zip");
System.out.printf(fr.toString());
Exec.exec("(tmp= flow_1 (h2o.runif a.hex -1))",ses);
Exec.exec("(tmp= f.25 (rows a.hex (< flow_1 0.25) ) )",ses);
Exec.exec("(tmp= f.75 (rows a.hex (>= flow_1 0.25) ) )",ses);
Exec.exec("(tmp= flow_2 (h2o.runif a.hex -1))",ses);
ses.end(null);
} catch( Throwable ex ) {
throw ses.endQuietly(ex);
} finally {
fr.delete();
}
}
@Test public void testChicago() {
String oldtz = Exec.exec("(getTimeZone)").getStr();
Session ses = new Session();
try {
parse_test_file(Key.make("weather.hex"),"smalldata/chicago/chicagoAllWeather.csv");
parse_test_file(Key.make( "crimes.hex"),"smalldata/chicago/chicagoCrimes10k.csv.zip");
String fname = "smalldata/chicago/chicagoCensus.csv";
File f = find_test_file(fname);
assert f != null && f.exists():" file not found: " + fname;
NFSFileVec nfs = NFSFileVec.make(f);
ParseSetup ps = ParseSetup.guessSetup(new Key[]{nfs._key}, false, 1);
ps.getColumnTypes()[1] = Vec.T_CAT;
ParseDataset.parse(Key.make( "census.hex"), new Key[]{nfs._key}, true, ps);
exec_str("(assign census.hex (colnames= census.hex [0 1 2 3 4 5 6 7 8] [\"Community.Area.Number\" \"COMMUNITY.AREA.NAME\" \"PERCENT.OF.HOUSING.CROWDED\" \"PERCENT.HOUSEHOLDS.BELOW.POVERTY\" \"PERCENT.AGED.16..UNEMPLOYED\" \"PERCENT.AGED.25..WITHOUT.HIGH.SCHOOL.DIPLOMA\" \"PERCENT.AGED.UNDER.18.OR.OVER.64\" \"PER.CAPITA.INCOME.\" \"HARDSHIP.INDEX\"]))", ses);
exec_str("(assign crimes.hex (colnames= crimes.hex [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21] [\"ID\" \"Case.Number\" \"Date\" \"Block\" \"IUCR\" \"Primary.Type\" \"Description\" \"Location.Description\" \"Arrest\" \"Domestic\" \"Beat\" \"District\" \"Ward\" \"Community.Area\" \"FBI.Code\" \"X.Coordinate\" \"Y.Coordinate\" \"Year\" \"Updated.On\" \"Latitude\" \"Longitude\" \"Location\"]))", ses);
exec_str("(setTimeZone \"Etc/UTC\")", ses);
exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_6 (day (tmp= nary_op_5 (as.Date (cols crimes.hex [2]) \"%m/%d/%Y %I:%M:%S %p\")))) \"Day\"))", ses);
checkSaneFrame();
exec_str("(assign crimes.hex (append crimes.hex (tmp= binary_op_31 (+ (tmp= unary_op_7 (month nary_op_5)) #1)) \"Month\"))", ses);
exec_str("(rm nary_op_30)",ses);
exec_str("(assign crimes.hex (append crimes.hex (tmp= binary_op_32 (+ (tmp= binary_op_9 (- (tmp= unary_op_8 (year nary_op_5)) #1900)) #1900)) \"Year\"))", ses);
exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_10 (week nary_op_5)) \"WeekNum\"))", ses);
exec_str("(rm binary_op_32)",ses);
exec_str("(rm binary_op_31)",ses);
exec_str("(rm unary_op_8)",ses);
checkSaneFrame();
exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_11 (dayOfWeek nary_op_5)) \"WeekDay\"))", ses);
exec_str("(rm nfs:\\C:\\Users\\cliffc\\Desktop\\h2o-3\\smalldata\\chicago\\chicagoCrimes10k.csv.zip)",ses);
exec_str("(assign crimes.hex (append crimes.hex (tmp= unary_op_12 (hour nary_op_5)) \"HourOfDay\"))", ses);
exec_str("(assign crimes.hex (append crimes.hex (tmp= nary_op_16 (ifelse (tmp= binary_op_15 (| (tmp= binary_op_13 (== unary_op_11 \"Sun\")) (tmp= binary_op_14 (== unary_op_11 \"Sat\")))) 1 0)) \"Weekend\"))", ses);
// Season is incorrectly assigned in the original chicago demo; picks up the Weekend flag
exec_str("(assign crimes.hex (append crimes.hex nary_op_16 \"Season\"))", ses);
// Standard "head of 10 rows" pattern for printing
exec_str("(tmp= subset_33 (rows crimes.hex [0:10]))", ses);
exec_str("(rm subset_33)",ses);
exec_str("(rm subset_33)",ses);
exec_str("(rm unary_op_29)",ses);
exec_str("(rm nary_op_28)",ses);
exec_str("(rm nary_op_27)",ses);
exec_str("(rm nary_op_26)",ses);
exec_str("(rm binary_op_25)",ses);
exec_str("(rm binary_op_24)",ses);
exec_str("(rm binary_op_23)",ses);
exec_str("(rm binary_op_22)",ses);
exec_str("(rm binary_op_21)",ses);
exec_str("(rm binary_op_20)",ses);
exec_str("(rm binary_op_19)",ses);
exec_str("(rm binary_op_18)",ses);
exec_str("(rm binary_op_17)",ses);
exec_str("(rm nary_op_16)",ses);
exec_str("(rm binary_op_15)",ses);
exec_str("(rm binary_op_14)",ses);
exec_str("(rm binary_op_13)",ses);
exec_str("(rm unary_op_12)",ses);
exec_str("(rm unary_op_11)",ses);
exec_str("(rm unary_op_10)",ses);
exec_str("(rm binary_op_9)",ses);
exec_str("(rm unary_op_8)",ses);
exec_str("(rm unary_op_7)",ses);
exec_str("(rm unary_op_6)",ses);
exec_str("(rm nary_op_5)",ses);
checkSaneFrame();
// Standard "head of 10 rows" pattern for printing
exec_str("(tmp= subset_34 (rows crimes.hex [0:10]))", ses);
exec_str("(rm subset_34)",ses);
exec_str("(assign census.hex (colnames= census.hex [0 1 2 3 4 5 6 7 8] [\"Community.Area\" \"COMMUNITY.AREA.NAME\" \"PERCENT.OF.HOUSING.CROWDED\" \"PERCENT.HOUSEHOLDS.BELOW.POVERTY\" \"PERCENT.AGED.16..UNEMPLOYED\" \"PERCENT.AGED.25..WITHOUT.HIGH.SCHOOL.DIPLOMA\" \"PERCENT.AGED.UNDER.18.OR.OVER.64\" \"PER.CAPITA.INCOME.\" \"HARDSHIP.INDEX\"]))", ses);
exec_str("(rm subset_34)",ses);
exec_str("(tmp= subset_35 (cols crimes.hex [-3]))", ses);
exec_str("(tmp= subset_36 (cols weather.hex [-1]))", ses);
exec_str("(tmp= subset_36_2 (colnames= subset_36 [0 1 2 3 4 5] [\"Month\" \"Day\" \"Year\" \"maxTemp\" \"meanTemp\" \"minTemp\"]))", ses);
exec_str("(rm crimes.hex)",ses);
exec_str("(rm weather.hex)",ses);
// nary_op_37 = merge( X Y ); Vecs in X & nary_op_37 shared
exec_str("(tmp= nary_op_37 (merge subset_35 census.hex TRUE FALSE [] [] \"auto\"))", ses);
// nary_op_38 = merge( nary_op_37 subset_36_2); Vecs in nary_op_38 and nary_pop_37 and X shared
exec_str("(tmp= subset_41 (rows (tmp= nary_op_38 (merge nary_op_37 subset_36_2 TRUE FALSE [] [] \"auto\")) (tmp= binary_op_40 (<= (tmp= nary_op_39 (h2o.runif nary_op_38 30792152736.5179)) #0.8))))", ses);
// Standard "head of 10 rows" pattern for printing
exec_str("(tmp= subset_44 (rows subset_41 [0:10]))", ses);
exec_str("(rm subset_44)",ses);
exec_str("(rm subset_44)",ses);
exec_str("(rm binary_op_40)",ses);
exec_str("(rm nary_op_37)",ses);
exec_str("(tmp= subset_43 (rows nary_op_38 (tmp= binary_op_42 (> nary_op_39 #0.8))))", ses);
// Chicago demo continues on past, but this is all I've captured for now
checkSaneFrame();
ses.end(null);
} catch( Throwable ex ) {
throw ses.endQuietly(ex);
} finally {
Exec.exec("(setTimeZone \""+oldtz+"\")"); // Restore time zone (which is global, and will affect following tests)
for( String s : new String[]{"weather.hex","crimes.hex","census.hex",
"nary_op_5", "unary_op_6", "unary_op_7", "unary_op_8", "binary_op_9",
"unary_op_10", "unary_op_11", "unary_op_12", "binary_op_13",
"binary_op_14", "binary_op_15", "nary_op_16", "binary_op_17",
"binary_op_18", "binary_op_19", "binary_op_20", "binary_op_21",
"binary_op_22", "binary_op_23", "binary_op_24", "binary_op_25",
"nary_op_26", "nary_op_27", "nary_op_28", "unary_op_29", "binary_op_30",
"binary_op_31", "binary_op_32", "subset_33", "subset_34", "subset_35",
"subset_36", "subset_36_2", "nary_op_37", "nary_op_38", "nary_op_39", "binary_op_40",
"subset_41", "binary_op_42", "subset_43", "subset_44", } )
Keyed.remove(Key.make(s));
}
}
} |
package com.orientechnologies.orient.test.database.auto;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.orient.client.db.ODatabaseHelper;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/**
* @author Michael Hiess
*
*/
public class MultipleDBTest {
private String baseUrl;
@Parameters(value = "url")
public MultipleDBTest(String iURL) {
baseUrl = iURL + "-";
}
@Test
public void testObjectMultipleDBsThreaded() throws Exception {
final int operations_write = 1000;
final int operations_read = 1;
final int dbs = 10;
final Semaphore sem = new Semaphore(4, true);
final AtomicInteger activeDBs = new AtomicInteger(dbs);
final Set<String> times = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
for (int i = 0; i < dbs; i++) {
sem.acquire();
final String dbUrl = baseUrl + i;
Thread t = new Thread(new Runnable() {
public void run() {
ODatabaseObjectTx tx = new ODatabaseObjectTx(dbUrl);
try {
ODatabaseHelper.deleteDatabase(tx);
ODatabaseHelper.createDatabase(tx, dbUrl);
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("(" + dbUrl + ") " + "Created");
if (tx.isClosed()) {
tx.open("admin", "admin");
}
tx.getEntityManager().registerEntityClass(DummyObject.class);
// System.out.println("(" + dbUrl + ") " + "Registered: " + DummyObject.class);
// System.out.println("(" + dbUrl + ") " + "Calling: " + operations + " operations");
long start = System.currentTimeMillis();
for (int j = 0; j < operations_write; j++) {
DummyObject dummy = new DummyObject("name" + j);
tx.save(dummy);
Assert.assertEquals(((ORID) dummy.getId()).getClusterPosition(), j);
if ((j + 1) % 20000 == 0) {
System.out.println("(" + dbUrl + ") " + "Operations (WRITE) executed: " + (j + 1));
}
}
long end = System.currentTimeMillis();
String time = "(" + dbUrl + ") " + "Executed operations (WRITE) in: " + (end - start) + " ms";
System.out.println(time);
times.add(time);
start = System.currentTimeMillis();
for (int j = 0; j < operations_read; j++) {
List<DummyObject> l = tx.query(new OSQLSynchQuery<DummyObject>(" select * from DummyObject "));
Assert.assertEquals(l.size(), operations_write);
if ((j + 1) % 20000 == 0) {
System.out.println("(" + dbUrl + ") " + "Operations (READ) executed: " + j + 1);
}
}
end = System.currentTimeMillis();
time = "(" + dbUrl + ") " + "Executed operations (READ) in: " + (end - start) + " ms";
System.out.println(time);
times.add(time);
tx.close();
sem.release();
activeDBs.decrementAndGet();
} finally {
try {
ODatabaseHelper.deleteDatabase(tx);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
while (activeDBs.get() != 0) {
Thread.sleep(300);
}
// System.out.println("Times:");
// for (String s : times) {
// System.out.println(s);
System.out.println("Test testObjectMultipleDBsThreaded ended");
}
@Test
public void testDocumentMultipleDBsThreaded() throws Exception {
final int operations_write = 1000;
final int operations_read = 1;
final int dbs = 10;
final Semaphore sem = new Semaphore(4, true);
final AtomicInteger activeDBs = new AtomicInteger(dbs);
final Set<String> times = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
for (int i = 0; i < dbs; i++) {
sem.acquire();
final String dbUrl = baseUrl + i;
Thread t = new Thread(new Runnable() {
public void run() {
ODatabaseDocumentTx tx = new ODatabaseDocumentTx(dbUrl);
try {
ODatabaseHelper.deleteDatabase(tx);
ODatabaseHelper.createDatabase(tx, dbUrl);
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("(" + dbUrl + ") " + "Created");
if (tx.isClosed()) {
tx.open("admin", "admin");
}
// tx.getEntityManager().registerEntityClass(DummyObject.class);
// System.out.println("(" + dbUrl + ") " + "Registered: " + DummyObject.class);
// System.out.println("(" + dbUrl + ") " + "Calling: " + operations + " operations");
long start = System.currentTimeMillis();
for (int j = 0; j < operations_write; j++) {
// DummyObject dummy = new DummyObject("name" + j);
// tx.save(dummy);
ODocument dummy = new ODocument(tx, "DummyObject");
dummy.field("name", "name" + j);
tx.save(dummy);
Assert.assertEquals(((ORID) dummy.getIdentity()).getClusterPosition(), j);
// Assert.assertEquals(dummy.getId().toString(), "#5:" + j);
if ((j + 1) % 20000 == 0) {
System.out.println("(" + dbUrl + ") " + "Operations (WRITE) executed: " + (j + 1));
}
}
long end = System.currentTimeMillis();
String time = "(" + dbUrl + ") " + "Executed operations (WRITE) in: " + (end - start) + " ms";
System.out.println(time);
times.add(time);
start = System.currentTimeMillis();
for (int j = 0; j < operations_read; j++) {
List<DummyObject> l = tx.query(new OSQLSynchQuery<DummyObject>(" select * from DummyObject "));
Assert.assertEquals(l.size(), operations_write);
if ((j + 1) % 20000 == 0) {
System.out.println("(" + dbUrl + ") " + "Operations (READ) executed: " + j + 1);
}
}
end = System.currentTimeMillis();
time = "(" + dbUrl + ") " + "Executed operations (READ) in: " + (end - start) + " ms";
System.out.println(time);
times.add(time);
tx.close();
sem.release();
activeDBs.decrementAndGet();
} finally {
try {
ODatabaseHelper.deleteDatabase(tx);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
while (activeDBs.get() != 0) {
Thread.sleep(300);
}
// System.out.println("Times:");
// for (String s : times) {
// System.out.println(s);
System.out.println("Test testDocumentMultipleDBsThreaded ended");
}
} |
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */
package jp.oist.flint.form.sub;
import jp.oist.flint.form.job.CombinationModel;
import jp.oist.flint.form.job.GadgetDialog;
import jp.oist.flint.form.job.ParameterFilter;
import jp.oist.flint.form.job.JobList;
import jp.oist.flint.garuda.GarudaClient;
import jp.oist.flint.phsp.entity.ParameterSet;
import jp.sbi.garuda.platform.commons.net.GarudaConnectionNotInitializedException;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import jp.oist.flint.control.FileChooser;
import jp.oist.flint.dao.JobDao;
import jp.oist.flint.dao.TaskDao;
import jp.oist.flint.executor.PhspSimulator;
import jp.oist.flint.export.ExportWorker;
import jp.oist.flint.filesystem.Workspace;
import jp.oist.flint.form.IFrame;
import jp.oist.flint.form.MainFrame;
import jp.oist.flint.form.job.ExportAllWorker;
import jp.oist.flint.form.job.IParameterInfo;
import jp.oist.flint.form.job.IProgressManager;
import jp.oist.flint.form.job.JobViewerComponent;
import jp.oist.flint.form.job.PlotWindow;
import jp.oist.flint.util.Utility;
import jp.physiome.Ipc;
public class JobWindow extends javax.swing.JFrame
implements MouseListener, MouseMotionListener, ActionListener,
IProgressManager {
private final static String ACTION_LIST = "jobwindow.action.joblist";
private final static String ACTION_VIEWER = "jobwindow.action.jobviewer";
private final static String ACTION_EXPORT_ALL = "jobwindow.action.exportAll";
private final static String ACTION_EXPORT_CANCEL = "jobwindow.action.exportCancel";
private final static String PANELKEY_LIST = "jobwindow.cardlayout.joblist";
private final static String PANELKEY_VIEWER = "jobwindow.cardlayout.jobviewer";
private final static String STATUSBAR_CARD_MESSAGE = "jobwindow.statusbar.message";
private final static String STATUSBAR_CARD_PROGRESS = "jobwindow.statusbar.progress";
private JobList mJobList;
private JobViewerComponent mJobViewer;
private final SubFrame mParent;
private ListSelectionModel mSelectionModel;
private CombinationModel mDataModel;
private PhspSimulator mSimulator;
private ExportAllWorker mExportWorker;
private JobViewerContextMenuHandler mContextMenuHandler;
public JobWindow(SubFrame parent, String title)
throws IOException {
super(title);
mParent = parent;
URL iconUrl = getClass().getResource("/jp/oist/flint/image/icon.png");
setIconImage(new ImageIcon(iconUrl).getImage());
initComponents();
initEvents();
}
private void initEvents () {
mSelectionModel = new DefaultListSelectionModel();
mDataModel = new CombinationModel();
mContextMenuHandler = new JobViewerContextMenuHandler();
JobList list = newJobList();
setJobList(list);
JobViewerComponent viewer = newJobViewer(null);
setJobViewer(viewer);
pack();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
}
});
btn_Viewer.addActionListener(this);
btn_List.addActionListener(this);
btn_ExportAll.addActionListener(this);
btn_ExportCancel.addActionListener(this);
}
private JobList newJobList () {
JobList jobList = new JobList();
jobList.setName(PANELKEY_LIST);
jobList.setParameterInfo(mDataModel);
jobList.setModel(mDataModel);
jobList.setSelectionModel(mSelectionModel);
jobList.setContextMenuHandler(mContextMenuHandler);
return jobList;
}
private void setJobList (JobList newComponent) {
for (Component c : pnl_Body.getComponents()) {
if (PANELKEY_LIST.equals(c.getName())) {
pnl_Body.remove(c);
break;
}
}
pnl_Body.add(newComponent, PANELKEY_LIST);
mJobList = newComponent;
}
private JobList getJobList () {
return mJobList;
}
private JobViewerComponent newJobViewer (IParameterInfo pInfo) {
JobViewerComponent viewer = JobViewerComponent.factory(pInfo);
viewer.setModel(mDataModel);
viewer.setSelectionModel(mSelectionModel);
viewer.setContextMenuHandler(mContextMenuHandler);
return viewer;
}
private void setJobViewer (JobViewerComponent newComponent) {
for (Component c : pnl_Body.getComponents()) {
if (PANELKEY_VIEWER.equals(c.getName())) {
c.removeMouseListener(this);
c.removeMouseMotionListener(this);
pnl_Body.remove(c);
break;
}
}
newComponent.addMouseListener(this);
newComponent.addMouseMotionListener(this);
JScrollPane scrollPane = new JScrollPane(newComponent);
scrollPane.setName(PANELKEY_VIEWER);
scrollPane.setPreferredSize(new Dimension(640, 480));
scrollPane.setOpaque(false);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
pnl_Body.add(scrollPane, PANELKEY_VIEWER);
mJobViewer = newComponent;
}
public JobViewerComponent getJobViewer () {
return mJobViewer;
}
public void load (ParameterSet parameterSet) {
if (mSelectionModel != null)
mSelectionModel.clearSelection();
mDataModel.removeAll();
mDataModel.load(parameterSet, new ParameterFilter () {
@Override
public boolean accept (Number[] values) {
return values.length > 1;
}
});
mDataModel.setParameterIsDummy(parameterSet instanceof ParameterSet.Dummy);
JobViewerComponent viewer = newJobViewer(mDataModel);
setJobViewer(viewer);
btn_Viewer.setVisible(!mDataModel.getParameterIsDummy());
btn_Viewer.repaint();
}
public void setSimulator (PhspSimulator simulator) {
mSimulator = simulator;
}
PhspSimulator getSimulator () {
return mSimulator;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
pnl_Head = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
lbl_View = new javax.swing.JLabel();
btn_List = new javax.swing.JToggleButton();
btn_Viewer = new javax.swing.JToggleButton();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
btn_ExportAll = new javax.swing.JButton();
pnl_Body = new javax.swing.JPanel();
pnl_StatusBar = new javax.swing.JPanel();
lbl_StatusBar = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
pb_StatusBar = new javax.swing.JProgressBar();
btn_ExportCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
pnl_Head.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0));
pnl_Head.setMaximumSize(new java.awt.Dimension(32767, 50));
pnl_Head.setMinimumSize(new java.awt.Dimension(10, 50));
pnl_Head.setOpaque(false);
pnl_Head.setPreferredSize(new java.awt.Dimension(700, 50));
pnl_Head.setRequestFocusEnabled(false);
pnl_Head.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0));
jPanel1.setMaximumSize(new java.awt.Dimension(32767, 50));
jPanel1.setMinimumSize(new java.awt.Dimension(350, 50));
jPanel1.setOpaque(false);
jPanel1.setPreferredSize(new java.awt.Dimension(350, 50));
jPanel1.setRequestFocusEnabled(false);
java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0);
flowLayout1.setAlignOnBaseline(true);
jPanel1.setLayout(flowLayout1);
jPanel4.setMaximumSize(new java.awt.Dimension(32767, 50));
jPanel4.setMinimumSize(new java.awt.Dimension(300, 50));
jPanel4.setPreferredSize(new java.awt.Dimension(300, 50));
jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));
lbl_View.setText("View : ");
jPanel4.add(lbl_View);
buttonGroup1.add(btn_List);
btn_List.setSelected(true);
btn_List.setText("List");
btn_List.setActionCommand("jobwindow.action.joblist");
btn_List.setAutoscrolls(true);
btn_List.setMaximumSize(new java.awt.Dimension(100, 22));
btn_List.setMinimumSize(new java.awt.Dimension(100, 22));
btn_List.setPreferredSize(new java.awt.Dimension(100, 22));
jPanel4.add(btn_List);
buttonGroup1.add(btn_Viewer);
btn_Viewer.setText("Chart");
btn_Viewer.setActionCommand("jobwindow.action.jobviewer");
btn_Viewer.setAutoscrolls(true);
btn_Viewer.setMaximumSize(new java.awt.Dimension(100, 22));
btn_Viewer.setMinimumSize(new java.awt.Dimension(100, 22));
btn_Viewer.setPreferredSize(new java.awt.Dimension(100, 22));
btn_Viewer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_ViewerActionPerformed(evt);
}
});
jPanel4.add(btn_Viewer);
jPanel1.add(jPanel4);
pnl_Head.add(jPanel1, java.awt.BorderLayout.WEST);
jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 0, 2, 0));
jPanel2.setMaximumSize(new java.awt.Dimension(32767, 50));
jPanel2.setMinimumSize(new java.awt.Dimension(350, 50));
jPanel2.setOpaque(false);
jPanel2.setPreferredSize(new java.awt.Dimension(350, 50));
jPanel2.setRequestFocusEnabled(false);
java.awt.FlowLayout flowLayout2 = new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 5, 0);
flowLayout2.setAlignOnBaseline(true);
jPanel2.setLayout(flowLayout2);
jPanel3.setMaximumSize(new java.awt.Dimension(32767, 50));
jPanel3.setMinimumSize(new java.awt.Dimension(110, 50));
jPanel3.setName(""); // NOI18N
jPanel3.setPreferredSize(new java.awt.Dimension(110, 50));
jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));
btn_ExportAll.setText("Export All");
btn_ExportAll.setActionCommand("jobwindow.action.exportAll");
btn_ExportAll.setEnabled(false);
btn_ExportAll.setMaximumSize(new java.awt.Dimension(110, 22));
btn_ExportAll.setMinimumSize(new java.awt.Dimension(110, 22));
btn_ExportAll.setPreferredSize(new java.awt.Dimension(110, 22));
jPanel3.add(btn_ExportAll);
jPanel2.add(jPanel3);
pnl_Head.add(jPanel2, java.awt.BorderLayout.EAST);
getContentPane().add(pnl_Head, java.awt.BorderLayout.NORTH);
pnl_Body.setBackground(java.awt.Color.white);
pnl_Body.setLayout(new java.awt.CardLayout());
getContentPane().add(pnl_Body, java.awt.BorderLayout.CENTER);
pnl_StatusBar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnl_StatusBar.setPreferredSize(new java.awt.Dimension(800, 20));
pnl_StatusBar.setLayout(new java.awt.CardLayout());
lbl_StatusBar.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
lbl_StatusBar.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 0));
lbl_StatusBar.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
pnl_StatusBar.add(lbl_StatusBar, "jobwindow.statusbar.message");
jPanel5.setLayout(new javax.swing.BoxLayout(jPanel5, javax.swing.BoxLayout.LINE_AXIS));
pb_StatusBar.setMaximumSize(new java.awt.Dimension(32767, 18));
pb_StatusBar.setMinimumSize(new java.awt.Dimension(20, 18));
pb_StatusBar.setPreferredSize(new java.awt.Dimension(148, 18));
jPanel5.add(pb_StatusBar);
btn_ExportCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jp/oist/flint/image/cancel.png"))); // NOI18N
btn_ExportCancel.setActionCommand("jobwindow.action.exportCancel");
btn_ExportCancel.setMaximumSize(new java.awt.Dimension(20, 20));
btn_ExportCancel.setMinimumSize(new java.awt.Dimension(20, 20));
btn_ExportCancel.setPreferredSize(new java.awt.Dimension(20, 20));
jPanel5.add(btn_ExportCancel);
pnl_StatusBar.add(jPanel5, "jobwindow.statusbar.progress");
getContentPane().add(pnl_StatusBar, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_ViewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ViewerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btn_ViewerActionPerformed
public void setMessageOnStatusBar (String msg) {
CardLayout layout = (CardLayout)pnl_StatusBar.getLayout();
layout.show(pnl_StatusBar, STATUSBAR_CARD_MESSAGE);
lbl_StatusBar.setText(msg);
}
public void setProgressOnStatusBar (String msg, int progress) {
CardLayout layout = (CardLayout)pnl_StatusBar.getLayout();
layout.show(pnl_StatusBar, STATUSBAR_CARD_PROGRESS);
pb_StatusBar.setValue(progress);
}
public int getSelectedIndex () {
return mJobViewer.getSelectedIndex();
}
public int[] getSelectedIndices () {
return mJobViewer.getSelectedIndices();
}
private void showMessageDialog (String msg, String title) {
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.INFORMATION_MESSAGE);
}
private void showErrorDialog (String msg, String title) {
JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
}
public void addPropertyChangeListenerForProgress(SwingWorker worker) {
worker.addPropertyChangeListener(new PropertyChangeListener (){
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
if ("progress".equals(propertyName)) {
int percentage = (Integer)newValue;
setProgressOnStatusBar(percentage + "%", percentage);
} else if ("state".equals(propertyName)
&& SwingWorker.StateValue.DONE.equals(newValue)) {
setMessageOnStatusBar("");
}
}
});
}
/*
* Implements IProgressManager
*/
@Override
public int getProgressCount () {
return mDataModel.getSize();
}
@Override
public void setProgress (int index, int progress) {
mJobViewer.setProgress(index, progress);
mJobList.setProgress(index, progress);
repaint();
}
@Override
public int getProgress (int index) {
return mJobList.getProgress(index);
}
@Override
public boolean isCancelled (int index) {
return mJobList.isCancelled(index);
}
@Override
public void setCancelled (int index, boolean cancelled) {
mJobList.setCancelled(index, cancelled);
mJobViewer.setCancelled(index, cancelled);
}
@Override
public int indexOf (Object key) {
Map<String, Number> combination = (Map<String, Number>)key;
Number[] target = new Number[combination.size()];
String[] titles = mDataModel.getTitles();
for (int i=0; i<titles.length; i++)
target[i] = combination.get(titles[i]);
return mDataModel.indexOf(target);
}
/*
* Implements MouseListener, ouse
*/
@Override
public void mouseClicked (MouseEvent evt) {
}
@Override
public void mouseEntered (MouseEvent evt) {
}
@Override
public void mouseExited (MouseEvent evt) {
lbl_StatusBar.setText("");
}
@Override
public void mousePressed(MouseEvent evt) {
}
@Override
public void mouseReleased(MouseEvent evt) {
}
/*
* Implements MouseMotionListener
*/
@Override
public void mouseMoved (MouseEvent evt) {
if (evt.getSource() instanceof JobViewerComponent.Empty)
return;
Map<Integer, Number>values = mJobViewer.getValuesAtHover(evt.getPoint());
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (values == null || values.isEmpty()) {
lbl_StatusBar.setText("");
return;
}
setCursor(new Cursor(Cursor.HAND_CURSOR));
StringBuilder sb = new StringBuilder();
for (Map.Entry<Integer, Number> v : values.entrySet())
sb.append(String.format("%s=%s ",
mDataModel.getTitle(v.getKey()),
v.getValue()));
lbl_StatusBar.setText(sb.toString());
}
@Override
public void mouseDragged(MouseEvent evt) {
}
/*
* Implements ActionListener
*/
@Override
public void actionPerformed(ActionEvent evt) {
String actionCommand = evt.getActionCommand();
if (actionCommand == null)
return;
CardLayout cardLayout = (CardLayout)pnl_Body.getLayout();
int selectedIndex = mSelectionModel.getMinSelectionIndex();
switch (actionCommand) {
case ACTION_LIST:
cardLayout.show(pnl_Body, PANELKEY_LIST);
if (selectedIndex >= 0)
mJobList.ensureIndexIsVisible(selectedIndex);
break;
case ACTION_VIEWER:
cardLayout.show(pnl_Body, PANELKEY_VIEWER);
if (selectedIndex >= 0)
mJobViewer.ensureIndexIsVisible(selectedIndex);
break;
case ACTION_EXPORT_ALL:
exportAllPerformed(evt);
break;
case ACTION_EXPORT_CANCEL:
exportCancelPerformed(evt);
break;
}
}
/*
* Implements JobViewComponent.Handler
*/
public void plotPerformed (JobViewerComponent.Event evt) {
Ipc.SimulationTrack st;
try {
if (evt == null || evt.getIndex() < 0)
throw new IOException("Please choose the job.");
int index = evt.getIndex();
if (mSimulator == null || mSimulator.getSimulationDao() == null)
throw new IOException("Don't run the simulation.");
TaskDao taskDao = mSimulator.getSimulationDao()
.obtainTask(new File(mParent.getRelativeModelPath()));
if (taskDao == null)
throw new IOException("Job Directory does not exist.");
File trackFile = taskDao.getTrackFile();
st = Ipc.SimulationTrack.parseFrom((new FileInputStream(trackFile)));
Number[] values = mDataModel.getValues(index);
String[] titles = mDataModel.getTitles();
int jobId = taskDao.indexOf(values, titles);
StringBuilder sb = new StringBuilder();
for (int i=0; i<titles.length; i++)
sb.append(String.format("%s=%s ", titles[i], values[i]));
PlotWindow plotWindow = new PlotWindow(mParent, sb.toString(), taskDao, jobId);
plotWindow.setLocationRelativeTo(mParent);
plotWindow.setVisible(true);
plotWindow.processSimulationTrack(st);
plotWindow.renderPlot();
} catch (IOException ex) {
if (mParent instanceof IFrame) {
IFrame frame = (IFrame)mParent;
frame.showErrorDialog("It has not finished yet.", "ERROR");
}
}
}
public void exportAllPerformed (ActionEvent evt) {
try {
if (mSimulator == null || mSimulator.getSimulationDao() == null)
throw new Exception("Could not open the simulation files.");
File defaultDir = new File(System.getProperty("user.home"));
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(defaultDir);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fileChooser.showDialog(mParent, "Export All");
if (result != JFileChooser.APPROVE_OPTION)
return;
File selectedDir = fileChooser.getSelectedFile();
if (!selectedDir.exists()) {
result = JOptionPane.showConfirmDialog(mParent,
String.format("%s does not exist; do you want to create the new directory and proceed?",
selectedDir.getName()),
"", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION)
return;
selectedDir.mkdirs();
}
TaskDao taskDao = mSimulator.getSimulationDao()
.obtainTask(new File(mParent.getRelativeModelPath()));
mExportWorker = new ExportAllWorker(this, selectedDir, taskDao);
mExportWorker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
ExportAllWorker worker = (ExportAllWorker)evt.getSource();
String propertyName = evt.getPropertyName();
Object nv = evt.getNewValue();
if ("progress".equals(propertyName)) {
int progress = (Integer)nv;
String msg = progress + " %";
setProgressOnStatusBar(msg, progress);
} else if (SwingWorker.StateValue.STARTED.equals(nv)
&& "state".equals(propertyName)) {
Window window = SwingUtilities.windowForComponent(mParent);
((MainFrame)window).setEditable(false);
} else if (SwingWorker.StateValue.DONE.equals(nv)
&& "state".equals(propertyName)) {
setMessageOnStatusBar("");
// FIXME
Window window = SwingUtilities.windowForComponent(mParent);
((MainFrame)window).setEditable(true);
try {
worker.get();
if (!worker.isExportingCancelled()) {
JOptionPane.showMessageDialog(JobWindow.this,
"Exported simulation data to "
+ worker.getExportedDirecotry().getPath(),
"Export is completed.",
JOptionPane.INFORMATION_MESSAGE);
}
} catch (CancellationException ex) {
JOptionPane.showMessageDialog(JobWindow.this,
"Exporting simulation data is cancelled.",
"Exporting is cancelled.", JOptionPane.INFORMATION_MESSAGE);
} catch (InterruptedException | ExecutionException | HeadlessException ex) {
showErrorDialog(ex.getMessage(),
"Error on exporting simulation data");
} finally {
mExportWorker = null;
}
}
}
});
mExportWorker.execute();
} catch (Exception ex) {
showErrorDialog(ex.getMessage(),
"Error on exporting simulation data");
}
}
public void exportCancelPerformed (ActionEvent evt) {
if (mExportWorker != null) {
mExportWorker.cancel(true);
mExportWorker = null;
}
}
public void exportPerformed(JobViewerComponent.Event evt) {
try {
if (evt == null || evt.getIndex() < 0)
throw new IOException("Please choose the job.");
if (mSimulator == null || mSimulator.getSimulationDao() == null)
throw new IOException("It has not finished yet.");
TaskDao taskDao = mSimulator.getSimulationDao().obtainTask(new File(mParent.getRelativeModelPath()));
if (taskDao == null)
throw new IOException("It has not finished yet.");
int jobId = taskDao.indexOf(mDataModel.getValues(
evt.getIndex()), mDataModel.getTitles());
if (jobId < 0)
throw new IOException("It has not finished yet.");
File isdFile = taskDao.obtainJob(jobId).getIsdFile();
if (isdFile == null || !isdFile.exists())
throw new IOException("It has not finished yet.");
String baseName = Utility.getFileName(mParent.getModelFile().getName());
File defaultFile = new File(mParent.getModelFile().getParent(),
baseName + "_" + jobId + ".csv");
FileChooser fileChooser = new FileChooser(mParent,
"Export file", FileChooser.Mode.SAVE, defaultFile);
if (fileChooser.showDialog()) {
final File file = fileChooser.getSelectedFile();
if (file.exists()) {
int ans = JOptionPane.showConfirmDialog(this,
"Is it OK to replace the existing file?",
"Replace the existing file?",
JOptionPane.YES_NO_OPTION);
if (ans != JOptionPane.YES_OPTION)
return;
}
String ext = Utility.getFileExtension(file);
if ("csv".equalsIgnoreCase(ext) ||
"txt".equalsIgnoreCase(ext)) { // export as CSV for these extension
// create a temporary target file
final File csvFile = Workspace.createTempFile("export", ".csv");
csvFile.deleteOnExit();
final ExportWorker worker = new ExportWorker((IFrame)mParent, isdFile, csvFile);
addPropertyChangeListenerForProgress(worker.getMonitor());
worker.addPropertyChangeListener(new PropertyChangeListener(){
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
if ("state".equals(propertyName)
&& SwingWorker.StateValue.DONE.equals(newValue)) {
try {
if (worker.get()) {
Workspace.publishFile(csvFile, file);
showMessageDialog("Exported successfully to " + file.getPath(),
"CSV Exported");
}
} catch (InterruptedException ex) {
showErrorDialog("Export interrupted\n\n" + ex.getMessage(),
"CSV Export interrupted");
} catch (ExecutionException ex) {
showErrorDialog("Export aborted\n\n" + ex.getMessage(),
"CSV Export aborted ");
} catch (IOException ex) {
showErrorDialog("Could not write to " + file.getPath(),
"CSV Export aborted.");
} finally {
// spare the disk space immediately,
// because the resulting CSV file can be quite large
csvFile.delete();
}
}
}
});
worker.execute();
} else {
// export as ISD
Workspace.publishFile(isdFile, file);
showMessageDialog("Exported successfully to " + file.getPath(),
"ISD Exported");
}
}
} catch (IOException ex) {
showErrorDialog("Export failed\n\n" + ex.getMessage(),
"Export failed");
}
}
public void sendViaGarudaPerformed(JobViewerComponent.Event evt) {
try {
if (evt == null || evt.getIndex() < 0)
throw new IOException("Please choose the job.");
if (mSimulator == null || mSimulator.getSimulationDao() == null)
throw new IOException("It has not finished yet.");
TaskDao taskDao = mSimulator.getSimulationDao().obtainTask(new File(mParent.getRelativeModelPath()));
if (taskDao == null)
throw new IOException("It has not finished yet.");
int jobId = taskDao.indexOf(mDataModel.getValues(
evt.getIndex()), mDataModel.getTitles());
if (jobId < 0)
throw new IOException("It has not finished yet.");
File isdFile = taskDao.obtainJob(jobId).getIsdFile();
if (isdFile == null || !isdFile.exists())
throw new IOException("It has not finished yet.");
GadgetDialog dialog = new GadgetDialog(this, mParent, isdFile);
dialog.setLocationRelativeTo(this);
GarudaClient.requestForLoadableGadgets(dialog, "csv");
} catch (GarudaConnectionNotInitializedException gcnie) {
showErrorDialog(gcnie.getMessage(), "Error with Garuda");
} catch (IOException ioe) {
showErrorDialog("Sending file failed\n\n" + ioe.getMessage(),
"Sending file failed");
}
}
public void cancelTaskPerformed (JobViewerComponent.Event evt) {
((SubFrame)mParent).cancelSimulation();
}
public void cancelJobPerformed (JobViewerComponent.Event evt) {
File tmp;
TaskDao taskDao;
try {
if (evt == null || evt.getIndex() < 0)
throw new IOException("Please choose the job.");
if (mSimulator == null || mSimulator.getSimulationDao() == null)
throw new IOException("It has not yet started");
taskDao = mSimulator.getSimulationDao().obtainTask(new File(mParent.getRelativeModelPath()));
if (taskDao == null)
throw new IOException("It has not yet started");
int ans = JOptionPane.showConfirmDialog(this,
"Would you like to cancel simulation job?",
"Cancel simulation?",
JOptionPane.YES_NO_OPTION);
if (ans != JOptionPane.YES_OPTION)
return;
int rowId = taskDao.indexOf(mDataModel.getValues(
evt.getIndex()), mDataModel.getTitles());
JobDao job = taskDao.obtainJob(rowId);
job.cancel(false);
mJobViewer.setCancelled(evt.getIndex(), true);
mJobList.setCancelled(evt.getIndex(), true);
} catch (IOException ex) {
showErrorDialog("Cancellation failed\n\n" + ex.getMessage(),
"Cancellation failed");
return;
}
}
public void onSimulationStarted(PhspSimulator.Event evt) {
}
public void onSimulationExited(PhspSimulator.Event evt) {
btn_ExportAll.setEnabled(true);
}
/*
* Inner classes
*/
private class JobViewerContextMenuHandler extends JobViewerComponent.ContextMenuHandler {
@Override
public void handleEvent(JobViewerComponent.Event evt) {
String action = evt.getAction();
if (action == null)
return;
switch (action) {
case "plot":
plotPerformed(evt);
break;
case "export":
exportPerformed(evt);
break;
case "sendViaGaruda":
sendViaGarudaPerformed(evt);
break;
case "cancelTask":
cancelTaskPerformed(evt);
break;
case "cancelJob":
cancelJobPerformed(evt);
break;
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_ExportAll;
private javax.swing.JButton btn_ExportCancel;
private javax.swing.JToggleButton btn_List;
private javax.swing.JToggleButton btn_Viewer;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JLabel lbl_StatusBar;
private javax.swing.JLabel lbl_View;
private javax.swing.JProgressBar pb_StatusBar;
private javax.swing.JPanel pnl_Body;
private javax.swing.JPanel pnl_Head;
private javax.swing.JPanel pnl_StatusBar;
// End of variables declaration//GEN-END:variables
} |
package com.sandwell.JavaSimulation3D;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Vector;
import com.sun.j3d.utils.behaviors.vp.ViewPlatformAWTBehavior;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import com.sandwell.JavaSimulation3D.util.Rectangle;
import com.sandwell.JavaSimulation3D.util.Shape;
import javax.media.j3d.Transform3D;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;
/**
* Provides mouse events processing of moving the viewer within a J3D environment.<br>
* Provides this functionality by providing the viewer location, the point to look at and the up vector.<br>
* Provides changes of the viewer of: zoom, pan, translate, orbit and field of view angle<br>
* Provides the position of the locator in model units
*/
public class OrbitBehavior extends ViewPlatformAWTBehavior {
public static final double DEFAULT_FOV = Math.PI / 3.15789d; // default if 57 degrees (about human FOV)
public static final double DEFAULT_RADIUS = 2.41d;
static final double MIN_RADIUS = 0.0000001d;
static final double MAX_RADIUS = Double.POSITIVE_INFINITY;
private static final double ORBIT_ANGLE_FACTOR = -0.01d;
// Temporary place where all the entityTooltip state will be shared
static MouseEvent tootipEvent = null;
static OrbitBehavior tooltipBehavior = null;
static boolean showtooltip = true;
static EntityToolTip entityToolTip = null;
// The enumerated mouse behavior modes
static final int CHANGE_PAN = 2;
static final int CHANGE_ROTATION = 4;
static final int CHANGE_TRANSLATION = 8;
static final int CHANGE_ZOOM_BOX = 64;
static final int CHANGE_NODE = 128;
static enum Plane { XY_PLANE, XZ_PLANE, YZ_PLANE };
private final Sim3DWindow window;
private final ModelView modelView;
private final Vector3d orbitCenter;
private final Vector3d orbitAngles;
private double orbitRadius;
private double fov;
// used for calculations (only create once)
private Vector3d universeDatumPoint = new Vector3d();
// Zoom box parameters
private int mouseX = 0;
private int mouseY = 0;
private Rectangle rectangle;
// Do/undo parameters
private Vector undoSteps = new Vector( 10, 1 ); // contains zoom steps
private int undoStep = 0; // The position of the current zoom step in undoSteps
private boolean windowMovedAndResized = false; // true => window both resized and moved
private static int mouseMode = OrbitBehavior.CHANGE_TRANSLATION;
private static boolean positionMode = true;
private static String currentCreationClass;
private Vector3d dragEntityStartPosition = new Vector3d();
// resize
protected static DisplayEntity selectedEntity = null;
private final Vector3d selectedStart = new Vector3d();
// moving in z direction
private int mouseXForZDragging; // x location needs to be fixed while moving in z direction
private boolean zDragging = false;
private static boolean resizeBounds = false;
public static final int CORNER_BOTTOMLEFT = 1;
public static final int CORNER_BOTTOMCENTER = 2;
public static final int CORNER_BOTTOMRIGHT = 3;
public static final int CORNER_MIDDLERIGHT = 4;
public static final int CORNER_TOPRIGHT = 5;
public static final int CORNER_TOPCENTER = 6;
public static final int CORNER_TOPLEFT = 7;
public static final int CORNER_MIDDLELEFT = 8;
public static final int CORNER_ROTATE = 9;
private Cursor rotation;
public static int resizeType = 0;
/**
* Creates a new OrbitBehavior
*
* @param c The Canvas3D to add the behavior to
* @param flags The option flags
*/
public OrbitBehavior(ModelView v, Sim3DWindow window) {
super(v.getCanvas3D(), MOUSE_LISTENER | MOUSE_MOTION_LISTENER);
modelView = v;
this.window = window;
setEnable( true );
orbitCenter = new Vector3d();
orbitAngles = new Vector3d();
orbitRadius = DEFAULT_RADIUS;
fov = DEFAULT_FOV;
integrateTransforms();
Toolkit tk = Toolkit.getDefaultToolkit();
// The middle of the image is the hot spot for rotating cursor
Dimension dim = tk.getBestCursorSize(32, 32);
dim.height /= 2;
dim.width /= 2;
// Create rotating cursor from image
Image cursorImage = tk.getImage(
GUIFrame.class.getResource("/resources/images/rotating.png"));
try {
rotation = tk.createCustomCursor(
cursorImage, new Point(dim.width,dim.height), "Rotating");
}
// use the default cursor, do not throw an exception
catch(Exception exc){
rotation = null;
}
}
protected synchronized void processAWTEvents( final java.awt.AWTEvent[] events ) {
motion = false;
for( int i = 0; i < events.length; i++ ) {
if( events[i] instanceof MouseEvent ) {
MouseEvent evt = (MouseEvent)events[i];
// Check if the next event is the same as this event to suppress
// a large class of duplicates (dragging/moving)
if (i + 1 < events.length && events[i + 1] instanceof MouseEvent) {
MouseEvent nextevt = (MouseEvent)events[i + 1];
// events have the same ID
if (evt.getID() == nextevt.getID()) {
if (evt.getID() == MouseEvent.MOUSE_DRAGGED)
continue;
if (evt.getID() == MouseEvent.MOUSE_MOVED)
continue;
}
}
processMouseEvent(evt);
}
}
GraphicsUpdateBehavior.forceUpdate = true;
}
public void destroy() {
canvases = null;
}
static void enableTooltip(boolean enable) {
if (!enable)
OrbitBehavior.killToolTip();
OrbitBehavior.showtooltip = enable;
}
static void killToolTip() {
if( entityToolTip != null ) {
entityToolTip.abort();
entityToolTip = null;
}
}
public static void selectEntity(Entity ent) {
if(ent == selectedEntity)
return;
// Unselect previous entity
resizeObjectDeselected();
if (ent instanceof DisplayEntity) {
selectedEntity = (DisplayEntity)ent;
resizeBounds = true;
selectedEntity.setResizeBounds( true );
}
GraphicsUpdateBehavior.forceUpdate = true;
}
protected void processMouseEvent( final MouseEvent evt ) {
// no processing if the right click menu is visible
if(window.getPicker().getMenu().isVisible()) {
// Back to default mouse icon
edgeSelected(null, null, 0.0d);
return;
}
if (evt.getID() == MouseEvent.MOUSE_WHEEL) {
orbitRadius *= Math.pow(0.9d, -((MouseWheelEvent)evt).getWheelRotation());
// Cap the radius to a minimum value
orbitRadius = Math.max(orbitRadius, MIN_RADIUS);
motion = true;
return;
}
// ToolTip belongs to this window now
if (evt.getID() == MouseEvent.MOUSE_ENTERED) {
if (OrbitBehavior.showtooltip && entityToolTip == null) {
entityToolTip = new EntityToolTip();
entityToolTip.start();
}
tooltipBehavior = this;
return;
}
if (evt.getID() == MouseEvent.MOUSE_EXITED) {
tooltipBehavior = null;
tootipEvent = null;
// display nothing for the position
if (positionMode)
DisplayEntity.simulation.getGUIFrame().showLocatorPosition(null, window.getRegion());
return;
}
Vector3d currentMousePosition = getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, 0.0d);
if(evt.getClickCount() >= 2) {
// Just catch everything and move on
try {
DisplayEntity.simulation.getGUIFrame().copyLocationToClipBoard(currentMousePosition);
}
catch (Throwable e) {}
}
// calculate and display the position in the UI
if (positionMode)
DisplayEntity.simulation.getGUIFrame().showLocatorPosition(currentMousePosition, window.getRegion());
// Select the new entity
DisplayEntity closest = window.getPicker().getClosestEntity(evt);
// display the location of the locator when the mouse moves
if( evt.getID() == MouseEvent.MOUSE_MOVED ) {
// This is the new mousEvent for the tooltip
tootipEvent = evt;
// mouse moves inside the entity with resizeBounds set
if (selectedEntity == closest && resizeBounds) {
if( !(selectedEntity instanceof MouseNode) ){
selectedEntity.preDrag();
selectedStart.set(this.getUniversePointFromMouseLoc(
evt.getX(), evt.getY(), Plane.XY_PLANE,
selectedEntity.getAbsoluteCenter().z));
// a point in the universe which is under the pixel
// that is HANDLE_DIM pixels away from the mouse loc
Vector3d dist = this.getUniversePointFromMouseLoc(
evt.getX(), evt.getY() +
(int)DisplayEntity.HANDLE_DIM, Plane.XY_PLANE,
selectedEntity.getAbsoluteCenter().z);
// length of dist is the diameter of a handle located
// in selectedStart
dist.sub(selectedStart);
// find the handle if any and set its mouse icon
resizeType = edgeSelected(selectedEntity, selectedStart,
dist.length());
}
}
else {
// Back to default mouse icon
edgeSelected(null, null, 0.0d);
}
return;
}
// Suppress tooltip when not a MOUSE_MOVED event
tootipEvent = null;
checkZDragging(evt);
// A) THE FIRST TIME MOUSE IS PRESSED
// setup the starting point
if( evt.getID() == MouseEvent.MOUSE_PRESSED ) {
this.storeUndoSteps();
FrameBox.setSelectedEntity( closest );
mouseX = evt.getX();
mouseY = evt.getY();
motion = true;
universeDatumPoint.set(currentMousePosition);
// ZOOM BOX INITIALIZATION
// The first point of the rectangle (Zoom box)
if( zoomBox( evt ) ) {
rectangle = new Rectangle(universeDatumPoint.x, universeDatumPoint.y, 0, 0, 0, Shape.SHAPE_OUTLINE);
rectangle.setLineStyle( Rectangle.LINE_DASH_1PX ); // box style
rectangle.setLayer( 4 );
rectangle.setColor( 1 ); // Black colour for the box
window.getRegion().addShape( rectangle );
}
if( drag( evt ) ) {
closest = window.getPicker().getClosestEntity(evt);
if (selectedEntity != null) {
// mouse clicked inside the entity with resizeBounds set
if (selectedEntity == closest && resizeBounds && !zDragging) {
selectedStart.set(this.getUniversePointFromMouseLoc(evt.getX(), evt.getY(), Plane.XY_PLANE, selectedEntity.getAbsoluteCenter().z));
}
else if(zDragging) {
selectedStart.set(this.getUniversePointFromMouseLoc(
mouseXForZDragging, evt.getY(), Plane.XZ_PLANE,
selectedEntity.getAbsoluteCenter().y) );
}
}
} else if ( "add Node".equals(currentCreationClass) ) {
Vector3d posn = new Vector3d(currentMousePosition);
if (closest != null) {
closest.addMouseNodeAt(posn);
}
}
}
// B) MOUSE IS MOVING WHILE IT IS PRESSED
// handle the motions as they occur
else if( evt.getID() == MouseEvent.MOUSE_DRAGGED ) {
int xchange = evt.getX() - mouseX;
int ychange = evt.getY() - mouseY;
// 1) ZOOM BOX
if( zoomBox( evt ) && rectangle != null ) {
double h = currentMousePosition.y - universeDatumPoint.y;
double w = currentMousePosition.x - universeDatumPoint.x;
// System.out.println( "h:" + h + " w: " + w );
rectangle.setSize(w, h);
rectangle.setCenter( universeDatumPoint.x + w/2, universeDatumPoint.y + h/2, 0 );
rectangle.updateGeometry();
}
// 2) PAN
// translate the viewer and center (viewer and direction of view are translated)
else if( translate( evt ) && selectedEntity == null) {
Vector3d translateDiff = new Vector3d();
translateDiff.sub(universeDatumPoint, currentMousePosition);
translateDiff.z = 0.0d;
orbitCenter.add(translateDiff);
integrateTransforms();
return;
}
// 3) ROTATION
// rotate the viewer (viewer orbits about viewpoint, direction of view changes distance does not)
if( rotate( evt ) ) {
double phi = orbitAngles.x + ychange * ORBIT_ANGLE_FACTOR;
if (phi < -Math.PI)
phi = -Math.PI;
if (phi > Math.PI)
phi = Math.PI;
orbitAngles.x = phi;
double theta = orbitAngles.z + xchange * ORBIT_ANGLE_FACTOR;
theta %= 2.0d * Math.PI;
orbitAngles.z = theta;
}
// 4) POSITION OBJECTS
// 5) Resize Object
// 6) Dragging object:
if( drag( evt ) ) {
if (selectedEntity != null) {
// Check if we are resizing
Vector3d dragEnd = this.getUniversePointFromMouseLoc(
evt.getX(), evt.getY(), Plane.XY_PLANE,
selectedEntity.getAbsoluteCenter().z);
if (resizeBounds == true && resizeType > 0 && !zDragging) {
resizeObject(selectedEntity, selectedStart, dragEnd);
}
// Otherwise it is object dragging
else {
Vector3d dragdist = new Vector3d();
// z-axis dragging
if (zDragging) {
dragEnd = this.getUniversePointFromMouseLoc(
mouseXForZDragging, evt.getY(), Plane.XZ_PLANE,
selectedEntity.getAbsoluteCenter().y);
// Avoid moving in x and y direction
dragEnd.x = selectedStart.x;
dragEnd.y = selectedStart.y;
}
dragdist.sub(dragEnd, selectedStart);
selectedEntity.dragged(dragdist);
}
// update the start position for the net darg we process
selectedStart.set(dragEnd);
}
}
// IN ANY OF THE 1 TO 7 CASES
// reset values for next change
mouseX = evt.getX();
mouseY = evt.getY();
motion = true;
}
// C) MOUSE IS RELEASED
// when the motion has finished
else if( evt.getID() == MouseEvent.MOUSE_RELEASED ) {
// entity has been dragged
if( selectedEntity != null && resizeBounds == false ) {
// find distance to check if it has been dragged
Vector3d distanceVec = selectedEntity.getPosition();
distanceVec.sub(dragEntityStartPosition);
// completed drag, update entity center
selectedEntity.postDrag();
selectedEntity = null;
}
if( selectedEntity != null && resizeBounds == true && !zDragging ) {
selectedEntity.updateGraphics();
}
// Zooming to the box and removing the rectangle
if( zoomBox( evt ) && rectangle != null) {
Dimension d = modelView.getCanvas3D().getSize();
double aspect = (double)d.width / d.height;
// Find the physical width that will be viewed
// (Note: field of view uses only the horizontal width)
double rectWidth = Math.abs( rectangle.getWidth() );
double rectHeight = Math.abs( rectangle.getHeight() );
double widthOfView = Math.max(rectWidth, rectHeight * aspect);
// Only if the size of the zoom box is not zero
if( widthOfView > 0 ) {
// Distance of the eye point from the model (in z=0)
double zDistance = (widthOfView / 2) / Math.tan(fov / 2);
Point3d temp = rectangle.getCenterInDouble();
temp.z = 0.0d;
setOrbitCenter(temp);
temp.z = zDistance;
this.setViewer(temp);
// Needs to update the graphics properly
motion = true;
}
window.getRegion().removeShape(rectangle);
rectangle = null;
}
this.updateBehaviour();
this.storeUndoSteps();
// Update view inputs
if(zoomBox( evt ) || translate( evt )) {
window.getRegion().updateViewCenterInput();
window.getRegion().updateViewerInput();
window.getRegion().updateFOVInput();
}
}
this.updateBehaviour();
}
private void checkZDragging(MouseEvent evt) {
if(selectedEntity == null) {
return;
}
if ( (evt.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) ==
MouseEvent.SHIFT_DOWN_MASK ) {
if(zDragging)
return;
// first time that shift pressed (dragging starts in z direction)
mouseXForZDragging = evt.getX();
selectedStart.set(this.getUniversePointFromMouseLoc(
mouseXForZDragging, evt.getY(), Plane.XZ_PLANE,
selectedEntity.getAbsoluteCenter().y));
zDragging = true;
return;
}
if(! zDragging){
return;
}
// Shift just released (dragging or resizing/rotating in xy plane)
selectedStart.set(this.getUniversePointFromMouseLoc(evt.getX(),
evt.getY(), Plane.XY_PLANE, selectedEntity.getAbsoluteCenter().z));
zDragging = false;
}
protected synchronized void integrateTransforms() {
Transform3D cameraTransform = new Transform3D();
Vector3d translation = new Vector3d(0.0d, 0.0d, orbitRadius);
cameraTransform.setEuler(orbitAngles);
cameraTransform.transform(translation);
translation.add(orbitCenter);
cameraTransform.setTranslation(translation);
modelView.setViewState(cameraTransform, fov, orbitRadius);
}
public void setOrbitCenter(Point3d cent) {
orbitCenter.set(cent);
}
public Point3d getCenterPosition() {
// make a copy and return the copy
Point3d ret = new Point3d();
ret.set(orbitCenter);
return ret;
}
public void setOrbitAngles(double phi, double theta) {
orbitAngles.set(phi, 0.0d, theta);
}
public void setViewer(Point3d view) {
Vector3d relView = new Vector3d();
relView.sub(view, orbitCenter);
double dist1 = Math.hypot(relView.x, relView.y);
// suppress small-angle errors
if (dist1 < 0.0001d)
dist1 = 0.0d;
double phi = Math.atan2(dist1, relView.z);
// calculate the theta Eular angle, the Pi/2 addition is to account for
// the initial rotation towards the negative y-axis when off the z-axis
double theta = Math.atan2(relView.y, relView.x);
if (dist1 == 0.0d)
theta = 0.0d;
if (phi > 0.0d)
theta += Math.PI / 2.0d;
orbitAngles.set(phi, 0.0d, theta);
orbitRadius = relView.length();
}
public Point3d getViewer() {
Transform3D eular = new Transform3D();
Vector3d translation = new Vector3d(0.0d, 0.0d, orbitRadius);
eular.setEuler(orbitAngles);
eular.transform(translation);
translation.add(orbitCenter);
return new Point3d(translation);
}
public double getFOV() {
return fov;
}
public void setFOV(double fov) {
this.fov = fov;
}
public void positionViewer(Region aRegion) {
this.positionViewer(aRegion.getCurrentCenter(),
aRegion.getCurrentViewer(),
aRegion.getCurrentFOV());
}
private void positionViewer(Point3d centerPosition, Point3d viewerPosition, double fov) {
this.fov = fov;
setOrbitCenter( centerPosition );
setViewer(viewerPosition);
integrateTransforms();
}
Sim3DWindow getWindow() {
return window;
}
boolean rotate(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_ROTATION && !evt.isMetaDown() && selectedEntity == null;
}
boolean zoomBox(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_ZOOM_BOX && !evt.isMetaDown() && selectedEntity == null;
}
boolean translate(MouseEvent evt) {
return mouseMode == OrbitBehavior.CHANGE_TRANSLATION && !evt.isMetaDown() && selectedEntity == null;
}
boolean drag(MouseEvent evt) {
return !evt.isMetaDown() && mouseMode != OrbitBehavior.CHANGE_NODE;
}
public static void setCreationBehaviour(String entityTypeToCreate) {
OrbitBehavior.setViewerBehaviour(OrbitBehavior.CHANGE_TRANSLATION);
DisplayEntity.simulation.pause();
if ("add Node".equals(entityTypeToCreate)) {
OrbitBehavior.setViewerBehaviour(OrbitBehavior.CHANGE_NODE);
}
OrbitBehavior.currentCreationClass = entityTypeToCreate;
}
public static void setViewerBehaviour(int behaviour) {
OrbitBehavior.currentCreationClass = null;
if (mouseMode == OrbitBehavior.CHANGE_NODE) {
OrbitBehavior.resizeObjectDeselected();
}
mouseMode = behaviour;
}
public static void showPosition( boolean show ) {
positionMode = show;
}
public Vector3d getUniversePointFromMouseLoc( int x, int y, Plane plane, double planeHeight) {
// get the location of eye and the locator in the image plate
Point3d eyePosn = new Point3d();
modelView.getCanvas3D().getCenterEyeInImagePlate(eyePosn);
Point3d mousePosn = new Point3d();
modelView.getCanvas3D().getPixelLocationInImagePlate(x, y, mousePosn);
// get the transform to convert imageplate to virtual world
Transform3D locatorTrans = new Transform3D();
modelView.getCanvas3D().getImagePlateToVworld(locatorTrans);
// convert the image plate points to the virtual world
locatorTrans.transform(eyePosn);
locatorTrans.transform(mousePosn);
// calculate the view vector for the locator
Vector3d universePos = new Vector3d();
universePos.sub(mousePosn, eyePosn);
universePos.normalize();
// determine the distance from the plane and scale the vector
double scale = 0.0d;
switch (plane) {
case XZ_PLANE:
scale = -(eyePosn.y - planeHeight) / universePos.y;
break;
case YZ_PLANE:
scale = -(eyePosn.x - planeHeight) / universePos.x;
break;
case XY_PLANE:
scale = -(eyePosn.z - planeHeight) / universePos.z;
break;
}
universePos.scale(scale);
universePos.add(eyePosn);
// If this is a view of another region, then it has a current region
Region aRegion = window.getRegion();
if (aRegion.getCurrentRegion() != null) {
aRegion = aRegion.getCurrentRegion();
}
// scale by the Region's position for region coordinates
universePos.sub( aRegion.getPositionForAlignment(new Vector3d()) );
Vector3d regionScale = aRegion.getScale();
universePos.x /= regionScale.x;
universePos.y /= regionScale.y;
universePos.z /= regionScale.z;
// return the Universe position
return universePos;
}
// Updates both Sim3Dwindow and OrbitBehavior
public void updateViewerAndWindow( Point3d centerPosition, Point3d viewerPosition, java.awt.Point position, java.awt.Dimension size, double fov ) {
this.positionViewer(centerPosition, viewerPosition, fov);
// Window size has been changed by do or undo in the program (not by the user)
if( ! window.getSize().equals( size ) ) {
window.setInteractiveSizeChenge( false );
window.setSize(size);
}
// Window location has been changed by do or undo in the program (not by the user)
if( ! window.getLocation().equals( position ) ) {
window.setInteractiveLocationChenge( false );
window.setLocation(position);
}
window.getRegion().updatePositionViewer(centerPosition, viewerPosition, position, size, fov);
}
public void updateBehaviour() {
// If this is not the active window
if (Sim3DWindow.lastActiveWindow != window)
return;
window.getRegion().updatePositionViewer( this.getCenterPosition(), this.getViewer(), window.getLocation(), window.getSize(), fov);
if( undoStep > 1 || ( undoStep == 1 && ( this.viewerChanged() || ( ( window.moved() || window.resized() ) && ! windowMovedAndResized ) ) ) ) {
DisplayEntity.simulation.getGUIFrame().setToolButtonUndoEnable( true );
}
else {
DisplayEntity.simulation.getGUIFrame().setToolButtonUndoEnable( false );
}
if( undoStep == ( undoSteps.size() / 6 ) || ( undoStep == undoSteps.size() / 6 - 1 && ( this.viewerChanged() || ( ( window.moved() || window.resized() ) && ! windowMovedAndResized ) ) ) ) {
DisplayEntity.simulation.getGUIFrame().setToolButtonRedoEnable( false );
}
else {
DisplayEntity.simulation.getGUIFrame().setToolButtonRedoEnable( true );
}
}
public boolean viewerChanged() {
// Any step but the first
if( undoStep > 0 && undoSteps.size() > 0 ) {
Point3d viewer = this.getViewer();
// Viewer changed
if( ! orbitCenter.equals( undoSteps.get( (undoStep - 1)*6 )) || ! viewer.equals( (Point3d) undoSteps.get( (undoStep -1)*6 + 1 )) ||
! ( fov == ((Double) undoSteps.get( (undoStep - 1)*6 + 5 )).doubleValue() ) ) {
return true;
}
}
// The first step
if( undoStep == 0 && undoSteps.size() > 0 ) {
Point3d viewer = this.getViewer();
// Viewer changed
if( ! orbitCenter.equals( undoSteps.get( (undoStep )*6 )) || ! viewer.equals( (Point3d) undoSteps.get( (undoStep )*6 + 1 )) ||
! ( fov == ((Double) undoSteps.get( (undoStep )*6 + 5 )).doubleValue() ) ) {
return true;
}
}
return false;
}
public int getUndoStep() {
return undoStep;
}
public Vector getUndoSteps() {
return undoSteps;
}
public void storeUndoSteps( ) {
//System.out.println( "storeZoomSteps " );
if( ! ( this.viewerChanged() || window.moved() || window.resized() ) && undoSteps.size() != 0 ) {
return;
}
// TODO: We could have ignored this step if the componentMoved event fired after the window has been moved; this event keeps firing while the window is moving;
//////////// The above is a known bug in component listener
// viewer has not changed
if( ! this.viewerChanged() ) {
// 1) Window both moved and resized
if( ( window.moved() && window.resized() ) || windowMovedAndResized ) {
windowMovedAndResized = true;
// a) componentResized of the window has been triggered
if ( window.resizeTriggered() ) {
windowMovedAndResized = false;
window.setResizeTriggered( false );
}
// b) Wait until componentMoved is triggered
else {
return;
}
}
// 2) Window moved only
else if ( window.moved() && undoStep > 1 ) {
undoStep
// The only difference in last two undo steps is the window location
if ( window.moved() ) {
undoStep++;
// Only update the window location in the last undo step
undoSteps.setElementAt( window.getLocation(), undoSteps.size() - 3 );
return;
}
undoStep++;
}
// 3) Window resized only is a normal situation
}
// Remove the steps which were undid ( when undo several steps and then modify the view or window, the redo steps after the current step should be removed )
for( int i = undoSteps.size() - 1; i >= undoStep*6 && i >= 6; i
undoSteps.removeElementAt( i );
}
//System.out.println( "adding a new step: Position:" + window.getWindowPosition() + " -- Size:" + window.getWindowSize());
//System.out.println( "center:" + center + " viewer:" + viewer + " up:" + up + " fov:" + fov );
undoSteps.add(orbitCenter.clone());
undoSteps.add(this.getViewer());
undoSteps.add( new Vector3d() );
undoSteps.add( window.getLocation() );
undoSteps.add( window.getSize() );
undoSteps.add( new Double(fov) );
undoStep++;
this.updateBehaviour();
}
/** Undo the previous zoom step */
public boolean undoPreviousStep() {
// the current step is the last step
if( undoStep == undoSteps.size() / 6 ) {
storeUndoSteps();
undoStep
}
// There is at least one step to undo
if( undoStep > 0 ) {
undoStep
this.updateViewerAndWindow(new Point3d((Vector3d)undoSteps.get( undoStep*6 )), (Point3d) undoSteps.get( undoStep*6 + 1), (java.awt.Point) undoSteps.get( undoStep*6 + 3 ), (java.awt.Dimension) undoSteps.get( undoStep*6 + 4 ), ((Double) undoSteps.get( undoStep*6 + 5 )).doubleValue());
}
updateBehaviour();
// There is no more step to undo
if( undoStep == 0 ) {
return false;
}
// Undo is still possible
else {
return true;
}
}
/** Redo the previous step */
public boolean redoPreviousStep() {
// The current step is not the last step
if( undoStep < ( undoSteps.size() / 6 - 1) ) {
undoStep++;
this.updateViewerAndWindow(new Point3d((Vector3d)undoSteps.get( undoStep*6 )), (Point3d) undoSteps.get( undoStep*6 + 1), (java.awt.Point) undoSteps.get( undoStep*6 + 3 ), (java.awt.Dimension) undoSteps.get( undoStep*6 + 4 ), ((Double) undoSteps.get( undoStep*6 + 5 )).doubleValue());
}
updateBehaviour();
// This is the last step
if( undoStep == ( undoSteps.size() / 6 - 1) ) {
return false;
}
// redo is still possible
else {
return true;
}
}
private static void resizeObjectDeselected(){
if (selectedEntity == null)
return;
resizeBounds = false;
resizeType = 0;
selectedEntity.setResizeBounds( false );
selectedEntity = null;
}
/**
* resize or rotate the selected Object
*/
private void resizeObject(DisplayEntity ent, Vector3d start, Vector3d end ){
if (ent == null)
return;
Vector3d orient = ent.getOrientation();
// calculate difference in x and y size
Vector3d diff = new Vector3d();
diff.sub(end, start); // Vector from start to end point
Transform3D temp = new Transform3D();
temp.setEuler(orient);
temp.invert();
temp.transform(diff);
Vector3d selectedEntitySize = ent.getSize();
Vector3d oppositeCorner = null; // opposite of selected corner
// resize the object according to which corner was selected
switch( resizeType ){
case CORNER_BOTTOMLEFT:
selectedEntitySize.x -= diff.x;
selectedEntitySize.y -= diff.y;
oppositeCorner = new Vector3d(0.5, 0.5, 0.5);
break;
case CORNER_BOTTOMCENTER:
selectedEntitySize.y -= diff.y;
oppositeCorner = new Vector3d(0.0, 0.5, 0.5);
break;
case CORNER_BOTTOMRIGHT:
selectedEntitySize.x += diff.x;
selectedEntitySize.y -= diff.y;
oppositeCorner = new Vector3d(-0.5, 0.5, 0.5);
break;
case CORNER_MIDDLERIGHT:
selectedEntitySize.x += diff.x;
oppositeCorner = new Vector3d(-0.5, 0.0, 0.5);
break;
case CORNER_TOPRIGHT:
selectedEntitySize.x += diff.x;
selectedEntitySize.y += diff.y;
oppositeCorner = new Vector3d(-0.5, -0.5, 0.5);
break;
case CORNER_TOPCENTER:
selectedEntitySize.y += diff.y;
oppositeCorner = new Vector3d(0.0, -0.5, 0.5);
break;
case CORNER_TOPLEFT:
selectedEntitySize.x -= diff.x;
selectedEntitySize.y += diff.y;
oppositeCorner = new Vector3d(0.5, -0.5, 0.5);
break;
case CORNER_MIDDLELEFT:
selectedEntitySize.x -= diff.x;
oppositeCorner = new Vector3d(0.5, 0.0, 0.5);
break;
case CORNER_ROTATE:
diff = new Vector3d();
diff.sub(end, ent.getAbsoluteCenter());
// add PI as the resize line points to the left
double zAngle = Math.atan2(diff.y, diff.x) + Math.PI;
diff.set(orient.x, orient.y, zAngle);
ent.setOrientation(diff);
ent.updateInputOrientation();
return;
}
// opposite of selected corner location before resizing
Vector3d loc = ent.getPositionForAlignment( oppositeCorner );
// negative size is not accepted
if(selectedEntitySize.x < 0) {
selectedEntitySize.x = 0;
}
if(selectedEntitySize.y < 0) {
selectedEntitySize.y = 0;
}
ent.setSize(selectedEntitySize); // new size after dragging
// move the opposite corner to its previous location, before resizing
loc.sub(loc, ent.getPositionForAlignment(oppositeCorner));
loc.add(ent.getPosition());
ent.setPosition(loc);
ent.updateInputPosition();
ent.updateInputSize();
}
private boolean calcEdgeDistance(DisplayEntity ent, Vector3d pt, Vector3d align, double dist) {
Vector3d alignPoint = ent.getAbsolutePositionForAlignment(align);
alignPoint.sub(pt);
return alignPoint.length() < dist;
}
/**
* find which handle corner of ent is within the dist of the currentPoint
*
* @param currentPoint
* @return
*/
private int edgeSelected(DisplayEntity ent, Vector3d currentPoint, double dist) {
if (ent == null) {
window.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
return 0;
}
Vector3d tmp = ent.getSize();
double rotatorPos = -0.5 -
Math.max(Math.max(tmp.x, tmp.y), tmp.z)/(4*tmp.x);
tmp.set(-0.5d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(1, ent);
return CORNER_BOTTOMLEFT;
}
tmp.set(0.0d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(2, ent);
return CORNER_BOTTOMCENTER;
}
tmp.set(0.5d, -0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(3, ent);
return CORNER_BOTTOMRIGHT;
}
tmp.set(0.5d, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(0, ent);
return CORNER_MIDDLERIGHT;
}
tmp.set(0.5d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(1, ent);
return CORNER_TOPRIGHT;
}
tmp.set(0.0d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(2, ent);
return CORNER_TOPCENTER;
}
tmp.set(-0.5d, 0.5d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(3, ent);
return CORNER_TOPLEFT;
}
tmp.set(-0.5d, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
setCursor(0, ent);
return CORNER_MIDDLELEFT;
}
tmp.set(rotatorPos, 0.0d, 0.0d);
if (calcEdgeDistance(ent, currentPoint, tmp, dist)) {
window.setCursor(rotation);
return CORNER_ROTATE;
}
window.setCursor(new Cursor(Cursor.MOVE_CURSOR));
return 0;
}
/**
* set cursor to match the selected edge
* @param cursor
* @param degree
*/
private void setCursor(int cursor, DisplayEntity ent) {
int rotate;
double degree = ent.getOrientation().z % Math.PI;
// If entity has been rotated, change resize cursor direction
if( degree > 2.7488 ){
// rotate 157.5 degree to 180 degree
rotate = 0;
} else if ( degree > 1.963495 ){
// rotate 112.5 degree to 157.5 degree
rotate = 3;
} else if( degree > 1.170097225 ){
// rotate 67.5 degree to 112.5 degree
rotate = 2;
} else if ( degree > 0.392699 ){
// rotate 22.5 degree to 67.5 degree
rotate = 1;
} else {
// no rotation
rotate = 0;
}
cursor = (cursor + rotate)%4;
switch(cursor) {
case 0: window.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR)); break;
case 1: window.setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR)); break;
case 2: window.setCursor(new Cursor(Cursor.N_RESIZE_CURSOR)); break;
case 3: window.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR)); break;
}
}
} |
// DateTools.java
package loci.common;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class DateTools {
// -- Constants --
/** Timestamp formats. */
public static final int UNIX = 0; // January 1, 1970
public static final int COBOL = 1; // January 1, 1601
public static final int MICROSOFT = 2; // December 30, 1899
public static final int ZVI = 3;
/** Milliseconds until UNIX epoch. */
public static final long UNIX_EPOCH = 0;
public static final long COBOL_EPOCH = 11644473600000L;
public static final long MICROSOFT_EPOCH = 2209143600000L;
public static final long ZVI_EPOCH = 2921084975759000L;
/** ISO 8601 date format string. */
public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
// -- Constructor --
private DateTools() { }
// -- Date handling --
/** Converts the given timestamp into an ISO 8601 date. */
public static String convertDate(long stamp, int format) {
// dates than you will ever need (or want)
long ms = stamp;
switch (format) {
case UNIX:
ms -= UNIX_EPOCH;
break;
case COBOL:
ms -= COBOL_EPOCH;
break;
case MICROSOFT:
ms -= MICROSOFT_EPOCH;
break;
case ZVI:
ms -= ZVI_EPOCH;
break;
}
SimpleDateFormat fmt = new SimpleDateFormat(ISO8601_FORMAT);
StringBuffer sb = new StringBuffer();
Date d = new Date(ms);
fmt.format(d, sb, new FieldPosition(0));
return sb.toString();
}
/**
* Formats the given date as an ISO 8601 date.
*
* @param date The date to format as ISO 8601.
* @param format The date's input format.
*/
public static String formatDate(String date, String format) {
if (date == null) return null;
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
Date d = sdf.parse(date, new ParsePosition(0));
if (d == null) return null;
sdf = new SimpleDateFormat(ISO8601_FORMAT);
return sdf.format(d);
}
/**
* Formats the given date as an ISO 8601 date.
*
* @param date The date to format as ISO 8601.
* @param formats The date's possible input formats.
*/
public static String formatDate(String date, String[] formats) {
for (int i=0; i<formats.length; i++) {
String result = formatDate(date, formats[i]);
if (result != null) return result;
}
return null;
}
/**
* Converts a string date in the given format to a long timestamp
* (in Unix format: milliseconds since January 1, 1970).
*/
public static long getTime(String date, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
Date d = f.parse(date, new ParsePosition(0));
if (d == null) return -1;
return d.getTime();
}
} |
package org.xbill.DNS.spi;
import java.lang.reflect.Proxy;
import sun.net.spi.nameservice.*;
/**
* The descriptor class for the dnsjava name service provider.
*
* @author Brian Wellington
* @author Paul Cowan (pwc21@yahoo.com)
*/
public class DNSJavaNameServiceDescriptor implements NameServiceDescriptor {
private static NameService nameService;
static {
ClassLoader loader = NameService.class.getClassLoader();
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
nameService = (NameService) Proxy.newProxyInstance(loader,
new Class[] { NameService.class },
new DNSJavaNameService());
}
/**
* Returns a reference to a dnsjava name server provider.
*/
public NameService
createNameService() {
return nameService;
}
public String
getType() {
return "dns";
}
public String
getProviderName() {
return "dnsjava";
}
} |
package de.kisi.android;
import org.json.JSONException;
import org.json.JSONObject;
import com.manavo.rest.RestCallback;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
private Button loginButton;
private EditText userNameField;
private EditText passwordField;
private CheckBox savePassword;
private TextView newUser;
private TextView forgotPw;
private TextView slogan;
private SharedPreferences settings;
private SharedPreferences.Editor editor;
private String email;
private String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login_activity);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(this);
loginButton.getBackground().setAlpha(185);
settings = getSharedPreferences("Config", MODE_PRIVATE);
userNameField = (EditText) findViewById(R.id.email);
passwordField = (EditText) findViewById(R.id.password);
passwordField.setTypeface(Typeface.DEFAULT);
savePassword = (CheckBox) findViewById(R.id.rememberCheckBox);
newUser = (TextView) findViewById(R.id.registerText);
newUser.setText(Html.fromHtml("New? "
+ "<a href=\"https:
newUser.setMovementMethod(LinkMovementMethod.getInstance());
slogan = (TextView) findViewById(R.id.Slogan);
Typeface font = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf");
slogan.setTypeface(font);
forgotPw = (TextView) findViewById(R.id.forgot);
forgotPw.setText(Html.fromHtml("<a href=\"https:
forgotPw.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
public void onBackPressed() {
// sends App to background if back button is pressed
// prevents security issues
moveTaskToBack(true);
}
@Override
protected void onStart() {
email = settings.getString("email", "");
password = settings.getString("password", "");
if (!email.isEmpty()) {
userNameField.setText(email);
if (password.isEmpty()) {
passwordField.requestFocus();
} else {
passwordField.setText(password);
savePassword.setChecked(true);
}
}
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
// user touched the login botton: gather all informations and send to next view
// clear auth token
editor = settings.edit();
editor.remove("authentication_token");
editor.commit();
email = userNameField.getText().toString(); // get Text of
password = passwordField.getText().toString();
KisiApi api = new KisiApi(this);
api.authorize(email, password);
api.setLoadingMessage("Logging in...");
final LoginActivity activity = this;
api.setCallback(new RestCallback() {
public void success(Object obj) {
JSONObject data = (JSONObject)obj;
try {
editor = settings.edit();
editor.putString("authentication_token", data.getString("authentication_token"));
editor.putInt("user_id", data.getInt("id"));
editor.commit();
Toast.makeText(activity, R.string.login_success, Toast.LENGTH_LONG).show();
Intent mainScreen = new Intent(getApplicationContext(), KisiMain.class);
startActivity(mainScreen);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// TODO set error handler
if (savePassword.isChecked()) {
// save login credentials
editor = settings.edit();
editor.putString("email", email);
editor.putString("password", password);
editor.putBoolean("saved", true);
editor.commit();
} else {
deleteLogin();
}
api.post("users/sign_in");
}
private void deleteLogin() {
editor = settings.edit();
//editor.remove("email"); // email should stay
editor.remove("password");;
editor.remove("saved");
editor.commit();
}
} |
package de.piratenpartei.id;
import java.io.*;
public class Messenger {
private PrintWriter outputStream;
private Account author;
private Message m;
public Messenger(Account author){
m = new Message(author);
}
public void message(String s) throws IOException, IllegalFormatException, KeyException, VerificationException{
this.m.setMessage(s);
this.m.send(this.outputStream);
}
public void sendVote(IniTopic topic, String vote, String type) throws IOException, IllegalFormatException, KeyException, VerificationException{
this.message("vote:{type:\"" + type + "\",topic:\"" + topic.getID() + "\",vote:\"" + vote + "\"");
}
public void sendMessageToUser(String userName, String message) throws IOException, IllegalFormatException, KeyException, VerificationException{
this.message("userMsg:{to:\"" + userName + "\",message:\"" + message + "\"}");
}
public void sendNickchange(String newNick) throws IOException, IllegalFormatException, KeyException, VerificationException{
this.message("nickChange:{newNick:\"" + newNick + "\"}");
}
} |
package de.dqi11.quickStarter.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.Observable;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import de.dqi11.quickStarter.controller.Search;
import de.dqi11.quickStarter.modules.ModuleAction;
/**
* Represents the main-application window, which
* shows the search-field and ModuleActions.
*/
public class MainWindow extends Observable {
private final int WIDTH = 500;
private final int TEXTFIELD_HEIGHT = 50;
private final int ADVICESLIST_MAXHEIGHT = 450;
private boolean visible;
private JFrame mainFrame;
private JPanel mainPanel;
private JTextField textField;
private JLabel errorLabel;
private JList<ModuleAction> advicesList;
private DefaultListModel<ModuleAction> moduleActionsListModel;
private KeyListener keyListener;
private DocumentListener documentListener;
private LinkedList<ModuleAction> moduleActions;
private Font defaultFont;
private Font boldFont;
private Thread updateHeightThread;
/**
* Constructor.
*/
public MainWindow() {
visible = false;
}
/**
* Initializes the whole GUI.
*/
public void init() {
initListeners();
initFonts();
initMainFrame();
initMainPanel();
initTextField();
initErrorLabel();
initModuleActionsPanel();
updateHeight();
}
/**
* Initializes the actions.
*/
private void initListeners() {
keyListener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// Nothing to do here.
}
@Override
public void keyReleased(KeyEvent e) {
// Nothing to do here.
}
@Override
public void keyPressed(KeyEvent e) {
// escape-key
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
toggleApplication();
// enter-key
} else if(e.getKeyCode() == KeyEvent.VK_ENTER) {
invokeSelectedModuleAction();
// down-arrow-key
} else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
e.consume();
selectNext();
// up-arrow-key
} else if(e.getKeyCode() == KeyEvent.VK_UP) {
e.consume();
selectPrevious();
}
}
};
documentListener = new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
setChanged();
notifyObservers();
}
@Override
public void insertUpdate(DocumentEvent e) {
setChanged();
notifyObservers();
}
@Override
public void changedUpdate(DocumentEvent e) {
// Nothing to do here.
}
};
}
/**
* Initializes all fonts.
*/
private void initFonts() {
// Initialize default font.
try {
defaultFont = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("res/fonts/ubuntu/Ubuntu-Light.ttf"));
defaultFont = defaultFont.deriveFont(20f);
} catch (Exception e) {
defaultFont = new Font("Arial", Font.PLAIN, 20);
}
// Initialize bold font.
try {
boldFont = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("res/fonts/ubuntu/Ubuntu-Bold.ttf"));
boldFont = boldFont.deriveFont(20f);
} catch (Exception e) {
boldFont = new Font("Arial", Font.BOLD, 20);
}
}
/**
* Initializes the mainFrame.
*/
private void initMainFrame() {
mainFrame = new JFrame();
mainFrame.setUndecorated(true);
mainFrame.setSize(WIDTH-20, TEXTFIELD_HEIGHT);
// mainFrame.setShape(new RoundRectangle2D.Double(10, 10, 100, 100, 50, 50));
mainFrame.setLocationRelativeTo(null);
mainFrame.setLocation(mainFrame.getLocation().x, 100);
mainFrame.setOpacity(0.8f);
mainFrame.setBackground(Color.BLACK);
}
/**
* Initializes the mainPanel.
*/
private void initMainPanel() {
mainPanel = new JPanel();
mainPanel.setOpaque(false);
mainFrame.setContentPane(mainPanel);
}
/**
* Initializes the textField.
*/
private void initTextField() {
textField = new JTextField();
Border line = BorderFactory.createLineBorder(Color.BLACK);
Border empty = new EmptyBorder(0, 70, 0, 0);
CompoundBorder border = new CompoundBorder(line, empty);
textField.setBorder(border);
textField.setPreferredSize(new Dimension(WIDTH, TEXTFIELD_HEIGHT));
textField.setFont(boldFont);
textField.setBackground(Color.BLACK);
textField.setForeground(Color.WHITE);
textField.setCaretColor(Color.WHITE);
textField.addKeyListener(keyListener);
textField.getDocument().addDocumentListener(documentListener);
mainPanel.add(textField);
}
private void initErrorLabel() {
errorLabel = new JLabel();
mainPanel.add(errorLabel);
}
/**
* Initializes the advicesPanel;
*/
private void initModuleActionsPanel() {
moduleActionsListModel = new DefaultListModel<ModuleAction>();
advicesList = new JList<ModuleAction>(moduleActionsListModel);
advicesList.setCellRenderer(new ModuleActionListCellRenderer(defaultFont));
advicesList.setPreferredSize(new Dimension(WIDTH, ADVICESLIST_MAXHEIGHT));
advicesList.setOpaque(false);
mainPanel.add(advicesList);
}
/**
* Updates the shown module actions.
*/
public void updateModuleActions() {
moduleActionsListModel.clear();
for(ModuleAction moduleAction : moduleActions) {
moduleActionsListModel.addElement(moduleAction);
}
selectFirst();
updateHeight();
}
/**
* Updates the window-height.
*/
public void updateHeight() {
final int startHeight = mainFrame.getHeight();
final int endHeight = moduleActionsListModel.getSize() * TEXTFIELD_HEIGHT + TEXTFIELD_HEIGHT + 10;
if(updateHeightThread != null) {
updateHeightThread.stop();
}
if(startHeight != endHeight) {
updateHeightThread = new Thread(new Runnable() {
@Override
public void run() {
int direction = 1;
if(startHeight > endHeight) direction = -1;
int speed = 25;
for(int i = startHeight; i < endHeight && direction > 0 || i > endHeight && direction < 0; i += direction * speed) {
final int currentHeight = i;
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
mainFrame.setSize(mainFrame.getWidth(), currentHeight);
mainFrame.repaint();
}
});
} catch (InvocationTargetException e1) {
} catch (InterruptedException e1) {
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
mainFrame.setSize(mainFrame.getWidth(), endHeight);
mainFrame.repaint();
}
});
} catch (InvocationTargetException e) {
} catch (InterruptedException e) {
}
}
});
updateHeightThread.start();
}
}
/**
* Toggles the visibility of the application.
*/
public void toggleApplication() {
visible = !visible;
mainFrame.setVisible(visible);
if(visible) {
mainFrame.setAlwaysOnTop(true);
mainFrame.toFront();
mainFrame.requestFocus();
mainFrame.setAlwaysOnTop(false);
}
textField.setText("");
textField.requestFocus();
}
/**
* Returns the current search-string.
*
* @return The search-string.
*/
public String getSearchString() {
return textField.getText();
}
/**
* Selects the first ModuleAction.
*/
public void selectFirst() {
advicesList.setSelectedIndex(0);
}
/**
* Selects the next ModuleAction.
*/
public void selectNext() {
int index = advicesList.getSelectedIndex()+1;
advicesList.setSelectedIndex(index > advicesList.getLastVisibleIndex() ? advicesList.getLastVisibleIndex() : index);
}
/**
* Selects the previous ModuleAction.
*/
public void selectPrevious() {
int index = advicesList.getSelectedIndex()-1;
advicesList.setSelectedIndex(index < 0 ? 0 : index);
}
/**
* Returns the index of the selected ModuleAction.
*
* @return the index
*/
public int getSelectedIndex() {
return advicesList.getSelectedIndex();
}
/**
* Returns the selected ModuleAction.
*
* @return the selected ModuleAction.
*/
public ModuleAction getSelectedModuleAction() {
return advicesList.getSelectedValue();
}
/**
* Invokes the currently selected ModuleAction.
*/
public void invokeSelectedModuleAction() {
Search search = new Search(getSearchString());
ModuleAction moduleAction = getSelectedModuleAction();
if(moduleAction != null) {
ModuleWindow moduleWindow = moduleAction.getModuleWindow(search);
toggleApplication();
if(moduleWindow == null) {
moduleAction.invoke(search);
} else {
moduleWindow.show();
}
}
}
/**
* Sets the ModuleActions and updates the GUI.
*
* @param moduleActions The List of ModuleActions.
*/
public void setModuleActions(LinkedList<ModuleAction> moduleActions) {
this.moduleActions = moduleActions;
updateModuleActions();
}
} |
package com.winterwell.web.data;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.winterwell.utils.StrUtils;
import com.winterwell.utils.io.FileUtils;
import com.winterwell.utils.log.Log;
import com.winterwell.utils.web.IHasJson;
import com.winterwell.utils.web.SimpleJson;
import com.winterwell.utils.web.WebUtils2;
import com.winterwell.web.LoginDetails;
/**
* An id for an external service.
*
* @see DBLogin (database backed)
* @see LoginDetails (this is lighter and a bit different)
* @author daniel
* @testedby XIdTest
*/
public final class XId implements Serializable, IHasJson {
private static final long serialVersionUID = 1L;
/**
* Group 1 is the name, group 2 is the service
*/
public static final Pattern XID_PATTERN = Pattern.compile(
"(\\S+)@([A-Za-z\\.]+)?");
/**
* Company-type. Added to the start of the XId name for SOME data-sources,
* to avoid any overlap with other types.
*/
public static final String WART_C = "c_";
/**
* Person-type. Added to the start of the XId name for SOME data-sources,
* to avoid any overlap with other types.
*/
public static final String WART_P = "p_";
/**
* Video-type. Added to the start of the XId name for SOME data-sources,
* to avoid any overlap with other types.
*/
public static final String WART_V = "v_";
/**
* Group-type. Added to the start of the XId name for SOME data-sources,
* to avoid any overlap with other types.
*/
public static final String WART_G = "g_";
/**
* XId for unknown person + unspecified service
*/
public static final XId ANON = new XId(WART_P+"anon@unspecified", false);
public final String name;
public final String service;
/**
* @param name Canonicalises via {@link IPlugin#canonical(XId, KKind)}
* @param plugin
*/
public XId(String name, String service, IDoCanonical plugin) {
this(name, null, service, plugin);
}
/**
*
* @param name
* @param kind Can be null
* @param service
* @param plugin
*/
public XId(String name, Object kind, String service, IDoCanonical plugin) {
if (plugin != null) name = plugin.canonical(name, kind);
this.name = name;
this.service = service;
// null@twitter is a real user :( c.f. bug #14109
assert notNullNameCheck() : name;
assert name != null;
assert ! service.contains("@") : service;
}
static Map<String,IDoCanonical> service2canonical = IDoCanonical.DUMMY_CANONICALISER;
/**
* Use with {@link IDoCanonical#DUMMY_CANONICALISER} to allow XIds to be used _without_ initialising Creole.
* @param service2canonical
*/
public static void setService2canonical(
Map<String, IDoCanonical> service2canonical)
{
XId.service2canonical = service2canonical;
}
/**
* @param name
* @param service
*/
public XId(String name, String service) {
this(name, service, service2canonical.get(service));
}
/**
* Usage: to bypass canonicalisation and syntax checks on name.
* This is handy where the plugin canonicalises for people, but XIds
* are used for both people and messages (e.g. Email).
*
* @param name
* @param service
* @param checkName Must be false to switch off the syntax checks performed by
* {@link #XId(String, String)}.
*/
public XId(String name, String service, boolean checkName) {
this.service = service;
this.name = name;
assert notNullNameCheck() : name+"@"+service;
assert ! checkName;
assert ! service.contains("@") : service;
return;
}
public XId(String id) {
this(id, (Object)null);
}
/**
*
* @param id e.g. "alice@twitter"
* @param kind e.g. KKind.Person
*/
public XId(String id, Object kind) {
int i = id.lastIndexOf('@');
if (i <= 0) {
throw new IllegalArgumentException("Invalid XId " + id);
}
this.service = id.substring(i+1);
// Text for XStream badness
assert ! id.startsWith("<xid>") : id;
// HACK: canonicalise here for main service (helps with boot-strapping)
if (isMainService()) {
this.name = id.substring(0, i).toLowerCase();
assert notNullNameCheck() : id;
return;
}
// a database object?
if (service.startsWith("DB")) {
// try { // commented out to cut creole dependency
// assert Fields.CLASS.fromString(service.substring(2)) != null : service;
// } catch (ClassNotFoundException e) {
// throw Utils.runtime(e);
this.name = id.substring(0, i);
assert notNullNameCheck() : id;
return;
}
IDoCanonical plugin = service2canonical.get(service);
String _name = id.substring(0, i);
this.name = plugin==null? _name : plugin.canonical(_name, kind);
assert notNullNameCheck() : id;
}
private boolean notNullNameCheck() {
if (name==null || name.length()==0) return false;
if (name.equals("null") && ! "twitter".equals(service)) return false;
return true;
}
/**
* Convert a name@service String (as produced by this class) into
* a XId object.
* @param canonicaliseName Must be false, to switch off using plugins to canonicalise
* the name.
*/
public XId(String id, boolean canonicaliseName) {
assert ! canonicaliseName;
int i = id.lastIndexOf('@');
// handle unescaped web inputs -- with some log noise 'cos we don't want this
if (i==-1 && id.contains("%40")) {
Log.e("XId", "(handling smoothly) Unescaped url id: "+id);
id = WebUtils2.urlDecode(id);
i = id.lastIndexOf('@');
}
assert i>0 : id;
this.service = id.substring(i+1);
this.name = id.substring(0, i);
assert notNullNameCheck() : id;
}
public XId(String name, IDoCanonical plugin) {
this(name, null, plugin.getService(), plugin);
}
public XId(String name, Object kind, IDoCanonical plugin) {
this(name, kind, plugin.getService(), plugin);
}
/**
* name@service
* This is the inverse of the String constructor, i.e.
* xid equals new Xid(xid.toString()). So you can use it for storage.
*/
@Override
public String toString() {
return name+"@"+service;
}
@Override
public int hashCode() {
final int prime = 31;
int result = name.hashCode();
result = prime * result + service.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) {
// Probably a bug!
// Log.d("xid", "XId.equals() "+this+" to "+obj.getClass()+" "+ReflectionUtils.getSomeStack(8));
return false;
}
XId other = (XId) obj;
if (!name.equals(other.name))
return false;
if (!service.equals(other.service))
return false;
return true;
}
/**
* Never null
*/
public String getName() {
return name;
}
public String getService() {
return service;
}
/**
* TODO poke this value on JVM start-up
*/
static String MAIN_SERVICE = initMAIN_SERVICE();
public boolean isMainService() {
return MAIN_SERVICE.equals(service);
}
private static String initMAIN_SERVICE() {
// NB: This property gets set by AWebsiteConfig
String s = System.getProperty("XId.MAIN_SERVICE");
if (s!=null) return s;
// HACK -- known WW instances
File dir = FileUtils.getWorkingDirectory();
if (dir.getName().equals("creole")) {
return "platypusinnovation.com";
}
return "soda.sh";
}
/**
* @return true for rubbish XIds of the form "row-id@soda.sh" or "foo@temp"
*/
public boolean isTemporary() {
return isService("temp") || (isMainService() && StrUtils.isNumber(name));
}
/**
* Convenience method
* @param other
* @return true if the services match
*/
public boolean isService(String _service) {
return this.service.equals(_service);
}
/**
* @return The name, minus any Hungarian warts SoDash has added
* to ensure uniqueness between types.
*/
public String dewart() {
// person?
if (name.startsWith(WART_P)) return name.substring(WART_P.length());
if (name.startsWith(WART_G)) return name.substring(WART_G.length());
if (name.startsWith(WART_V)) return name.substring(WART_V.length());
if (name.startsWith(WART_C)) return name.substring(WART_C.length());
// TODO do we use any others?
return name;
}
public boolean hasWart(String wart) {
return name.startsWith(wart);
}
/**
* Convenience for ensuring a List contains XId objects.
* @param xids May be Strings or XIds or IHasXIds (or a mix).
* Note: Strings are NOT run through canonicalisation -- they are assumed to be OK!
* @return a copy of xids
*/
public static List<XId> xids(Collection xids) {
return xids(xids, false);
}
/**
* Convenience for ensuring a List contains XId objects. Uses {@link #xid(Object, boolean)}
* @param xids May be Strings or XIds (or a mix).
* @return a copy of xids, can be modified
*/
public static List<XId> xids(Collection xids, boolean canonicalise) {
final ArrayList _xids = new ArrayList(xids.size());
for (Object x : xids) {
if (x==null) continue;
XId xid = xid(x, canonicalise);
_xids.add(xid);
}
return _xids;
}
/**
* Flexible type coercion / constructor convenience.
* @param xid Can be String (actually any CharSequence) or XId or IHasXId or null (returns null). Does NOT canonicalise
* */
public static XId xid(Object xid) {
return xid(xid, false);
}
public static XId xid(Object xid, boolean canon) {
if (xid==null) return null;
if (xid instanceof XId) return (XId) xid;
if (xid instanceof CharSequence) new XId(xid.toString(), canon);
IHasXId hasxid = (IHasXId) xid;
return hasxid.getXId();
}
@Override
public String toJSONString() {
return new SimpleJson().toJson(toString());
}
@Override
public Object toJson2() throws UnsupportedOperationException {
return toString();
}
} |
package dr.evomodel.continuous;
import dr.evolution.tree.MultivariateTraitTree;
import dr.evomodel.tree.TreeModel;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
/**
* @author Marc A. Suchard
* @author Guy Baele
*/
public interface MissingTraits {
public void handleMissingTips();
public boolean isCompletelyMissing(int index);
public boolean isPartiallyMissing(int index);
void computeWeightedAverage(double[] meanCache, int meanOffset0, double precision0,
int meanOffset1, double precision1, int meanThisOffset, int dim);
abstract class Abstract implements MissingTraits {
protected static final boolean DEBUG = false;
Abstract(MultivariateTraitTree treeModel, List<Integer> missingIndices, int dim) {
this.treeModel = treeModel;
this.dim = dim;
this.missingIndices = missingIndices;
completelyMissing = new boolean[treeModel.getNodeCount()];
Arrays.fill(completelyMissing, 0, treeModel.getExternalNodeCount(), false);
Arrays.fill(completelyMissing, treeModel.getExternalNodeCount(), treeModel.getNodeCount(), true); // All internal and root nodes are missing
}
final protected MultivariateTraitTree treeModel;
final protected int dim;
final protected List<Integer> missingIndices;
final protected boolean[] completelyMissing;
}
public class CompletelyMissing extends Abstract {
CompletelyMissing(MultivariateTraitTree treeModel, List<Integer> missingIndices, int dim) {
super(treeModel, missingIndices, dim);
}
public void handleMissingTips() {
for (Integer i : missingIndices) {
int whichTip = i / dim;
Logger.getLogger("dr.evomodel").info(
"\tMarking taxon " + treeModel.getTaxonId(whichTip) + " as completely missing");
completelyMissing[whichTip] = true;
}
}
public boolean isCompletelyMissing(int index) {
return completelyMissing[index];
}
public boolean isPartiallyMissing(int index) {
return false;
}
public void computeWeightedAverage(double[] meanCache,
int meanOffset0, double precision0,
int meanOffset1, double precision1,
int meanThisOffset, int dim) {
IntegratedMultivariateTraitLikelihood.computeWeightedAverage(
meanCache, meanOffset0, precision0,
meanCache, meanOffset1, precision1,
meanCache, meanThisOffset, dim);
}
}
public class PartiallyMissing extends Abstract {
PartiallyMissing(TreeModel treeModel, List<Integer> missingIndices, int dim) {
super(treeModel, missingIndices, dim);
}
public void handleMissingTips() {
throw new RuntimeException("Not yet implemented");
}
public boolean isCompletelyMissing(int index) {
throw new RuntimeException("Not yet implemented");
}
public boolean isPartiallyMissing(int index) {
throw new RuntimeException("Not yet implemented");
}
public void computeWeightedAverage(double[] meanCache, int meanOffset0, double precision0, int meanOffset1, double precision1, int meanThisOffset, int dim) {
throw new RuntimeException("Not yet implemented");
}
}
} |
package dr.inference.markovchain;
import dr.evomodel.operators.AbstractImportanceDistributionOperator;
import dr.evomodel.operators.SimpleMetropolizedGibbsOperator;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.CompoundLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* A concrete markov chain. This is final as the only things that should need
* overriding are in the delegates (prior, likelihood, schedule and acceptor).
* The design of this class is to be fairly immutable as far as settings goes.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
*/
public final class MarkovChain {
private final static boolean DEBUG = false;
private final OperatorSchedule schedule;
private final Acceptor acceptor;
private final Prior prior;
private final Likelihood likelihood;
private boolean pleaseStop = false;
private boolean isStopped = false;
private double bestScore, currentScore, initialScore;
private int currentLength;
private boolean useCoercion = true;
private final int fullEvaluationCount;
private final int minOperatorCountForFullEvaluation = 1;
public MarkovChain(Prior prior, Likelihood likelihood,
OperatorSchedule schedule, Acceptor acceptor,
int fullEvaluationCount, boolean useCoercion) {
currentLength = 0;
this.prior = prior;
this.likelihood = likelihood;
this.schedule = schedule;
this.acceptor = acceptor;
this.useCoercion = useCoercion;
this.fullEvaluationCount = fullEvaluationCount;
currentScore = evaluate(likelihood, prior);
}
/**
* Resets the markov chain
*/
public void reset() {
currentLength = 0;
// reset operator acceptance levels
for(int i = 0; i < schedule.getOperatorCount(); i++) {
schedule.getOperator(i).reset();
}
}
/**
* Run the chain for a given number of states.
*
* @param length
* number of states to run the chain.
* @param onTheFlyOperatorWeights
*/
public int chain(int length, boolean disableCoerce,
int onTheFlyOperatorWeights) {
currentScore = evaluate(likelihood, prior);
int currentState = currentLength;
final Model currentModel = likelihood.getModel();
if( currentState == 0 ) {
initialScore = currentScore;
bestScore = currentScore;
fireBestModel(currentState, currentModel);
}
if( currentScore == Double.NEGATIVE_INFINITY ) {
// identify which component of the score is zero...
if( prior != null ) {
double logPrior = prior.getLogPrior(likelihood.getModel());
if( logPrior == Double.NEGATIVE_INFINITY ) {
throw new IllegalArgumentException(
"The initial model is invalid because one of the priors has zero probability.");
}
}
String message = "The initial likelihood is zero";
if( likelihood instanceof CompoundLikelihood ) {
message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis();
} else {
message += "!";
}
throw new IllegalArgumentException(message);
}
pleaseStop = false;
isStopped = false;
int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights
: 0;
double[] logr = {0.0};
boolean usingFullEvaluation = true;
boolean fullEvaluationError = false;
while( !pleaseStop && (currentState < (currentLength + length)) ) {
// periodically log states
fireCurrentModel(currentState, currentModel);
if( pleaseStop ) {
isStopped = true;
break;
}
// Get the operator
final int op = schedule.getNextOperatorIndex();
final MCMCOperator mcmcOperator = schedule.getOperator(op);
final double oldScore = currentScore;
// assert Profiler.startProfile("Store");
// The current model is stored here in case the proposal fails
if( currentModel != null ) {
currentModel.storeModelState();
}
// assert Profiler.stopProfile("Store");
boolean operatorSucceeded = true;
double hastingsRatio = 1.0;
boolean accept = false;
logr[0] = -Double.MAX_VALUE;
try {
// The new model is proposed
// assert Profiler.startProfile("Operate");
if( DEBUG ) {
System.out.println("\n&& Operator: " + mcmcOperator.getOperatorName());
}
if( mcmcOperator instanceof SimpleMetropolizedGibbsOperator ) {
hastingsRatio = ((SimpleMetropolizedGibbsOperator) mcmcOperator).operate(prior, likelihood);
} else if( mcmcOperator instanceof AbstractImportanceDistributionOperator ) {
hastingsRatio = ((AbstractImportanceDistributionOperator) mcmcOperator).operate(prior, likelihood);
} else {
hastingsRatio = mcmcOperator.operate();
}
// assert Profiler.stopProfile("Operate");
} catch( OperatorFailedException e ) {
operatorSucceeded = false;
}
double score = 0.0;
double deviation = 0.0;
if( operatorSucceeded ) {
// The new model is proposed
// assert Profiler.startProfile("Evaluate");
if( DEBUG ) {
System.out.println("** Evaluate");
}
// The new model is evaluated
score = evaluate(likelihood, prior);
// assert Profiler.stopProfile("Evaluate");
if (usingFullEvaluation) {
// This is a test that the state is correctly restored. The
// restored state is fully evaluated and the likelihood compared with
// that before the operation was made.
likelihood.makeDirty();
final double testScore = evaluate(likelihood, prior);
if( Math.abs(testScore - score) > 1e-6 ) {
Logger.getLogger("error").severe(
"State was not correctly calculated after an operator move.\n"
+ "Likelihood evaluation: " + score
+ "\nFull Likelihood evaluation: " + testScore
+ "\n" + "Operator: " + mcmcOperator
+ " " + mcmcOperator.getOperatorName());
fullEvaluationError = true;
}
}
if( score > bestScore ) {
bestScore = score;
fireBestModel(currentState, currentModel);
}
accept = mcmcOperator instanceof GibbsOperator || acceptor.accept(oldScore, score, hastingsRatio, logr);
deviation = score - oldScore;
}
// The new model is accepted or rejected
if( accept ) {
if( DEBUG ) {
System.out.println("** Move accepted: new score = " + score
+ ", old score = " + oldScore);
}
mcmcOperator.accept(deviation);
currentModel.acceptModelState();
currentScore = score;
if( otfcounter > 0 ) {
--otfcounter;
if( otfcounter == 0 ) {
adjustOpWeights(currentState);
otfcounter = onTheFlyOperatorWeights;
}
}
} else {
if( DEBUG ) {
System.out.println("** Move rejected: new score = " + score
+ ", old score = " + oldScore);
}
mcmcOperator.reject();
// assert Profiler.startProfile("Restore");
currentModel.restoreModelState();
// assert Profiler.stopProfile("Restore");
if( usingFullEvaluation ) {
// This is a test that the state is correctly restored. The
// restored state is fully evaluated and the likelihood compared with
// that before the operation was made.
likelihood.makeDirty();
final double testScore = evaluate(likelihood, prior);
if( Math.abs(testScore - oldScore) > 1e-6 ) {
Logger.getLogger("error").severe(
"State was not correctly restored after reject step.\n"
+ "Likelihood before: " + oldScore
+ " Likelihood after: " + testScore
+ "\n" + "Operator: " + mcmcOperator
+ " " + mcmcOperator.getOperatorName());
fullEvaluationError = true;
}
}
}
if( !disableCoerce && mcmcOperator instanceof CoercableMCMCOperator ) {
coerceAcceptanceProbability((CoercableMCMCOperator) mcmcOperator, logr[0]);
}
if (usingFullEvaluation &&
schedule.getMinimumOperatorCount() >= minOperatorCountForFullEvaluation &&
currentState >= fullEvaluationCount ) {
// full evaluation is only switched off when each operator has done a
// minimum number of operations (currently 1) and fullEvalationCount
// operations in total.
usingFullEvaluation = false;
if (fullEvaluationError) {
// If there has been an error then stop with an error
throw new RuntimeException(
"One or more evaluation errors occured during the test phase of this\n" +
"run. These errors imply critical errors which may produce incorrect\n" +
"results.");
}
}
currentState += 1;
}
currentLength = currentState;
fireFinished(currentLength);
// Profiler.report();
return currentLength;
}
private void adjustOpWeights(int currentState) {
final int count = schedule.getOperatorCount();
double[] s = new double[count];
final double factor = 100;
final double limitSpan = 1000;
System.err.println("start cycle " + currentState);
double sHas = 0.0/* , sNot = 0.0 */, nHas = 0.0;
for(int no = 0; no < count; ++no) {
final MCMCOperator op = schedule.getOperator(no);
final double v = op.getSpan(true);
if( v == 0 ) {
// sNot += op.getWeight();
s[no] = 0;
} else {
sHas += op.getWeight();
s[no] = Math.max(factor * Math.min(v, limitSpan), 1);
nHas += s[no];
}
}
// for(int no = 0; no < count; ++no) {
// final MCMCOperator op = schedule.getOperator(no);
// final double v = op.getSpan(false);
// if( v == 0 ) {
// System.err.println(op.getOperatorName() + " blocks");
// return;
// keep sum of changed parts unchanged
final double scaleHas = sHas / nHas;
for(int no = 0; no < count; ++no) {
final MCMCOperator op = schedule.getOperator(no);
if( s[no] > 0 ) {
final double val = s[no] * scaleHas;
op.setWeight(val);
System.err.println("set " + op.getOperatorName() + " " + val);
} else {
System.err.println("** " + op.getOperatorName() + " = "
+ op.getWeight());
}
}
schedule.operatorsHasBeenUpdated();
}
public Prior getPrior() {
return prior;
}
public Likelihood getLikelihood() {
return likelihood;
}
public Model getModel() {
return likelihood.getModel();
}
public OperatorSchedule getSchedule() {
return schedule;
}
public Acceptor getAcceptor() {
return acceptor;
}
public double getInitialScore() {
return initialScore;
}
public double getBestScore() {
return bestScore;
}
public int getCurrentLength() {
return currentLength;
}
public void setCurrentLength(int currentLength) {
this.currentLength = currentLength;
}
public double getCurrentScore() {
return currentScore;
}
public void pleaseStop() {
pleaseStop = true;
}
public boolean isStopped() {
return isStopped;
}
private double evaluate(Likelihood likelihood, Prior prior) {
double logPosterior = 0.0;
if( prior != null ) {
final double logPrior = prior.getLogPrior(likelihood.getModel());
if( logPrior == Double.NEGATIVE_INFINITY ) {
return Double.NEGATIVE_INFINITY;
}
logPosterior += logPrior;
}
final double logLikelihood = likelihood.getLogLikelihood();
if( Double.isNaN(logLikelihood) ) {
return Double.NEGATIVE_INFINITY;
}
// System.err.println("** " + logPosterior + " + " + logLikelihood +
// " = " + (logPosterior + logLikelihood));
logPosterior += logLikelihood;
return logPosterior;
}
/**
* Updates the proposal parameter, based on the target acceptance
* probability This method relies on the proposal parameter being a
* decreasing function of acceptance probability.
*
* @param op The operator
* @param logr
*/
private void coerceAcceptanceProbability(CoercableMCMCOperator op, double logr) {
if( isCoercable(op) ) {
final double p = op.getCoercableParameter();
final double i = schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op));
final double target = op.getTargetAcceptanceProbability();
final double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target));
if( newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE ) {
op.setCoercableParameter(newp);
}
}
}
private boolean isCoercable(CoercableMCMCOperator op) {
return op.getMode() == CoercionMode.COERCION_ON
|| (op.getMode() != CoercionMode.COERCION_OFF && useCoercion);
}
public void addMarkovChainListener(MarkovChainListener listener) {
listeners.add(listener);
}
public void removeMarkovChainListener(MarkovChainListener listener) {
listeners.remove(listener);
}
public void fireBestModel(int state, Model bestModel) {
for(MarkovChainListener listener : listeners) {
listener.bestState(state, bestModel);
}
}
public void fireCurrentModel(int state, Model currentModel) {
for(MarkovChainListener listener : listeners) {
listener.currentState(state, currentModel);
}
}
public void fireFinished(int chainLength) {
for(MarkovChainListener listener : listeners) {
listener.finished(chainLength);
}
}
private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
} |
package foam.lib.parse;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ErrorReportingPStream
extends ProxyPStream
{
public static final List<Character> ASCII_CHARS = IntStream.rangeClosed(0, 255)
.mapToObj(i -> (char) i)
.collect(Collectors.toList());
protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
@Override
public StringBuilder get() {
StringBuilder b = super.get();
b.setLength(0);
return b;
}
};
protected Parser errParser = null;
protected ParserContext errContext = null;
protected ErrorReportingNodePStream errStream = null;
protected int pos;
protected ErrorReportingNodePStream tail_ = null;
protected Set<Character> validCharacters = new HashSet<>();
public ErrorReportingPStream(PStream delegate) {
this(delegate, 0);
}
public ErrorReportingPStream(PStream delegate, int pos) {
setDelegate(delegate);
this.pos = pos;
}
@Override
public PStream tail() {
// tail becomes new node with increased position
if ( tail_ == null ) tail_ = new ErrorReportingNodePStream(this, super.tail(), pos + 1);
return tail_;
}
@Override
public PStream setValue(Object value) {
// create a new node
return new ErrorReportingNodePStream(this, super.setValue(value), pos);
}
@Override
public PStream apply(Parser parser, ParserContext x) {
PStream result = parser.parse(this, x);
if ( result == null ) {
// if result is null then self report
this.report(new ErrorReportingNodePStream(this, getDelegate(), pos), parser, x);
}
return result;
}
public void report(ErrorReportingNodePStream ernps, Parser parser, ParserContext x) {
// get the report with the furthest position
if ( errStream == null || errStream.pos < ernps.pos ) {
errStream = ernps;
errParser = parser;
errContext = x;
}
}
public void reportValidCharacter(Character character) {
validCharacters.add(character);
}
public String getMessage() {
// check if err is valid and print the char, if not print EOF
String invalid = ( errStream.valid() ) ? String.valueOf(errStream.head()) : "EOF";
// get a list of valid characters
TrapPStream trap = new TrapPStream(this);
Iterator i = ASCII_CHARS.iterator();
while ( i.hasNext() ) {
Character character = (Character) i.next();
trap.setHead(character);
trap.apply(errParser, errContext);
}
StringBuilder builder = sb.get()
.append("Invalid character '")
.append(invalid)
.append("' found at ")
.append(errStream.pos)
.append("\n")
.append("Valid characters include: ")
.append(validCharacters.stream().map(Object::toString).collect(Collectors.joining(",")));
return builder.toString();
}
} |
package com.admicro.vertx.utils;
import io.vertx.core.json.JsonObject;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class XmlConverterTest {
@Test
public void test_toJson() {
StringBuilder builder = new StringBuilder();
builder.append("<server>\n");
builder.append("<server_options>\n" +
"<address>0.0.0.0</address>\n" +
"<port>8888</port>\n" +
"</server_options>");
builder.append("<database>\n" +
"<driver_class>com.mysql.jdbc.Driver</driver_class>\n" +
"<url>jdbc:mysql://localhost/server_load</url>\n" +
"<user>root</user>\n" +
"<password>root</password>\n" +
"<max_pool_size>30</max_pool_size>\n" +
"</database>\n");
builder.append("<deployment_options></deployment_options>\n");
builder.append("<vertx_options></vertx_options>\n");
builder.append("</server>");
try {
JsonObject server = XmlConverter.toJson(builder.toString(), "server").getJsonObject("server");
JsonObject serverOptions = server.getJsonObject("server_options");
JsonObject database = server.getJsonObject("database");
JsonObject deploymentOptions = server.getJsonObject("deployment_options");
JsonObject vertxOptions = server.getJsonObject("vertx_options");
assertTrue(serverOptions != null);
assertTrue(database != null);
assertTrue(deploymentOptions != null);
assertTrue(vertxOptions != null);
assertEquals(serverOptions.getString("address"), "0.0.0.0");
assertEquals(serverOptions.getInteger("port"), (Integer) 888);
assertEquals(database.getString("driver_class"), "com.mysql.jdbc.Driver");
assertEquals(database.getString("url"), "jdbc:mysql://localhost/server_load");
assertEquals(database.getString("user"), "root");
assertEquals(database.getString("password"), "root");
assertEquals(database.getInteger("max_pool_size"), (Integer) 30);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
} |
package com.faforever.api.email;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.config.FafApiProperties.PasswordReset;
import com.faforever.api.config.FafApiProperties.Registration;
import com.faforever.api.error.ApiExceptionWithCode;
import com.faforever.api.error.ErrorCode;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EmailServiceTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private EmailService instance;
private FafApiProperties properties;
@Mock
private DomainBlacklistRepository domainBlacklistRepository;
@Mock
private EmailSender emailSender;
@Before
public void setUp() throws Exception {
properties = new FafApiProperties();
instance = new EmailService(domainBlacklistRepository, properties, emailSender);
}
@Test
public void validateEmailAddress() throws Exception {
instance.validateEmailAddress("test@example.com");
}
@Test
public void validateEmailAddressMissingAt() throws Exception {
expectedException.expect(ApiExceptionWithCode.apiExceptionWithCode(ErrorCode.EMAIL_INVALID));
instance.validateEmailAddress("testexample.com");
}
@Test
public void validateEmailAddressMissingTld() throws Exception {
expectedException.expect(ApiExceptionWithCode.apiExceptionWithCode(ErrorCode.EMAIL_INVALID));
instance.validateEmailAddress("test@example");
}
@Test
public void validateEmailAddressBlacklisted() throws Exception {
when(domainBlacklistRepository.existsByDomain("example.com")).thenReturn(true);
expectedException.expect(ApiExceptionWithCode.apiExceptionWithCode(ErrorCode.EMAIL_BLACKLISTED));
instance.validateEmailAddress("test@example.com");
}
@Test
public void sendActivationMail() throws Exception {
Registration registration = properties.getRegistration();
registration.setFromEmail("foo@bar.com");
registration.setFromName("foobar");
registration.setSubject("Hello");
registration.setHtmlFormat("Hello {0}, bla: {1}");
instance.sendActivationMail("junit", "junit@example.com", "http://example.com");
verify(emailSender).sendMail("foo@bar.com", "foobar", "junit@example.com", "Hello", "Hello junit, bla: http://example.com");
}
@Test
public void sendPasswordResetMail() {
PasswordReset passwordReset = properties.getPasswordReset();
passwordReset.setFromEmail("foo@bar.com");
passwordReset.setFromName("foobar");
passwordReset.setSubject("Hello");
passwordReset.setHtmlFormat("Hello {0}, bla: {1}");
instance.sendPasswordResetMail("junit", "junit@example.com", "http://example.com");
verify(emailSender).sendMail("foo@bar.com", "foobar", "junit@example.com", "Hello", "Hello junit, bla: http://example.com");
}
} |
package com.googlecode.objectify.test;
import static com.googlecode.objectify.test.util.TestObjectifyService.fact;
import static com.googlecode.objectify.test.util.TestObjectifyService.ofy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.google.appengine.api.datastore.Blob;
import com.googlecode.objectify.annotation.Index;
import org.testng.annotations.Test;
import com.google.appengine.api.datastore.ReadPolicy.Consistency;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.LoadResult;
import com.googlecode.objectify.SaveException;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Parent;
import com.googlecode.objectify.test.entity.Employee;
import com.googlecode.objectify.test.entity.NamedTrivial;
import com.googlecode.objectify.test.entity.Trivial;
import com.googlecode.objectify.test.util.TestBase;
/**
* Tests of basic entity manipulation.
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
public class BasicTests extends TestBase
{
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(BasicTests.class.getName());
@Test
public void idIsGenerated() throws Exception {
fact().register(Trivial.class);
// Note that 5 is not the id, it's part of the payload
Trivial triv = new Trivial("foo", 5);
Key<Trivial> k = ofy().save().entity(triv).now();
assert k.getKind().equals(triv.getClass().getSimpleName());
assert k.getId() == triv.getId();
Key<Trivial> created = Key.create(Trivial.class, k.getId());
assert k.equals(created);
Trivial fetched = ofy().load().key(k).now();
assert fetched.getId().equals(k.getId());
assert fetched.getSomeNumber() == triv.getSomeNumber();
assert fetched.getSomeString().equals(triv.getSomeString());
}
@Test(expectedExceptions=SaveException.class)
public void savingNullNamedIdThrowsException() throws Exception {
fact().register(NamedTrivial.class);
NamedTrivial triv = new NamedTrivial(null, "foo", 5);
ofy().save().entity(triv).now();
}
@Test
public void savingEntityWithSameIdOverwritesData() throws Exception {
fact().register(Trivial.class);
Trivial triv = new Trivial("foo", 5);
Key<Trivial> k = ofy().save().entity(triv).now();
Trivial triv2 = new Trivial(k.getId(), "bar", 6);
Key<Trivial> k2 = ofy().save().entity(triv2).now();
assert k2.equals(k);
Trivial fetched = ofy().load().key(k).now();
assert fetched.getId() == k.getId();
assert fetched.getSomeNumber() == triv2.getSomeNumber();
assert fetched.getSomeString().equals(triv2.getSomeString());
}
@Test
public void savingEntityWithNameIdWorks() throws Exception {
fact().register(NamedTrivial.class);
NamedTrivial triv = new NamedTrivial("first", "foo", 5);
Key<NamedTrivial> k = ofy().save().entity(triv).now();
assert k.getName().equals("first");
Key<NamedTrivial> createdKey = Key.create(NamedTrivial.class, "first");
assert k.equals(createdKey);
NamedTrivial fetched = ofy().load().key(k).now();
assert fetched.getName().equals(k.getName());
assert fetched.getSomeNumber() == triv.getSomeNumber();
assert fetched.getSomeString().equals(triv.getSomeString());
}
@Test
public void testBatchOperations() throws Exception {
fact().register(Trivial.class);
Trivial triv1 = new Trivial("foo", 5);
Trivial triv2 = new Trivial("foo2", 6);
List<Trivial> objs = new ArrayList<>();
objs.add(triv1);
objs.add(triv2);
Map<Key<Trivial>, Trivial> map = ofy().save().entities(objs).now();
List<Key<Trivial>> keys = new ArrayList<>(map.keySet());
// Verify the put keys
assert keys.size() == objs.size();
for (int i=0; i<objs.size(); i++)
{
assert keys.get(i).getId() == objs.get(i).getId();
}
// Now fetch and verify the data
Map<Key<Trivial>, Trivial> fetched = ofy().load().keys(keys);
assert fetched.size() == keys.size();
for (Trivial triv: objs)
{
Trivial fetchedTriv = fetched.get(Key.create(triv));
assert triv.getSomeNumber() == fetchedTriv.getSomeNumber();
assert triv.getSomeString().equals(fetchedTriv.getSomeString());
}
}
@Test
public void testManyToOne() throws Exception {
fact().register(Employee.class);
Employee fred = new Employee("fred");
ofy().save().entity(fred).now();
Key<Employee> fredKey = Key.create(fred);
List<Employee> employees = new ArrayList<>(100);
for (int i = 0; i < 100; i++)
{
Employee emp = new Employee("foo" + i, fredKey);
employees.add(emp);
}
ofy().save().entities(employees).now();
assert employees.size() == 100;
int count = 0;
for (Employee emp: ofy().load().type(Employee.class).filter("manager", fred))
{
emp.getName(); // Just to make eclipse happy
count++;
}
assert count == 100;
}
@Test
public void testConsistencySetting() throws Exception {
fact().register(Trivial.class);
Trivial triv = new Trivial("foo", 5);
ofy().consistency(Consistency.EVENTUAL).save().entity(triv).now();
}
@Test
public void testKeyToString() throws Exception {
Key<Trivial> trivKey = Key.create(Trivial.class, 123);
String stringified = trivKey.getString();
Key<Trivial> andBack = Key.create(stringified);
assert trivKey.equals(andBack);
}
@Test
public void testPutNothing() throws Exception {
ofy().save().entities(Collections.emptyList()).now();
}
@Test
public void deleteBatch() throws Exception {
fact().register(Trivial.class);
Trivial triv1 = new Trivial("foo5", 5);
Trivial triv2 = new Trivial("foo6", 6);
ofy().save().entities(triv1, triv2).now();
assert ofy().load().entities(triv1, triv2).size() == 2;
ofy().delete().entities(triv1, triv2).now();
Map<Key<Trivial>, Trivial> result = ofy().load().entities(triv1, triv2);
System.out.println("Result is " + result);
assert result.size() == 0;
}
@SuppressWarnings("unchecked")
@Test
public void loadNonexistant() throws Exception {
fact().register(Trivial.class);
Trivial triv1 = new Trivial("foo5", 5);
ofy().save().entity(triv1).now();
Key<Trivial> triv1Key = Key.create(triv1);
Key<Trivial> triv2Key = Key.create(Trivial.class, 998);
Key<Trivial> triv3Key = Key.create(Trivial.class, 999);
LoadResult<Trivial> res = ofy().load().key(triv2Key);
assert res.now() == null;
Map<Key<Trivial>, Trivial> result = ofy().load().keys(triv2Key, triv3Key);
assert result.size() == 0;
Map<Key<Trivial>, Trivial> result2 = ofy().load().keys(triv1Key, triv2Key);
assert result2.size() == 1;
}
@SuppressWarnings("unchecked")
@Test
public void loadNonexistantWithoutSession() throws Exception {
fact().register(Trivial.class);
Trivial triv1 = new Trivial("foo5", 5);
ofy().save().entity(triv1).now();
Key<Trivial> triv1Key = Key.create(triv1);
Key<Trivial> triv2Key = Key.create(Trivial.class, 998);
Key<Trivial> triv3Key = Key.create(Trivial.class, 999);
ofy().clear();
LoadResult<Trivial> res = ofy().load().key(triv2Key);
assert res.now() == null;
ofy().clear();
Map<Key<Trivial>, Trivial> result = ofy().load().keys(triv2Key, triv3Key);
assert result.size() == 0;
ofy().clear();
Map<Key<Trivial>, Trivial> result2 = ofy().load().keys(triv1Key, triv2Key);
assert result2.size() == 1;
}
@Test
public void simpleFetchById() throws Exception {
fact().register(Trivial.class);
Trivial triv1 = new Trivial("foo5", 5);
ofy().save().entity(triv1).now();
ofy().clear();
Trivial fetched = ofy().load().type(Trivial.class).id(triv1.getId()).now();
assert fetched.getSomeString().equals(triv1.getSomeString());
}
@Entity
static class HasParent {
@Parent Key<Trivial> parent;
@Id long id;
}
/** Simply delete an entity which has a parent */
@Test
public void deleteAnEntityWithAParent() throws Exception {
fact().register(Trivial.class);
fact().register(HasParent.class);
HasParent hp = new HasParent();
hp.parent = Key.create(Trivial.class, 123L);
hp.id = 456L;
Key<HasParent> hpKey = ofy().save().entity(hp).now();
ofy().clear();
assert ofy().load().key(hpKey).now() != null;
ofy().delete().entity(hp).now();
ofy().clear();
assert ofy().load().key(hpKey).now() == null;
}
@Entity
static class HasIndexedBlob {
@Id Long id;
@Index Blob blob;
}
@Test
public void indexSomethingThatCannotBeIndexed() throws Exception {
fact().register(HasIndexedBlob.class);
byte[] stuff = "asdf".getBytes();
HasIndexedBlob hib = new HasIndexedBlob();
hib.blob = new Blob(stuff);
HasIndexedBlob fetched = ofy().saveClearLoad(hib);
byte[] fetchedStuff = fetched.blob.getBytes();
assert Arrays.equals(fetchedStuff, stuff);
}
} |
package hdm.pk070.jscheme.eval;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.obj.SchemeObject;
import hdm.pk070.jscheme.obj.builtin.function.SchemeBuiltinFunction;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeCons;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeNil;
import hdm.pk070.jscheme.obj.builtin.simple.SchemeSymbol;
import hdm.pk070.jscheme.obj.builtin.simple.number.exact.SchemeInteger;
import hdm.pk070.jscheme.obj.builtin.syntax.SchemeBuiltinSyntax;
import hdm.pk070.jscheme.obj.custom.SchemeCustomUserFunction;
import hdm.pk070.jscheme.stack.SchemeCallStack;
import hdm.pk070.jscheme.table.environment.Environment;
import hdm.pk070.jscheme.table.environment.LocalEnvironment;
import hdm.pk070.jscheme.table.environment.entry.EnvironmentEntry;
import hdm.pk070.jscheme.util.ReflectionCallArg;
import hdm.pk070.jscheme.util.ReflectionUtils;
import hdm.pk070.jscheme.util.exception.ReflectionMethodCallException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
/**
* A test class for {@link ListEvaluator}
*
* @author patrick.kleindienst
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PrepareForTest({SchemeCallStack.class, SymbolEvaluator.class, LocalEnvironment.class, SchemeEval.class})
public class ListEvaluatorTest {
private static final String METHOD_EVAL_BUILTIN_FUNC = "evaluateBuiltinFunction";
private static final String METHOD_EVAL_CUST_USER_FUNC = "evaluateCustomUserFunction";
private ListEvaluator listEvaluator;
private SchemeCons argumentListWithTwoArgs;
private SchemeCons argumentListWithSingleArg;
private SchemeCons parameterListWithSingleParam;
private SchemeCons parameterListWithTwoParams;
@Before
public void setUp() {
this.listEvaluator = ListEvaluator.getInstance();
this.argumentListWithTwoArgs = new SchemeCons(new SchemeInteger(2), new SchemeCons(new SchemeInteger(3), new
SchemeNil()));
this.argumentListWithSingleArg = new SchemeCons(new SchemeInteger(42), new SchemeNil());
this.parameterListWithSingleParam = new SchemeCons(new SchemeSymbol("x"), new SchemeNil());
this.parameterListWithTwoParams = new SchemeCons(new SchemeSymbol("x"), new SchemeCons(new SchemeSymbol("y"),
new SchemeNil()));
}
@Test
public void testEvaluateBuiltinFunction() throws SchemeError {
int expectedArgCount = 2;
// Setup SchemeCallStack mock and ensure its returned on request for an instance
SchemeCallStack mockedStack = mock(SchemeCallStack.class);
PowerMockito.mockStatic(SchemeCallStack.class);
PowerMockito.when(SchemeCallStack.instance()).thenReturn(mockedStack);
// Setup SchemeBuiltinFunction mock
SchemeBuiltinFunction schemeBuiltinFunction = Mockito.mock(SchemeBuiltinFunction.class);
// Invoke target method via reflection
ReflectionUtils.invokeMethod(listEvaluator, METHOD_EVAL_BUILTIN_FUNC,
new ReflectionCallArg(SchemeBuiltinFunction.class, schemeBuiltinFunction),
new ReflectionCallArg(SchemeObject.class, argumentListWithTwoArgs),
new ReflectionCallArg(Environment.class, LocalEnvironment.withSize(42)));
// Ensure arguments have been pushed on stack
verify(mockedStack).push(eq(new SchemeInteger(2)));
verify(mockedStack).push(eq(new SchemeInteger(3)));
// Ensure the built-in function mock has been called with the right number of arguments
verify(schemeBuiltinFunction).call(expectedArgCount);
}
@Test
public void testDoEvalWithBuiltinFunction() throws SchemeError {
SchemeSymbol plusSymbol = new SchemeSymbol("+");
LocalEnvironment dummyEnv = LocalEnvironment.withSize(42);
// Setup a built-in function mock
SchemeBuiltinFunction builtinFunctionMock = mock(SchemeBuiltinFunction.class);
SymbolEvaluator symbolEvaluator = mock(SymbolEvaluator.class);
Mockito.when(symbolEvaluator.doEval(plusSymbol, dummyEnv)).thenReturn(builtinFunctionMock);
// Setup the SymbolEvaluator mock which returns the function mock
PowerMockito.mockStatic(SymbolEvaluator.class);
PowerMockito.when(SymbolEvaluator.getInstance()).thenReturn(symbolEvaluator);
// Create a dummy expression (function call)
SchemeCons expression = new SchemeCons(new SchemeSymbol("+"), new SchemeCons(new
SchemeInteger(1), new SchemeCons(new SchemeInteger(2), new SchemeNil())));
// Call ListEvaluator
listEvaluator.doEval(expression, dummyEnv);
// Verify that the function mock has been called as expected
verify(builtinFunctionMock, times(1)).call(2);
}
@Test
public void testBuiltinSyntaxIsCalledWithExpectedArgs() throws SchemeError {
SchemeSymbol defineSymbol = new SchemeSymbol("define");
LocalEnvironment dummyEnv = LocalEnvironment.withSize(42);
// Setup SymbolEvaluator mock for returning our SchemeBuiltinSyntax mock
SchemeBuiltinSyntax mockedBuiltinSyntax = mock(SchemeBuiltinSyntax.class);
SymbolEvaluator mockedSymbolEvaluator = mock(SymbolEvaluator.class);
when(mockedSymbolEvaluator.doEval(defineSymbol, dummyEnv)).thenReturn(mockedBuiltinSyntax);
// Setup SymbolEvaluator class for returning our prepared mock
PowerMockito.mockStatic(SymbolEvaluator.class);
PowerMockito.when(SymbolEvaluator.getInstance()).thenReturn(mockedSymbolEvaluator);
SchemeCons expression = new SchemeCons(new SchemeSymbol("define"), new SchemeCons(new SchemeSymbol("abc"),
new SchemeCons(new SchemeInteger(42), new SchemeNil())));
listEvaluator.doEval(expression, dummyEnv);
// Verify that our SchemeBuiltinSyntax mock is called exactly once and with the expected arguments
verify(mockedBuiltinSyntax, times(1)).apply(expression.getCdr(), dummyEnv);
}
@Test
public void testEvaluateCustomUserFunctionThrowsErrorOnMissingArgument() throws SchemeError {
SchemeCustomUserFunction customFunction = mock(SchemeCustomUserFunction.class);
prepareCustomUserFunctionMock(customFunction, null, parameterListWithTwoParams, 2);
try {
ReflectionUtils.invokeMethod(this.listEvaluator, METHOD_EVAL_CUST_USER_FUNC, new ReflectionCallArg
(SchemeCustomUserFunction.class, customFunction), new ReflectionCallArg(SchemeObject.class,
argumentListWithSingleArg), new ReflectionCallArg(Environment.class, null));
fail("Expected exception has not been thrown!");
} catch (ReflectionMethodCallException e) {
assertException(e.getCause().getCause(), new SchemeError("(eval): arity mismatch, expected number of " +
"arguments does not match the given number [expected: 2, given: 1]"));
}
}
@Test
public void testEvaluateCustomUserFunctionAddsArgumentToEnvProperly() throws SchemeError {
LocalEnvironment localEnvMock = mock(LocalEnvironment.class);
PowerMockito.mockStatic(LocalEnvironment.class);
PowerMockito.when(LocalEnvironment.withSizeAndParent(1, null)).thenReturn(localEnvMock);
SchemeCons emptyBodyList = new SchemeCons(new SchemeNil(), new SchemeNil());
SchemeCustomUserFunction customFunctionMock = mock(SchemeCustomUserFunction.class);
prepareCustomUserFunctionMock(customFunctionMock, emptyBodyList, parameterListWithSingleParam, 1);
ReflectionUtils.invokeMethod(this.listEvaluator, METHOD_EVAL_CUST_USER_FUNC, new ReflectionCallArg
(SchemeCustomUserFunction.class, customFunctionMock), new ReflectionCallArg(SchemeObject.class,
argumentListWithSingleArg), new ReflectionCallArg(Environment.class, null));
verify(localEnvMock, times(1)).add(EnvironmentEntry.create((SchemeSymbol) parameterListWithSingleParam.getCar(),
argumentListWithSingleArg.getCar()));
}
@Test
public void testEvaluateCustomUserFunctionThrowsErrorOnToManyArguments() {
SchemeCustomUserFunction customFunctionMock = mock(SchemeCustomUserFunction.class);
prepareCustomUserFunctionMock(customFunctionMock, null, parameterListWithSingleParam, 1);
try {
ReflectionUtils.invokeMethod(this.listEvaluator, METHOD_EVAL_CUST_USER_FUNC, new ReflectionCallArg
(SchemeCustomUserFunction.class, customFunctionMock), new ReflectionCallArg(SchemeObject.class,
argumentListWithTwoArgs), new ReflectionCallArg(Environment.class, null));
fail("Expected exception has not been thrown!");
} catch (ReflectionMethodCallException e) {
assertException(e.getCause().getCause(), new SchemeError("(eval): arity mismatch, expected number of " +
"arguments does not match the given number [expected: 1, more given!]"));
}
}
@Test
public void testEvaluateCustomUserFunctionReturnsExpectedResultOnValidInput() throws SchemeError {
SchemeCons bodyList = new SchemeCons(new SchemeCons(new SchemeSymbol("+"), new SchemeCons(new SchemeSymbol
("x"), new SchemeCons(new SchemeSymbol("y"), new SchemeNil()))), new SchemeNil());
SchemeCustomUserFunction customFunctionMock = mock(SchemeCustomUserFunction.class);
prepareCustomUserFunctionMock(customFunctionMock, bodyList, parameterListWithTwoParams, 2);
LocalEnvironment localEnvDummy = mock(LocalEnvironment.class);
PowerMockito.mockStatic(LocalEnvironment.class);
PowerMockito.when(LocalEnvironment.withSizeAndParent(2, null)).thenReturn(localEnvDummy);
SchemeEval schemeEvalMock = mock(SchemeEval.class);
when(schemeEvalMock.eval(new SchemeInteger(2), null)).thenReturn(new SchemeInteger(2));
when(schemeEvalMock.eval(new SchemeInteger(3), null)).thenReturn(new SchemeInteger(3));
when(schemeEvalMock.eval(bodyList.getCar(), localEnvDummy)).thenReturn(new SchemeInteger(5));
PowerMockito.mockStatic(SchemeEval.class);
PowerMockito.when(SchemeEval.getInstance()).thenReturn(schemeEvalMock);
Object result = ReflectionUtils.invokeMethod(this.listEvaluator,
METHOD_EVAL_CUST_USER_FUNC, new ReflectionCallArg(SchemeCustomUserFunction.class, customFunctionMock)
, new ReflectionCallArg(SchemeObject.class, argumentListWithTwoArgs), new ReflectionCallArg
(Environment.class, null));
assertThat(result, notNullValue());
assertThat(result.getClass(), equalTo(SchemeInteger.class));
assertThat(result, equalTo(new SchemeInteger(5)));
}
private void prepareCustomUserFunctionMock(SchemeCustomUserFunction customUserFunctionMock, SchemeCons bodyList,
SchemeCons paramList, int paramCount) {
when(customUserFunctionMock.getRequiredSlotsCount()).thenReturn(paramCount);
when(customUserFunctionMock.getHomeEnvironment()).thenReturn(null);
when(customUserFunctionMock.getParameterList()).thenReturn(paramList);
when(customUserFunctionMock.getParamCount()).thenReturn(paramCount);
when(customUserFunctionMock.getFunctionBodyList()).thenReturn(bodyList);
}
private void assertException(Throwable actual, Throwable expected) {
assertThat(actual.getClass(), equalTo(expected.getClass()));
assertThat(actual.getMessage(), equalTo(expected.getMessage()));
}
} |
package hudson.plugins.warnings;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.junit.Assert.*;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.warnings.GroovyParser.DescriptorImpl;
import hudson.plugins.warnings.parser.AbstractWarningsParser;
import hudson.util.FormValidation;
import hudson.util.FormValidation.Kind;
/**
* Tests the class {@link GroovyParser}.
*
* @author Ulli Hafner
*/
public class GroovyParserTest {
// CHECKSTYLE:OFF
private static final String SINGLE_LINE_EXAMPLE = "file/name/relative/unix:42:evil: this is a warning message";
private static final String MULTI_LINE_EXAMPLE = " [javac] 1. WARNING in C:\\Desenvolvimento\\Java\\jfg\\src\\jfg\\AttributeException.java (at line 3)\n"
+ " [javac] public class AttributeException extends RuntimeException\n"
+ " [javac] ^^^^^^^^^^^^^^^^^^\n"
+ " [javac] The serializable class AttributeException does not declare a static final serialVersionUID field of type long\n"
+ " [javac]
private static final String MULTILINE_SCRIPT = "import hudson.plugins.warnings.parser.Warning\n" +
"import hudson.plugins.analysis.util.model.Priority\n" +
"\n" +
"String type = matcher.group(1)\n" +
"Priority priority;\n" +
"if (\"warning\".equalsIgnoreCase(type)) {\n" +
" priority = Priority.NORMAL;\n" +
"}\n" +
"else {\n" +
" priority = Priority.HIGH;\n" +
"}\n" +
"\n" +
"String fileName = matcher.group(2)\n" +
"String lineNumber = matcher.group(3)\n" +
"String message = matcher.group(4)\n" +
"\n" +
"return new Warning(fileName, Integer.parseInt(lineNumber), \"Generic Parser\", \"\", message);\n";
@SuppressWarnings("javadoc")
public static final String MULTI_LINE_REGEXP = "(WARNING|ERROR)\\s*in\\s*(.*)\\(at line\\s*(\\d+)\\).*(?:\\r?\\n[^\\^]*)+(?:\\r?\\n.*[\\^]+.*)\\r?\\n(?:\\s*\\[.*\\]\\s*)?(.*)";
@SuppressWarnings("javadoc")
public static final String SINGLE_LINE_REGEXP = "^\\s*(.*):(\\d+):(.*):\\s*(.*)$";
// CHECKSTYLE:ON
@Test @Issue("35262")
public void issue35262() throws IOException {
String multiLineRegexp = "(make(?:(?!make)[\\s\\S])*?make-error:.*\\n)";
String textToMatch = "start build\n" +
"make: thisFile.js\n" +
"everything okay\n" +
"make: thisOtherFile.js\n" +
"error detail1: wrong character\n" +
"error detail2: ecnoding issue\n" +
"make-error: thisOtherFile.js: wrong encoding detected\n" +
"make: anotherFile.js\n" +
"make: yetAnotherFile.js\n" +
"end build";
String script = "import hudson.plugins.warnings.parser.Warning\n" +
"import hudson.plugins.analysis.util.model.Priority\n" +
"String fileName = \"\"\n" +
"String type = \"TEST\"\n" +
"String category = \"make-error\"\n" +
"String errors = matcher.group(1)\n" +
"return new Warning(fileName, 0, type, category, errors, Priority.HIGH);\n";
GroovyParser parser = new GroovyParser("name", multiLineRegexp, script);
assertTrue("Wrong multi line support guess", parser.hasMultiLineSupport());
DescriptorImpl descriptor = createDescriptor();
assertOk(descriptor.doCheckExample(textToMatch, multiLineRegexp, script));
AbstractWarningsParser instance = parser.getParser();
Collection<FileAnnotation> warnings = instance.parse(new StringReader(textToMatch));
assertEquals("No warning found.", 1, warnings.size());
}
/**
* Verifies that multi line expressions are correctly detected.
*/
@Test
public void testMultiLine() {
GroovyParser parser = new GroovyParser("name", MULTI_LINE_REGEXP, "empty");
assertTrue("Wrong multi line support guess", parser.hasMultiLineSupport());
}
/**
* Verifies that single line expressions are correctly detected.
*/
@Test
public void testSingleLine() {
GroovyParser parser = new GroovyParser("name", SINGLE_LINE_REGEXP, "empty");
assertFalse("Wrong single line support guess", parser.hasMultiLineSupport());
}
/**
* Test the validation of the name parameter.
*/
@Test
public void testNameValidation() {
DescriptorImpl descriptor = createDescriptor();
assertError(descriptor.doCheckName(null));
assertError(descriptor.doCheckName(StringUtils.EMPTY));
assertOk(descriptor.doCheckName("Java Parser 2"));
}
/**
* Test the validation of the regexp parameter.
*/
@Test
public void testRegexpValidation() {
DescriptorImpl descriptor = createDescriptor();
assertError(descriptor.doCheckRegexp(null));
assertError(descriptor.doCheckRegexp(StringUtils.EMPTY));
assertError(descriptor.doCheckRegexp("one brace ("));
assertError(descriptor.doCheckRegexp("backslash \\"));
assertOk(descriptor.doCheckRegexp("^.*[a-z]"));
}
/**
* Test the validation of the script parameter.
*
* @throws IOException
* if the example file could not be read
*/
@Test
public void testScriptValidationWithoutExample() throws IOException {
DescriptorImpl descriptor = createDescriptor();
assertError(descriptor.doCheckScript(null));
assertError(descriptor.doCheckScript(StringUtils.EMPTY));
assertError(descriptor.doCheckScript("Hello World"));
assertOk(descriptor.doCheckScript(readScript()));
}
private String readScript() throws IOException {
return IOUtils.toString(GroovyParserTest.class.getResourceAsStream("groovy.snippet"));
}
/**
* Test the validation of the script parameter with a given regular
* expression and example. Expected result: the expected result is a
* warning.
*
* @throws IOException
* if the example file could not be read
*/
@Test
public void testScriptValidationOneWarning() throws IOException {
DescriptorImpl descriptor = createDescriptor();
assertOk(descriptor.doCheckExample(SINGLE_LINE_EXAMPLE, SINGLE_LINE_REGEXP, readScript()));
}
/**
* Test the validation of the script parameter with a given regular
* expression and example. Expected result: the regular expression will not
* match.
*
* @throws IOException
* if the example file could not be read
*/
@Test
public void testScriptValidationNoMatchesFound() throws IOException {
DescriptorImpl descriptor = createDescriptor();
assertError(descriptor.doCheckExample("this is a warning message", SINGLE_LINE_REGEXP, readScript()));
}
/**
* Test the validation of the script parameter with a given regular
* expression and example. Expected result: the regular expression will not
* match.
*
* @throws IOException
* if the example file could not be read
*/
@Test
public void testScriptValidationIllegalMatchAccess() throws IOException {
DescriptorImpl descriptor = createDescriptor();
assertError(descriptor.doCheckExample(SINGLE_LINE_EXAMPLE, "^\\s*(.*):(\\d+):(.*)$", readScript()));
}
/**
* Test the validation of the script parameter with a given regular
* expression and a multi-line example. Expected result: the regular
* expression will match.
*
* @throws IOException
* if the example file could not be read
*/
@Test
public void testMultiLineExpressionWillMatch() throws IOException {
DescriptorImpl descriptor = createDescriptor();
assertOk(descriptor.doCheckExample(MULTI_LINE_EXAMPLE, MULTI_LINE_REGEXP, MULTILINE_SCRIPT));
}
private DescriptorImpl createDescriptor() {
return new DescriptorImpl();
}
private void assertOk(final FormValidation actualResult) {
verify(actualResult, FormValidation.Kind.OK);
}
private void assertError(final FormValidation actualResult) {
verify(actualResult, FormValidation.Kind.ERROR);
}
private void verify(final FormValidation actualResult, final Kind expectedResult) {
assertEquals("Wrong validation result", expectedResult, actualResult.kind);
}
} |
package mho.wheels.iterables;
import mho.wheels.math.BinaryFraction;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import java.math.BigInteger;
import java.util.List;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.testing.Testing.*;
@SuppressWarnings("UnusedDeclaration")
public class RandomProviderDemos {
private static final boolean USE_RANDOM = false;
private static int LIMIT;
private static final int SMALL_LIMIT = 1000;
private static IterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = RandomProvider.example();
LIMIT = 1000;
} else {
P = ExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
private static void demoConstructor() {
initialize();
for (Void v : take(LIMIT, repeat((Void) null))) {
System.out.println("RandomProvider() = " + new RandomProvider());
}
}
private static void demoConstructor_List_Integer() {
initialize();
for (List<Integer> is : take(LIMIT, P.lists(IsaacPRNG.SIZE, P.integers()))) {
System.out.println("RandomProvider(" + is + ") = " + new RandomProvider(is));
}
}
private static void demoGetScale() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getScale(" + rp + ") = " + rp.getScale());
}
}
private static void demoGetSecondaryScale() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getSecondaryScale(" + rp + ") = " + rp.getSecondaryScale());
}
}
private static void demoGetSeed() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getSeed(" + rp + ") = " + rp.getSeed());
}
}
private static void demoWithScale() {
initialize();
for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) {
System.out.println("withScale(" + p.a + ", " + p.b + ") = " + p.a.withScale(p.b));
}
}
private static void demoWithSecondaryScale() {
initialize();
for (Pair<RandomProvider, Integer> p : take(LIMIT, P.pairs(P.randomProviders(), P.naturalIntegers()))) {
System.out.println("withSecondaryScale(" + p.a + ", " + p.b + ") = " + p.a.withSecondaryScale(p.b));
}
}
private static void demoCopy() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("copy(" + rp + ") = " + rp.copy());
}
}
private static void demoDeepCopy() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("deepCopy(" + rp + ") = " + rp.deepCopy());
}
}
private static void demoReset() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
rp.nextInt();
RandomProvider beforeReset = rp.deepCopy();
rp.reset();
System.out.println("reset(" + beforeReset + ") = " + rp);
}
}
private static void demoGetId() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println("getId(" + rp + ") = " + rp.getId());
}
}
private static void demoNextInt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextInt(" + rp + ") = " + rp.nextInt());
}
}
private static void demoIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("integers(" + rp + ") = " + its(rp.integers()));
}
}
private static void demoNextLong() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextLong(" + rp + ") = " + rp.nextLong());
}
}
private static void demoLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("longs(" + rp + ") = " + its(rp.longs()));
}
}
private static void demoNextBoolean() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextBoolean(" + rp + ") = " + rp.nextBoolean());
}
}
private static void demoBooleans() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("booleans(" + rp + ") = " + its(rp.booleans()));
}
}
private static void demoNextUniformSample_Iterable() {
initialize();
Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs(
P.randomProvidersDefault(),
P.listsAtLeast(1, P.withNull(P.integers()))
);
for (Pair<RandomProvider, List<Integer>> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextUniformSample(" + p.a + ", " + p.b.toString() + ") = " +
p.a.nextUniformSample(p.b));
}
}
private static void demoUniformSample_Iterable() {
initialize();
Iterable<Pair<RandomProvider, List<Integer>>> ps = P.pairs(
P.randomProvidersDefault(),
P.lists(P.withNull(P.integers()))
);
for (Pair<RandomProvider, List<Integer>> p : take(SMALL_LIMIT, ps)) {
System.out.println("uniformSample(" + p.a + ", " + p.b.toString() + ") = " + its(p.a.uniformSample(p.b)));
}
}
private static void demoNextUniformSample_String() {
initialize();
Iterable<Pair<RandomProvider, String>> ps = P.pairs(P.randomProvidersDefault(), P.stringsAtLeast(1));
for (Pair<RandomProvider, String> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextUniformSample(" + p.a + ", " + nicePrint(p.b) + ") = " +
nicePrint(p.a.nextUniformSample(p.b)));
}
}
private static void demoUniformSample_String() {
initialize();
Iterable<Pair<RandomProvider, String>> ps = P.pairs(P.randomProvidersDefault(), P.strings());
for (Pair<RandomProvider, String> p : take(SMALL_LIMIT, ps)) {
System.out.println("uniformSample(" + p.a + ", " + nicePrint(p.b) + ") = " +
cits(p.a.uniformSample(p.b)));
}
}
private static void demoNextOrdering() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextOrdering(" + rp + ") = " + rp.nextOrdering());
}
}
private static void demoOrderings() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("orderings(" + rp + ") = " + its(rp.orderings()));
}
}
private static void demoNextRoundingMode() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextRoundingMode(" + rp + ") = " + rp.nextRoundingMode());
}
}
private static void demoRoundingModes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("roundingModes(" + rp + ") = " + its(rp.roundingModes()));
}
}
private static void demoNextPositiveByte() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveByte(" + rp + ") = " + rp.nextPositiveByte());
}
}
private static void demoPositiveBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveBytes(" + rp + ") = " + its(rp.positiveBytes()));
}
}
private static void demoNextPositiveShort() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveShort(" + rp + ") = " + rp.nextPositiveShort());
}
}
private static void demoPositiveShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveShorts(" + rp + ") = " + its(rp.positiveShorts()));
}
}
private static void demoNextPositiveInt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveInt(" + rp + ") = " + rp.nextPositiveInt());
}
}
private static void demoPositiveIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveIntegers(" + rp + ") = " + its(rp.positiveIntegers()));
}
}
private static void demoNextPositiveLong() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveLong(" + rp + ") = " + rp.nextPositiveLong());
}
}
private static void demoPositiveLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveLongs(" + rp + ") = " + its(rp.positiveLongs()));
}
}
private static void demoNextNegativeByte() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeByte(" + rp + ") = " + rp.nextNegativeByte());
}
}
private static void demoNegativeBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeBytes(" + rp + ") = " + its(rp.negativeBytes()));
}
}
private static void demoNextNegativeShort() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeShort(" + rp + ") = " + rp.nextNegativeShort());
}
}
private static void demoNegativeShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeShorts(" + rp + ") = " + its(rp.negativeShorts()));
}
}
private static void demoNextNegativeInt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeInt(" + rp + ") = " + rp.nextNegativeInt());
}
}
private static void demoNegativeIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeIntegers(" + rp + ") = " + its(rp.negativeIntegers()));
}
}
private static void demoNextNegativeLong() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeLong(" + rp + ") = " + rp.nextNegativeLong());
}
}
private static void demoNegativeLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeLongs(" + rp + ") = " + its(rp.negativeLongs()));
}
}
private static void demoNextNaturalByte() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNaturalByte(" + rp + ") = " + rp.nextNaturalByte());
}
}
private static void demoNaturalBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalBytes(" + rp + ") = " + its(rp.naturalBytes()));
}
}
private static void demoNextNaturalShort() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNaturalShort(" + rp + ") = " + rp.nextNaturalShort());
}
}
private static void demoNaturalShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalShorts(" + rp + ") = " + its(rp.naturalShorts()));
}
}
private static void demoNextNaturalInt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNaturalInt(" + rp + ") = " + rp.nextNaturalInt());
}
}
private static void demoNaturalIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalIntegers(" + rp + ") = " + its(rp.naturalIntegers()));
}
}
private static void demoNextNaturalLong() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNaturalLong(" + rp + ") = " + rp.nextNaturalLong());
}
}
private static void demoNaturalLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("naturalLongs(" + rp + ") = " + its(rp.naturalLongs()));
}
}
private static void demoNextNonzeroByte() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroByte(" + rp + ") = " + rp.nextNonzeroByte());
}
}
private static void demoNonzeroBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroBytes(" + rp + ") = " + its(rp.nonzeroBytes()));
}
}
private static void demoNextNonzeroShort() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroShort(" + rp + ") = " + rp.nextNonzeroShort());
}
}
private static void demoNonzeroShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroShorts(" + rp + ") = " + its(rp.nonzeroShorts()));
}
}
private static void demoNextNonzeroInt() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroInt(" + rp + ") = " + rp.nextNonzeroInt());
}
}
private static void demoNonzeroIntegers() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroIntegers(" + rp + ") = " + its(rp.nonzeroIntegers()));
}
}
private static void demoNextNonzeroLong() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroLong(" + rp + ") = " + rp.nextNonzeroLong());
}
}
private static void demoNonzeroLongs() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroLongs(" + rp + ") = " + its(rp.nonzeroLongs()));
}
}
private static void demoNextByte() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextByte(" + rp + ") = " + rp.nextByte());
}
}
private static void demoBytes() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("bytes(" + rp + ") = " + its(rp.bytes()));
}
}
private static void demoNextShort() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextShort(" + rp + ") = " + rp.nextShort());
}
}
private static void demoShorts() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("shorts(" + rp + ") = " + its(rp.shorts()));
}
}
private static void demoNextAsciiChar() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextAsciiChar(" + rp + ") = " + nicePrint(rp.nextAsciiChar()));
}
}
private static void demoAsciiCharacters() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("asciiCharacters(" + rp + ") = " + cits(rp.asciiCharacters()));
}
}
private static void demoNextChar() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextChar(" + rp + ") = " + nicePrint(rp.nextChar()));
}
}
private static void demoCharacters() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("characters(" + rp + ") = " + cits(rp.characters()));
}
}
private static void demoNextFromRangeUp_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeUp_short() {
initialize();
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_short() {
initialize();
Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.shorts());
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeUp_int() {
initialize();
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_int() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.integers());
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeUp_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeUp_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextFromRangeUp(" + p.a + ", " + nicePrint(p.b) + ") = " +
nicePrint(p.a.nextFromRangeUp(p.b)));
}
}
private static void demoRangeUp_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeDown_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_byte() {
initialize();
for (Pair<RandomProvider, Byte> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.bytes()))) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRangeDown_short() {
initialize();
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.shorts()))) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_short() {
initialize();
Iterable<Pair<RandomProvider, Short>> ps = P.pairs(P.randomProvidersDefault(), P.shorts());
for (Pair<RandomProvider, Short> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRangeDown_int() {
initialize();
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.integers()))) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_int() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = P.pairs(P.randomProvidersDefault(), P.integers());
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRangeDown_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_long() {
initialize();
for (Pair<RandomProvider, Long> p : take(SMALL_LIMIT, P.pairs(P.randomProvidersDefault(), P.longs()))) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRangeDown_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextFromRangeDown(" + p.a + ", " + nicePrint(p.b) + ") = " +
nicePrint(p.a.nextFromRangeDown(p.b)));
}
}
private static void demoRangeDown_char() {
initialize();
Iterable<Pair<RandomProvider, Character>> ps = P.pairs(P.randomProvidersDefault(), P.characters());
for (Pair<RandomProvider, Character> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + nicePrint(p.b) + ") = " + cits(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRange_byte_byte() {
initialize();
Iterable<Triple<RandomProvider, Byte, Byte>> ts = filterInfinite(
t -> t.b <= t.c,
P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes())
);
for (Triple<RandomProvider, Byte, Byte> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " +
p.a.nextFromRange(p.b, p.c));
}
}
private static void demoRange_byte_byte() {
initialize();
Iterable<Triple<RandomProvider, Byte, Byte>> ts = P.triples(P.randomProvidersDefault(), P.bytes(), P.bytes());
for (Triple<RandomProvider, Byte, Byte> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoNextFromRange_short_short() {
initialize();
Iterable<Triple<RandomProvider, Short, Short>> ts = filterInfinite(
t -> t.b <= t.c,
P.triples(P.randomProvidersDefault(), P.shorts(), P.shorts())
);
for (Triple<RandomProvider, Short, Short> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " +
p.a.nextFromRange(p.b, p.c));
}
}
private static void demoRange_short_short() {
initialize();
Iterable<Triple<RandomProvider, Short, Short>> ts = P.triples(
P.randomProvidersDefault(),
P.shorts(),
P.shorts()
);
for (Triple<RandomProvider, Short, Short> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoNextFromRange_int_int() {
initialize();
Iterable<Triple<RandomProvider, Integer, Integer>> ts = filterInfinite(
t -> t.b <= t.c,
P.triples(P.randomProvidersDefault(), P.integers(), P.integers())
);
for (Triple<RandomProvider, Integer, Integer> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " +
p.a.nextFromRange(p.b, p.c));
}
}
private static void demoRange_int_int() {
initialize();
Iterable<Triple<RandomProvider, Integer, Integer>> ts = P.triples(
P.randomProvidersDefault(),
P.integers(),
P.integers()
);
for (Triple<RandomProvider, Integer, Integer> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoNextFromRange_long_long() {
initialize();
Iterable<Triple<RandomProvider, Long, Long>> ts = filterInfinite(
t -> t.b <= t.c,
P.triples(P.randomProvidersDefault(), P.longs(), P.longs())
);
for (Triple<RandomProvider, Long, Long> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " +
p.a.nextFromRange(p.b, p.c));
}
}
private static void demoRange_long_long() {
initialize();
Iterable<Triple<RandomProvider, Long, Long>> ts = P.triples(P.randomProvidersDefault(), P.longs(), P.longs());
for (Triple<RandomProvider, Long, Long> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoNextFromRange_BigInteger_BigInteger() {
initialize();
Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = filterInfinite(
t -> le(t.b, t.c),
P.triples(P.randomProvidersDefault(), P.bigIntegers(), P.bigIntegers())
);
for (Triple<RandomProvider, BigInteger, BigInteger> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + p.b + ", " + p.c + ") = " +
p.a.nextFromRange(p.b, p.c));
}
}
private static void demoRange_BigInteger_BigInteger() {
initialize();
Iterable<Triple<RandomProvider, BigInteger, BigInteger>> ts = P.triples(
P.randomProvidersDefault(),
P.bigIntegers(),
P.bigIntegers()
);
for (Triple<RandomProvider, BigInteger, BigInteger> p : take(LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + its(p.a.range(p.b, p.c)));
}
}
private static void demoNextFromRange_char_char() {
initialize();
Iterable<Triple<RandomProvider, Character, Character>> ts = filterInfinite(
t -> t.b <= t.c,
P.triples(P.randomProvidersDefault(), P.characters(), P.characters())
);
for (Triple<RandomProvider, Character, Character> p : take(SMALL_LIMIT, ts)) {
System.out.println("nextFromRange(" + p.a + ", " + nicePrint(p.b) + ", " + nicePrint(p.c) + ") = " +
nicePrint(p.a.nextFromRange(p.b, p.c)));
}
}
private static void demoRange_char_char() {
initialize();
Iterable<Triple<RandomProvider, Character, Character>> ts = P.triples(
P.randomProvidersDefault(),
P.characters(),
P.characters()
);
for (Triple<RandomProvider, Character, Character> p : take(SMALL_LIMIT, ts)) {
System.out.println("range(" + p.a + ", " + p.b + ", " + p.c + ") = " + cits(p.a.range(p.b, p.c)));
}
}
private static void demoNextPositiveIntGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextPositiveIntGeometric(" + rp + ") = " + rp.nextPositiveIntGeometric());
}
}
private static void demoPositiveIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("positiveIntegersGeometric(" + rp + ") = " + its(rp.positiveIntegersGeometric()));
}
}
private static void demoNextNegativeIntGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNegativeIntGeometric(" + rp + ") = " + rp.nextNegativeIntGeometric());
}
}
private static void demoNegativeIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("negativeIntegersGeometric(" + rp + ") = " + its(rp.negativeIntegersGeometric()));
}
}
private static void demoNextNaturalIntGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNaturalIntGeometric(" + rp + ") = " + rp.nextNaturalIntGeometric());
}
}
private static void demoNaturalIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("naturalIntegersGeometric(" + rp + ") = " + its(rp.naturalIntegersGeometric()));
}
}
private static void demoNextNonzeroIntGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNonzeroIntGeometric(" + rp + ") = " + rp.nextNonzeroIntGeometric());
}
}
private static void demoNonzeroIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nonzeroIntegersGeometric(" + rp + ") = " + its(rp.nonzeroIntegersGeometric()));
}
}
private static void demoNextIntGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextIntGeometric(" + rp + ") = " + rp.nextIntGeometric());
}
}
private static void demoIntegersGeometric() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("integersGeometric(" + rp + ") = " + its(rp.integersGeometric()));
}
}
private static void demoNextIntGeometricFromRangeUp() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getScale() > p.b && (p.b > 1 || p.a.getScale() >= Integer.MAX_VALUE + p.b),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextIntGeometricFromRangeUp(" + p.a + ", " + p.b + ") = " +
p.a.nextIntGeometricFromRangeUp(p.b));
}
}
private static void demoRangeUpGeometric() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getScale() > p.b && (p.b > 1 || p.a.getScale() >= Integer.MAX_VALUE + p.b),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUpGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUpGeometric(p.b)));
}
}
private static void demoNextIntGeometricFromRangeDown() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextIntGeometricFromRangeDown(" + p.a + ", " + p.b + ") = " +
p.a.nextIntGeometricFromRangeDown(p.b));
}
}
private static void demoRangeDownGeometric() {
initialize();
Iterable<Pair<RandomProvider, Integer>> ps = filterInfinite(
p -> p.a.getScale() < p.b && (p.b <= -1 || p.a.getScale() > p.b - Integer.MAX_VALUE),
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.integersGeometric())
);
for (Pair<RandomProvider, Integer> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDownGeometric(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDownGeometric(p.b)));
}
}
private static void demoNextPositiveBigInteger() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextPositiveBigInteger(" + rp + ") = " + rp.nextPositiveBigInteger());
}
}
private static void demoPositiveBigIntegers() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("positiveBigIntegers(" + rp + ") = " + its(rp.positiveBigIntegers()));
}
}
private static void demoNextNegativeBigInteger() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNegativeBigInteger(" + rp + ") = " + rp.nextNegativeBigInteger());
}
}
private static void demoNegativeBigIntegers() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("negativeBigIntegers(" + rp + ") = " + its(rp.negativeBigIntegers()));
}
}
private static void demoNextNaturalBigInteger() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNaturalBigInteger(" + rp + ") = " + rp.nextNaturalBigInteger());
}
}
private static void demoNaturalBigIntegers() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("naturalBigIntegers(" + rp + ") = " + its(rp.naturalBigIntegers()));
}
}
private static void demoNextNonzeroBigInteger() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextNonzeroBigInteger(" + rp + ") = " + rp.nextNonzeroBigInteger());
}
}
private static void demoNonzeroBigIntegers() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nonzeroBigIntegers(" + rp + ") = " + its(rp.nonzeroBigIntegers()));
}
}
private static void demoNextBigInteger() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nextBigInteger(" + rp + ") = " + rp.nextBigInteger());
}
}
private static void demoBigIntegers() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("bigIntegers(" + rp + ") = " + its(rp.bigIntegers()));
}
}
private static void demoNextFromRangeUp_BigInteger() {
initialize();
Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite(
p -> {
int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength();
return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE);
},
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers())
);
for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_BigInteger() {
initialize();
Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite(
p -> {
int minBitLength = p.b.signum() == -1 ? 0 : p.b.bitLength();
return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE);
},
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers())
);
for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeDown_BigInteger() {
initialize();
Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite(
p -> {
int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength();
return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE);
},
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers())
);
for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_BigInteger() {
initialize();
Iterable<Pair<RandomProvider, BigInteger>> ps = filterInfinite(
p -> {
int minBitLength = p.b.signum() == 1 ? 0 : p.b.negate().bitLength();
return p.a.getScale() > minBitLength && (minBitLength == 0 || p.a.getScale() != Integer.MAX_VALUE);
},
P.pairs(P.randomProvidersDefaultSecondaryScale(), P.bigIntegers())
);
for (Pair<RandomProvider, BigInteger> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextPositiveBinaryFraction() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(LIMIT, rps)) {
System.out.println("nextPositiveBinaryFraction(" + rp + ") = " + rp.nextPositiveBinaryFraction());
}
}
private static void demoPositiveBinaryFractions() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("positiveBinaryFractions(" + rp + ") = " + its(rp.positiveBinaryFractions()));
}
}
private static void demoNextNegativeBinaryFraction() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(LIMIT, rps)) {
System.out.println("nextNegativeBinaryFraction(" + rp + ") = " + rp.nextNegativeBinaryFraction());
}
}
private static void demoNegativeBinaryFractions() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("negativeBinaryFractions(" + rp + ") = " + its(rp.negativeBinaryFractions()));
}
}
private static void demoNextNonzeroBinaryFraction() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(LIMIT, rps)) {
System.out.println("nextNonzeroBinaryFraction(" + rp + ") = " + rp.nextNonzeroBinaryFraction());
}
}
private static void demoNonzeroBinaryFractions() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() >= 2 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("nonzeroBinaryFractions(" + rp + ") = " + its(rp.nonzeroBinaryFractions()));
}
}
private static void demoNextBinaryFraction() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(LIMIT, rps)) {
System.out.println("nextBinaryFraction(" + rp + ") = " + rp.nextBinaryFraction());
}
}
private static void demoBinaryFractions() {
initialize();
Iterable<RandomProvider> rps = filterInfinite(
x -> x.getScale() > 0 && x.getSecondaryScale() > 0,
P.randomProviders()
);
for (RandomProvider rp : take(SMALL_LIMIT, rps)) {
System.out.println("binaryFractions(" + rp + ") = " + its(rp.binaryFractions()));
}
}
private static void demoNextFromRangeUp_BinaryFraction() {
initialize();
Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs(
filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()),
P.binaryFractions()
);
for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_BinaryFraction() {
initialize();
Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs(
filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()),
P.binaryFractions()
);
for (Pair<RandomProvider, BinaryFraction> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeDown_BinaryFraction() {
initialize();
Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs(
filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()),
P.binaryFractions()
);
for (Pair<RandomProvider, BinaryFraction> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_BinaryFraction() {
initialize();
Iterable<Pair<RandomProvider, BinaryFraction>> ps = P.pairs(
filterInfinite(x -> x.getScale() > 0 && x.getSecondaryScale() > 0, P.randomProviders()),
P.binaryFractions()
);
for (Pair<RandomProvider, BinaryFraction> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRange_BinaryFraction_BinaryFraction() {
initialize();
Iterable<Triple<RandomProvider, BinaryFraction, BinaryFraction>> ts = filterInfinite(
t -> lt(t.b, t.c),
P.triples(
filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
),
P.binaryFractions(),
P.binaryFractions()
)
);
for (Triple<RandomProvider, BinaryFraction, BinaryFraction> t : take(LIMIT, ts)) {
System.out.println("nextFromRange(" + t.a + ", " + t.b + ", " + t.c + ") = " +
t.a.nextFromRange(t.b, t.c));
}
}
private static void demoRange_BinaryFraction_BinaryFraction() {
initialize();
Iterable<Triple<RandomProvider, BinaryFraction, BinaryFraction>> ts = P.triples(
filterInfinite(
x -> x.getScale() > 0 && x.getScale() != Integer.MAX_VALUE,
P.randomProvidersDefaultSecondaryScale()
),
P.binaryFractions(),
P.binaryFractions()
);
for (Triple<RandomProvider, BinaryFraction, BinaryFraction> t : take(SMALL_LIMIT, ts)) {
System.out.println("range(" + t.a + ", " + t.b + ", " + t.c + ") = " + its(t.a.range(t.b, t.c)));
}
}
private static void demoNextPositiveFloat() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveFloat(" + rp + ") = " + rp.nextPositiveFloat());
}
}
private static void demoPositiveFloats() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveFloats(" + rp + ") = " + its(rp.positiveFloats()));
}
}
private static void demoNextNegativeFloat() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeFloat(" + rp + ") = " + rp.nextNegativeFloat());
}
}
private static void demoNegativeFloats() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeFloats(" + rp + ") = " + its(rp.negativeFloats()));
}
}
private static void demoNextNonzeroFloat() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroFloat(" + rp + ") = " + rp.nextNonzeroFloat());
}
}
private static void demoNonzeroFloats() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroFloats(" + rp + ") = " + its(rp.nonzeroFloats()));
}
}
private static void demoNextFloat() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextFloat(" + rp + ") = " + rp.nextFloat());
}
}
private static void demoFloats() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("floats(" + rp + ") = " + its(rp.floats()));
}
}
private static void demoNextPositiveDouble() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveDouble(" + rp + ") = " + rp.nextPositiveDouble());
}
}
private static void demoPositiveDoubles() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveDoubles(" + rp + ") = " + its(rp.positiveDoubles()));
}
}
private static void demoNextNegativeDouble() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeDouble(" + rp + ") = " + rp.nextNegativeDouble());
}
}
private static void demoNegativeDoubles() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeDoubles(" + rp + ") = " + its(rp.negativeDoubles()));
}
}
private static void demoNextNonzeroDouble() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroDouble(" + rp + ") = " + rp.nextNonzeroDouble());
}
}
private static void demoNonzeroDoubles() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroDoubles(" + rp + ") = " + its(rp.nonzeroDoubles()));
}
}
private static void demoNextDouble() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextDouble(" + rp + ") = " + rp.nextDouble());
}
}
private static void demoDoubles() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("doubles(" + rp + ") = " + its(rp.doubles()));
}
}
private static void demoNextPositiveFloatUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveFloatUniform(" + rp + ") = " + rp.nextPositiveFloatUniform());
}
}
private static void demoPositiveFloatsUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveFloatsUniform(" + rp + ") = " + its(rp.positiveFloatsUniform()));
}
}
private static void demoNextNegativeFloatUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeFloatUniform(" + rp + ") = " + rp.nextNegativeFloatUniform());
}
}
private static void demoNegativeFloatsUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeFloatsUniform(" + rp + ") = " + its(rp.negativeFloatsUniform()));
}
}
private static void demoNextNonzeroFloatUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroFloatUniform(" + rp + ") = " + rp.nextNonzeroFloatUniform());
}
}
private static void demoNonzeroFloatsUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroFloatsUniform(" + rp + ") = " + its(rp.nonzeroFloatsUniform()));
}
}
private static void demoNextFloatUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextFloatUniform(" + rp + ") = " + rp.nextFloatUniform());
}
}
private static void demoFloatsUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("floatsUniform(" + rp + ") = " + its(rp.floatsUniform()));
}
}
private static void demoNextPositiveDoubleUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextPositiveDoubleUniform(" + rp + ") = " + rp.nextPositiveDoubleUniform());
}
}
private static void demoPositiveDoublesUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("positiveDoublesUniform(" + rp + ") = " + its(rp.positiveDoublesUniform()));
}
}
private static void demoNextNegativeDoubleUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNegativeDoubleUniform(" + rp + ") = " + rp.nextNegativeDoubleUniform());
}
}
private static void demoNegativeDoublesUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("negativeDoublesUniform(" + rp + ") = " + its(rp.negativeDoublesUniform()));
}
}
private static void demoNextNonzeroDoubleUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextNonzeroDoubleUniform(" + rp + ") = " + rp.nextNonzeroDoubleUniform());
}
}
private static void demoNonzeroDoublesUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("nonzeroDoublesUniform(" + rp + ") = " + its(rp.nonzeroDoublesUniform()));
}
}
private static void demoNextDoubleUniform() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProvidersDefault())) {
System.out.println("nextDoubleUniform(" + rp + ") = " + rp.nextDoubleUniform());
}
}
private static void demoDoublesUniform() {
initialize();
for (RandomProvider rp : take(SMALL_LIMIT, P.randomProvidersDefault())) {
System.out.println("doublesUniform(" + rp + ") = " + its(rp.doublesUniform()));
}
}
private static void demoNextFromRangeUp_float() {
initialize();
Iterable<Pair<RandomProvider, Float>> ps = P.pairs(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats())
);
for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_float() {
initialize();
Iterable<Pair<RandomProvider, Float>> ps = P.pairs(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats())
);
for (Pair<RandomProvider, Float> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeDown_float() {
initialize();
Iterable<Pair<RandomProvider, Float>> ps = P.pairs(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats())
);
for (Pair<RandomProvider, Float> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_float() {
initialize();
Iterable<Pair<RandomProvider, Float>> ps = P.pairs(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats())
);
for (Pair<RandomProvider, Float> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRange_float_float() {
initialize();
Iterable<Triple<RandomProvider, Float, Float>> ts = filter(
t -> t.b <= t.c,
P.triples(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats()),
filter(f -> !Float.isNaN(f), P.floats())
)
);
for (Triple<RandomProvider, Float, Float> t : take(LIMIT, ts)) {
System.out.println("nextFromRange(" + t.a + ", " + t.b + ", " + t.c + ") = " +
t.a.nextFromRange(t.b, t.c));
}
}
private static void demoRange_float_float() {
initialize();
Iterable<Triple<RandomProvider, Float, Float>> ts = P.triples(
P.randomProvidersDefault(),
filter(f -> !Float.isNaN(f), P.floats()),
filter(f -> !Float.isNaN(f), P.floats())
);
for (Triple<RandomProvider, Float, Float> t : take(SMALL_LIMIT, ts)) {
System.out.println("range(" + t.a + ", " + t.b + ", " + t.c + ") = " + its(t.a.range(t.b, t.c)));
}
}
private static void demoNextFromRangeUp_double() {
initialize();
Iterable<Pair<RandomProvider, Double>> ps = P.pairs(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles())
);
for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeUp(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeUp(p.b));
}
}
private static void demoRangeUp_double() {
initialize();
Iterable<Pair<RandomProvider, Double>> ps = P.pairs(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles())
);
for (Pair<RandomProvider, Double> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeUp(" + p.a + ", " + p.b + ") = " + its(p.a.rangeUp(p.b)));
}
}
private static void demoNextFromRangeDown_double() {
initialize();
Iterable<Pair<RandomProvider, Double>> ps = P.pairs(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles())
);
for (Pair<RandomProvider, Double> p : take(LIMIT, ps)) {
System.out.println("nextFromRangeDown(" + p.a + ", " + p.b + ") = " + p.a.nextFromRangeDown(p.b));
}
}
private static void demoRangeDown_double() {
initialize();
Iterable<Pair<RandomProvider, Double>> ps = P.pairs(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles())
);
for (Pair<RandomProvider, Double> p : take(SMALL_LIMIT, ps)) {
System.out.println("rangeDown(" + p.a + ", " + p.b + ") = " + its(p.a.rangeDown(p.b)));
}
}
private static void demoNextFromRange_double_double() {
initialize();
Iterable<Triple<RandomProvider, Double, Double>> ts = filter(
t -> t.b <= t.c,
P.triples(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles()),
filter(d -> !Double.isNaN(d), P.doubles())
)
);
for (Triple<RandomProvider, Double, Double> t : take(LIMIT, ts)) {
System.out.println("nextFromRange(" + t.a + ", " + t.b + ", " + t.c + ") = " +
t.a.nextFromRange(t.b, t.c));
}
}
private static void demoRange_double_double() {
initialize();
Iterable<Triple<RandomProvider, Double, Double>> ts = P.triples(
P.randomProvidersDefault(),
filter(d -> !Double.isNaN(d), P.doubles()),
filter(d -> !Double.isNaN(d), P.doubles())
);
for (Triple<RandomProvider, Double, Double> t : take(SMALL_LIMIT, ts)) {
System.out.println("range(" + t.a + ", " + t.b + ", " + t.c + ") = " + its(t.a.range(t.b, t.c)));
}
}
private static void demoEquals_RandomProvider() {
initialize();
for (Pair<RandomProvider, RandomProvider> p : take(LIMIT, P.pairs(P.randomProviders()))) {
System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b);
}
}
private static void demoEquals_null() {
initialize();
for (RandomProvider r : take(LIMIT, P.randomProviders())) {
//noinspection ObjectEqualsNull
System.out.println(r + (r.equals(null) ? " = " : " ≠ ") + null);
}
}
private static void demoHashCode() {
initialize();
for (RandomProvider r : take(LIMIT, P.randomProviders())) {
System.out.println("hashCode(" + r + ") = " + r.hashCode());
}
}
private static void demoToString() {
initialize();
for (RandomProvider rp : take(LIMIT, P.randomProviders())) {
System.out.println(rp);
}
}
} |
package org.junit.rules;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* <tt>TemporaryFolderUsageTest</tt> provides tests for API usage correctness
* and ensure implementation symmetry of public methods against a root folder.
*/
public class TemporaryFolderUsageTest {
private TemporaryFolder tempFolder;
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
tempFolder = new TemporaryFolder();
}
@After
public void tearDown() {
tempFolder.delete();
}
@Test(expected = IllegalStateException.class)
public void getRootShouldThrowIllegalStateExceptionIfCreateWasNotInvoked() {
new TemporaryFolder().getRoot();
}
@Test(expected = IllegalStateException.class)
public void newFileThrowsIllegalStateExceptionIfCreateWasNotInvoked()
throws IOException {
new TemporaryFolder().newFile();
}
@Test(expected = IllegalStateException.class)
public void newFileWithGivenNameThrowsIllegalStateExceptionIfCreateWasNotInvoked()
throws IOException {
new TemporaryFolder().newFile("MyFile.txt");
}
@Test
public void newFileWithGivenFilenameThrowsIOExceptionIfFileExists() throws IOException {
tempFolder.create();
tempFolder.newFile("MyFile.txt");
thrown.expect(IOException.class);
thrown.expectMessage("a file with the name 'MyFile.txt' already exists in the test folder");
tempFolder.newFile("MyFile.txt");
}
@Test(expected = IllegalStateException.class)
public void newFolderThrowsIllegalStateExceptionIfCreateWasNotInvoked()
throws IOException {
new TemporaryFolder().newFolder();
}
@Test(expected = IllegalStateException.class)
public void newFolderWithGivenPathThrowsIllegalStateExceptionIfCreateWasNotInvoked() throws IOException {
new TemporaryFolder().newFolder("level1", "level2", "level3");
}
@Test
public void newFolderWithGivenFolderThrowsIOExceptionIfFolderExists() throws IOException {
tempFolder.create();
tempFolder.newFolder("level1");
thrown.expect(IOException.class);
thrown.expectMessage("a folder with the path 'level1' already exists");
tempFolder.newFolder("level1");
}
@Test
public void newFolderWithGivenFolderThrowsIOExceptionIfFileExists() throws IOException {
tempFolder.create();
File file = new File(tempFolder.getRoot(), "level1");
assertTrue("Could not create" + file, file.createNewFile());
thrown.expect(IOException.class);
thrown.expectMessage("could not create a folder with the path 'level1'");
tempFolder.newFolder("level1");
}
@Test
public void newFolderWithPathStartingWithFileSeparatorThrowsIOException()
throws IOException {
String fileAtRoot;
File[] roots = File.listRoots();
if (roots != null && roots.length > 0) {
fileAtRoot = roots[0].getAbsolutePath() + "temp1";
} else {
fileAtRoot = File.separator + "temp1";
}
tempFolder.create();
thrown.expect(IOException.class);
thrown.expectMessage("folder path '/temp1' is not a relative path");
tempFolder.newFolder(fileAtRoot);
}
@Test
public void newFolderWithPathContainingFileSeparaterCreatesDirectories()
throws IOException {
tempFolder.create();
tempFolder.newFolder("temp1" + File.separator + "temp2");
File temp1 = new File(tempFolder.getRoot(), "temp1");
assertFileIsDirectory(temp1);
assertFileIsDirectory(new File(temp1, "temp2"));
}
@Test
public void newFolderWithPathContainingForwardSlashCreatesDirectories()
throws IOException {
tempFolder.create();
tempFolder.newFolder("temp1/temp2");
File temp1 = new File(tempFolder.getRoot(), "temp1");
assertFileIsDirectory(temp1);
assertFileIsDirectory(new File(temp1, "temp2"));
}
@Test
public void newFolderWithGivenPathThrowsIOExceptionIfFolderExists() throws IOException {
tempFolder.create();
tempFolder.newFolder("level1", "level2", "level3");
thrown.expect(IOException.class);
String path = "level1" + File.separator + "level2" + File.separator + "level3";
thrown.expectMessage("a folder with the path '" + path + "' already exists");
tempFolder.newFolder("level1", "level2", "level3");
}
@Test
public void newFolderWithGivenEmptyArrayThrowsIllegalArgumentException() throws IOException {
tempFolder.create();
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("must pass at least one path");
tempFolder.newFolder(new String[0]);
}
@Test
public void newFolderWithPathsContainingForwardSlashCreatesFullPath()
throws IOException {
tempFolder.create();
tempFolder.newFolder("temp1", "temp2", "temp3/temp4");
File directory = new File(tempFolder.getRoot(), "temp1");
assertFileIsDirectory(directory);
directory = new File(directory, "temp2/temp3/temp4");
assertFileIsDirectory(directory);
}
@Test
public void newFolderWithPathsContainingFileSeparatorCreatesFullPath()
throws IOException {
tempFolder.create();
tempFolder.newFolder("temp1", "temp2", "temp3" + File.separator + "temp4");
File directory = new File(tempFolder.getRoot(), "temp1");
assertFileIsDirectory(directory);
directory = new File(directory, "temp2/temp3/temp4");
assertFileIsDirectory(directory);
}
@Test
public void createInitializesRootFolder() throws IOException {
tempFolder.create();
assertFileIsDirectory(tempFolder.getRoot());
}
@Test
public void deleteShouldDoNothingIfRootFolderWasNotInitialized() {
tempFolder.delete();
}
@Test
public void deleteRemovesRootFolder() throws IOException {
tempFolder.create();
tempFolder.delete();
assertFileDoesNotExist(tempFolder.getRoot());
}
@Test
public void newRandomFileIsCreatedUnderRootFolder() throws IOException {
tempFolder.create();
File f = tempFolder.newFile();
assertFileExists(f);
assertFileCreatedUnderRootFolder("Random file", f);
}
@Test
public void newNamedFileIsCreatedUnderRootFolder() throws IOException {
final String fileName = "SampleFile.txt";
tempFolder.create();
File f = tempFolder.newFile(fileName);
assertFileExists(f);
assertFileCreatedUnderRootFolder("Named file", f);
assertThat("file name", f.getName(), equalTo(fileName));
}
@Test
public void newRandomFolderIsCreatedUnderRootFolder() throws IOException {
tempFolder.create();
File f = tempFolder.newFolder();
assertFileIsDirectory(f);
assertFileCreatedUnderRootFolder("Random folder", f);
}
@Test
public void newNestedFoldersCreatedUnderRootFolder() throws IOException {
tempFolder.create();
File f = tempFolder.newFolder("top", "middle", "bottom");
assertFileIsDirectory(f);
assertParentFolderForFileIs(f, new File(tempFolder.getRoot(),
"top/middle"));
assertParentFolderForFileIs(f.getParentFile(),
new File(tempFolder.getRoot(), "top"));
assertFileCreatedUnderRootFolder("top", f.getParentFile()
.getParentFile());
}
@Test
public void canSetTheBaseFileForATemporaryFolder() throws IOException {
File tempDir = createTemporaryFolder();
TemporaryFolder folder = new TemporaryFolder(tempDir);
folder.create();
assertThat(tempDir, is(folder.getRoot().getParentFile()));
}
private File createTemporaryFolder() throws IOException {
File tempDir = File.createTempFile("junit", "tempFolder");
assertTrue("Unable to delete temporary file", tempDir.delete());
assertTrue("Unable to create temp directory", tempDir.mkdir());
return tempDir;
}
private void assertFileDoesNotExist(File file) {
checkFileExists("exists", file, false);
}
private void checkFileExists(String msg, File file, boolean exists) {
assertThat("File is null", file, is(notNullValue()));
assertThat("File '" + file.getAbsolutePath() + "' " + msg,
file.exists(), is(exists));
}
private void checkFileIsDirectory(String msg, File file, boolean isDirectory) {
assertThat("File is null", file, is(notNullValue()));
assertThat("File '" + file.getAbsolutePath() + "' " + msg,
file.isDirectory(), is(isDirectory));
}
private void assertFileExists(File file) {
checkFileExists("does not exist", file, true);
checkFileIsDirectory("is a directory", file, false);
}
private void assertFileIsDirectory(File file) {
checkFileExists("does not exist", file, true);
checkFileIsDirectory("is not a directory", file, true);
}
private void assertFileCreatedUnderRootFolder(String msg, File f) {
assertParentFolderForFileIs(f, tempFolder.getRoot());
}
private void assertParentFolderForFileIs(File f, File parentFolder) {
assertThat("'" + f.getAbsolutePath() + "': not under root",
f.getParentFile(), is(parentFolder));
}
} |
package org.xins.tests.server;
import java.io.*;
import java.net.*;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.xins.common.collections.BasicPropertyReader;
import org.xins.common.http.HTTPCallRequest;
import org.xins.common.http.HTTPCallResult;
import org.xins.common.http.HTTPServiceCaller;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.text.FastStringBuffer;
import org.xins.common.text.HexConverter;
import org.xins.common.text.ParseException;
import org.xins.common.xml.Element;
import org.xins.common.xml.ElementParser;
import org.xins.tests.AllTests;
/**
* Tests for calling conventions.
*
* @version $Revision$ $Date$
* @author <a href="mailto:anthony.goubard@orange-ftgroup.com">Anthony Goubard</a>
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*/
public class CallingConventionTests extends TestCase {
/**
* The random number generator.
*/
private final static Random RANDOM = new Random();
/**
* Constructs a new <code>CallingConventionTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public CallingConventionTests(String name) {
super(name);
}
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(CallingConventionTests.class);
}
/**
* Tests the standard calling convention which should be the default.
*/
public void testStandardCallingConvention1() throws Throwable {
callResultCodeStandard(null);
}
/**
* Tests the standard calling convention.
*/
public void testStandardCallingConvention2() throws Throwable {
callResultCodeStandard("_xins-std");
}
/**
* Tests that when different parameter values are passed to the
* _xins-std calling convention, it must return a 400 status code
* (invalid HTTP request).
*/
public void testStandardCallingConvention3() throws Throwable {
doTestMultipleParamValues("_xins-std");
}
/**
* Tests with an unknown calling convention.
*/
public void testInvalidCallingConvention() throws Throwable {
TargetDescriptor descriptor = new TargetDescriptor(AllTests.url(), 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "ResultCode");
params.set("inputText", "blablabla");
params.set("_convention", "_xins-bla");
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
assertEquals(400, result.getStatusCode());
}
/**
* Calls the ResultCode function and expect the standard calling convention back.
*
* @param convention
* the name of the calling convention parameter, or <code>null</code>
* if no calling convention parameter should be sent.
*
* @throw Throwable
* if anything goes wrong.
*/
public void callResultCodeStandard(String convention) throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
Element result1 = callResultCode(convention, randomFive);
assertNull("The method returned an error code for the first call: " + result1.getAttribute("errorcode"), result1.getAttribute("errorcode"));
assertNull("The method returned a code attribute for the first call: " + result1.getAttribute("code"), result1.getAttribute("code"));
assertNull("The method returned a success attribute for the first call: " + result1.getAttribute("success"), result1.getAttribute("success"));
Element result2 = callResultCode(convention, randomFive);
assertNotNull("The method did not return an error code for the second call.", result2.getAttribute("errorcode"));
assertNull("The method returned a code attribute for the second call: " + result2.getAttribute("code"), result2.getAttribute("code"));
assertNull("The method returned a success attribute for the second call: " + result2.getAttribute("success"), result2.getAttribute("success"));
}
/**
* Call the ResultCode function with the specified calling convention.
*
* @param convention
* the name of the calling convention parameter, or <code>null</code>
* if no calling convention parameter should be sent.
*
* @param inputText
* the value of the parameter to send as input.
*
* @return
* the parsed result as an Element.
*
* @throw Throwable
* if anything goes wrong.
*/
private Element callResultCode(String convention, String inputText) throws Throwable {
TargetDescriptor descriptor = new TargetDescriptor(AllTests.url() + "allinone/", 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "ResultCode");
params.set("useDefault", "false");
params.set("inputText", inputText);
if (convention != null) {
params.set("_convention", convention);
}
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
byte[] data = result.getData();
ElementParser parser = new ElementParser();
return parser.parse(new StringReader(new String(data)));
}
/**
* Test the XML calling convention.
*/
public void testXMLCallingConvention() throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
// Successful call
postXMLRequest(randomFive, true);
// Unsuccessful call
postXMLRequest(randomFive, false);
}
/**
* Posts XML request.
*
* @param randomFive
* A randomly generated String.
* @param success
* <code>true</code> if the expected result should be successfal,
* <code>false</code> otherwise.
*
* @throws Exception
* If anything goes wrong.
*/
private void postXMLRequest(String randomFive, boolean success) throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-xml";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<request function=\"ResultCode\">" +
" <param name=\"useDefault\">false</param>" +
" <param name=\"inputText\">" + randomFive + "</param>" +
"</request>";
Element result = postXML(destination, data);
assertEquals("result", result.getLocalName());
if (success) {
assertNull("The method returned an error code: " + result.getAttribute("errorcode"), result.getAttribute("errorcode"));
} else {
assertNotNull("The method did not return an error code for the second call: " + result.getAttribute("errorcode"), result.getAttribute("errorcode"));
assertEquals("AlreadySet", result.getAttribute("errorcode"));
}
assertNull("The method returned a code attribute: " + result.getAttribute("code"), result.getAttribute("code"));
assertNull("The method returned a success attribute.", result.getAttribute("success"));
List child = result.getChildElements();
assertEquals(1, child.size());
Element param = (Element) child.get(0);
assertEquals("param", param.getLocalName());
if (success) {
assertEquals("outputText", param.getAttribute("name"));
assertEquals(randomFive + " added.", param.getText());
} else {
assertEquals("count", param.getAttribute("name"));
assertEquals("1", param.getText());
}
}
/**
* Tests the XSLT calling convention.
*/
public void testXSLTCallingConvention1() throws Throwable {
String html = getHTMLVersion(false);
assertTrue("The returned data is not an HTML file: " + html, html.startsWith("<html>"));
assertTrue("Incorrect HTML data returned.", html.indexOf("XINS version") != -1);
String html2 = getHTMLVersion(true);
assertTrue("The returned data is not an HTML file: " + html2, html2.startsWith("<html>"));
assertTrue("Incorrect HTML data returned.", html2.indexOf("API version") != -1);
}
/**
* Tests that when different parameter values are passed to the
* _xins-xslt calling convention, it must return a 400 status code
* (invalid HTTP request).
*/
public void testXSLTCallingConvention2() throws Throwable {
doTestMultipleParamValues("_xins-xslt");
}
private String getHTMLVersion(boolean useTemplateParam) throws Exception {
TargetDescriptor descriptor = new TargetDescriptor(AllTests.url(), 2000);
BasicPropertyReader params = new BasicPropertyReader();
params.set("_function", "_GetVersion");
params.set("_convention", "_xins-xslt");
if (useTemplateParam) {
String userDir = new File(System.getProperty("user.dir")).toURL().toString();
params.set("_template", "src/tests/getVersion2.xslt");
}
HTTPCallRequest request = new HTTPCallRequest(params);
HTTPServiceCaller caller = new HTTPServiceCaller(descriptor);
HTTPCallResult result = caller.call(request);
return result.getString();
}
/**
* Tests the SOAP calling convention.
*/
public void testSOAPCallingConvention() throws Throwable {
FastStringBuffer buffer = new FastStringBuffer(16);
HexConverter.toHexString(buffer, RANDOM.nextLong());
String randomFive = buffer.toString().substring(0, 5);
// Successful call
postSOAPRequest(randomFive, true);
// Unsuccessful call
postSOAPRequest(randomFive, false);
}
/**
* Posts SOAP request.
*
* @param randomFive
* A randomly generated String.
* @param success
* <code>true</code> if the expected result should be successfal,
* <code>false</code> otherwise.
*
* @throws Exception
* If anything goes wrong.
*/
private void postSOAPRequest(String randomFive, boolean success) throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:ResultCodeRequest>" +
" <useDefault>false</useDefault>" +
" <inputText>" + randomFive + "</inputText>" +
" </ns0:ResultCodeRequest>" +
" </soap:Body>" +
"</soap:Envelope>";
int expectedStatus = success ? 200 : 500;
Element result = postXML(destination, data, expectedStatus);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
if (success) {
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("ResultCodeResponse").size());
Element responseElem = (Element) bodyElem.getChildElements("ResultCodeResponse").get(0);
assertEquals("Incorrect number of \"outputText\" elements.", 1, responseElem.getChildElements("outputText").size());
Element outputTextElem = (Element) responseElem.getChildElements("outputText").get(0);
assertEquals("Incorrect returned text", randomFive + " added.", outputTextElem.getText());
} else {
assertEquals("Incorrect number of \"Fault\" elements.", 1, bodyElem.getChildElements("Fault").size());
Element faultElem = (Element) bodyElem.getChildElements("Fault").get(0);
assertEquals("Incorrect number of \"faultcode\" elements.", 1, faultElem.getChildElements("faultcode").size());
Element faultCodeElem = (Element) faultElem.getChildElements("faultcode").get(0);
assertEquals("Incorrect faultcode text", "soap:Server", faultCodeElem.getText());
assertEquals("Incorrect number of \"faultstring\" elements.", 1, faultElem.getChildElements("faultstring").size());
Element faultStringElem = (Element) faultElem.getChildElements("faultstring").get(0);
assertEquals("Incorrect faultstring text", "AlreadySet", faultStringElem.getText());
}
}
/**
* Tests the SOAP calling convention for the type convertion.
*/
public void testSOAPCallingConvention2() throws Throwable {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:SimpleTypesRequest>" +
" <inputBoolean>0</inputBoolean>" +
" <inputByte>0</inputByte>" +
" <inputInt>0</inputInt>" +
" <inputLong>0</inputLong>" +
" <inputFloat>1.0</inputFloat>" +
" <inputText>0</inputText>" +
" </ns0:SimpleTypesRequest>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("SimpleTypesResponse").size());
}
/**
* Tests the SOAP calling convention with a data section.
*/
public void testSOAPCallingConvention3() throws Throwable {
String destination = AllTests.url() + "allinone/?_convention=_xins-soap";
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns0=\"urn:allinone\">" +
" <soap:Body>" +
" <ns0:DataSection3Request>" +
" <data>" +
" <address company=\"McDo\" postcode=\"1234\" />" +
" <address company=\"Drill\" postcode=\"4567\" />" +
" </data>" +
" </ns0:DataSection3Request>" +
" </soap:Body>" +
"</soap:Envelope>";
Element result = postXML(destination, data);
assertEquals("Envelope", result.getLocalName());
assertEquals("Incorrect number of \"Fault\" elements.", 0, result.getChildElements("Fault").size());
assertEquals("Incorrect number of \"Body\" elements.", 1, result.getChildElements("Body").size());
Element bodyElem = (Element) result.getChildElements("Body").get(0);
assertEquals("Incorrect number of response elements.", 1, bodyElem.getChildElements("DataSection3Response").size());
}
/**
* Tests the XML-RPC calling convention with an incomplete request.
*/
public void testXMLRPCCallingConvention() throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-xmlrpc";
// Send an incorrect request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>SimpleTypes</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputBoolean</name>" +
" <value><boolean>0</boolean></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element faultElem = getUniqueChild(result, "fault");
Element valueElem = getUniqueChild(faultElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
Element member1 = (Element) structElem.getChildElements("member").get(0);
Element member1Name = getUniqueChild(member1, "name");
assertEquals("faultCode", member1Name.getText());
Element member1Value = getUniqueChild(member1, "value");
Element member1IntValue = getUniqueChild(member1Value, "int");
assertEquals("3", member1IntValue.getText());
Element member2 = (Element) structElem.getChildElements("member").get(1);
Element member2Name = getUniqueChild(member2, "name");
assertEquals("faultString", member2Name.getText());
Element member2Value = getUniqueChild(member2, "value");
Element member2StringValue = getUniqueChild(member2Value, "string");
assertEquals("_InvalidRequest", member2StringValue.getText());
}
/**
* Tests the XML-RPC calling convention for a successful result.
*/
public void testXMLRPCCallingConvention2() throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-xmlrpc";
// Send a correct request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>SimpleTypes</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputBoolean</name>" +
" <value><boolean>1</boolean></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputByte</name>" +
" <value><i4>0</i4></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputInt</name>" +
" <value><i4>50</i4></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputLong</name>" +
" <value><string>123456460</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputFloat</name>" +
" <value><double>3.14159265</double></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputText</name>" +
" <value><string>Hello World!</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputDate</name>" +
" <value><dateTime.iso8601>19980717T14:08:55</dateTime.iso8601></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>inputTimestamp</name>" +
" <value><dateTime.iso8601>19980817T15:08:55</dateTime.iso8601></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element paramsElem = getUniqueChild(result, "params");
Element paramElem = getUniqueChild(paramsElem, "param");
Element valueElem = getUniqueChild(paramElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
}
/**
* Tests the XML-RPC calling convention for a data section.
*/
public void testXMLRPCCallingConvention3() throws Exception {
String destination = AllTests.url() + "allinone/?_convention=_xins-xmlrpc";
// Send a correct request
String data = "<?xml version=\"1.0\"?>" +
"<methodCall>" +
" <methodName>DataSection3</methodName>" +
" <params>" +
" <param><value><struct><member>" +
" <name>inputText</name>" +
" <value><string>hello</string></value>" +
" </member></struct></value></param>" +
" <param><value><struct><member>" +
" <name>data</name>" +
" <value><array><data>" +
" <value><struct><member>" +
" <name>address</name>" +
" <value><string></string></value>" +
" </member>" +
" <member>" +
" <name>company</name>" +
" <value><string>MyCompany</string></value>" +
" </member>" +
" <member>" +
" <name>postcode</name>" +
" <value><string>72650</string></value>" +
" </member></struct></value>" +
" </data></array></value>" +
" </member></struct></value></param>" +
" </params>" +
"</methodCall>";
Element result = postXML(destination, data);
assertEquals("methodResponse", result.getLocalName());
Element paramsElem = getUniqueChild(result, "params");
Element paramElem = getUniqueChild(paramsElem, "param");
Element valueElem = getUniqueChild(paramElem, "value");
Element structElem = getUniqueChild(valueElem, "struct");
}
/**
* Test the custom calling convention.
*/
public void testCustomCallingConvention() throws Exception {
URL url = new URL(AllTests.url() + "?query=hello%20Custom&_convention=xins-tests");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
assertEquals(200, connection.getResponseCode());
URL url2 = new URL(AllTests.url() + "?query=hello%20Custom&_convention=xins-tests");
HttpURLConnection connection2 = (HttpURLConnection) url2.openConnection();
connection2.connect();
try {
assertEquals(400, connection2.getResponseCode());
} catch (IOException ioe) {
assertTrue(ioe.getMessage(), ioe.getMessage().indexOf(" 400") != -1);
}
}
/**
* Tests the HTTP OPTIONS method.
*/
public void testOptionsMethod() throws Exception {
String[] yes = new String[] { "GET", "HEAD", "POST", "OPTIONS" };
String[] no = new String[] { "CONNECT", "PUT", "DELETE" };
doTestOptions("*", yes, no);
doTestOptions("/?_convention=_xins-std", yes, no);
yes = new String[] { "POST", "OPTIONS" };
no = new String[] { "CONNECT", "PUT", "DELETE", "GET", "HEAD" };
doTestOptions("/?_convention=_xins-soap", yes, no);
}
private void doTestOptions(String queryString, String[] yes, String[] no)
throws Exception {
String host = AllTests.host();
int port = AllTests.port();
String method = "OPTIONS";
Properties headers = new Properties();
headers.put("Content-Length", "0");
// Call the server
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Expect 200 OK
assertEquals("Expected 200 OK in response to HTTP OPTIONS request.", "200 OK", result.getStatus());
// Expect an empty body
String body = result.getBody();
assertTrue("Expected no body in response to an HTTP OPTIONS request.", body == null || body.length() < 1);
// Expect "Accept" field in the response (case-insensitive)
List acceptHeaders = result.getHeaderValues("accept");
assertTrue("Expected one \"Accept\" header in response to an HTTP OPTIONS request. Received " + acceptHeaders.size() + '.', acceptHeaders.size() == 1);
// Make sure field is not empty
String acceptHeader = (String) acceptHeaders.get(0);
assertTrue("Expected \"Accept\" header in response to HTTP OPTIONS request to have a non-empty value.", acceptHeader.trim().length() > 0);
// Split the list of acceptable HTTP methods
List acceptValues = splitCommas(acceptHeader);
// Make sure all expected HTTP methods are in the list
for (int i = 0; i < yes.length; i++) {
assertTrue("Expected \"Accept\" header in response to HTTP OPTIONS request to indicate the \"" + yes[i] + "\" method is supported. Instead the response is \"" + acceptHeader + "\".", acceptValues.contains(yes[i]));
}
// Make sure all forbidden HTTP methods are not in the list
for (int i = 0; i < no.length; i++) {
assertFalse("Expected \"Accept\" header in response to HTTP OPTIONS request to not indicate the \"" + no[i] + "\" method is supported. Instead the response is \"" + acceptHeader + "\".", acceptValues.contains(no[i]));
}
}
private List splitCommas(String in) {
// XXX: Before, this was the following code, but that is Java 1.4+ only:
// return Arrays.asList(acceptHeader.split("[ ]*,[ ]*"));
List list = new ArrayList();
StringTokenizer st = new StringTokenizer(in, ",");
while (st.hasMoreTokens()) {
String item = (String) st.nextToken();
list.add(item.trim());
}
return list;
}
/**
* Posts the XML data the the given destination.
*
* @param destination
* the destination where the XML has to be posted.
* @param data
* the XML to post.
*
* @return
* the returned XML already parsed.
*
* @throw Exception
* if anything goes wrong.
*/
private Element postXML(String destination, String data) throws Exception {
return postXML(destination, data, 200);
}
/**
* Posts the XML data the the given destination.
*
* @param destination
* the destination where the XML has to be posted.
*
* @param data
* the XML to post.
*
* @param expectedStatus
* the HTTP status code that is expected.
*
* @return
* the returned XML already parsed.
*
* @throw Exception
* if anything goes wrong.
*/
private Element postXML(String destination, String data, int expectedStatus)
throws Exception {
PostMethod post = new PostMethod(destination);
post.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
post.setRequestBody(data);
HttpClient client = new HttpClient();
client.setConnectionTimeout(5000);
client.setTimeout(5000);
try {
int code = client.executeMethod(post);
assertEquals(expectedStatus, code);
byte[] returnedData = post.getResponseBody();
ElementParser parser = new ElementParser();
String content = new String(returnedData);
// System.out.println("content: " + content);
Element result = parser.parse(new StringReader(content));
return result;
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
/**
* Gets the unique child of the element.
*
* @param parentElement
* the parent element, cannot be <code>null</code>.
*
* @param elementName
* the name of the child element to get, or <code>null</code> if the
* parent have a unique child.
*
* @throws InvalidRequestException
* if no child was found or more than one child was found.
*/
private Element getUniqueChild(Element parentElement, String elementName)
throws ParseException {
List childList = null;
if (elementName == null) {
childList = parentElement.getChildElements();
} else {
childList = parentElement.getChildElements(elementName);
}
if (childList.size() == 0) {
throw new ParseException("No \"" + elementName +
"\" children found in the \"" + parentElement.getLocalName() +
"\" element of the XML-RPC request.");
} else if (childList.size() > 1) {
throw new ParseException("More than one \"" + elementName +
"\" children found in the \"" + parentElement.getLocalName() +
"\" element of the XML-RPC request.");
}
return (Element) childList.get(0);
}
/**
* Tests that when different parameter values are passed to the
* specified calling convention, it must return a 400 status code
* (invalid HTTP request).
*/
private void doTestMultipleParamValues(String convention)
throws Throwable {
String destination = AllTests.url() + "allinone/";
HttpClient client = new HttpClient();
client.setConnectionTimeout(5000);
client.setTimeout(5000);
PostMethod post;
String paramName, value1, value2, message;
int actual, expected;
// Different values for the same parameter
post = new PostMethod(destination);
paramName = "_function";
value1 = "_GetFunctionList";
value2 = "_GetStatistics";
post.addParameter("_convention", convention);
post.addParameter(paramName, value1);
post.addParameter(paramName, value2);
try {
actual = client.executeMethod(post);
} finally {
post.releaseConnection();
}
expected = 400;
message = "Expected the \""
+ convention
+ "\" calling convention to return HTTP response code "
+ expected
+ " instead of "
+ actual
+ " when two different values are given for the \""
+ paramName
+ "\" parameter.";
assertEquals(message, expected, actual);
// Equal values for the same parameter
post = new PostMethod(destination);
paramName = "_function";
value1 = "_GetVersion";
value2 = value1;
post.addParameter("_convention", convention);
post.addParameter(paramName, value1);
post.addParameter(paramName, value2);
try {
actual = client.executeMethod(post);
} finally {
post.releaseConnection();
}
expected = 200;
message = "Expected the \""
+ convention
+ "\" calling convention to return HTTP response code "
+ expected
+ " instead of "
+ actual
+ " when two equal values are given for the \""
+ paramName
+ "\" parameter.";
assertEquals(message, expected, actual);
}
/**
* Tests that unsupported HTTP methods return the appropriate HTTP error.
*/
public void testUnsupportedHTTPMethods() throws Exception {
String[] unsupported = new String[] { "GET", "HEAD", };
String queryString = "/?_convention=_xins-xml";
String host = AllTests.host();
int port = AllTests.port();
Properties headers = new Properties();
headers.put("Content-Length", "0");
for (int i=0; i<unsupported.length; i++) {
String method = unsupported[i];
// Call the server
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Expect "405 Method Not Allowed"
assertEquals("Expected HTTP status code 405 in response to an HTTP " + method + " request for a calling convention that does not support that method.",
"405 Method Not Allowed", result.getStatus());
}
}
/**
* Tests that unknown HTTP methods return the appropriate HTTP error.
*/
public void testUnknownHTTPMethods() throws Exception {
String[] unknown = new String[] { "PUT", "DELETE", "POLL", "JO-JO", "get", "post" };
String queryString = "/?_convention=_xins-xml";
String host = AllTests.host();
int port = AllTests.port();
Properties headers = new Properties();
headers.put("Content-Length", "0");
for (int i=0; i<unknown.length; i++) {
String method = unknown[i];
// Call the server
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Expect "501 Not Implemented"
assertEquals("Expected HTTP status code 501 in response to an HTTP " + method + " request for a calling convention that does not support that method.",
"501 Not Implemented", result.getStatus());
}
// Same, but now without the content length header
headers = new Properties();
for (int i=0; i<unknown.length; i++) {
String method = unknown[i];
// Call the server
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Expect "501 Not Implemented"
assertEquals("Expected HTTP status code 501 in response to an HTTP " + method + " request for a calling convention that does not support that method.",
"501 Not Implemented", result.getStatus());
}
}
/**
* Tests that a HEAD request returns a correct Content-Length header, but
* no actual content.
*/
public void testContentLengthFromHEAD() throws Exception {
String queryString = "/?_convention=_xins-std&_function=Echo";
String host = AllTests.host();
int port = AllTests.port();
Properties headers = null;
// Perform a GET
String method = "GET";
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Content-length header should be set and correct
List lengthHeaders = result.getHeaderValues("content-length");
assertEquals("Expected GET request to return 1 \"Content-Length\" header. Instead it returned " + lengthHeaders.size(), 1, lengthHeaders.size());
int bodyLength = result.getBody().length();
int lengthHeader = Integer.parseInt((String) lengthHeaders.get(0));
assertEquals("Expected \"Content-Length\" header from GET request (" + lengthHeader + ") to match actual body length (" + bodyLength + ").", bodyLength, lengthHeader);
// Perform a HEAD
method = "HEAD";
result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Content-length header should be set and correct
lengthHeaders = result.getHeaderValues("content-length");
assertEquals("Expected HEAD request to return 1 \"Content-Length\" header. Instead it returned " + lengthHeaders.size(), 1, lengthHeaders.size());
assertEquals("Expected actual HEAD response length to be 0.", 0, result.getBody().length());
lengthHeader = Integer.parseInt((String) lengthHeaders.get(0));
assertEquals("Expected \"Content-Length\" header from HEAD request (" + lengthHeader + ") to match the one from GET (" + bodyLength + ").", bodyLength, lengthHeader);
}
public void testFileContentLength() throws Exception {
String fileName = "src/tests/apis/allinone/spec/Age.typ";
String queryString = "/specs/Age.typ";
String host = AllTests.host();
int port = AllTests.port();
Properties headers = null;
// Perform a GET
String method = "GET";
HTTPCallerResult result = HTTPCaller.call("1.1", host, port, method, queryString, headers);
// Status should be 200 OK
assertEquals("Expected 200 OK in response to HTTP/1.1 GET request.", "200 OK", result.getStatus());
// Content-length header should be set and correct
List lengthHeaders = result.getHeaderValues("content-length");
assertEquals("Expected GET request to return 1 \"Content-Length\" header instead of " + lengthHeaders.size() + '.', 1, lengthHeaders.size());
long lengthHeader = Long.parseLong((String) lengthHeaders.get(0));
long expectedLength = determineFileSize(fileName);;
assertEquals("Expected \"Content-Length\" header for \"" + queryString + "\" to return " + expectedLength + '.', expectedLength, lengthHeader);
long bodyLength = result.getBody().length();
assertEquals("Expected \"Content-Length\" header from GET request (" + lengthHeader + ") to match actual body length (" + bodyLength + ").", bodyLength, lengthHeader);
}
private long determineFileSize(String fileName) throws Exception {
File file = new File(fileName);
if (!file.exists()) {
throw new Exception("File \"" + file.getName() + "\" does not exist. Absolute: \"" + file.getAbsolutePath() + "\". Canonical: \"" + file.getCanonicalPath() + "\".");
}
return file.length();
}
public void testHTTP_1_0() throws Exception {
String queryString = "/?_convention=_xins-std&_function=Echo";
String host = AllTests.host();
int port = AllTests.port();
Properties headers = null;
// Perform a GET
String method = "GET";
HTTPCallerResult result = HTTPCaller.call("1.0", host, port, method, queryString, headers);
// Status should be 200 OK
assertEquals("Expected 200 OK in response to HTTP/1.0 GET request.", "200 OK", result.getStatus());
}
} |
package org.commcare.utils;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.commcare.CommCareApplication;
import org.commcare.dalvik.R;
import org.commcare.tasks.LogSubmissionTask;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.util.ArrayUtilities;
import org.javarosa.xpath.expr.XPathExpression;
import java.util.Vector;
/**
* Basically Copy+Paste code from CCJ2ME that needs to be unified or re-indexed to somewhere more reasonable.
*
* @author ctsims
*/
public class CommCareUtil {
public static FormInstance loadFixture(String refId, String userId) {
IStorageUtilityIndexed<FormInstance> userFixtureStorage = CommCareApplication.instance().getFileBackedUserStorage("fixture", FormInstance.class);
IStorageUtilityIndexed<FormInstance> appFixtureStorage = CommCareApplication.instance().getFileBackedAppStorage("fixture", FormInstance.class);
Vector<Integer> userFixtures = userFixtureStorage.getIDsForValue(FormInstance.META_ID, refId);
///... Nooooot so clean.
if (userFixtures.size() == 1) {
//easy case, one fixture, use it
return userFixtureStorage.read(userFixtures.elementAt(0));
//TODO: Userid check anyway?
} else if (userFixtures.size() > 1) {
//intersect userid and fixtureid set.
//TODO: Replace context call here with something from the session, need to stop relying on that coupling
Vector<Integer> relevantUserFixtures = userFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, userId);
if (relevantUserFixtures.size() != 0) {
Integer userFixture = ArrayUtilities.intersectSingle(userFixtures, relevantUserFixtures);
if (userFixture != null) {
return userFixtureStorage.read(userFixture);
}
}
}
//ok, so if we've gotten here there were no fixtures for the user, let's try the app fixtures.
Vector<Integer> appFixtures = appFixtureStorage.getIDsForValue(FormInstance.META_ID, refId);
Integer globalFixture = ArrayUtilities.intersectSingle(appFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, ""), appFixtures);
if (globalFixture != null) {
return appFixtureStorage.read(globalFixture);
} else {
//See if we have one manually placed in the suite
Integer userFixture = ArrayUtilities.intersectSingle(appFixtureStorage.getIDsForValue(FormInstance.META_XMLNS, userId), appFixtures);
if (userFixture != null) {
return appFixtureStorage.read(userFixture);
}
//Otherwise, nothing
return null;
}
}
/**
* Used around to count up the degree of specificity for this reference
*/
public static int countPreds(TreeReference reference) {
int preds = 0;
if (reference == null) {
return 0;
}
for (int i = 0; i < reference.size(); ++i) {
Vector<XPathExpression> predicates = reference.getPredicate(i);
if (predicates != null) {
preds += predicates.size();
}
}
return preds;
}
public static void triggerLogSubmission(Context c, boolean forceLogs) {
String url = LogSubmissionTask.getSubmissionUrl(CommCareApplication.instance().getCurrentApp().getAppPreferences());
if (url == null) {
//This is mostly for dev purposes
Toast.makeText(c, "Couldn't submit logs! Invalid submission URL...", Toast.LENGTH_LONG).show();
} else {
executeLogSubmission(url, forceLogs);
}
}
public static void executeLogSubmission(String url, boolean forceLogs) {
LogSubmissionTask reportSubmitter =
new LogSubmissionTask(CommCareApplication.instance().getSession().getListenerForSubmissionNotification(R.string.submission_logs_title),
url,
forceLogs);
// Execute on a true multithreaded chain, since this is an asynchronous process
reportSubmitter.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
} |
package us.kbase.auth2.service.exceptions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import us.kbase.auth2.lib.Authentication;
import us.kbase.auth2.lib.exceptions.ExternalConfigMappingException;
import us.kbase.auth2.lib.storage.exceptions.AuthStorageException;
import us.kbase.auth2.service.AuthExternalConfig;
import us.kbase.auth2.service.AuthExternalConfig.AuthExternalConfigMapper;
import us.kbase.auth2.service.SLF4JAutoLogger;
import us.kbase.auth2.service.template.TemplateProcessor;
public class ExceptionHandler implements ExceptionMapper<Throwable> {
//TODO TEST unit tests
//TODO JAVADOC
@Context
private HttpHeaders headers;
@Inject
private TemplateProcessor template;
private final ObjectMapper mapper = new ObjectMapper();
@Inject
private SLF4JAutoLogger logger;
@Inject
private Authentication auth;
@Inject
private UriInfo uriInfo;
@Override
public Response toResponse(Throwable ex) {
MediaType mt = getMediaType();
//TODO CODE this is a gross hack. Really want to know the produces annotation for the method that threw the error
if (mt == null) {
if (uriInfo.getPath().startsWith("api")) {
mt = MediaType.APPLICATION_JSON_TYPE;
} else {
mt = MediaType.TEXT_HTML_TYPE;
}
}
LoggerFactory.getLogger(getClass()).error("Logging exception:", ex);
boolean includeStack = false;
try {
final AuthExternalConfig ext = auth.getExternalConfig(
new AuthExternalConfigMapper());
includeStack = ext.isIncludeStackTraceInResponse();
} catch (AuthStorageException | ExternalConfigMappingException e) {
LoggerFactory.getLogger(getClass()).error(
"An error occurred in the error handler when attempting " +
"to get the server configuration", e);
}
final ErrorMessage em = new ErrorMessage(ex, logger.getCallID(),
includeStack);
String ret;
if (mt.equals(MediaType.APPLICATION_JSON_TYPE)) {
final Map<String, Object> err = new HashMap<>();
err.put("error", em);
try {
ret = mapper.writeValueAsString(err);
} catch (JsonProcessingException e) {
ret = "An error occured in the error handler when " +
"processing the error object to JSON. " +
"This shouldn't happen.";
LoggerFactory.getLogger(getClass()).error(ret, e);
}
} else {
ret = template.process("error", em);
}
return Response.status(em.getHttpCode()).entity(ret).type(mt).build();
}
// either html or json
private MediaType getMediaType() {
MediaType mt = null;
//sorted by q-value
final List<MediaType> mtypes = headers.getAcceptableMediaTypes();
if (mtypes != null) {
for (final MediaType m: mtypes) {
if (m.equals(MediaType.TEXT_HTML_TYPE) ||
m.equals(MediaType.APPLICATION_JSON_TYPE)) {
mt = m;
break;
}
}
}
return mt;
}
} |
package apijson.orm;
import static apijson.JSONObject.KEY_EXPLAIN;
import static apijson.RequestMethod.GET;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeoutException;
import javax.activation.UnsupportedDataTypeException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import apijson.JSON;
import apijson.JSONRequest;
import apijson.JSONResponse;
import apijson.Log;
import apijson.NotNull;
import apijson.RequestMethod;
import apijson.RequestRole;
import apijson.StringUtil;
import apijson.orm.exception.ConditionErrorException;
import apijson.orm.exception.ConflictException;
import apijson.orm.exception.NotExistException;
import apijson.orm.exception.NotLoggedInException;
import apijson.orm.exception.OutOfRangeException;
/**parser for parsing request to JSONObject
* @author Lemon
*/
public abstract class AbstractParser<T> implements Parser<T>, ParserCreator<T>, VerifierCreator<T>, SQLCreator {
protected static final String TAG = "AbstractParser";
/**
* false
* {@link Log#DEBUG} true
*/
public static boolean IS_PRINT_REQUEST_STRING_LOG = false;
/**
* false
* {@link Log#DEBUG} true
*/
public static boolean IS_PRINT_BIG_LOG = false;
/**
* false
* {@link Log#DEBUG} true
*/
public static boolean IS_PRINT_REQUEST_ENDTIME_LOG = false;
/**
* method = null
*/
public AbstractParser() {
this(null);
}
/**needVerify = true
* @param requestMethod null ? requestMethod = GET
*/
public AbstractParser(RequestMethod method) {
this(method, true);
}
/**
* @param requestMethod null ? requestMethod = GET
* @param needVerify false Table true
*/
public AbstractParser(RequestMethod method, boolean needVerify) {
super();
setMethod(method);
setNeedVerify(needVerify);
}
@NotNull
protected Visitor<T> visitor;
@NotNull
@Override
public Visitor<T> getVisitor() {
if (visitor == null) {
visitor = new Visitor<T>() {
@Override
public T getId() {
return null;
}
@Override
public List<T> getContactIdList() {
return null;
}
};
}
return visitor;
}
@Override
public AbstractParser<T> setVisitor(@NotNull Visitor<T> visitor) {
this.visitor = visitor;
return this;
}
protected RequestMethod requestMethod;
@NotNull
@Override
public RequestMethod getMethod() {
return requestMethod;
}
@NotNull
@Override
public AbstractParser<T> setMethod(RequestMethod method) {
this.requestMethod = method == null ? GET : method;
this.transactionIsolation = RequestMethod.isQueryMethod(method) ? Connection.TRANSACTION_NONE : Connection.TRANSACTION_REPEATABLE_READ;
return this;
}
protected int version;
@Override
public int getVersion() {
return version;
}
@Override
public AbstractParser<T> setVersion(int version) {
this.version = version;
return this;
}
protected String tag;
@Override
public String getTag() {
return tag;
}
@Override
public AbstractParser<T> setTag(String tag) {
this.tag = tag;
return this;
}
protected JSONObject requestObject;
@Override
public JSONObject getRequest() {
return requestObject;
}
@Override
public AbstractParser<T> setRequest(JSONObject request) {
this.requestObject = request;
return this;
}
protected Boolean globleFormat;
public AbstractParser<T> setGlobleFormat(Boolean globleFormat) {
this.globleFormat = globleFormat;
return this;
}
@Override
public Boolean getGlobleFormat() {
return globleFormat;
}
protected RequestRole globleRole;
public AbstractParser<T> setGlobleRole(RequestRole globleRole) {
this.globleRole = globleRole;
return this;
}
@Override
public RequestRole getGlobleRole() {
return globleRole;
}
protected String globleDatabase;
public AbstractParser<T> setGlobleDatabase(String globleDatabase) {
this.globleDatabase = globleDatabase;
return this;
}
@Override
public String getGlobleDatabase() {
return globleDatabase;
}
protected String globleSchema;
public AbstractParser<T> setGlobleSchema(String globleSchema) {
this.globleSchema = globleSchema;
return this;
}
@Override
public String getGlobleSchema() {
return globleSchema;
}
protected String globleDatasource;
@Override
public String getGlobleDatasource() {
return globleDatasource;
}
public AbstractParser<T> setGlobleDatasource(String globleDatasource) {
this.globleDatasource = globleDatasource;
return this;
}
protected Boolean globleExplain;
public AbstractParser<T> setGlobleExplain(Boolean globleExplain) {
this.globleExplain = globleExplain;
return this;
}
@Override
public Boolean getGlobleExplain() {
return globleExplain;
}
protected String globleCache;
public AbstractParser<T> setGlobleCache(String globleCache) {
this.globleCache = globleCache;
return this;
}
@Override
public String getGlobleCache() {
return globleCache;
}
@Override
public AbstractParser<T> setNeedVerify(boolean needVerify) {
setNeedVerifyLogin(needVerify);
setNeedVerifyRole(needVerify);
setNeedVerifyContent(needVerify);
return this;
}
protected boolean needVerifyLogin;
@Override
public boolean isNeedVerifyLogin() {
return needVerifyLogin;
}
@Override
public AbstractParser<T> setNeedVerifyLogin(boolean needVerifyLogin) {
this.needVerifyLogin = needVerifyLogin;
return this;
}
protected boolean needVerifyRole;
@Override
public boolean isNeedVerifyRole() {
return needVerifyRole;
}
@Override
public AbstractParser<T> setNeedVerifyRole(boolean needVerifyRole) {
this.needVerifyRole = needVerifyRole;
return this;
}
protected boolean needVerifyContent;
@Override
public boolean isNeedVerifyContent() {
return needVerifyContent;
}
@Override
public AbstractParser<T> setNeedVerifyContent(boolean needVerifyContent) {
this.needVerifyContent = needVerifyContent;
return this;
}
protected SQLExecutor sqlExecutor;
protected Verifier<T> verifier;
protected Map<String, Object> queryResultMap;//path-result
@Override
public SQLExecutor getSQLExecutor() {
if (sqlExecutor == null) {
sqlExecutor = createSQLExecutor();
}
return sqlExecutor;
}
@Override
public Verifier<T> getVerifier() {
if (verifier == null) {
verifier = createVerifier().setVisitor(getVisitor());
}
return verifier;
}
/**json
* @param request
* @return
*/
@Override
public String parse(String request) {
return JSON.toJSONString(parseResponse(request));
}
/**json
* @param request
* @return
*/
@NotNull
@Override
public String parse(JSONObject request) {
return JSON.toJSONString(parseResponse(request));
}
/**json
* @param request parseRequestURLDecoder.decode(request, UTF_8);parseResponse(getCorrectRequest(...))
* @return parseResponse(requestObject);
*/
@NotNull
@Override
public JSONObject parseResponse(String request) {
Log.d(TAG, "\n\n\n\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n"
+ requestMethod + "/parseResponse request = \n" + request + "\n\n");
try {
requestObject = parseRequest(request);
} catch (Exception e) {
return newErrorResult(e);
}
return parseResponse(requestObject);
}
private int queryDepth;
/**json
* @param request
* @return requestObject
*/
@NotNull
@Override
public JSONObject parseResponse(JSONObject request) {
long startTime = System.currentTimeMillis();
Log.d(TAG, "parseResponse startTime = " + startTime
+ "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n ");
requestObject = request;
verifier = createVerifier().setVisitor(getVisitor());
if (RequestMethod.isPublicMethod(requestMethod) == false) {
try {
if (isNeedVerifyLogin()) {
onVerifyLogin();
}
if (isNeedVerifyContent()) {
onVerifyContent();
}
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
}
//parseCorrectRequestparseCorrectRequest @role
if (isNeedVerifyRole() && globleRole == null) {
try {
setGlobleRole(RequestRole.get(requestObject.getString(JSONRequest.KEY_ROLE)));
requestObject.remove(JSONRequest.KEY_ROLE);
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
}
try {
setGlobleFormat(requestObject.getBoolean(JSONRequest.KEY_FORMAT));
setGlobleDatabase(requestObject.getString(JSONRequest.KEY_DATABASE));
setGlobleSchema(requestObject.getString(JSONRequest.KEY_SCHEMA));
setGlobleDatasource(requestObject.getString(JSONRequest.KEY_DATASOURCE));
setGlobleExplain(requestObject.getBoolean(JSONRequest.KEY_EXPLAIN));
setGlobleCache(requestObject.getString(JSONRequest.KEY_CACHE));
requestObject.remove(JSONRequest.KEY_FORMAT);
requestObject.remove(JSONRequest.KEY_DATABASE);
requestObject.remove(JSONRequest.KEY_SCHEMA);
requestObject.remove(JSONRequest.KEY_DATASOURCE);
requestObject.remove(JSONRequest.KEY_EXPLAIN);
requestObject.remove(JSONRequest.KEY_CACHE);
} catch (Exception e) {
return extendErrorResult(requestObject, e);
}
final String requestString = JSON.toJSONString(request);//request
queryResultMap = new HashMap<String, Object>();
Exception error = null;
sqlExecutor = createSQLExecutor();
onBegin();
try {
queryDepth = 0;
requestObject = onObjectParse(request, null, null, null, false);
onCommit();
}
catch (Exception e) {
e.printStackTrace();
error = e;
onRollback();
}
requestObject = error == null ? extendSuccessResult(requestObject) : extendErrorResult(requestObject, error);
JSONObject res = (globleFormat != null && globleFormat) && JSONResponse.isSuccess(requestObject) ? new JSONResponse(requestObject) : requestObject;
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
if (Log.DEBUG) {
requestObject.put("sql:generate|cache|execute|maxExecute", getSQLExecutor().getGeneratedSQLCount() + "|" + getSQLExecutor().getCachedSQLCount() + "|" + getSQLExecutor().getExecutedSQLCount() + "|" + getMaxSQLCount());
requestObject.put("depth:count|max", queryDepth + "|" + getMaxQueryDepth());
requestObject.put("time:start|duration|end", startTime + "|" + duration + "|" + endTime);
if (error != null) {
requestObject.put("throw", error.getClass().getName());
requestObject.put("trace", error.getStackTrace());
}
}
onClose();
if (IS_PRINT_REQUEST_STRING_LOG||Log.DEBUG||error != null) {
Log.sl("\n\n\n",'<',"");
Log.fd(TAG , requestMethod + "/parseResponse request = \n" + requestString + "\n\n");
}
if (IS_PRINT_BIG_LOG||Log.DEBUG||error != null) { // bug
Log.fd(TAG,requestMethod + "/parseResponse return response = \n" + JSON.toJSONString(requestObject) + "\n\n");
}
if (IS_PRINT_REQUEST_ENDTIME_LOG||Log.DEBUG||error != null) {
Log.fd(TAG , requestMethod + "/parseResponse endTime = " + endTime + "; duration = " + duration);
Log.sl("",'>',"\n\n\n");
}
return res;
}
@Override
public void onVerifyLogin() throws Exception {
getVerifier().verifyLogin();
}
@Override
public void onVerifyContent() throws Exception {
requestObject = parseCorrectRequest();
}
/**
* @param config
* @return
* @throws Exception
*/
@Override
public void onVerifyRole(@NotNull SQLConfig config) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "onVerifyRole config = " + JSON.toJSONString(config));
}
if (isNeedVerifyRole()) {
if (config.getRole() == null) {
if (globleRole != null) {
config.setRole(globleRole);
} else {
config.setRole(getVisitor().getId() == null ? RequestRole.UNKNOWN : RequestRole.LOGIN);
}
}
getVerifier().verifyAccess(config);
}
}
/**JSONObject
* @param request => URLDecoder.decode(request, UTF_8);
* @return
* @throws Exception
*/
@NotNull
public static JSONObject parseRequest(String request) throws Exception {
JSONObject obj = JSON.parseObject(request);
if (obj == null) {
throw new UnsupportedEncodingException("JSON");
}
return obj;
}
@Override
public JSONObject parseCorrectRequest(RequestMethod method, String tag, int version, String name, @NotNull JSONObject request
, int maxUpdateCount, SQLCreator creator) throws Exception {
if (RequestMethod.isPublicMethod(method)) {
return request;//JSONgetpostGET
}
if (StringUtil.isEmpty(tag, true)) {
throw new IllegalArgumentException(" tag Table \"tag\": \"User\" ");
}
//JSON <<<<<<<<<<<<
JSONObject object = null;
String error = "";
try {
object = getStructure("Request", method.name(), tag, version);
} catch (Exception e) {
error = e.getMessage();
}
if (object == null) { //empty || object.isEmpty()) {
throw new UnsupportedOperationException(" version: " + version + ", method: " + method.name() + ", tag: " + tag + " structure "
+ " Request \n " + error + "\n Request ");
}
//JSON >>>>>>>>>>>>>>
JSONObject target = wrapRequest(object, tag, false);
//JSONObject clone Structure.parse structure {}
return getVerifier().verifyRequest(method, name, target, request, maxUpdateCount, getGlobleDatabase(), getGlobleSchema(), creator);
}
/** tag TableKey object { tag: object, "tag": tag }
* @param object
* @param tag
* @return
*/
public static JSONObject wrapRequest(JSONObject object, String tag, boolean putTag) {
if (object == null || object.containsKey(tag)) { //tag Table Table[]
if (putTag) {
if (object == null) {
object = new JSONObject(true);
}
object.put(JSONRequest.KEY_TAG, tag);
}
return object;
}
boolean isDiffArrayKey = tag.endsWith(":[]");
boolean isArrayKey = isDiffArrayKey || JSONRequest.isArrayKey(tag);
String key = isArrayKey ? tag.substring(0, tag.length() - (isDiffArrayKey ? 3 : 2)) : tag;
JSONObject target = object;
if (apijson.JSONObject.isTableKey(key)) {
if (isDiffArrayKey) { // tag = Comment:[] { ... } "Comment[]":[] { "Comment[]":[], ... }
target.put(key + "[]", new JSONArray());
}
else { // tag = Comment { ... } { "Comment": { ... } }
target = new JSONObject(true);
target.put(tag, object);
}
}
if (putTag) {
target.put(JSONRequest.KEY_TAG, tag);
}
return target;
}
/**JSONObject
* @param code
* @param msg
* @return
*/
public static JSONObject newResult(int code, String msg) {
return extendResult(null, code, msg);
}
/**JSONObject
* @param object
* @param code
* @param msg
* @return
*/
public static JSONObject extendResult(JSONObject object, int code, String msg) {
if (object == null) {
object = new JSONObject(true);
}
if (object.containsKey(JSONResponse.KEY_OK) == false) {
object.put(JSONResponse.KEY_OK, JSONResponse.isSuccess(code));
}
if (object.containsKey(JSONResponse.KEY_CODE) == false) {
object.put(JSONResponse.KEY_CODE, code);
}
String m = StringUtil.getString(object.getString(JSONResponse.KEY_MSG));
if (m.isEmpty() == false) {
msg = m + " ;\n " + StringUtil.getString(msg);
}
object.put(JSONResponse.KEY_MSG, msg);
return object;
}
/**
* @param object
* @return
*/
public static JSONObject extendSuccessResult(JSONObject object) {
return extendResult(object, JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED);
}
/**
* @return
*/
public static JSONObject newSuccessResult() {
return newResult(JSONResponse.CODE_SUCCESS, JSONResponse.MSG_SUCCEED);
}
/**
* @param object
* @return
*/
public static JSONObject extendErrorResult(JSONObject object, Exception e) {
JSONObject error = newErrorResult(e);
return extendResult(object, error.getIntValue(JSONResponse.KEY_CODE), error.getString(JSONResponse.KEY_MSG));
}
/**
* @param e
* @return
*/
public static JSONObject newErrorResult(Exception e) {
if (e != null) {
e.printStackTrace();
int code;
if (e instanceof UnsupportedEncodingException) {
code = JSONResponse.CODE_UNSUPPORTED_ENCODING;
}
else if (e instanceof IllegalAccessException) {
code = JSONResponse.CODE_ILLEGAL_ACCESS;
}
else if (e instanceof UnsupportedOperationException) {
code = JSONResponse.CODE_UNSUPPORTED_OPERATION;
}
else if (e instanceof NotExistException) {
code = JSONResponse.CODE_NOT_FOUND;
}
else if (e instanceof IllegalArgumentException) {
code = JSONResponse.CODE_ILLEGAL_ARGUMENT;
}
else if (e instanceof NotLoggedInException) {
code = JSONResponse.CODE_NOT_LOGGED_IN;
}
else if (e instanceof TimeoutException) {
code = JSONResponse.CODE_TIME_OUT;
}
else if (e instanceof ConflictException) {
code = JSONResponse.CODE_CONFLICT;
}
else if (e instanceof ConditionErrorException) {
code = JSONResponse.CODE_CONDITION_ERROR;
}
else if (e instanceof UnsupportedDataTypeException) {
code = JSONResponse.CODE_UNSUPPORTED_TYPE;
}
else if (e instanceof OutOfRangeException) {
code = JSONResponse.CODE_OUT_OF_RANGE;
}
else if (e instanceof NullPointerException) {
code = JSONResponse.CODE_NULL_POINTER;
}
else {
code = JSONResponse.CODE_SERVER_ERROR;
}
return newResult(code, e.getMessage());
}
return newResult(JSONResponse.CODE_SERVER_ERROR, JSONResponse.MSG_SERVER_ERROR);
}
//TODO Request
/**GET
* @param method
* @param request
* @return
* @throws Exception
*/
@Override
public JSONObject parseCorrectRequest() throws Exception {
setTag(requestObject.getString(JSONRequest.KEY_TAG));
setVersion(requestObject.getIntValue(JSONRequest.KEY_VERSION));
requestObject.remove(JSONRequest.KEY_TAG);
requestObject.remove(JSONRequest.KEY_VERSION);
return parseCorrectRequest(requestMethod, tag, version, "", requestObject, getMaxUpdateCount(), this);
}
//TODO
/**
* @param method
* @param response
* @return
* @throws Exception
*/
@Override
public JSONObject parseCorrectResponse(String table, JSONObject response) throws Exception {
// Log.d(TAG, "getCorrectResponse method = " + method + "; table = " + table);
// if (response == null || response.isEmpty()) {//result:{}
// Log.e(TAG, "getCorrectResponse response == null || response.isEmpty() >> return response;");
return response;
// JSONObject target = apijson.JSONObject.isTableKey(table) == false
// ? new JSONObject() : getStructure(method, "Response", "model", table);
// return MethodStructure.parseResponse(method, table, target, response, new OnParseCallback() {
// @Override
// protected JSONObject onParseJSONObject(String key, JSONObject tobj, JSONObject robj) throws Exception {
// return getCorrectResponse(method, key, robj);
}
/**RequestResponseJSON
* @param table
* @param method
* @param tag
* @param version
* @return
* @throws Exception
*/
@Override
public JSONObject getStructure(@NotNull String table, String method, String tag, int version) throws Exception {
// TODO Request Response REQUEST_MAP Response Request
String cacheKey = AbstractVerifier.getCacheKeyForRequest(method, tag);
SortedMap<Integer, JSONObject> versionedMap = AbstractVerifier.REQUEST_MAP.get(cacheKey);
JSONObject result = versionedMap == null ? null : versionedMap.get(Integer.valueOf(version));
if (result == null) { // version <= 0 version > 0 > version
Set<Entry<Integer, JSONObject>> set = versionedMap == null ? null : versionedMap.entrySet();
if (set != null && set.isEmpty() == false) {
Entry<Integer, JSONObject> maxEntry = null;
for (Entry<Integer, JSONObject> entry : set) {
if (entry == null || entry.getKey() == null || entry.getValue() == null) {
continue;
}
if (version <= 0 || version == entry.getKey()) { // versionedMap.get(Integer.valueOf(version))
maxEntry = entry;
break;
}
if (entry.getKey() < version) {
break;
}
maxEntry = entry;
}
result = maxEntry == null ? null : maxEntry.getValue();
}
if (result != null) {
if (versionedMap == null) {
versionedMap = new TreeMap<>((o1, o2) -> {
return o2 == null ? -1 : o2.compareTo(o1);
});
}
versionedMap.put(Integer.valueOf(version), result);
AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap);
}
}
if (result == null) {
if (AbstractVerifier.REQUEST_MAP.isEmpty() == false) {
return null; // REQUEST_MAP
}
//JSON <<<<<<<<<<<<<<
SQLConfig config = createSQLConfig().setMethod(GET).setTable(table);
config.setPrepared(false);
config.setColumn(Arrays.asList("structure"));
Map<String, Object> where = new HashMap<String, Object>();
where.put("method", method);
where.put(JSONRequest.KEY_TAG, tag);
if (version > 0) {
where.put(JSONRequest.KEY_VERSION + "{}", ">=" + version);
}
config.setWhere(where);
config.setOrder(JSONRequest.KEY_VERSION + (version > 0 ? "+" : "-"));
config.setCount(1);
//too many connections error: try-catch
result = getSQLExecutor().execute(config, false);
// version, method, tag JDK LRUCache
// versionedMap.put(Integer.valueOf(version), result);
// AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap);
}
return getJSONObject(result, "structure"); // "structure":{}
}
protected Map<String, ObjectParser> arrayObjectParserCacheMap = new HashMap<>();
// protected SQLConfig itemConfig;
/**parentObject
* @param parentPath parentObject
* @param name parentObjectkey
* @param request parentObjectvalue
* @param config for array item
* @return
* @throws Exception
*/
@Override
public JSONObject onObjectParse(final JSONObject request
, String parentPath, String name, final SQLConfig arrayConfig, boolean isSubquery) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "\ngetObject: parentPath = " + parentPath
+ ";\n name = " + name + "; request = " + JSON.toJSONString(request));
}
if (request == null) {// Moment:{} || request.isEmpty()) {//key-value
return null;
}
int type = arrayConfig == null ? 0 : arrayConfig.getType();
int position = arrayConfig == null ? 0 : arrayConfig.getPosition();
String[] arr = StringUtil.split(parentPath, "/");
if (position == 0) {
int d = arr == null ? 1 : arr.length + 1;
if (queryDepth < d) {
queryDepth = d;
int maxQueryDepth = getMaxQueryDepth();
if (queryDepth > maxQueryDepth) {
throw new IllegalArgumentException(parentPath + "/" + name + ":{} () " + queryDepth + " 1-" + maxQueryDepth + " !");
}
}
}
apijson.orm.Entry<String, String> entry = Pair.parseEntry(name, true);
String table = entry.getKey(); //Comment
// String alias = entry.getValue(); //to
boolean isTable = apijson.JSONObject.isTableKey(table);
boolean isArrayMainTable = isSubquery == false && isTable && type == SQLConfig.TYPE_ITEM_CHILD_0 && arrayConfig != null && RequestMethod.isGetMethod(arrayConfig.getMethod(), true);
boolean isReuse = isArrayMainTable && position > 0;
ObjectParser op = null;
if (isReuse) {
op = arrayObjectParserCacheMap.get(parentPath.substring(0, parentPath.lastIndexOf("[]") + 2));
}
if (op == null) {
op = createObjectParser(request, parentPath, arrayConfig, isSubquery, isTable, isArrayMainTable);
}
op = op.parse(name, isReuse);
JSONObject response = null;
if (op != null) {//SQLfunctionMapcustomMap
if (arrayConfig == null) { //Common
response = op.setSQLConfig().executeSQL().response();
}
else {//Array Item Child
int query = arrayConfig.getQuery();
//total arrayConfig.getType()createObjectParser.onChildParseonObjectParse
if (type == SQLConfig.TYPE_ITEM_CHILD_0 && query != JSONRequest.QUERY_TABLE && position == 0) {
RequestMethod method = op.getMethod();
JSONObject rp = op.setMethod(RequestMethod.HEAD).setSQLConfig().executeSQL().getSqlReponse();
op.setMethod(method);
if (rp != null) {
int index = parentPath.lastIndexOf("]/");
if (index >= 0) {
int total = rp.getIntValue(JSONResponse.KEY_COUNT);
String pathPrefix = parentPath.substring(0, index) + "]/";
putQueryResult(pathPrefix + JSONResponse.KEY_TOTAL, total);
int count = arrayConfig.getCount();
int page = arrayConfig.getPage();
int max = (int) ((total - 1)/count);
if (max < 0) {
max = 0;
}
JSONObject pagination = new JSONObject(true);
Object explain = rp.get(JSONResponse.KEY_EXPLAIN);
if (explain instanceof JSONObject) {
pagination.put(JSONResponse.KEY_EXPLAIN, explain);
}
pagination.put(JSONResponse.KEY_TOTAL, total);
pagination.put(JSONRequest.KEY_COUNT, count);
pagination.put(JSONRequest.KEY_PAGE, page);
pagination.put(JSONResponse.KEY_MAX, max);
pagination.put(JSONResponse.KEY_MORE, page < max);
pagination.put(JSONResponse.KEY_FIRST, page == 0);
pagination.put(JSONResponse.KEY_LAST, page == max);
putQueryResult(pathPrefix + JSONResponse.KEY_INFO, pagination);
if (total <= count*page) {
query = JSONRequest.QUERY_TOTAL;
}
}
}
op.setMethod(requestMethod);
}
//Table
if (query == JSONRequest.QUERY_TOTAL) {
response = null;
} else {
response = op
.setSQLConfig(arrayConfig.getCount(), arrayConfig.getPage(), position)
.executeSQL()
.response();
// itemConfig = op.getConfig();
}
}
if (isArrayMainTable) {
if (position == 0) {
arrayObjectParserCacheMap.put(parentPath.substring(0, parentPath.lastIndexOf("[]") + 2), op);
}
}
// else {
// op.recycle();
op = null;
}
return response;
}
/**parentObject
* @param parentPath parentObject
* @param name parentObjectkey
* @param request parentObjectvalue
* @return
* @throws Exception
*/
@Override
public JSONArray onArrayParse(JSONObject request, String parentPath, String name, boolean isSubquery) throws Exception {
if (Log.DEBUG) {
Log.i(TAG, "\n\n\n onArrayParse parentPath = " + parentPath
+ "; name = " + name + "; request = " + JSON.toJSONString(request));
}
//GETS"[]":{"@role":"ADMIN"},"Table":{},"tag":"Table"
if (isSubquery == false && RequestMethod.isGetMethod(requestMethod, false) == false) {
throw new UnsupportedOperationException("key[]:{}GET " + name + ":{} ");
}
if (request == null || request.isEmpty()) {//jsonKey-jsonValue
return null;
}
String path = getAbsPath(parentPath, name);
//1 []:{0:{Comment[]:{0:{Comment:{}},1:{...},...}},1:{...},...}
final String query = request.getString(JSONRequest.KEY_QUERY);
final Integer count = request.getInteger(JSONRequest.KEY_COUNT); //TODO getIntValue(JSONRequest.KEY_COUNT);
final int page = request.getIntValue(JSONRequest.KEY_PAGE);
final Object join = request.get(JSONRequest.KEY_JOIN);
int query2;
if (query == null) {
query2 = JSONRequest.QUERY_TABLE;
}
else {
switch (query) {
case "0":
case JSONRequest.QUERY_TABLE_STRING:
query2 = JSONRequest.QUERY_TABLE;
break;
case "1":
case JSONRequest.QUERY_TOTAL_STRING:
query2 = JSONRequest.QUERY_TOTAL;
break;
case "2":
case JSONRequest.QUERY_ALL_STRING:
query2 = JSONRequest.QUERY_ALL;
break;
default:
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_QUERY + ":value value [0,1,2] [TABLE, TOTAL, ALL] !");
}
}
int maxPage = getMaxQueryPage();
if (page < 0 || page > maxPage) {
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_PAGE + ":value value 0-" + maxPage + " !");
}
//totaltotalquery = 1,2
int count2 = isSubquery || count != null ? (count == null ? 0 : count) : getDefaultQueryCount();
int max = isSubquery ? count2 : getMaxQueryCount();
if (count2 < 0 || count2 > max) {
throw new IllegalArgumentException(path + "/" + JSONRequest.KEY_COUNT + ":value value 0-" + max + " !");
}
request.remove(JSONRequest.KEY_QUERY);
request.remove(JSONRequest.KEY_COUNT);
request.remove(JSONRequest.KEY_PAGE);
request.remove(JSONRequest.KEY_JOIN);
Log.d(TAG, "onArrayParse query = " + query + "; count = " + count + "; page = " + page + "; join = " + join);
if (request.isEmpty()) { // parentPath/name:request request
Log.e(TAG, "onArrayParse request.isEmpty() >> return null;");
return null;
}
JSONArray response = null;
try {
int size = count2 == 0 ? max : count2;//countsizepagemax(size) = count
Log.d(TAG, "onArrayParse size = " + size + "; page = " + page);
//key[]:{Table:{}}key equals Table Table
int index = isSubquery || name == null ? -1 : name.lastIndexOf("[]");
String childPath = index <= 0 ? null : Pair.parseEntry(name.substring(0, index), true).getKey(); // Table-key1-key2...
//keyTable
String[] childKeys = StringUtil.split(childPath, "-", false);
if (childKeys == null || childKeys.length <= 0 || request.containsKey(childKeys[0]) == false) {
childKeys = null;
}
//Table<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
response = new JSONArray();
SQLConfig config = createSQLConfig()
.setMethod(requestMethod)
.setCount(size)
.setPage(page)
.setQuery(query2)
.setJoinList(onJoinParse(join, request));
JSONObject parent;
//size
for (int i = 0; i < (isSubquery ? 1 : size); i++) {
parent = onObjectParse(request, isSubquery ? parentPath : path, isSubquery ? name : "" + i, config.setType(SQLConfig.TYPE_ITEM).setPosition(i), isSubquery);
if (parent == null || parent.isEmpty()) {
break;
}
//key[]:{Table:{}}key equals Table Table
response.add(getValue(parent, childKeys)); //null
}
//Table>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/*
*
{
"User-id[]": {
"User": {
"contactIdList<>": 82002
}
},
"Moment-userId[]": {
"Moment": {
"userId{}@": "User-id[]"
}
}
}
*/
Object fo = childKeys == null || response.isEmpty() ? null : response.get(0);
if (fo instanceof Boolean || fo instanceof Number || fo instanceof String) {
putQueryResult(path, response);
}
} finally {
request.put(JSONRequest.KEY_QUERY, query);
request.put(JSONRequest.KEY_COUNT, count);
request.put(JSONRequest.KEY_PAGE, page);
request.put(JSONRequest.KEY_JOIN, join);
}
if (Log.DEBUG) {
Log.i(TAG, "onArrayParse return response = \n" + JSON.toJSONString(response) + "\n>>>>>>>>>>>>>>>\n\n\n");
}
return response;
}
/**
* @param join "&/User/id@,</User[]/User/id{}@,</[]/Comment/momentId@"
* @param request
* @return
* @throws Exception
*/
private List<Join> onJoinParse(Object join, JSONObject request) throws Exception {
JSONObject joinMap = null;
if (join instanceof JSONObject) {
joinMap = (JSONObject) join;
}
else if (join instanceof String) {
String[] sArr = request == null || request.isEmpty() ? null : StringUtil.split((String) join);
if (sArr != null && sArr.length > 0) {
joinMap = new JSONObject(true); //joinjoinSQL
for (int i = 0; i < sArr.length; i++) {
joinMap.put(sArr[i], new JSONObject());
}
}
}
else if (join != null){
throw new UnsupportedDataTypeException(TAG + ".onJoinParse join String JSONObject ");
}
Set<Entry<String, Object>> set = joinMap == null ? null : joinMap.entrySet();
if (set == null || set.isEmpty()) {
Log.e(TAG, "onJoinParse set == null || set.isEmpty() >> return null;");
return null;
}
List<Join> joinList = new ArrayList<>();
JSONObject tableObj;
String targetPath;
JSONObject targetObj;
String targetTable;
String targetKey;
String path;
// List<String> onList = new ArrayList<>();
for (Entry<String, Object> e : set) {//User/id@
if (e.getValue() instanceof JSONObject == false) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value value"
+ " &/Table0/key0,</Table1/key1,... { '&/Table0/key0':{}, '</Table1/key1':{},... } ");
}
// /Table/key
path = "" + e.getKey();
int index = path.indexOf("/");
if (index < 0) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value value " + path + " "
+ " &/Table0/key0,</Table1/key1,... { '&/Table0/key0':{}, '</Table1/key1':{},... } ");
}
String joinType = path.substring(0, index);
// if (StringUtil.isEmpty(joinType, true)) {
// joinType = "|"; // FULL JOIN
path = path.substring(index + 1);
index = path.indexOf("/");
String tableKey = index < 0 ? null : path.substring(0, index); //User:owner
apijson.orm.Entry<String, String> entry = Pair.parseEntry(tableKey, true);
String table = entry.getKey(); //User
if (StringUtil.isName(table) == false) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value value Table " + table + " "
+ " &/Table0/key0,</Table1:alias1/key1,... Table0 key ");
}
String alias = entry.getValue(); //owner
if (StringUtil.isNotEmpty(alias, true) && StringUtil.isName(alias) == false) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value value alias " + alias + " "
+ " &/Table0/key0,</Table1:alias1/key1,... Table:alias alias ");
}
String key = StringUtil.isEmpty(table, true) ? null : path.substring(index + 1);
//TableJSONObject key:value
try {
tableObj = request.getJSONObject(tableKey);
}
catch (Exception e2) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":'" + path + "' " + tableKey + ":value value {} JSONObject " + e2.getMessage());
}
targetPath = tableObj == null ? null : tableObj.getString(key);
if (StringUtil.isEmpty(targetPath, true)) {
throw new IllegalArgumentException("/" + path + ":value value " + targetPath + " '/targetTable/targetKey' ");
}
//targetPathTablekey
index = targetPath.lastIndexOf("/");
targetKey = index < 0 ? null : targetPath.substring(index + 1);
if (StringUtil.isName(targetKey) == false) {
throw new IllegalArgumentException("/" + path + ":'/targetTable/targetKey' targetKey " + targetKey + " ");
}
targetPath = targetPath.substring(0, index);
index = targetPath.lastIndexOf("/");
String targetTableKey = index < 0 ? targetPath : targetPath.substring(index + 1);
// apijson.orm.Entry<String, String> targetEntry = Pair.parseEntry(targetTableKey, true);
// targetTable = targetEntry.getKey(); //User
// if (StringUtil.isName(targetTable) == false) {
// String targetAlias = targetEntry.getValue(); //owner
// if (StringUtil.isNotEmpty(targetAlias, true) && StringUtil.isName(targetAlias) == false) {
targetTable = targetTableKey;
if (StringUtil.isName(targetTable) == false) {
throw new IllegalArgumentException("/" + path + ":'/targetTable/targetKey' targetTable " + targetTable + " key ");
}
//JSONObject
try {
targetObj = request.getJSONObject(targetTableKey);
}
catch (Exception e2) {
throw new IllegalArgumentException("/" + path + ":'/targetTable/targetKey' '" + targetTableKey + "':value value {} JSONObject " + e2.getMessage());
}
if (targetObj == null) {
throw new IllegalArgumentException("/" + path + ":'/targetTable/targetKey' '" + targetTableKey + "':{} null {} JSONObject ");
}
// SQLExcecutor Config where SQL <<<<<<<<<
// AbstractSQLConfig.newSQLConfig id, id{}, userId, userId{} tableObj.put(key, tableObj.remove(key));
if (tableObj.size() > 1) { // key AbstractSQLExcecutor config.putWhere
JSONObject newTableObj = new JSONObject(tableObj.size(), true);
newTableObj.put(key, tableObj.remove(key));
newTableObj.putAll(tableObj);
tableObj = newTableObj;
request.put(tableKey, tableObj);
}
// SQLExcecutor Config where SQL >>>>>>>>>
Join j = new Join();
j.setPath(path);
j.setOriginKey(key);
j.setOriginValue(targetPath);
j.setJoinType(joinType);
j.setTable(table);
j.setAlias(alias);
j.setTargetTable(targetTable);
// j.setTargetAlias(targetAlias);
j.setTargetKey(targetKey);
j.setKeyAndType(key);
j.setRequest(getJoinObject(table, tableObj, key));
j.setOuter((JSONObject) e.getValue());
if (StringUtil.isName(j.getKey()) == false) {
throw new IllegalArgumentException(JSONRequest.KEY_JOIN + ":value value key@ key " + j.getKey() + " ");
}
joinList.add(j);
// onList.add(table + "." + key + " = " + targetTable + "." + targetKey); // ON User.id = Moment.userId
}
// SQLConfig SQL(Moment, User) SQLExecutor cacheMap
// AbstractSQLConfig config0 = null;
// String sql = "SELECT " + config0.getColumnString() + " FROM " + config0.getTable() + " INNER JOIN " + targetTable + " ON "
// + onList.get(0) + config0.getGroupString() + config0.getHavingString() + config0.getOrderString();
return joinList;
}
private static final List<String> JOIN_COPY_KEY_LIST;
static { // TODO
JOIN_COPY_KEY_LIST = new ArrayList<String>();
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_ROLE);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_DATABASE);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_SCHEMA);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_DATASOURCE);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_COLUMN);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_COMBINE);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_GROUP);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_HAVING);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_ORDER);
JOIN_COPY_KEY_LIST.add(JSONRequest.KEY_RAW);
}
/** JSON id
* @param table
* @param key
* @param obj
* @return null ? :
*/
private JSONObject getJoinObject(String table, JSONObject obj, String key) {
if (obj == null || obj.isEmpty()) {
Log.e(TAG, "getIdList obj == null || obj.isEmpty() >> return null;");
return null;
}
if (StringUtil.isEmpty(key, true)) {
Log.e(TAG, "getIdList StringUtil.isEmpty(key, true) >> return null;");
return null;
}
// join
JSONObject requestObj = new JSONObject(true); // (JSONObject) obj.clone();
Set<String> set = new LinkedHashSet<>(obj.keySet());
for (String k : set) {
if (StringUtil.isEmpty(k, true)) {
continue;
}
if (k.startsWith("@")) {
if (JOIN_COPY_KEY_LIST.contains(k)) {
requestObj.put(k, obj.get(k));
}
}
else {
if (k.endsWith("@")) {
if (k.equals(key)) {
continue;
}
throw new UnsupportedOperationException(table + "." + k + " " + JSONRequest.KEY_JOIN
+ " Table1 key@:value "); // TODO join on
}
if (k.contains("()") == false) {
// requestObj.put(k, obj.remove(k)); //remove
requestObj.put(k, obj.get(k)); //remove
}
}
}
return requestObj;
}
@Override
public int getDefaultQueryCount() {
return DEFAULT_QUERY_COUNT;
}
@Override
public int getMaxQueryPage() {
return MAX_QUERY_PAGE;
}
@Override
public int getMaxQueryCount() {
return MAX_QUERY_COUNT;
}
@Override
public int getMaxUpdateCount() {
return MAX_UPDATE_COUNT;
}
@Override
public int getMaxSQLCount() {
return MAX_SQL_COUNT;
}
@Override
public int getMaxObjectCount() {
return MAX_OBJECT_COUNT;
}
@Override
public int getMaxArrayCount() {
return MAX_ARRAY_COUNT;
}
@Override
public int getMaxQueryDepth() {
return MAX_QUERY_DEPTH;
}
/**
* @param parent
* @param pathKeys
* @return
*/
protected static Object getValue(JSONObject parent, String[] pathKeys) {
if (parent == null || pathKeys == null || pathKeys.length <= 0) {
Log.w(TAG, "getChild parent == null || pathKeys == null || pathKeys.length <= 0 >> return parent;");
return parent;
}
//childJSONObject parent
final int last = pathKeys.length - 1;
for (int i = 0; i < last; i++) {
if (parent == null) {//(keyvalueJSONObject)
break;
}
parent = getJSONObject(parent, pathKeys[i]);
}
return parent == null ? null : parent.get(pathKeys[last]);
}
/**key, [] -> []/i
* @param parentPath
* @param valuePath
* @return
*/
public static String getValuePath(String parentPath, String valuePath) {
if (valuePath.startsWith("/")) {
valuePath = getAbsPath(parentPath, valuePath);
} else {
valuePath = replaceArrayChildPath(parentPath, valuePath);
}
return valuePath;
}
/**
* @param path
* @param name
* @return
*/
public static String getAbsPath(String path, String name) {
Log.i(TAG, "getPath path = " + path + "; name = " + name + " <<<<<<<<<<<<<");
path = StringUtil.getString(path);
name = StringUtil.getString(name);
if (StringUtil.isNotEmpty(path, false)) {
if (StringUtil.isNotEmpty(name, false)) {
path += ((name.startsWith("/") ? "" : "/") + name);
}
} else {
path = name;
}
if (path.startsWith("/")) {
path = path.substring(1);
}
Log.i(TAG, "getPath return " + path + " >>>>>>>>>>>>>>>>");
return path;
}
/**[] -> []/i
* getAbsPathname
* @param parentPath
* @param valuePath
* @return
*/
public static String replaceArrayChildPath(String parentPath, String valuePath) {
String[] ps = StringUtil.split(parentPath, "]/");
if (ps != null && ps.length > 1) {
String[] vs = StringUtil.split(valuePath, "]/");
if (vs != null && vs.length > 0) {
String pos;
for (int i = 0; i < ps.length - 1; i++) {
if (ps[i] == null || ps[i].equals(vs[i]) == false) {
break;
}
pos = ps[i+1].contains("/") == false ? ps[i+1]
: ps[i+1].substring(0, ps[i+1].indexOf("/"));
if (
//StringUtil.isNumer(pos) &&
vs[i+1].startsWith(pos + "/") == false) {
vs[i+1] = pos + "/" + vs[i+1];
}
}
return StringUtil.getString(vs, "]/");
}
}
return valuePath;
}
/**objectrequestObject
* @param path object
* @param result object
*/
@Override
public synchronized void putQueryResult(String path, Object result) {
Log.i(TAG, "\n putQueryResult valuePath = " + path + "; result = " + result + "\n <<<<<<<<<<<<<<<<<<<<<<<");
// if (queryResultMap.containsKey(valuePath)) {//value
Log.d(TAG, "putQueryResult queryResultMap.containsKey(valuePath) >> queryResultMap.put(path, result);");
queryResultMap.put(path, result);
}
/**
* @param valuePath -the path need to get value
* @return parent == null ? valuePath : parent.get(keys[keys.length - 1])
* <p>use entrySet+getValue() to replace keySet+get() to enhance efficiency</p>
*/
@Override
public Object getValueByPath(String valuePath) {
Log.i(TAG, "<<<<<<<<<<<<<<< \n getValueByPath valuePath = " + valuePath + "\n <<<<<<<<<<<<<<<<<<");
if (StringUtil.isEmpty(valuePath, true)) {
Log.e(TAG, "getValueByPath StringUtil.isNotEmpty(valuePath, true) == false >> return null;");
return null;
}
Object target = queryResultMap.get(valuePath);
if (target != null) {
return target;
}
//keyvaluePathresultkeyvalue
JSONObject parent = null;
String[] keys = null;
for (Entry<String,Object> entry : queryResultMap.entrySet()){
String path = entry.getKey();
if (valuePath.startsWith(path + "/")) {
try {
parent = (JSONObject) entry.getValue();
} catch (Exception e) {
Log.e(TAG, "getValueByPath try { parent = (JSONObject) queryResultMap.get(path); } catch { "
+ "\n parent not instanceof JSONObject!");
parent = null;
}
if (parent != null) {
keys = StringUtil.splitPath(valuePath.substring(path.length()));
}
break;
}
}
//targetKeyJSONObject parent
if (keys != null && keys.length > 1) {
for (int i = 0; i < keys.length - 1; i++) {//parentPath
if (parent == null) {//(keyvalueJSONObject)
break;
}
parent = getJSONObject(parent, keys[i]);
}
}
if (parent != null) {
Log.i(TAG, "getValueByPath >> get from queryResultMap >> return parent.get(keys[keys.length - 1]);");
target = keys == null || keys.length <= 0 ? parent : parent.get(keys[keys.length - 1]); //nullNotExistExeptionidnull
if (target != null) {
Log.i(TAG, "getValueByPath >> getValue >> return target = " + target);
return target;
}
}
//requestObject
target = getValue(requestObject, StringUtil.splitPath(valuePath));
if (target != null) {
Log.i(TAG, "getValueByPath >> getValue >> return target = " + target);
return target;
}
Log.i(TAG, "getValueByPath return valuePath;");
return valuePath;
}
public static JSONObject getJSONObject(JSONObject object, String key) {
try {
return object.getJSONObject(key);
} catch (Exception e) {
Log.i(TAG, "getJSONObject try { return object.getJSONObject(key);"
+ " } catch (Exception e) { \n" + e.getMessage());
}
return null;
}
public static final String KEY_CONFIG = "config";
public static final String KEY_SQL = "sql";
protected Map<String, List<JSONObject>> arrayMainCacheMap = new HashMap<>();
public void putArrayMainCache(String arrayPath, List<JSONObject> mainTableDataList) {
arrayMainCacheMap.put(arrayPath, mainTableDataList);
}
public List<JSONObject> getArrayMainCache(String arrayPath) {
return arrayMainCacheMap.get(arrayPath);
}
public JSONObject getArrayMainCacheItem(String arrayPath, int position) {
List<JSONObject> list = getArrayMainCache(arrayPath);
return list == null || position >= list.size() ? null : list.get(position);
}
/** SQL JSONObject
* @param config
* @return
* @throws Exception
*/
@Override
public JSONObject executeSQL(SQLConfig config, boolean isSubquery) throws Exception {
if (config == null) {
Log.d(TAG, "executeSQL config == null >> return null;");
return null;
}
if (isSubquery) {
JSONObject sqlObj = new JSONObject(true);
sqlObj.put(KEY_CONFIG, config);
return sqlObj;// JSON.parseObject(config);
}
try {
JSONObject result;
boolean explain = config.isExplain();
if (explain) {
// explain execute explain
config.setExplain(false); // config.getSQL(false);
JSONObject res = getSQLExecutor().execute(config, false);
//explain
if (RequestMethod.isQueryMethod(config.getMethod())){
config.setExplain(explain);
JSONObject explainResult = config.isMain() && config.getPosition() != 0 ? null : getSQLExecutor().execute(config, false);
if (explainResult == null) {
result = res;
}
else {
result = new JSONObject(true);
result.put(KEY_EXPLAIN, explainResult);
result.putAll(res);
}
}else{//explainsql
result = new JSONObject(true);
result.put(KEY_SQL, config.getSQL(false));
result.putAll(res);
}
}
else {
result = getSQLExecutor().execute(config, false);
}
return parseCorrectResponse(config.getTable(), result);
}
catch (Exception e) {
if (Log.DEBUG == false && e instanceof SQLException) {
throw new SQLException("SQLException Log.DEBUG ", e);
}
throw e;
}
finally {
if (config.getPosition() == 0 && config.limitSQLCount()) {
int maxSQLCount = getMaxSQLCount();
int sqlCount = getSQLExecutor().getExecutedSQLCount();
Log.d(TAG, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \n\n\n " + sqlCount + "/" + maxSQLCount + " SQL \n\n\n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
if (sqlCount > maxSQLCount) {
throw new IllegalArgumentException(" " + config.getTable() + " " + sqlCount + " SQL 0-" + maxSQLCount + " !");
}
}
}
}
private int transactionIsolation = Connection.TRANSACTION_NONE;
@Override
public int getTransactionIsolation() {
return transactionIsolation;
}
@Override
public void setTransactionIsolation(int transactionIsolation) {
this.transactionIsolation = transactionIsolation;
}
@Override
public void begin(int transactionIsolation) {
Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< begin transactionIsolation = " + transactionIsolation + " >>>>>>>>>>>>>>>>>>>>>>> \n\n");
getSQLExecutor().setTransactionIsolation(transactionIsolation); // connection getSqlExecutor().begin(transactionIsolation);
}
@Override
public void rollback() throws SQLException {
Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< rollback >>>>>>>>>>>>>>>>>>>>>>> \n\n");
getSQLExecutor().rollback();
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< rollback savepoint " + (savepoint == null ? "" : "!") + "= null >>>>>>>>>>>>>>>>>>>>>>> \n\n");
getSQLExecutor().rollback(savepoint);
}
@Override
public void commit() throws SQLException {
Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< commit >>>>>>>>>>>>>>>>>>>>>>> \n\n");
getSQLExecutor().commit();
}
@Override
public void close() {
Log.d("\n\n" + TAG, "<<<<<<<<<<<<<<<<<<<<<<< close >>>>>>>>>>>>>>>>>>>>>>> \n\n");
getSQLExecutor().close();
}
protected void onBegin() {
// Log.d(TAG, "onBegin >>");
if (RequestMethod.isQueryMethod(requestMethod)) {
return;
}
begin(getTransactionIsolation());
}
protected void onCommit() {
// Log.d(TAG, "onCommit >>");
if (RequestMethod.isQueryMethod(requestMethod)) {
return;
}
try {
commit();
}
catch (SQLException e) {
e.printStackTrace();
}
}
protected void onRollback() {
// Log.d(TAG, "onRollback >>");
if (RequestMethod.isQueryMethod(requestMethod)) {
return;
}
try {
rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
try {
rollback(null);
}
catch (SQLException e2) {
e2.printStackTrace();
}
}
}
protected void onClose() {
// Log.d(TAG, "onClose >>");
close();
verifier = null;
sqlExecutor = null;
queryResultMap.clear();
queryResultMap = null;
}
} |
package io.branch.indexing;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import io.branch.referral.util.LinkProperties;
class AppIndexingHelper {
public static void addToAppIndex(final Context context, final BranchUniversalObject buo) {
new Thread(new Runnable() {
@Override
public void run() {
String urlForAppIndexing = buo.getShortUrl(context, new LinkProperties());
if (!TextUtils.isEmpty(urlForAppIndexing)) {
try {
listOnGoogleSearch(urlForAppIndexing, context, buo);
} catch (Exception ignore) {
}
}
}
}).run();
}
private static void listOnGoogleSearch(String shortLink, Context context, BranchUniversalObject branchUniversalObject) throws Exception {
// Create a Thing instance for the BUO with the link to the BUO
Class<?> ThingClass = Class.forName("com.google.android.gms.appindexing.Thing");
Class<?> ThingBuilderClass = Class.forName("com.google.android.gms.appindexing.Thing$Builder");
Constructor<?> constructor = ThingBuilderClass.getConstructor();
Object thingBuilder = constructor.newInstance();
Method setNameMethod = ThingBuilderClass.getMethod("setName", String.class);
Method setDescMethod = ThingBuilderClass.getMethod("setDescription", String.class);
Method setUrlMethod = ThingBuilderClass.getMethod("setUrl", Uri.class);
Method thingBuildMethod = ThingBuilderClass.getMethod("build");
setNameMethod.invoke(thingBuilder, branchUniversalObject.getTitle());
setDescMethod.invoke(thingBuilder, branchUniversalObject.getDescription());
setUrlMethod.invoke(thingBuilder, Uri.parse(shortLink));
Object thingObj = thingBuildMethod.invoke(thingBuilder);
// Now Create an View Action for the Thing created
Class<?> ThingActionClass = Class.forName("com.google.android.gms.appindexing.Action");
Class<?> ThingActionBuilderClass = Class.forName("com.google.android.gms.appindexing.Action$Builder");
Constructor<?> thingActionBuilderConstructor = ThingActionBuilderClass.getConstructor(String.class);
Object actionBuilder = thingActionBuilderConstructor.newInstance((String) ThingActionClass.getDeclaredField("TYPE_VIEW").get(null));
Method setObjectMethod = ThingActionBuilderClass.getMethod("setObject", ThingClass);
Method setActionStatusMethod = ThingActionBuilderClass.getMethod("setActionStatus", String.class);
Method actionBuildMethod = ThingActionBuilderClass.getMethod("build");
setObjectMethod.invoke(actionBuilder, thingObj);
setActionStatusMethod.invoke(actionBuilder, (String) ThingActionClass.getDeclaredField("STATUS_TYPE_COMPLETED").get(null));
Object actionObj = actionBuildMethod.invoke(actionBuilder);
// Create and connect with Api Client
Class<?> AppIndexClass = Class.forName("com.google.android.gms.appindexing.AppIndex");
Class<?> ApiClass = Class.forName("com.google.android.gms.common.api.Api");
Class<?> GoogleApiClientClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient");
Class<?> GoogleApiClientBuilderClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$Builder");
Constructor<?> googleApiClientBuilderConstructor = GoogleApiClientBuilderClass.getConstructor(Context.class);
Object apiClientBuilder = googleApiClientBuilderConstructor.newInstance(context);
Method addApiMethod = GoogleApiClientBuilderClass.getMethod("addApi", ApiClass);
Method apiClientBuildMethod = GoogleApiClientBuilderClass.getMethod("build");
Method apiClientConnectMethod = GoogleApiClientClass.getMethod("connect");
Method apiClientDisConnectMethod = GoogleApiClientClass.getMethod("disconnect");
addApiMethod.invoke(apiClientBuilder, ApiClass.cast(AppIndexClass.getDeclaredField("API").get(null)));
Object googleApiClientApiClientObj = apiClientBuildMethod.invoke(apiClientBuilder);
// Connect API Client, add to app index and then disconnect
apiClientConnectMethod.invoke(googleApiClientApiClientObj);
Class<?> AppIndexApiClass = Class.forName("com.google.android.gms.appindexing.AppIndexApi");
Object appIndexApiObj = AppIndexClass.getDeclaredField("AppIndexApi").get(null);
Method startMethod = AppIndexApiClass.getMethod("start", GoogleApiClientClass, ThingActionClass);
startMethod.invoke(appIndexApiObj, googleApiClientApiClientObj, actionObj);
apiClientDisConnectMethod.invoke(googleApiClientApiClientObj);
}
} |
package com.sharparam.minecraft.ccsharp;
import com.sharparam.minecraft.ccsharp.blocks.CardReaderBlock;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.MinecraftForge;
import java.util.logging.Logger;
@Mod(modid = CCSharp.ID, name = CCSharp.NAME, version = CCSharp.VERSION)
@NetworkMod(clientSideRequired = true, serverSideRequired = false)
public class CCSharp {
public static final String ID = "CCSharp";
public static final String NAME = "CCSharp";
public static final String VERSION = "0.0.3";
@Mod.Instance(ID)
public static CCSharp instance;
private Logger log;
private Configuration config;
public Block cardReaderBlock;
@SidedProxy(
clientSide = "com.sharparam.minecraft.ccsharp.client.ClientProxy",
serverSide = "com.sharparam.minecraft.ccsharp.server.ServerProxy")
public static IProxy proxy;
@Mod.PreInit
public void preInit(FMLPreInitializationEvent event) {
log = Logger.getLogger(ID);
log.setParent(FMLLog.getLogger());
config = new Configuration(event.getSuggestedConfigurationFile());
config.load();
config.getBlock("cardReader.id", 2050);
config.save();
}
@Mod.Init
public void init(FMLInitializationEvent event) {
cardReaderBlock = new CardReaderBlock(config.getBlock("cardReader.id", 2050).getInt(), 0, Material.rock);
LanguageRegistry.addName(cardReaderBlock, "Card Reader");
MinecraftForge.setBlockHarvestLevel(cardReaderBlock, "pickaxe", 1);
GameRegistry.registerBlock(cardReaderBlock, "cardReader");
proxy.registerRenderers();
}
@Mod.PostInit
public void postInit(FMLPostInitializationEvent event) {
}
} |
package au.com.codeka.warworlds.model;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import au.com.codeka.warworlds.RealmContext;
import au.com.codeka.warworlds.Util;
public class RealmManager {
public static RealmManager i = new RealmManager();
private List<Realm> mRealms;
private ArrayList<RealmChangedHandler> mRealmChangedHandlers;
private RealmManager() {
mRealmChangedHandlers = new ArrayList<RealmChangedHandler>();
mRealms = new ArrayList<Realm>();
try {
if (Util.isDebug()) {
mRealms.add(new Realm(DEBUG_REALM_ID, "http://192.168.1.4:8080/realms/beta/",
"Debug",
"The debug realm runs on my local dev box for testing.",
Realm.AuthenticationMethod.Default, false));
mRealms.add(new Realm(ALPHA_REALM_ID, "https://warworldsmmo.appspot.com/api/v1/",
"Alpha",
"The Alpha realm is officially deprecated and new players should join Beta.",
Realm.AuthenticationMethod.AppEngine, true));
}
mRealms.add(new Realm(BETA_REALM_ID, "https://game.war-worlds.com/realms/beta/",
"Beta",
"If you're new to War Worlds, you should join this realm. eXplore, eXpand, eXploit, eXterminate!",
Realm.AuthenticationMethod.Default, false));
mRealms.add(new Realm(BLITZ_REALM_ID, "https://game.war-worlds.com/realms/blitz/",
"Blitz",
"The goal of Blitz is to build as big an empire as you can in 1 month. Each month, the universe is reset and the winner is the one with the highest total population.",
Realm.AuthenticationMethod.Default, false));
} catch(URISyntaxException e) {
// should never happen
}
}
// The IDs for the realms can NEVER change, once set
public static int DEBUG_REALM_ID = 1000;
public static int ALPHA_REALM_ID = 1;
public static int BETA_REALM_ID = 2;
public static int BLITZ_REALM_ID = 10;
public void setup() {
SharedPreferences prefs = Util.getSharedPreferences();
if (prefs.getString("RealmName", null) != null) {
selectRealm(prefs.getString("RealmName", null), false);
}
}
public void addRealmChangedHandler(RealmChangedHandler handler) {
synchronized(mRealmChangedHandlers) {
mRealmChangedHandlers.add(handler);
}
}
public void removeRealmChangedHandler(RealmChangedHandler handler) {
synchronized(mRealmChangedHandlers) {
mRealmChangedHandlers.remove(handler);
}
}
protected void fireRealmChangedHandler(Realm newRealm) {
synchronized(mRealmChangedHandlers) {
for (RealmChangedHandler handler : mRealmChangedHandlers) {
handler.onRealmChanged(newRealm);
}
}
}
public List<Realm> getRealms() {
return mRealms;
}
public Realm getRealmByName(String name) {
for (Realm realm : mRealms) {
if (realm.getDisplayName().equalsIgnoreCase(name)) {
return realm;
}
}
return null;
}
public void selectRealm(String realmName) {
selectRealm(realmName, true);
}
public void selectRealm(int realmID) {
selectRealm(realmID, true);
}
private void selectRealm(String realmName, boolean saveSelection) {
for (Realm realm : mRealms) {
if (realm.getDisplayName().equalsIgnoreCase(realmName)) {
selectRealm(realm.getID(), saveSelection);
return;
}
}
}
private void selectRealm(int realmID, boolean saveSelection) {
Realm currentRealm = null;
if (realmID <= 0) {
RealmContext.i.setGlobalRealm(null);
} else {
for (Realm realm : mRealms) {
if (realm.getID() == realmID) {
currentRealm = realm;
RealmContext.i.setGlobalRealm(realm);
}
}
}
if (saveSelection) {
Util.getSharedPreferences().edit()
.putString("RealmName", currentRealm == null ? null : currentRealm.getDisplayName())
.commit();
}
fireRealmChangedHandler(currentRealm);
}
public interface RealmChangedHandler {
public void onRealmChanged(Realm newRealm);
}
} |
package org.jetel.component;
import java.util.Enumeration;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.jms.DataRecord2JmsMsg;
import org.jetel.connection.jms.JmsConnection;
import org.jetel.data.DataRecord;
import org.jetel.database.IConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.compile.DynamicJavaCode;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.w3c.dom.Element;
public class JmsWriter extends Node {
public final static String COMPONENT_TYPE = "JMS_READER";
static Log logger = LogFactory.getLog(JmsWriter.class);
private static final String XML_CONNECTION_ATTRIBUTE = "connection";
private static final String XML_PSORCODE_ATTRIBUTE = "processorCode";
private static final String XML_PSORCLASS_ATTRIBUTE = "processorClass";
private static final String XML_PSORURL_ATTRIBUTE = "processorURL";
private static final String XML_CHARSET_ATTRIBUTE = "charset";
// component attributes
private String conId;
private String psorClass;
private String psorCode;
private String psorURL = null;
private String charset = null;
private Properties psorProperties;
private InputPort inPort;
private JmsConnection connection;
private MessageProducer producer;
private DataRecord2JmsMsg psor;
/** Sole ctor.
* @param id Component ID
* @param conId JMS connection ID
* @param psorClass Processor class
* @param psorCode Inline processor definition
* @param psorProperties Properties to be passed to data processor.
*/
public JmsWriter(String id, String conId, String psorClass, String psorCode,
String psorURL, Properties psorProperties) {
super(id);
this.conId = conId;
this.psorClass = psorClass;
this.psorCode = psorCode;
this.psorURL = psorURL;
this.psorProperties = psorProperties;
}
public JmsWriter(String id, String conId, DataRecord2JmsMsg psor, Properties psorProperties) {
super(id);
this.conId = conId;
this.psor = psor;
this.psorProperties = psorProperties;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
if (psor == null && psorClass == null && psorCode == null && psorURL == null) {
throw new ComponentNotReadyException("Message processor not specified");
}
IConnection c = getGraph().getConnection(conId);
if (c == null || !(c instanceof JmsConnection)) {
throw new ComponentNotReadyException("Specified connection '" + conId + "' doesn't seem to be a JMS connection");
}
connection = (JmsConnection)c;
inPort = getInputPort(0);
if (psor == null) {
if (psorClass == null && psorCode == null) {
psorCode = FileUtils.getStringFromURL(getGraph().getProjectURL(), psorURL, charset);
}
psor = psorClass == null ? createProcessorDynamic(psorCode) : createProcessor(psorClass);
}
try {
connection.init();
producer = connection.createProducer();
} catch (Exception e) {
throw new ComponentNotReadyException("Unable to initialize JMS consumer: " + e.getMessage());
}
psor.init(inPort.getMetadata(), connection.getSession(), psorProperties);
}
/*
* (non-Javadoc)
* @see org.jetel.graph.GraphElement#reset()
*/
synchronized public void reset() throws ComponentNotReadyException {
super.reset();
connection.reset();
psor.reset();
}
/*
* (non-Javadoc)
* @see org.jetel.graph.GraphElement#free()
*/
@Override
public synchronized void free() {
super.free();
if (psor != null)
psor.finished();
closeConnection();
}
/** Creates processor instance of a class specified by its name.
* @param psorClass
* @return
* @throws ComponentNotReadyException
*/
private static DataRecord2JmsMsg createProcessor(String psorClass) throws ComponentNotReadyException {
DataRecord2JmsMsg psor;
try {
psor = (DataRecord2JmsMsg)Class.forName(psorClass).newInstance();
}catch (InstantiationException ex){
throw new ComponentNotReadyException("Can't instantiate msg processor class: "+ex.getMessage());
}catch (IllegalAccessException ex){
throw new ComponentNotReadyException("Can't instantiate msg processor class: "+ex.getMessage());
}catch (ClassNotFoundException ex) {
throw new ComponentNotReadyException("Can't find specified msg processor class: " + psorClass);
}
return psor;
}
/**
* Creates processor instance of a class specified by its source code.
* @param psorCode
* @return
* @throws ComponentNotReadyException
*/
private static DataRecord2JmsMsg createProcessorDynamic(String psorCode) throws ComponentNotReadyException {
DynamicJavaCode dynCode = new DynamicJavaCode(psorCode, JmsWriter.class.getClassLoader());
logger.info(" (compiling dynamic source) ");
// use DynamicJavaCode to instantiate transformation class
Object transObject = null;
try {
transObject = dynCode.instantiate();
} catch (RuntimeException ex) {
logger.debug(dynCode.getCompilerOutput());
logger.debug(dynCode.getSourceCode());
throw new ComponentNotReadyException("Msg processor code is not compilable.\n" + "Reason: " + ex.getMessage());
}
if (transObject instanceof DataRecord2JmsMsg) {
return (DataRecord2JmsMsg)transObject;
} else {
throw new ComponentNotReadyException("Provided msg processor class doesn't implement required interface.");
}
}
@Override
public Result execute() throws Exception {
DataRecord currentRecord = new DataRecord(inPort.getMetadata());
currentRecord.init();
DataRecord nextRecord = new DataRecord(inPort.getMetadata());
nextRecord.init();
try {
nextRecord = inPort.readRecord(nextRecord);
while (runIt && nextRecord != null) {
// move next to current; read new next
DataRecord rec = currentRecord;
currentRecord = nextRecord;
nextRecord = inPort.readRecord(rec);
// last message may differ from the other ones
Message msg = nextRecord != null ? psor.createMsg(currentRecord) : psor.createLastMsg(currentRecord);
if (msg == null) {
throw new JetelException(psor.getErrorMsg());
}
producer.send(msg);
}
// send terminating message
if (runIt) {
Message termMsg = psor.createLastMsg(null);
if (termMsg != null) {
producer.send(termMsg);
}
}
} catch (Exception e) {
logger.error("JmxWriter execute", e);
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
/**
* Tries to close JMS connection. It keeps silence regardless of operation success/failure.
*/
private void closeConnection() {
try {
if (producer != null)
producer.close();
} catch (JMSException e) {
// ignore it, the connection is probably already closed
}
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#getType()
*/
public String getType() {
return COMPONENT_TYPE;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#toXML(org.w3c.dom.Element)
*/
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_ID_ATTRIBUTE, getId());
if (conId != null) {
xmlElement.setAttribute(XML_CONNECTION_ATTRIBUTE, conId);
}
if (psorCode != null) {
xmlElement.setAttribute(XML_PSORCODE_ATTRIBUTE, psorCode);
}
if (psorClass != null) {
xmlElement.setAttribute(XML_PSORCLASS_ATTRIBUTE, psorClass);
}
if (psorURL != null) {
xmlElement.setAttribute(XML_PSORURL_ATTRIBUTE, psorURL);
}
if (charset != null){
xmlElement.setAttribute(XML_CHARSET_ATTRIBUTE, charset);
}
// set processor attributes
for (Enumeration<Object> names = psorProperties.keys(); names.hasMoreElements();) {
Object name = names.nextElement();
Object value = psorProperties.get(name);
xmlElement.setAttribute((String)name, (String)value);
}
}
/** Creates an instance according to XML specification.
* @param graph
* @param xmlElement
* @return
* @throws XMLConfigurationException
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
JmsWriter jmsReader = null;
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
try {
jmsReader = new JmsWriter(xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_CONNECTION_ATTRIBUTE, null),
xattribs.getString(XML_PSORCLASS_ATTRIBUTE, "org.jetel.component.jms.DataRecord2JmsMsgProperties"),
xattribs.getString(XML_PSORCODE_ATTRIBUTE, null),
xattribs.getString(XML_PSORURL_ATTRIBUTE, null),
xattribs.attributes2Properties(new String[]{ // all unknown attributes will be passed to the processor
XML_ID_ATTRIBUTE, XML_CONNECTION_ATTRIBUTE,
XML_PSORCLASS_ATTRIBUTE, XML_PSORCODE_ATTRIBUTE
}));
if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) {
jmsReader.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE));
}
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
return jmsReader;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig(org.jetel.exception.ConfigurationStatus)
*/
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 1, 1)
|| !checkOutputPorts(status, 0, 0)) {
return status;
}
// try {
// if (psor == null && psorClass == null && psorCode == null) {
// throw new ComponentNotReadyException("Message processor not specified");
// IConnection c = getGraph().getConnection(conId);
// if (c == null || !(c instanceof JmsConnection)) {
// throw new ComponentNotReadyException("Specified connection '" + conId + "' doesn't seem to be a JMS connection");
// connection = (JmsConnection)c;
// inPort = getInputPort(0);
// try {
// connection.init();
// producer = connection.createProducer();
// } catch (Exception e) {
// throw new ComponentNotReadyException("Unable to initialize JMS consumer: " + e.getMessage());
// init();
// free();
// } catch (ComponentNotReadyException e) {
// ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
// if(!StringUtils.isEmpty(e.getAttributeName())) {
// problem.setAttributeName(e.getAttributeName());
// status.add(problem);
return status;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
} |
package edu.iu.grid.oim.model;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.webif.divex.DivExRoot;
import edu.iu.grid.oim.lib.Authorization;
public class Context {
static Logger log = Logger.getLogger(Context.class);
private DivExRoot divex_root;
private Authorization auth = new Authorization();
private Connection connection = null;
private HttpServletRequest request;
public Context(HttpServletRequest _request)
{
request = _request;
try {
javax.naming.Context initContext = new InitialContext();
javax.naming.Context envContext = (javax.naming.Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/oim");
connection = ds.getConnection();
initContext.close();
auth = new Authorization(request, connection);
} catch (SQLException e) {
log.error(e);
} catch (NamingException e) {
log.error(e);
}
divex_root = DivExRoot.getInstance(request);
//log.info("Context initialized with " + connection.toString());
}
public void finalize() throws Throwable
{
if(connection != null) {
connection.close();
}
}
public static Context getGuestContext(Connection db)
{
return new Context(db);
}
private Context(Connection db)
{
//initialize with only the connection db
connection = db;
}
//getters
public Connection getConnection()
{
return connection;
}
public Authorization getAuthorization()
{
return auth;
}
public DivExRoot getDivExRoot()
{
return divex_root;
}
public HttpServletRequest getRequest()
{
return request;
}
} |
package com.lds.parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import com.lds.game.R;
import com.lds.game.entity.Entity;
import com.lds.game.entity.PhysBlock;
public class Parser //this is a perser
{
public HashMap<String, String> attributes;
public ArrayList<EntityData> parsedList = new ArrayList<EntityData>();
public XmlResourceParser xrp;
int x, y, curx, cury;
public Parser(Context context)
{
xrp = context.getResources().getXml(R.xml.tempdata);
attributes = new HashMap<String, String>();
}
public void parseLevel()
throws XmlPullParserException, IOException
{
while (xrp.getEventType() != xrp.END_DOCUMENT)
{
if (xrp.getEventType() == xrp.START_TAG)
{
System.out.println(xrp.getName());
if(xrp.getName().equals("Entity"))
parseEntity();
else if(xrp.getName().equals("Tileset"))
parseTileset();
}
xrp.next();
}
}
public void parseEntity() throws XmlPullParserException, IOException
{
xrp.next();
HashMap <String, String> dataHashMap = new HashMap<String, String>();
while (!((xrp.getEventType() == xrp.END_TAG && xrp.getName().equals("Entity"))))
{
String tempDataType = null;
tempDataType = xrp.getName();
xrp.next();
dataHashMap.put(tempDataType, xrp.getText());
xrp.next();
xrp.next();
}
PhysBlockData pbd = new PhysBlockData(dataHashMap);
parsedList.add(pbd);
}
public void parseTileset() throws XmlPullParserException, IOException
{
HashMap<String, String> tileHashMap = new HashMap<String, String>();
x = Integer.parseInt(attributes.get("x"));
y = Integer.parseInt(attributes.get("y"));
TileData[][] tdma = new TileData[y][x];
curx = -1;
cury = -1;
while(!(xrp.getEventType() == xrp.END_TAG && xrp.getName().equals("Tileset")))
{
parseAttributes();
cury++;
xrp.next();
while(!(xrp.getEventType() == xrp.END_TAG && xrp.getName().equals("TileRow")))
{
curx++;
xrp.next();
while(!(xrp.getEventType() == xrp.END_TAG && xrp.getName().equals("Tile")))
{
xrp.next();
String tempTag = xrp.getName();
xrp.next();
tileHashMap.put(tempTag, xrp.getText());
tdma[cury][curx] = new TileData(tileHashMap);
xrp.next();
xrp.next();
}
}
curx = -1;
}
cury = -1;
}
public void parseAttributes()
{
String tag = xrp.getName();
tag = tag.substring(tag.indexOf(" "));
while(tag.indexOf(" ") < 0)
{
attributes.put(tag.substring(1, tag.indexOf("=") - 1), tag.substring((tag.indexOf("=") + 1), tag.indexOf(" ")));
tag = tag.trim();
tag = tag.substring(tag.indexOf(" "));
}
}
public ArrayList<Entity> convertDataToEnts()
{
ArrayList<Entity> entList = new ArrayList<Entity>();
for(EntityData ent : parsedList)
{
if (ent instanceof PhysBlockData)
{
PhysBlock phy = new PhysBlock(ent.getSize(), ent.getXPos(), ent.getYPos());
entList.add(phy);
}
}
return entList;
}
} |
package com.redomar.game;
import com.redomar.game.audio.AudioHandler;
import com.redomar.game.entities.Dummy;
import com.redomar.game.entities.Player;
import com.redomar.game.entities.Vendor;
import com.redomar.game.gfx.Screen;
import com.redomar.game.gfx.SpriteSheet;
import com.redomar.game.level.LevelHandler;
import com.redomar.game.lib.Font;
import com.redomar.game.lib.Time;
import com.redomar.game.script.PrintTypes;
import com.redomar.game.script.Printing;
import org.apache.commons.lang3.text.WordUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.im.InputContext;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
/*
* This module forms the core architecture of the JavaGame. It coordinates the various
* audio and input handler components, generates the frame, renders the screen graphics, spawns
* NPCs and customizes the player. Game is also responsible for changing the maps and levels, as well
* as displaying various messages on the screen (e.g. fps)
*/
public class Game extends Canvas implements Runnable {
// Setting the size and name of the frame/canvas
private static final long serialVersionUID = 1L;
private static final String game_Version = "v1.8.3 Alpha";
private static final int WIDTH = 160; // The width of the screen
private static final int HEIGHT = (WIDTH / 3 * 2); // The height of the screen (two thirds of the width)
private static final int SCALE = 3; // Scales the size of the screen
private static final String NAME = "Game"; // The name of the JFrame panel
private static Game game;
private static Time time = new Time(); // Represents the calender's time value, in hh:mm:ss
// The properties of the player, npc, and fps/tps
private static int Jdata_Host; // The host of a multiplayer game (only available in earlier versions)
private static String Jdata_UserName = "";
private static String Jdata_IP = "127.0.0.1";
private static boolean changeLevel = false; // Determines whether the player teleports to another level
private static boolean npc = false; // Non-player character (NPC) initialized to non-existing
private static int map = 0; // Map of the level, initialized to no map (0)
private static int shirtCol; // The colour of the character's shirt
private static int faceCol; // The colour (ethnicity) of the character (their face)
private static boolean[] alternateCols = new boolean[2]; // Boolean array describing shirt and face colour
private static int fps; // The frame rate (frames per second), frequency at which images are displayed on the canvas
private static int tps; // The ticks (ticks per second), unit measure of time for one iteration of the game logic loop.
private static int steps;
private static boolean devMode; // Determines whether the game is in developer mode
private static boolean closingMode; // Determines whether the game will exit
// Audio, input, and mouse handler objects
private static JFrame frame;
private static AudioHandler backgroundMusic;
private static boolean running = false; // Determines whether the game is currently in process (i.e. whether the game is running)
private static InputHandler input; // Accepts keyboard input and follows the appropriate actions
private static MouseHandler mouse; // Tracks mouse movement and clicks, and follows the appropriate actions
private static InputContext context; // Provides methods to control text input facilities
private int tickCount = 0;
// Graphics
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()) // Array of red, green and blue values for each pixel
.getData();
private int[] colours = new int[6 * 6 * 6]; // Array of 216 unique colours (6 shades of red, 6 of green, and 6 of blue)
private BufferedImage image2 = new BufferedImage(WIDTH, HEIGHT - 30,
BufferedImage.TYPE_INT_RGB);
private Screen screen;
private WindowHandler window;
private LevelHandler level; // Loads and renders levels along with tiles, entities, projectiles and more.
//The entities of the game
private Player player;
private Dummy dummy; // Dummy NPC follows the player around
private Vendor vendor; // Vendor NPC exhibits random movement and is only found on cutom_level
private Font font = new Font(); // Font object capable of displaying 2 fonts: Arial and Segoe UI
private String nowPlaying;
private boolean notActive = true;
private int trigger = 0;
private Printing print = new Printing();
/**
* @author Redomar
* @version Alpha 1.8.3
*/
public Game() {
context = InputContext.getInstance();
// The game can only be played in one distinct window size
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFrame(new JFrame(NAME)); // Creates the frame with a defined name
getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exits the program when user closes the frame
getFrame().setLayout(new BorderLayout());
getFrame().add(this, BorderLayout.CENTER); // Centers the canvas inside the JFrame
getFrame().pack(); // Sizes the frame so that all its contents are at or above their preferred sizes
getFrame().setResizable(false);
getFrame().setLocationRelativeTo(null); // Centres the window on the screen
getFrame().setVisible(true);
requestFocus();
setDevMode(false);
setClosing(false);
}
/*
* This method will spawn a dummy NPC into the level only if they are allowed to be spawned in.
* They will be spawned at position (100, 150) with a red shirt and caucasian face.
*/
public static void npcSpawn() {
if (isNpc() == true) { // If NPCs are allowed in the level
game.setDummy(new Dummy(game.level, "Dummy", 100, 150, 500, // Create a new dummy NPC on the current game level, with name 'Dummy'
543)); // at position (100, 150), with a red shirt and caucasian ethnicity
game.level.addEntity(Game.getDummy());
}
}
/*
* This method will remove a dummy NPC from the level only if they are not allowed to be in it.
*/
public static void npcKill() {
if (isNpc() == false) { // If NPCs are not allowed in the level
game.level.removeEntity(Game.getDummy());
}
}
public static JFrame getFrame() {
return Game.frame;
}
public static void setFrame(JFrame frame) {
Game.frame = frame;
}
public static Player getPlayer() {
return game.player;
}
public void setPlayer(Player player) {
game.player = player;
}
public static LevelHandler getLevel() {
return game.level;
}
public void setLevel(LevelHandler level) {
this.level = level;
}
public static Time getTime() {
return Game.time;
}
public void setTime(Time time) {
Game.time = time;
}
public static Game getGame() {
return game;
}
public static void setGame(Game game) {
Game.game = game;
}
public static boolean isRunning() {
return running;
}
public static void setRunning(boolean running) {
Game.running = running;
}
public static boolean isChangeLevel() {
return changeLevel;
}
public static void setChangeLevel(boolean changeLevel) {
Game.changeLevel = changeLevel;
}
public static int getMap() {
return map;
}
public void setMap(String Map_str) {
setLevel(new LevelHandler(Map_str));
if (alternateCols[0]) { // If the first element (shirt colour) is set to True
Game.setShirtCol(240); // The player's shirt colour will be green
}
if (!alternateCols[0]) { // If the first element (shirt colour) is set to False
Game.setShirtCol(111); // The player's shirt colour will be black
}
if (alternateCols[1]) { // If the last element (face colour) is set to True
Game.setFaceCol(310); // The player will be African
}
if (!alternateCols[1]) { // If the last element (face colour) is set to False
Game.setFaceCol(543); // The player will be caucasian
}
setPlayer(new Player(level, 100, 100, input,
getJdata_UserName(), shirtCol, faceCol));
level.addEntity(player);
}
public static void setMap(int map) {
Game.map = map;
}
public static boolean isNpc() {
return npc;
}
public static void setNpc(boolean npc) {
Game.npc = npc;
}
public static Dummy getDummy() {
return game.dummy;
}
public void setDummy(Dummy dummy) {
this.dummy = dummy;
}
public static String getJdata_IP() {
return Jdata_IP;
}
public static void setJdata_IP(String jdata_IP) {
Jdata_IP = jdata_IP;
}
public static int getJdata_Host() {
return Jdata_Host;
}
public static void setJdata_Host(int jdata_Host) {
Jdata_Host = jdata_Host;
}
public static String getJdata_UserName() {
return Jdata_UserName;
}
public static void setJdata_UserName(String jdata_UserName) {
Jdata_UserName = jdata_UserName;
}
public static String getGameVersion() {
return game_Version;
}
public static int getShirtCol() {
return shirtCol;
}
public static void setShirtCol(int shirtCol) {
Game.shirtCol = shirtCol;
}
public static int getFaceCol() {
return faceCol;
}
public static void setFaceCol(int faceCol) {
Game.faceCol = faceCol;
}
public static boolean[] getAlternateCols() {
return alternateCols;
}
public static void setAlternateCols(boolean[] alternateCols) { // Boolean array should have a size of only two elements
Game.alternateCols = alternateCols;
}
// Sets ethnicity/face colour for the player
public static void setAlternateColsR(boolean alternateCols) {
Game.alternateCols[1] = alternateCols;
}
// Sets the shirt colour for the player
public static void setAlternateColsS(boolean alternateCols) {
Game.alternateCols[0] = alternateCols;
}
public static void setBackgroundMusic(AudioHandler backgroundMusic) {
Game.backgroundMusic = backgroundMusic;
}
public static AudioHandler getBackgroundMusic(){
return Game.backgroundMusic;
}
public static InputHandler getInput() {
return input;
}
public void setInput(InputHandler input) {
Game.input = input;
}
public static MouseHandler getMouse() {
return mouse;
}
public static void setMouse(MouseHandler mouse) {
Game.mouse = mouse;
}
public static boolean isDevMode() {
return devMode;
}
public static void setDevMode(boolean devMode) {
Game.devMode = devMode;
}
public static boolean isClosing() {
return closingMode;
}
public static void setClosing(boolean closing) {
Game.closingMode = closing;
}
/*
* This method initializes the game once it starts. It populates the colour array with actual colours (6 shades each of RGB).
* This method also builds the initial game level (custom_level), spawns a new vendor NPC, and begins accepting keyboard and mouse input/tracking.
*/
public void init() {
setGame(this);
int index = 0;
for (int r = 0; r < 6; r++) { // For all 6 shades of red
for (int g = 0; g < 6; g++) { // For all 6 shades of green
for (int b = 0; b < 6; b++) { // For all 6 shades of blue
int rr = (r * 255 / 5); // Split all 256 colours into 6 shades (0, 51, 102 ... 255)
int gg = (g * 255 / 5);
int bb = (b * 255 / 5);
colours[index++] = rr << 16 | gg << 8 | bb; // All colour values (RGB) are placed into one 32-bit integer, populating the colour array
}
}
}
screen = new Screen(WIDTH, HEIGHT, new SpriteSheet("/sprite_sheet.png"));
input = new InputHandler(this); // Input begins to record key presses
setMouse(new MouseHandler(this)); // Mouse tracking and clicking is now recorded
setWindow(new WindowHandler(this));
setMap("/levels/custom_level.png");
setMap(1); // 1 corresponds to custom_level
game.setVendor(new Vendor(level, "Vendor", 215, 215, 304, 543)); // Create a new vendor NPC on custom_level, with name "Vendor", at position (215, 215), with a red shirt and caucasian ethnicity
level.addEntity(getVendor());
}
/*
* This method will start the game and allow the user to start playing
*/
public synchronized void start() {
Game.setRunning(true); // Game will run
new Thread(this, "GAME").start(); // Thread is an instance of Runnable. Whenever it is started, it will run the run() method
}
/*
* This method will stop the game
*/
public synchronized void stop() {
Game.setRunning(false); // Game will not run
}
/*
* This method forms the game loop, determining how the game runs. It runs throughout the entire game,
* continuously updating the game state and rendering the game.
*/
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D; // The number of nanoseconds in one tick (number of ticks limited to 60 per update)
// 1 billion nanoseconds in one second
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis(); // Used for updating ticks and frames once every second
double delta = 0;
init(); // Initialize the game environment
while (Game.isRunning()) {
long now = System.nanoTime(); // Current time (now) compared to lastTime to calculate elapsed time
delta += (now - lastTime) / nsPerTick; // Elapsed time in seconds multiplied by 60
lastTime = now;
boolean shouldRender = false;
while (delta >= 1) { // Once 1/60 seconds or more have passed
ticks++;
tick(); // Tick updates
delta -= 1; // Delta becomes less than one again and the loop will close
shouldRender = true; // Limits the frames to 60 per second
}
try {
Thread.sleep(2); // Delays the thread by 2 milliseconds
} catch (InterruptedException e) { // If the current thread is interrupted, the interrupted status is cleared
e.printStackTrace();
}
if (shouldRender) {
frames++;
render();
}
if (System.currentTimeMillis() - lastTimer >= 1000) { // If elapsed time is greater than or equal to 1 second, update
lastTimer += 1000; // Updates in another second
getFrame().setTitle(
"JavaGame - Version "
+ WordUtils.capitalize(game_Version).substring(
1, game_Version.length()));
fps = frames;
tps = ticks;
frames = 0; // Reset the frames once per second
ticks = 0; // Reset the ticks once per second
}
}
}
/*
* This method updates the logic of the game.
*/
public void tick() {
setTickCount(getTickCount() + 1);
level.tick();
}
/*
* This method displays the current state of the game.
*/
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3); // Creates a new bs with triple buffering, which reduces tearing and cross-image pixelation
return;
}
// Centres the player in the middle of the screen
int xOffset = (int) getPlayer().getX() - (screen.getWidth() / 2);
int yOffset = (int) getPlayer().getY() - (screen.getHeight() / 2);
level.renderTiles(screen, xOffset, yOffset);
/*
* for (int x = 0; x < level.width; x++) { int colour = Colours.get(-1,
* -1, -1, 000); if (x % 10 == 0 && x != 0) { colour = Colours.get(-1,
* -1, -1, 500); } Font.render((x % 10) + "", screen, 0 + (x * 8), 0,
* colour, 1); }
*/
level.renderEntities(screen);
level.renderProjectileEntities(screen);
// Copies pixel data from the screen into the game
for (int y = 0; y < screen.getHeight(); y++) {
for (int x = 0; x < screen.getWidth(); x++) {
int colourCode = screen.getPixels()[x + y * screen.getWidth()];
if (colourCode < 255) { // If it is a valid colour code
pixels[x + y * WIDTH] = colours[colourCode]; // Sets the corresponding pixel from the screen to the game
}
}
}
if (isChangeLevel() == true && getTickCount() % 60 == 0) {
Game.setChangeLevel(true);
setChangeLevel(false);
}
if (changeLevel == true) { // If the player is teleporting to a different level
print.print("Teleported into new world", PrintTypes.GAME);
if (getMap() == 1) { // If the player is currently on custom_level
setMap("/levels/water_level.png");
if (getDummy() != null) { // Gave nullPointerException(); upon
// entering new world.
level.removeEntity(getDummy());
setNpc(false);
}
level.removeEntity(getVendor()); // When teleporting away from custom_level, remove vendor NPC (always found on custom_level)
setMap(2);
} else if (getMap() == 2) { // If the player is currently on water_level
setMap("/levels/custom_level.png");
level.removeEntity(getDummy());
setNpc(false);
level.addEntity(getVendor()); // Add a vendor NPC - they are always found on custom_level
setMap(1);
}
changeLevel = false;
}
Graphics g = bs.getDrawGraphics();
g.drawRect(0, 0, getWidth(), getHeight()); // Creates a rectangle the same size as the screen
g.drawImage(image, 0, 0, getWidth(), getHeight() - 30, null);
status(g, isDevMode(), isClosing());
// Font.render("Hi", screen, 0, 0, Colours.get(-1, -1, -1, 555), 1);
g.drawImage(image2, 0, getHeight() - 30, getWidth(), getHeight(), null);
g.setColor(Color.WHITE);
g.setFont(font.getSegoe());
g.drawString(
"Welcome " // Welcomes the player's username in white in the bottom left corner of the screen
+ WordUtils.capitalizeFully(player
.getSanitisedUsername()), 3, getHeight() - 17);
g.setColor(Color.ORANGE);
if (context.getLocale().getCountry().equals("BE") // If the player resides in Belgium or France (i.e. uses AZERTY keyboard)
|| context.getLocale().getCountry().equals("FR")) { // Displays "Press A to quit" in orange at the bottom-middle portion of the screen
g.drawString("Press A to quit", (getWidth() / 2)
- ("Press A to quit".length() * 3), getHeight() - 17);
} else { // If the player resides anywhere else (i.e. uses QWERTY keyboard)
g.drawString("Press Q to quit", (getWidth() / 2) // Displays "Press Q to quit" in orange at the bottom-middle portion of the screen
- ("Press Q to quit".length() * 3), getHeight() - 17);
}
g.setColor(Color.YELLOW);
g.drawString(time.getTime(), (getWidth() - 58), (getHeight() - 3)); // Displays the current time in yellow in the bottom right corner of the screen (hh:mm:ss)
g.setColor(Color.GREEN);
if(backgroundMusic.getActive()) { // If music is turned on
g.drawString("MUSIC is ON ", 3, getHeight() - 3); // Displays "MUSIC IS ON" in green in the bottom left corner of the screen.
}
g.dispose(); // Frees up memory and resources for graphics
bs.show();
}
/*
* This method displays information regarding various aspects/stats of the game, dependent upon
* whether it is running in developer mode, or if the application is closing.
*/
private void status(Graphics g, boolean TerminalMode, boolean TerminalQuit) {
if (TerminalMode == true) { // If running in developer mode
g.setColor(Color.CYAN);
g.drawString("JavaGame Stats", 0, 10); // Display "JavaGame Stats" in cyan at the bottom left of the screen
g.drawString("FPS/TPS: " + fps + "/" + tps, 0, 25); // Display the FPS and TPS in cyan directly above "JavaGame Stats"
if ((player.getNumSteps() & 15) == 15) {
steps += 1;
}
g.drawString("Foot Steps: " + steps, 0, 40); // Display the number of "Foot Steps" (in cyan, above the previous)
g.drawString(
"NPC: " + WordUtils.capitalize(String.valueOf(isNpc())), 0, // Displays whether the NPC is on the level (in cyan, above the previous)
55);
g.drawString("Mouse: " + getMouse().getX() + "x |" // Displays the position of the cursor (in cyan, above the previous)
+ getMouse().getY() + "y", 0, 70);
if (getMouse().getButton() != -1) // If a mouse button is pressed
g.drawString("Button: " + getMouse().getButton(), 0, 85); // Displays the mouse button that is pressed (in cyan, above the previous)
g.setColor(Color.CYAN);
g.fillRect(getMouse().getX() - 12, getMouse().getY() - 12, 24, 24);
}
if (TerminalQuit == true) { // If the game is shutting off
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight()); // Make the screen fully black
g.setColor(Color.RED);
g.drawString("Shutting down the Game", (getWidth() / 2) - 70, // Display "Shutting down the Game" in red in the middle of the screen
(getHeight() / 2) - 8);
g.dispose(); // Free up memory for graphics
}
}
public WindowHandler getWindow() {
return window;
}
public void setWindow(WindowHandler window) {
this.window = window;
}
public String getNowPlaying() {
return nowPlaying;
}
public void setNowPlaying(String nowPlaying) {
this.nowPlaying = nowPlaying;
}
public int getTickCount() {
return tickCount;
}
public void setTickCount(int tickCount) {
this.tickCount = tickCount;
}
public Vendor getVendor() {
return vendor;
}
public void setVendor(Vendor vendor) {
this.vendor = vendor;
}
} |
package com.yubico.base;
/**
* <p>
* Represents decrypted and parsed YubiKey OTP.
* </p>
* @author Simon
*/
public class Token
{
static int BLOCK_SIZE = 16;
static int KEY_SIZE = 16;
static int UID_SIZE = 6;
static long CRC_OK_RESIDUE = 0xf0b8;
/* Unique (secret) ID. */
byte[] uid; //UID_SIZE
/* Session counter (incremented by 1 at each startup + real use).
High bit indicates whether caps-lock triggered the token. */
byte[] sessionCounter;
/* Timestamp incremented by approx 8Hz (low part). */
byte[] timestampLow;
/* Timestamp (high part). */
byte timestampHigh;
/* Number of times used within session + activation flags. */
byte timesUsed;
/* Pseudo-random value. */
byte[] random;
/* CRC16 value of all fields. */
byte[] crc;
private static int calculateCrc(byte[] b)
{
//System.out.println("in calc crc, b[] = "+toString(b));
int crc = 0xffff;
for (int i = 0; i < b.length; i += 1) {
crc ^= b[i] & 0xFF;
for (int j = 0; j < 8; j++){
int n = crc & 1;
crc >>= 1;
if (n != 0) {
crc ^= 0x8408;
}
}
}
return crc;
}
/**
* <p>
* Gets <i>reference</i> to the CRC16 checksum of the OTP.
* </p>
* <p>
* This property is of little interest to other then unit test code since
* the checksum was validated when constructing {@code this}.
* </p>
* @return CRC16.
*/
public byte[] getCrc(){ return crc; }
/**
* <p>
* Gets <i>reference</i> to the random bytes of the OTP.
* </p>
* <p>
* This property is of little interest to other then unit test code.
* </p>
* @return Random bytes.
*/
public byte[] getRandom(){ return random; }
/**
* <p>
* Gets <i>reference</i> to bytes making up secret id.
* </p>
* @return Secret id.
*/
public byte[] getUid(){ return uid; }
/**
* <p>
* Gets <i>reference</i> to byte sequence of session counter.
* </p>
* @return Session counter byte sequence.
* @see #getCleanCounter()
*/
public byte[] getSessionCounter(){ return sessionCounter; }
/**
* <p>
* Gets high byte of time stamp.
* </p>
* @return High time stamp.
*/
public byte getTimestampHigh(){ return timestampHigh; }
/**
* <p>
* Gets <i>reference</i> to byte sequence of low part of time stamp.
* </p>
* @return Session counter byte sequence of length {@code 2}.
*/
public byte[] getTimestampLow(){ return timestampLow; }
public Token(byte[] b)
{
if (b.length != BLOCK_SIZE) {
throw new IllegalArgumentException("Not "+BLOCK_SIZE+" length");
}
int calcCrc = Token.calculateCrc(b);
//System.out.println("calc crc = "+calcCrc);
//System.out.println("ok crc is = "+Token.CRC_OK_RESIDUE);
if (calcCrc != Token.CRC_OK_RESIDUE) {
throw new IllegalArgumentException("CRC failure");
}
int start = 0;
uid = new byte[UID_SIZE];
System.arraycopy(b, start, uid, 0, UID_SIZE);
start += UID_SIZE;
sessionCounter = new byte[2];
System.arraycopy(b, start, sessionCounter, 0, 2);
start += 2;
timestampLow = new byte[2];
System.arraycopy(b, start, timestampLow, 0, 2);
start += 2;
timestampHigh = b[start];
start += 1;
timesUsed = b[start];
start += 1;
random = new byte[2];
System.arraycopy(b, start, random, 0, 2);
start += 2;
crc = new byte[2];
System.arraycopy(b, start, crc, 0, 2);
}
private static String toString(byte b)
{
return toString(new byte[]{b});
}
static String toString(byte[] b)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i += 1){
if (i > 0) sb.append(",");
sb.append(Integer.toHexString(b[i] & 0xFF));
}
return sb.toString();
}
/**
* <p>
* Gets session counter bytes with cap-lock triggered bit cleared.
* </p>
* @return Session counter.
*/
public byte[] getCleanCounter()
{
byte[] b = new byte[2];
b[0] = (byte) (sessionCounter[0] & (byte) 0xFF);
b[1] = (byte) (sessionCounter[1] & (byte) 0x7F);
return b;
}
/**
* <p>
* Gets byte value of counter that increases for each generated OTP during
* a session.
* </p>
* @return Value.
*/
public byte getTimesUsed(){ return timesUsed; }
/**
* <p>
* Tells if triggered by caps lock.
* </p>
* @return {@code true} if, {@code false} if not.
*/
public boolean wasCapsLockOn()
{
return ((byte) (sessionCounter[1] & (byte) 0x80)) != 0;
}
// Overrides.
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("[Token uid: "+Token.toString(uid));
sb.append(", counter: "+Token.toString(sessionCounter));
sb.append(", timestamp (low): "+Token.toString(timestampLow));
sb.append(", timestamp (high): "+Token.toString(timestampHigh));
sb.append(", session use: "+Token.toString(timesUsed));
sb.append(", random: "+Token.toString(random));
sb.append(", crc: "+Token.toString(crc));
sb.append(", clean counter: "+Token.toString(getCleanCounter()));
sb.append(", CAPS pressed: "+wasCapsLockOn()+"]");
return sb.toString();
}
} |
package com.zerulus.main;
import javax.swing.JFrame;
public class Game extends JFrame {
private static final long serialVersionUID = 1L;
public Game() {
setTitle("New Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setContentPane(new GamePanel());
pack();
setLocationRelativeTo(null);
setVisible(true);
}
} |
package ru.sendto.util.dto;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.reflections.Reflections;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import ru.sendto.dto.Dto;
public class Resolver implements TypeIdResolver {
@Override
public String getDescForKnownTypeIds() {
return null;
}
@Override
public Id getMechanism() {
return Id.CUSTOM;
}
@Override
public String idFromBaseType() {
return idFromValueAndType(null, base.getRawClass());
}
@Override
public String idFromValue(Object arg0) {
return idFromValueAndType(arg0, arg0.getClass());
}
@Override
public String idFromValueAndType(Object arg0, Class<?> arg1) {
return map.inverse().get(arg1);
}
JavaType base;
static BiMap<String, Class<?>> map = HashBiMap.create(100);
@Override
public void init(JavaType base) {
this.base = base;
fillMap();
}
static public BiMap<String, Class<?>> fillMap() {
if (!map.isEmpty())
return map;
Set<Class<? extends Dto>> sub = Collections.newSetFromMap(new ConcurrentHashMap<>());
Stream<String> pkgs = Arrays.stream(System.getenv("ru.sendto.util.dto.packages").split(","));
Stream<String> defaultPkgs = Arrays.stream(new String[] {"ru.sendto.dto","dto"});
Stream.concat(pkgs,defaultPkgs)
.peek(String::trim)
.filter(s->!s.isEmpty())
.distinct().map(Reflections::new)
.flatMap(r->r.getSubTypesOf(Dto.class).stream())
.forEach(clz -> {
if(Modifier.isAbstract(clz.getModifiers()))
return;
String id;
JsonTypeName typeName = clz.getAnnotation(JsonTypeName.class);
if (typeName != null && !(id = typeName.value()).isEmpty() && !map.containsKey(id)) {
// } else if (!map.containsKey(id = clz.getSimpleName().replaceAll("[^A-Z0-9]", ""))) {
// } else if (!map.containsKey(id = clz.getSimpleName())) {
// } else if (!map.containsKey(id = clz.getName())) {
} else if (!map.containsKey(id = Base64.getEncoder().withoutPadding().encodeToString(ByteBuffer.allocate(4).putInt(clz.getCanonicalName().hashCode()).array()))) {
} else if (!map.containsKey(id = clz.getCanonicalName())) {
} else {
throw new RuntimeException("Resolver cann`t create id for " +
clz.getCanonicalName() + ". "
+ "There are another classes with the same id. Try another @JsonTypeName.");
}
map.put(id, clz);
});
System.out.println(map);
return map;
}
@Override
public JavaType typeFromId(DatabindContext ctx, String id) throws IOException {
return TypeFactory.defaultInstance().constructSpecializedType(base, map.get(id));
}
// public static void main(String[] args) throws JsonProcessingException {
// Resolver r = new Resolver();
// ObjectMapper mapper = new ObjectMapper();
// MessageTextDto dto = new MessageTextDto().setText("ok");
// String json = mapper.writeValueAsString(dto);
// System.out.println(json);
// System.out.println(r.idFromValue(dto));
} |
package foam.nanos.cron;
import foam.core.ContextAwareSupport;
import foam.core.Detachable;
import foam.core.FObject;
import foam.dao.AbstractDAO;
import foam.dao.AbstractSink;
import foam.dao.DAO;
import foam.dao.MapDAO;
import foam.mlang.MLang;
import foam.mlang.sink.Min;
import foam.nanos.auth.EnabledAware;
import foam.nanos.logger.Logger;
import foam.nanos.NanoService;
import foam.nanos.script.ScriptStatus;
import foam.nanos.pm.PM;
import java.util.Date;
public class CronScheduler
extends ContextAwareSupport
implements NanoService, Runnable, EnabledAware
{
protected static long CRON_DELAY = 5000L;
protected DAO cronDAO_;
protected boolean enabled_ = true;
/**
* Gets the minimum scheduled cron job
*
* @return Date of the minimum scheduled cron job
*/
private Date getMinScheduledTime() {
Min min = (Min) cronDAO_
.where(MLang.EQ(Cron.ENABLED, true))
.select(MLang.MIN(Cron.SCHEDULED_TIME));
if ( min.getValue().equals(0) ) {
return null;
}
return (Date) min.getValue();
}
public void setEnabled(boolean enabled) {
enabled_ = enabled;
}
public boolean getEnabled() {
return enabled_;
}
public void start() {
cronDAO_ = (DAO) getX().get("cronDAO");
new Thread(this).start();
}
@Override
public void run() {
final Logger logger = (Logger) getX().get("logger");
try {
while ( true ) {
if ( getEnabled() ) {
Date now = new Date();
cronDAO_.where(
MLang.AND(
MLang.LTE(Cron.SCHEDULED_TIME, now),
MLang.EQ(Cron.ENABLED, true),
MLang.IN(Cron.STATUS, new ScriptStatus[] {
ScriptStatus.UNSCHEDULED,
ScriptStatus.ERROR,
})
)
)
.orderBy(Cron.SCHEDULED_TIME)
.select(new AbstractSink() {
@Override
public void put(Object obj, Detachable sub) {
Cron cron = (Cron) ((FObject) obj).fclone();
PM pm = new PM(CronScheduler.class, "cron:" + cron.getId());
try {
cron.setStatus(ScriptStatus.SCHEDULED);
cronDAO_.put(cron);
} catch (Throwable t) {
logger.error(this.getClass(), "Error running Cron Job", cron.getId(), t.getMessage(), t);
} finally {
pm.log(getX());
}
}
});
}
// Check for new cronjobs every 5 seconds if no current jobs
// or if their next scheduled execution time is > 5s away
// Delay at least a little bit to avoid blocking in case of a script error.
long delay = CRON_DELAY;
Date minScheduledTime = getMinScheduledTime();
if( minScheduledTime != null &&
getEnabled() ) {
delay = Math.abs(minScheduledTime.getTime() - System.currentTimeMillis());
delay = Math.min(CRON_DELAY, delay);
delay = Math.max(500, delay);
}
Thread.sleep(delay);
}
} catch (Throwable t) {
logger.error(this.getClass(), t.getMessage());
}
}
} |
package com.exedio.copernica;
import java.util.Collection;
public interface Category extends Component
{
/**
* @return a collection of {@link Category categories}.
*/
public Collection getCopernicaSubCategories();
/**
* @return a collection of {@link com.exedio.cope.lib.Type types}.
*/
public Collection getCopernicaTypes();
} |
package com.exedio.copernica;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import com.exedio.cope.lib.Attribute;
import com.exedio.cope.lib.BooleanAttribute;
import com.exedio.cope.lib.ConstraintViolationException;
import com.exedio.cope.lib.DateAttribute;
import com.exedio.cope.lib.DoubleAttribute;
import com.exedio.cope.lib.EnumAttribute;
import com.exedio.cope.lib.EnumValue;
import com.exedio.cope.lib.IntegerAttribute;
import com.exedio.cope.lib.Item;
import com.exedio.cope.lib.ItemAttribute;
import com.exedio.cope.lib.LongAttribute;
import com.exedio.cope.lib.MediaAttribute;
import com.exedio.cope.lib.Model;
import com.exedio.cope.lib.NestingRuntimeException;
import com.exedio.cope.lib.NoSuchIDException;
import com.exedio.cope.lib.NotNullViolationException;
import com.exedio.cope.lib.ObjectAttribute;
import com.exedio.cope.lib.StringAttribute;
import com.exedio.cope.lib.Type;
import com.exedio.cope.lib.pattern.Qualifier;
import com.exedio.cope.lib.search.EqualCondition;
import com.exedio.cops.CheckboxField;
import com.exedio.cops.DateField;
import com.exedio.cops.DoubleField;
import com.exedio.cops.Field;
import com.exedio.cops.Form;
import com.exedio.cops.IntegerField;
import com.exedio.cops.LongField;
import com.exedio.cops.RadioField;
import com.exedio.cops.StringField;
import com.exedio.cops.TextField;
final class ItemForm extends Form
{
static final String SAVE_BUTTON = "SAVE";
static final String CHECK_BUTTON = "CHECK";
static final String SECTION = "section";
final Item item;
final Type type;
/*TODO final*/ boolean hasFiles;
boolean toSave = false;
final CopernicaSection currentSection;
ItemForm(final ItemCop cop, final HttpServletRequest request)
{
super(request);
this.item = cop.item;
this.type = item.getType();
final CopernicaProvider provider = cop.provider;
final Model model = provider.getModel();
final List displayedAttributes;
final List hiddenAttributes;
final Collection sections = provider.getSections(type);
boolean sectionButton = false;
if(sections!=null)
{
{
CopernicaSection buttonSection = null;
CopernicaSection previousSection = null;
CopernicaSection firstSection = null;
final String previousSectionParam = getParameter(SECTION);
for(Iterator i = sections.iterator(); i.hasNext(); )
{
final CopernicaSection section = (CopernicaSection)i.next();
if(firstSection==null)
firstSection = section;
final String id = section.getCopernicaID();
if(getParameter(id)!=null)
{
buttonSection = section;
sectionButton = true;
break;
}
if(id.equals(previousSectionParam))
previousSection = section;
}
if(buttonSection!=null)
currentSection = buttonSection;
else if(previousSection!=null)
currentSection = previousSection;
else
currentSection = firstSection;
}
displayedAttributes = new ArrayList(provider.getMainAttributes(type));
hiddenAttributes = new ArrayList();
for(Iterator i = sections.iterator(); i.hasNext(); )
{
final CopernicaSection section = (CopernicaSection)i.next();
new Section(section.getCopernicaID(), section.getCopernicaName(cop.language));
final Collection sectionAttributes = section.getCopernicaAttributes();
if(section.equals(currentSection))
displayedAttributes.addAll(sectionAttributes);
else
hiddenAttributes.addAll(sectionAttributes);
}
}
else
{
currentSection = null;
displayedAttributes = type.getAttributes();
hiddenAttributes = Collections.EMPTY_LIST;
}
final ArrayList attributes = new ArrayList(displayedAttributes.size()+hiddenAttributes.size());
attributes.addAll(displayedAttributes);
attributes.addAll(hiddenAttributes);
final boolean save = getParameter(SAVE_BUTTON)!=null;
final boolean post = save || sectionButton || getParameter(CHECK_BUTTON)!=null;
boolean hasFilesTemp = false;
for(Iterator j = attributes.iterator(); j.hasNext(); )
{
final Attribute anyAttribute = (Attribute)j.next();
final Field field;
if(anyAttribute instanceof ObjectAttribute)
{
field = createField((ObjectAttribute)anyAttribute, post, cop, hiddenAttributes.contains(anyAttribute), model);
}
else if(anyAttribute instanceof MediaAttribute)
{
final MediaAttribute attribute = (MediaAttribute)anyAttribute;
field = new StringField(this, attribute, null, true, "", hiddenAttributes.contains(attribute));
if(!attribute.isReadOnly())
{
toSave = true;
hasFilesTemp = true;
}
}
else
continue;
if(!field.isReadOnly())
toSave = true;
}
this.hasFiles = hasFilesTemp;
for(Iterator j = type.getQualifiers().iterator(); j.hasNext(); )
{
final Qualifier qualifier = (Qualifier)j.next();
final Collection values = qualifier.getQualifyUnique().getType().search(new EqualCondition(qualifier.getParent(), item));
for(Iterator k = qualifier.getAttributes().iterator(); k.hasNext(); )
{
final Attribute anyAttribute = (Attribute)k.next();
for(Iterator l = values.iterator(); l.hasNext(); )
{
final Item value = (Item)l.next();
if(anyAttribute instanceof ObjectAttribute)
{
final ObjectAttribute attribute = (ObjectAttribute)anyAttribute;
final Object qualifiedValue = value.getAttribute(attribute);
if(qualifiedValue!=null)
createField(attribute, value, value.getID()+'.'+attribute.getName(), true, false, cop, false, model);
}
}
}
}
if(save)
{
save();
}
}
private final Field createField(
final ObjectAttribute attribute,
final boolean post, final ItemCop cop, final boolean hidden, final Model model)
{
return createField(attribute, this.item, attribute.getName(), attribute.isReadOnly(), post, cop, hidden, model);
}
private final Field createField(
final ObjectAttribute attribute, final Item item, final String name, final boolean readOnly,
final boolean post, final ItemCop cop, final boolean hidden, final Model model)
{
if(attribute instanceof EnumAttribute)
{
if(post)
return new EnumField((EnumAttribute)attribute, hidden, cop);
else
return new EnumField((EnumAttribute)attribute, (EnumValue)item.getAttribute(attribute), hidden, cop);
}
else if(attribute instanceof BooleanAttribute)
{
if(attribute.isNotNull())
{
if(post)
return new CheckboxField(this, attribute, name, readOnly, hidden);
else
return new CheckboxField(this, attribute, name, readOnly, ((Boolean)item.getAttribute(attribute)).booleanValue(), hidden);
}
else
{
if(post)
return new BooleanEnumField((BooleanAttribute)attribute, hidden, cop);
else
return new BooleanEnumField((BooleanAttribute)attribute, (Boolean)item.getAttribute(attribute), hidden, cop);
}
}
else if(attribute instanceof IntegerAttribute)
{
if(post)
return new IntegerField(this, attribute, name, readOnly, hidden);
else
return new IntegerField(this, attribute, name, readOnly, (Integer)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof LongAttribute)
{
if(post)
return new LongField(this, attribute, name, readOnly, hidden);
else
return new LongField(this, attribute, name, readOnly, (Long)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof DoubleAttribute)
{
if(post)
return new DoubleField(this, attribute, name, readOnly, hidden);
else
return new DoubleField(this, attribute, name, readOnly, (Double)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof DateAttribute)
{
if(post)
return new DateField(this, attribute, name, readOnly, hidden);
else
return new DateField(this, attribute, name, readOnly, (Date)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof StringAttribute)
{
if(post)
return new StringField(this, attribute, name, readOnly, hidden);
else
return new StringField(this, attribute, name, readOnly, (String)item.getAttribute(attribute), hidden);
}
else if(attribute instanceof ItemAttribute)
{
if(post)
return new ItemField(attribute, name, readOnly, hidden, model, cop);
else
return new ItemField(attribute, name, readOnly, (Item)item.getAttribute(attribute), hidden, model, cop);
}
else
{
throw new RuntimeException(attribute.getClass().toString());
}
}
public class ItemField extends TextField
{
final Model model;
final ItemCop cop;
final Item content;
/**
* Constructs a form field with an initial value.
*/
public ItemField(final Object key, final String name, final boolean readOnly, final Item value, final boolean hidden, final Model model, final ItemCop cop)
{
super(ItemForm.this, key, name, readOnly, (value==null) ? "" : value.getID(), hidden);
this.model = model;
this.cop = cop;
this.content = value;
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
public ItemField(final Object key, final String name, final boolean readOnly, final boolean hidden, final Model model, final ItemCop cop)
{
super(ItemForm.this, key, name, readOnly, hidden);
this.model = model;
this.cop = cop;
final String value = this.value;
if(value.length()>0)
{
Item parsed = null;
try
{
parsed = model.findByID(value);
}
catch(NoSuchIDException e)
{
error = e.getMessage();
}
content = error==null ? parsed : null;
}
else
content = null;
}
public void write(final PrintStream out) throws IOException
{
super.write(out);
ItemCop_Jspm.write(out, this);
}
public Object getContent()
{
return content;
}
}
final class EnumField extends RadioField
{
private static final String VALUE_NULL = "null";
final EnumAttribute attribute;
final EnumValue content;
/**
* Constructs a form field with an initial value.
*/
EnumField(final EnumAttribute attribute, final EnumValue value, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), (value==null) ? VALUE_NULL : value.getCode(), hidden);
this.attribute = attribute;
this.content = value;
addOptions(cop);
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
EnumField(final EnumAttribute attribute, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), hidden);
this.attribute = attribute;
addOptions(cop);
final String value = this.value;
if(VALUE_NULL.equals(value))
content = null;
else
{
content = attribute.getValue(value);
if(content==null)
throw new RuntimeException(value);
}
}
private void addOptions(final ItemCop cop)
{
if(!attribute.isNotNull())
{
addOption(VALUE_NULL, cop.getDisplayNameNull());
}
for(Iterator k = attribute.getValues().iterator(); k.hasNext(); )
{
final EnumValue currentValue = (EnumValue)k.next();
final String currentCode = currentValue.getCode();
final String currentName = cop.getDisplayName(currentValue);
addOption(currentCode, currentName);
}
}
public Object getContent()
{
return content;
}
}
final class BooleanEnumField extends RadioField
{
private static final String VALUE_NULL = "null";
private static final String VALUE_ON = "on";
private static final String VALUE_OFF = "off";
final Boolean content;
/**
* Constructs a form field with an initial value.
*/
BooleanEnumField(final BooleanAttribute attribute, final Boolean value, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), value==null ? VALUE_NULL : value.booleanValue() ? VALUE_ON : VALUE_OFF, hidden);
this.content = value;
addOptions(cop);
}
/**
* Constructs a form field with a value obtained from the submitted form.
*/
BooleanEnumField(final BooleanAttribute attribute, final boolean hidden, final ItemCop cop)
{
super(ItemForm.this, attribute, attribute.getName(), attribute.isReadOnly(), hidden);
addOptions(cop);
final String value = this.value;
if(VALUE_NULL.equals(value))
content = null;
else if(VALUE_ON.equals(value))
content = Boolean.TRUE;
else if(VALUE_OFF.equals(value))
content = Boolean.FALSE;
else
throw new RuntimeException(value);
}
private final void addOptions(final ItemCop cop)
{
addOption(VALUE_NULL, cop.getDisplayNameNull());
addOption(VALUE_ON, cop.getDisplayNameOn());
addOption(VALUE_OFF, cop.getDisplayNameOff());
}
public Object getContent()
{
return content;
}
}
private void save()
{
for(Iterator i = getAllFields().iterator(); i.hasNext(); )
{
final Field field = (Field)i.next();
if(field.key instanceof MediaAttribute)
{
final MediaAttribute attribute = (MediaAttribute)field.key;
final FileItem fileItem = getParameterFile(attribute.getName());
if(fileItem!=null)
{
final String contentType = fileItem.getContentType();
if(contentType!=null)
{
final int pos = contentType.indexOf('/');
if(pos<=0)
throw new RuntimeException("invalid content type "+contentType);
final String mimeMajor = contentType.substring(0, pos);
String mimeMinor = contentType.substring(pos+1);
// fix for MSIE behaviour
if("image".equals(mimeMajor) && "pjpeg".equals(mimeMinor))
mimeMinor = "jpeg";
try
{
final InputStream data = fileItem.getInputStream();
item.setMediaData(attribute, data, mimeMajor, mimeMinor);
}
catch(IOException e)
{
throw new NestingRuntimeException(e);
}
catch(NotNullViolationException e)
{
throw new NestingRuntimeException(e);
}
}
}
}
if(!field.isReadOnly())
{
if(field.error==null)
{
try
{
final ObjectAttribute attribute = (ObjectAttribute)field.key;
item.setAttribute(attribute, field.getContent());
}
catch(NotNullViolationException e)
{
field.error = "error.notnull:"+e.getNotNullAttribute().toString();
}
catch(ConstraintViolationException e)
{
field.error = e.getClass().getName();
}
}
}
}
}
} |
// DotSite.java -- Java class DotSite
// Project OrcScala
package orc.values.sites.compatibility;
import java.util.Map;
import java.util.TreeMap;
import orc.Handle;
import orc.error.runtime.TokenException;
import orc.error.runtime.UncallableValueException;
import orc.error.runtime.NoSuchMemberException;
/**
* Dot-accessible sites should extend this class and declare their Orc-available
* methods using <code>addMembers()</code>. The code is forward-compatible with many possible
* optimizations on the field lookup strategy.
*
* A dot site may also have a default behavior which allows it to behave like
* a normal site. If its argument is not a message, it displays that
* default behavior, if implemented. If there is no default behavior, it
* raises a type error.
*
* @author dkitchin
*/
public abstract class DotSite extends SiteAdaptor {
Map<String, Object> methodMap;
public DotSite() {
methodMap = new TreeMap<String, Object>();
this.addMembers();
}
@Override
public void callSite(final Args args, final Handle t) throws TokenException {
String f;
// Check if the argument is a message
try {
f = args.fieldName();
} catch (final TokenException e) {
// If not, invoke the default behavior and return.
defaultTo(args, t);
return;
}
// If it is a message, look it up.
final Object m = getMember(f);
if (m != null) {
t.publish(object2value(m));
} else {
throw new NoSuchMemberException(this, f);
}
}
Object getMember(final String f) {
return methodMap.get(f);
}
protected abstract void addMembers();
protected void addMember(final String f, final Object s) {
methodMap.put(f, s);
}
protected void defaultTo(final Args args, final Handle token) throws TokenException {
throw new UncallableValueException("This dot site has no default behavior; it only responds to messages.");
}
} |
package net.mawenjian.utils.text;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import net.mawenjian.masf.utils.text.StringFormatUtil;
import net.mawenjian.masf.utils.text.StringFormatUtil.PostHandleIface;
import net.mawenjian.masf.utils.text.StringFormatUtil.PostHandleType;
public class StringFormatUtilTest {
// Map
private final static String formatForMap = "{name}, {china.name}, {usa.name}, {china.beijing.name}, {china.beijing.xicheng.name}, {world.region1}, {world.child.region1}.";
private final static String formatForBean = "{region1}, {region2}, {child.region1}, {child.region2}, {child.child.region1}, {child.child.region2}, {date}, {child.date}.";
private Map<String, Object> paramMap = null;
private StringFormatTestBean paramBean = null;
@Before
public void testPrepare() {
// paramBean
paramBean = new StringFormatTestBean();
paramBean.setRegion1("");
paramBean.setRegion2(null);
StringFormatTestBean subBean = new StringFormatTestBean();
subBean.setRegion1("");
subBean.setRegion2("");
paramBean.setChild(subBean);
StringFormatTestBean subSubBean = new StringFormatTestBean();
subSubBean.setRegion1("");
subSubBean.setRegion2("");
subBean.setChild(subSubBean);
// paramMap
paramMap = new HashMap<String, Object>();
paramMap.put("name", "");
Map<String, Object> subParam = new HashMap<String, Object>();
subParam.put("name", "");
paramMap.put("china", subParam);
Map<String, Object> subParam2 = new HashMap<String, Object>();
subParam2.put("name", "");
paramMap.put("usa", subParam2);
Map<String, Object> subSubParam = new HashMap<String, Object>();
subSubParam.put("name", "");
subParam.put("beijing", subSubParam);
Map<String, Object> subSubSubParam = new HashMap<String, Object>();
subSubSubParam.put("name", "");
subSubParam.put("xicheng", subSubSubParam);
//MapBean
paramMap.put("world", subBean);
}
/**
* Map
*/
@Test
public void testFormatString1() {
String result = StringFormatUtil.format(formatForMap, paramMap);
System.out.print("TEST-101 => ");
System.out.println(result);
}
/**
* Bean
*/
@Test
public void testFormatString2() {
String result = StringFormatUtil.format(formatForBean, paramBean);
System.out.print("TEST-201 => ");
System.out.println(result);
}
/**
* NULL
*/
@Test
public void testFormatString3() {
// NULL
String result = StringFormatUtil.format(formatForBean, paramBean, PostHandleType.NULL_IGNOREANCE);
System.out.print("TEST-301 => ");
System.out.println(result);
// NULL
result = StringFormatUtil.format(formatForBean, paramBean, PostHandleType.NULL_AS_EMPTY);
System.out.print("TEST-302 => ");
System.out.println(result);
result = StringFormatUtil.format(formatForBean, paramBean, PostHandleType.NULL_AS_STRING);
System.out.print("TEST-303 => ");
System.out.println(result);
}
@Test
public void testFormatString4() {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
StringFormatUtil.PostHandleIface postHandler = new PostHandleIface() {
// private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public String handle(Object containerObject, String name, String fullVariableName, Object value) {
/**
* 1 2value==nulltoString()
*/
String returnString = null;
if ("region2".equals(name)) {
returnString = String.format("region2: %s", value);
} else if ("date".equals(name) && "date".equals(fullVariableName) && value != null
&& value instanceof Date) {
returnString = sdf.format(value);
} else if (value == null) {
returnString = null;
} else {
returnString = value.toString();
}
return returnString;
}
};
String result = StringFormatUtil.format(formatForBean, paramBean, postHandler);
System.out.print("TEST-401 => ");
System.out.println(result);
}
public class StringFormatTestBean {
private String region1;
private String region2;
private Date date = new Date();
private StringFormatTestBean child;
public String getRegion1() {
return region1;
}
public void setRegion1(String region1) {
this.region1 = region1;
}
public String getRegion2() {
return region2;
}
public void setRegion2(String region2) {
this.region2 = region2;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public StringFormatTestBean getChild() {
return child;
}
public void setChild(StringFormatTestBean child) {
this.child = child;
}
}
} |
package ie.gmit.sw.ai.node;
import ie.gmit.sw.ai.fuzzyLogic.FuzzyEnemyStatusClassifier;
import ie.gmit.sw.ai.fuzzyLogic.FuzzyHealthClassifier;
import ie.gmit.sw.ai.neuralNetwork.CombatDecisionNN;
import ie.gmit.sw.ai.traversers.AStarTraversator;
import ie.gmit.sw.ai.traversers.PlayerDepthLimitedDFSTraverser;
import ie.gmit.sw.ai.traversers.Traversator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
public class PlayerNode extends Node {
private int health = 100;
private int bombs;
private int swords;
private int noOfEnemies;
private int damage = 10;
private int bombDamage = 20;
private int swordDamage = 10;
private Node[][] maze = null;
private Node nextMove = null;
private boolean hasNextMove = false;
private boolean inCombat=false;
private long movementSpeed = 3000;
private ExecutorService executor = Executors.newFixedThreadPool(1);
private PlayerDepthLimitedDFSTraverser depthLimitedDFSTraverser;
private CombatDecisionNN combatNet = null;
private FuzzyHealthClassifier healthClassifier = null;
private FuzzyEnemyStatusClassifier enemyStatusClassifier = null;
private Random rand = new Random();
public boolean isDead = false;
public PlayerNode(int row, int col, Node[][] maze) {
super(row, col, 5);
//Init Variables
this.maze = maze;
this.health=100;
this.bombs=0;
this.swords=0;
this.noOfEnemies=0;
// instantiate neural network that decides whether to fight, panic, heal or run away
combatNet = new CombatDecisionNN();
healthClassifier = new FuzzyHealthClassifier();
enemyStatusClassifier = new FuzzyEnemyStatusClassifier();
depthLimitedDFSTraverser = new PlayerDepthLimitedDFSTraverser();
Traversator aStar = new AStarTraversator(maze[3][3]);
aStar.traverse(maze,this);
System.out.println(aStar.getNextNode() +" current node: "+this);
// start player thread
executor.submit(() -> {
while (true) {
try {
// check that player is dead
if(getHealth() <= 0){
// player is dead
isDead = true;
System.out.println("\n===============================================");
System.out.println("Player is Dead!");
System.out.println("===============================================\n");
}
// sleep thread to simulate a movement pace
Thread.sleep(movementSpeed);
checkForPickup();
// don't do anything if in combat
if(!inCombat) {
// check for enemies right next to the player
checkForEnemies();
}
} catch (Exception ex) {
} // try catch
} // while
});
}
public void startCombat(SpiderNode spider){
// initialise combat with selected spider
// tell spider combat is starting
spider.setInCombat(true);
// flag self as in combat
this.inCombat = true;
// decide what to do
try {
/*
1 = Health (1 = Healthy, 0.5 = Minor Injuries, 0 = Serious Injuries)
2 = Has Sword (1 = Yes, 0 = No)
3 = Has Bomb (1 = Yes, 0 = No)
4 = Enemies Status (0 = One, 0.5 = Two, 1 = Three or More)
*/
double healthStatus = 1;
double swordStatus = 0;
double bombStatus = 0;
double enemyStatus = 0;
// scan for enemies
depthLimitedDFSTraverser.traverseForEnemies(maze, maze[getRow()][getCol()], 4);
// get number of enemies
setNoOfEnemies(depthLimitedDFSTraverser.traverseForEnemies(maze, maze[getRow()][getCol()], 4).size());
System.out.println("Enemies Nearby: " + getNoOfEnemies());
// set health in health classifier
healthClassifier.setInputVariable("health", getHealth());
// get the health stat from fuzzy health classifier
String injuriesStatus = healthClassifier.getWinningMembership("injuries");
// get health status
switch (injuriesStatus){
case "none":
healthStatus = 1;
break;
case "minor":
healthStatus = 0.5;
break;
case "serious":
healthStatus = 0;
break;
} // switch
// set the number of enemies in fuzzy logic classifier
enemyStatusClassifier.setInputVariable("enemies", getNoOfEnemies());
// get enemy status
String enemyStat = enemyStatusClassifier.getWinningMembership("enemyStatus");
// get enemy status
switch (enemyStat){
case "ok":
enemyStatus = 0;
break;
case "risky":
enemyStatus = 0.5;
break;
case "tooMany":
enemyStatus = 1;
break;
} // switch
// get sword status
if(getSwords() > 0)
swordStatus = 1;
// get bomb status
if(getBombs() > 0)
bombStatus = 1;
// get combat decision
int result = combatNet.action(healthStatus, swordStatus, bombStatus, enemyStatus);
System.out.println("\n===============================================");
System.out.println("Stats");
System.out.println("HealthStat: " + healthStatus);
System.out.println("SwordStat: " + swordStatus);
System.out.println("BombStat: " + bombStatus);
System.out.println("enemyStatus: " + enemyStatus);
System.out.println("Actual Health: " + getHealth());
System.out.println("===============================================");
// execute decision
switch (result){
case 1: // attack
attack(spider);
break;
case 2: // panic
panic(spider);
break;
case 3: // heal
heal(spider);
break;
default: // run away
runAway(spider);
} // switch
}catch (Exception ex){
// tell spider combat is over
spider.setInCombat(false);
// flag self as not in combat
this.inCombat = false;
} // try
} // startCombat()
private void attack(SpiderNode spider){
System.out.println("===============================================");
System.out.println("Attacking!");
// get spider health
int spiderHealth = spider.getHealth();
System.out.println("Spider Health: " + spiderHealth);
System.out.println("Player Health: " + getHealth());
System.out.println("Player Damage: " + getDamage());
//green spider - Heal player
if(spider.getId()==9){
increaseHealth(20);
}
// use bomb if have one and can't one hit spider
if(spiderHealth > getDamage() && getBombs() > 0){
// use bomb and normal attack
spider.decreaseHealth(getDamage() + bombDamage);
// you have used a bomb
decreaseBombs();
System.out.println("Player Use A Bomb");
} else {
// use normal attack
spider.decreaseHealth(getDamage());
}
// check spiders health
spiderHealth = spider.getHealth();
// check if dead
if(spiderHealth <= 0){
// spider is dead
// not in combat
inCombat = false;
//if attack a yellow spider all yellow turn hostile
if(spider.getId()==13){
SpiderNode.setYellowhostile(true);
}
// remove spider
maze[spider.getRow()][spider.getCol()] = new Node(spider.getRow(), spider.getCol(), -1);
} else {
System.out.println("Damage Taken: " + spiderHealth);
// player takes remaining spider health as damage
decreaseHealth(spiderHealth);
// spider dies
//if attack a yellow spider all yellow turn hostile
if(spider.getId()==13){
SpiderNode.setYellowhostile(true);
}
// not in combat
inCombat = false;
// remove spider
maze[spider.getRow()][spider.getCol()] = new Node(spider.getRow(), spider.getCol(), -1);
}
System.out.println("Player's Health: " + getHealth());
System.out.println("===============================================\n");
} // attack()
private void panic(SpiderNode spider){
System.out.println("===============================================");
System.out.println("Starting to Panic!");
// 50% chance to take damage
if(rand.nextInt(100) > 49){
System.out.println("Took Damage While Panicking!");
System.out.println("Player Health: " + getHealth());
// take small damage
decreaseHealth(10);
// check that player is dead
if(getHealth() <= 0){
// player is dead
isDead = true;
System.out.println("\n===============================================");
System.out.println("Player is Dead!");
System.out.println("===============================================\n");
}
}
System.out.println("===============================================");
// go into attack
attack(spider);
} // panic()
private void heal(SpiderNode spider){
System.out.println("===============================================");
System.out.println("Trying to Heal!");
// 50% chance to heal
if(rand.nextInt(100) > 49) {
System.out.println("Healing!");
// try and flee
flee(spider);
// heal
increaseHealth(10);
// flag spider as in combat
spider.setInCombat(false);
// flag self as in combat
this.inCombat = false;
System.out.println("===============================================");
} else {
System.out.println("Heal Failed!");
System.out.println("===============================================");
// failed, attack
attack(spider);
}
} // heal()
private void runAway(SpiderNode spider){
System.out.println("===============================================");
System.out.println("Trying to Run Away!");
// 50% chance to heal
if(rand.nextInt(100) > 49) {
System.out.println("Running Away!");
// try and flee
flee(spider);
// flag spider as not in combat
spider.setInCombat(false);
// flag self as not in combat
this.inCombat = false;
System.out.println("===============================================");
} else { // run failed!
System.out.println("Running Away Failed!");
System.out.println("===============================================");
// attack!
attack(spider);
}
} // runAway()
// checks for enemies that are right next to the player
private void checkForEnemies(){
Node[] adjacentNodes = null;
List<Node> enemies = new ArrayList<>();
// get the spiders adjacent nodes
adjacentNodes = adjacentNodes(maze);
for (Node n : adjacentNodes) {
// check that the node is an enemy
if (n.getId() > 5) {
// add node to list of enemies
enemies.add(n);
}
}
// check if there are enemies
if(enemies.size() > 0){
// start combat with first enemy
startCombat((SpiderNode) enemies.get(0));
}
} // checkForEnemies()
public void flee(Node enemy){
Node[] adjacentNodes = adjacentNodes(maze);
Node move = null;
int lowestHeurstic=0;
for (Node n : adjacentNodes) {
if(n.getHeuristic(enemy)>lowestHeurstic){
move=n;
}
} // for
// save next move
nextMove=move;
// if there is a place to move
if(nextMove != null) {
// move the player
swapNodes(this, nextMove);
}
} // flee()
public void checkForPickup(){
Node[] adjacentNodes = adjacentNodes(maze);
for (Node n : adjacentNodes) {
if(n.getId()==1){
//sword - increase swords by one
increaseSwords();
//replaces pickup with hedge
n.setId(0);
System.out.println("Picked up a sword");
}
if(n.getId()==2){
//random Pickup
int randNum = rand.nextInt(3) + 1;
switch (randNum){
case 1:
increaseHealth(20);
System.out.println("Random Pickup was +20 Health");
break;
case 2:
increaseSwords();
System.out.println("Random Pickup was a sword");
break;
case 3:
increaseBombs();
System.out.println("Random Pickup was a bomb");
break;
}
//replaces pickup with hedge
n.setId(0);
}
if(n.getId()==3){
//regular bomb - increase bombs by 1
increaseBombs();
//replaces pickup with hedge
n.setId(0);
System.out.println("Picked up a bomb");
}
if(n.getId()==4){
// hydrogen bomb - gives 2 bombs
increaseBombs();
increaseBombs();
//replaces pickup with hedge
n.setId(0);
System.out.println("Picked up a Hydrogen Bomb");
}
} // for
} // flee()
private void swapNodes(Node x, Node y){
int newX, newY, oldX, oldY;
// save indexes
oldX = x.getRow();
oldY = x.getCol();
newX = y.getRow();
newY = y.getCol();
// update X and Y
x.setRow(newX);
x.setCol(newY);
y.setRow(oldX);
y.setCol(oldY);
// randomMove to that node
maze[newX][newY] = x;
// remove self from original spot
maze[oldX][oldY] = y;
} // swapNodes()
public int getHealth() {
return health;
}
public void increaseHealth(int health) {
this.health += health;
if(this.health>100)
this.health=100;
}
public void decreaseHealth(int health) {
this.health -= health;
}
public int getBombs() {
return bombs;
}
public void increaseBombs() {
this.bombs++;
}
public void decreaseBombs() {
this.bombs
if(bombs < 0)
bombs = 0;
}
public int getSwords() {
return swords;
}
public void increaseSwords() {this.swords++;}
public int getNoOfEnemies() {
return noOfEnemies;
}
public void setNoOfEnemies(int noOfEnemies){
this.noOfEnemies = noOfEnemies;
}
// gets the players damage
// includes sword if player has one
public int getDamage(){
int totalDamage = this.damage;
if(swords > 0)
totalDamage += this.swordDamage;
return totalDamage;
} // getDamage()
} |
package model.leveleditor;
import model.Matrix;
import model.drawables.Point;
public class Coordinates {
private final double x;
private final double y;
// Position des Punktes
private double posx;
private double posy;
private double angle;
// Faktor, um den skaliert wird
private int factor;
public Coordinates(double x, double y){
this.x = x;
this.posx = x;
this.y = y;
this.posy = y;
this.angle = 0;
this.factor = 10;
}
public Point getScaledIntCoordinates() {
// Basis Trafo der Koordinatensysteme
int x = (int) ((factor * this.posx) + 0.5);
int y = (int) ((factor * this.posy) + 0.5);
return new Point(x,y);
}
/**
* Nimmt einen Punkt mit int-Koordinaten und setzt damit die Position neu
* @param point Neue Position
*/
public void setScaledIntCoordinates(Point point) {
}
/**
* Rotiert den Punkt um eine Winkel um einen Punkt
* @param angle Winkel, un den rotiert wird
* @param point Punkt, um den Rotiert wird
*/
public void rotation(double angle, Coordinates point){
double[][] translate = {{1, 0, -point.getPosx()},
{0, 1, -point.getPosy()},{0,0,1}};
Matrix translateTo = new Matrix(translate);
translate[0][2] = point.getPosx();
translate[1][3] = point.getPosy();
Matrix translateFrom = new Matrix(translate);
double[][] rotate = {{Math.cos(angle), -Math.sin(angle), 0},
{Math.sin(angle), Math.cos(angle), 0},{0,0,1}};
Matrix rotation = new Matrix(rotate);
double[][] arrPoint = {{this.posx},
{this.posy},{1}};
Matrix matPoint = new Matrix(arrPoint);
matPoint = translateTo.multiply(matPoint);
matPoint = rotation.multiply(matPoint);
matPoint = translateFrom.multiply(matPoint);
this.posx = matPoint.getValue(0, 0);
this.posy = matPoint.getValue(1, 0);
this.angle = this.angle + angle % 2 * Math.PI;
}
public void translateTo(Coordinates point) {
}
/**
* Berechnet die Distanz zu einem anderen Punkt
* @param point Punkt, zu dem die Distanz berechnet wird
* @return Distanz
*/
public double distanceTo(Coordinates point) {
return 0.0;
}
/**
* Addiert einen Punkt auf den aktuellen Punkt
* @param point Punkt, der addiert wird
* @return Summe der Punkte
*/
public Coordinates addCoordinats(Coordinates point) {
return null;
}
public static Coordinates basisChangeDoubleInt() {
return null;
}
public static Coordinates basisChangeIntDouble() {
return null;
}
public double getPosx() {
return posx;
}
public void setPosx(double posx) {
this.posx = posx;
}
public double getPosy() {
return posy;
}
public void setPosy(double posy) {
this.posy = posy;
}
public double getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
} |
package net.katsuster.ememu.test;
import net.katsuster.ememu.generic.*;
import org.junit.*;
public class BusTest {
@Test
public void testAddSlaveCore() throws Exception {
String msg1 = "addSlaveCore() failed.";
String msg2 = "addSlaveCore() address check failed.";
String msg3 = "addSlaveCore() duplicate check failed.";
String msg4 = "addSlaveCore() null check failed.";
Bus bus = new Bus();
RAM16 ram1 = new RAM16(0x1000);
RAM32 ram2 = new RAM32(0x1000);
RAM64 ram3 = new RAM64(0x1000);
try {
bus.addSlaveCore(ram1, 0x0, 0xfff);
bus.addSlaveCore(ram2, 0x8000, 0x8fff);
bus.addSlaveCore(ram3, 0x10000, 0x10fff);
//mirror
bus.addSlaveCore(ram1, 0x2000, 0x2fff);
//over 32bit
bus.addSlaveCore(ram1, 0x100000000L, 0x1ffffffffL);
} catch (Exception e) {
Assert.fail(msg1);
}
try {
//wrong range
bus.addSlaveCore(ram1, 0x1000, 0xff);
Assert.fail(msg2);
} catch (Exception e) {
}
try {
//duplicate
bus.addSlaveCore(ram1, 0x0, 0xfff);
Assert.fail(msg3);
} catch (Exception e) {
}
try {
//null
bus.addSlaveCore(null, 0x0, 0xfff);
Assert.fail(msg4);
} catch (Exception e) {
}
}
@Test
public void testGetSlaveCore() throws Exception {
String msg1 = "getSlaveCore() failed.";
String msg2 = "getSlaveCore() non-exist check failed.";
String msg3 = "getSlaveCore() address check failed.";
Bus bus = new Bus();
RAM16 ram1 = new RAM16(0x1000);
RAM32 ram2 = new RAM32(0x1000);
bus.addSlaveCore(ram1, 0x0, 0xfff);
bus.addSlaveCore(ram1, 0x100000000L, 0x100000fffL);
bus.addSlaveCore(ram2, 0x20000, 0x207ff);
//simple
Assert.assertEquals(msg1, ram1, bus.getSlaveCore(0x100, 0x200));
Assert.assertEquals(msg1, ram1, bus.getSlaveCore(0x100000100L, 0x100000200L));
Assert.assertEquals(msg1, ram2, bus.getSlaveCore(0x20100, 0x20200));
//non-exist
Assert.assertNull(msg2, bus.getSlaveCore(0x1000, 0x1100));
Assert.assertNull(msg2, bus.getSlaveCore(0x100001000L, 0x100001100L));
Assert.assertNull(msg2, bus.getSlaveCore(0x20800, 0x20900));
try {
//wrong range
bus.getSlaveCore(0x100, 0x80);
Assert.fail(msg3);
} catch (Exception e) {
}
try {
//wrong range
bus.getSlaveCore(0x4000, 0x3000);
Assert.fail(msg3);
} catch (Exception e) {
}
}
@Test
public void testRemoveSlaveCore() throws Exception {
String msg1 = "removeSlaveCore() failed.";
String msg2 = "removeSlaveCore() re-add failed.";
String msg3 = "removeSlaveCore(null) ignore failed.";
Bus bus = new Bus();
RAM16 ram1 = new RAM16(0x1000);
RAM32 ram2 = new RAM32(0x1000);
RAM64 ram3 = new RAM64(0x1000);
boolean result;
bus.addSlaveCore(ram1, 0x0, 0xfff);
bus.addSlaveCore(ram1, 0x2000, 0x7fff);
bus.addSlaveCore(ram2, 0x8000, 0x8fff);
bus.addSlaveCore(ram3, 0x10000, 0x10fff);
try {
//simple
result = bus.removeSlaveCore(ram1);
Assert.assertTrue(msg1, result);
result = bus.removeSlaveCore(ram2);
Assert.assertTrue(msg1, result);
result = bus.removeSlaveCore(ram3);
Assert.assertTrue(msg1, result);
//non exist
result = bus.removeSlaveCore(ram1);
Assert.assertFalse(msg1, result);
} catch (Exception e) {
Assert.fail(msg1);
}
try {
//re-add
bus.addSlaveCore(ram1, 0x0, 0xfff);
bus.addSlaveCore(ram1, 0x20000, 0x20fff);
} catch (Exception e) {
Assert.fail(msg2);
}
try {
result = bus.removeSlaveCore(null);
Assert.assertFalse(msg3, result);
} catch (Exception e) {
Assert.fail(msg1);
}
}
@Test
public void testAlignedAccess() throws Exception {
Bus bus = new Bus();
RAM16 ram16 = new RAM16(0x3000);
RAM32 ram32 = new RAM32(0x3000);
RAM64 ram64 = new RAM64(0x3000);
bus.addSlaveCore(ram16, 0x10000, 0x12fff);
bus.addSlaveCore(ram32, 0x13000, 0x15fff);
bus.addSlaveCore(ram64, 0x16000, 0x18fff);
bus.addSlaveCore(ram16, 0x100000000L, 0x100002fffL);
bus.addSlaveCore(ram32, 0x100003000L, 0x100005fffL);
bus.addSlaveCore(ram64, 0x100006000L, 0x100008fffL);
//Aligned
unalignedAccess(0x10ff0, bus);
unalignedAccess(0x12ff0, bus);
unalignedAccess(0x14ff0, bus);
//Unaligned
for (int i = 0; i < 8; i++) {
unalignedAccess(0x11ff0 + i, bus);
unalignedAccess(0x13ff0 + i, bus);
unalignedAccess(0x15ff0 + i, bus);
}
}
public void unalignedAccess(long start, Bus bus) throws Exception {
unalignedAccess8(start, bus);
unalignedAccess16(start, bus);
unalignedAccess32(start, bus);
unalignedAccess64(start, bus);
}
public void unalignedAccess8(long start, Bus bus) throws Exception {
String msg1 = "Bus unaligned access 8bits failed.";
byte[] actual8 = {
(byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67,
(byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef,
(byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78,
(byte)0x9a, (byte)0xbc, (byte)0xde, (byte)0xf9,
(byte)0x01, (byte)0x23, (byte)0x67, (byte)0xcd,
(byte)0x89, (byte)0xab, (byte)0xef, (byte)0x45,
(byte)0x12, (byte)0x56, (byte)0x78, (byte)0xbc,
(byte)0x9a, (byte)0xde, (byte)0xf9, (byte)0x34,
};
for (int i = 0; i < actual8.length; i++) {
bus.write8(start + i, actual8[i]);
}
long[] expected8_8= {
0x01L, 0x23L, 0x45L, 0x67L, 0x89L, 0xabL, 0xcdL, 0xefL,
0x12L, 0x34L, 0x56L, 0x78L, 0x9aL, 0xbcL, 0xdeL, 0xf9L,
0x01L, 0x23L, 0x67L, 0xcdL, 0x89L, 0xabL, 0xefL, 0x45L,
0x12L, 0x56L, 0x78L, 0xbcL, 0x9aL, 0xdeL, 0xf9L, 0x34L,
};
for (int i = 0; i < expected8_8.length; i++) {
Assert.assertEquals(msg1, expected8_8[i], bus.read8(start + i) & 0xffL);
}
long[] expected8_16 = {
0x2301L, 0x6745L, 0xab89L, 0xefcdL,
0x3412L, 0x7856L, 0xbc9aL, 0xf9deL,
0x2301L, 0xcd67L, 0xab89L, 0x45efL,
0x5612L, 0xbc78L, 0xde9aL, 0x34f9L,
};
for (int i = 0; i < expected8_16.length; i++) {
Assert.assertEquals(msg1, expected8_16[i], bus.read_ua16(start + i * 2) & 0xffffL);
}
long[] expected8_32 = {
0x67452301L, 0xefcdab89L, 0x78563412L, 0xf9debc9aL,
0xcd672301L, 0x45efab89L, 0xbc785612L, 0x34f9de9aL,
};
for (int i = 0; i < expected8_32.length; i++) {
Assert.assertEquals(msg1, expected8_32[i], bus.read_ua32(start + i * 4) & 0xffffffffL);
}
long[] expected8_64 = {
0xefcdab8967452301L, 0xf9debc9a78563412L,
0x45efab89cd672301L, 0x34f9de9abc785612L,
};
for (int i = 0; i < expected8_64.length; i++) {
Assert.assertEquals(msg1, expected8_64[i], bus.read_ua64(start + i * 8));
}
}
public void unalignedAccess16(long start, Bus bus) throws Exception {
String msg1 = "Bus unaligned access 16bits failed.";
short[] actual16 = {
(short)0x0123, (short)0x4567, (short)0x89ab, (short)0xcdef,
(short)0x1234, (short)0x5678, (short)0x9abc, (short)0xdef9,
(short)0x4567, (short)0x89ab, (short)0xcdef, (short)0x0123,
(short)0xdef9, (short)0x1234, (short)0x5678, (short)0x9abc,
};
for (int i = 0; i < actual16.length; i++) {
bus.write_ua16(start + i * 2, actual16[i]);
}
long[] expected16_8 = {
0x23L, 0x01L, 0x67L, 0x45L, 0xabL, 0x89L, 0xefL, 0xcdL,
0x34L, 0x12L, 0x78L, 0x56L, 0xbcL, 0x9aL, 0xf9L, 0xdeL,
0x67L, 0x45L, 0xabL, 0x89L, 0xefL, 0xcdL, 0x23L, 0x01L,
0xf9L, 0xdeL, 0x34L, 0x12L, 0x78L, 0x56L, 0xbcL, 0x9aL,
};
for (int i = 0; i < expected16_8.length; i++) {
Assert.assertEquals(msg1, expected16_8[i], bus.read8(start + i) & 0xffL);
}
long[] expected16_16 = {
0x0123L, 0x4567L, 0x89abL, 0xcdefL,
0x1234L, 0x5678L, 0x9abcL, 0xdef9L,
0x4567L, 0x89abL, 0xcdefL, 0x0123L,
0xdef9L, 0x1234L, 0x5678L, 0x9abcL,
};
for (int i = 0; i < expected16_16.length; i++) {
Assert.assertEquals(msg1, expected16_16[i], bus.read_ua16(start + i * 2) & 0xffffL);
}
long[] expected16_32 = {
0x45670123L, 0xcdef89abL, 0x56781234L, 0xdef99abcL,
0x89ab4567L, 0x0123cdefL, 0x1234def9L, 0x9abc5678L,
};
for (int i = 0; i < expected16_32.length; i++) {
Assert.assertEquals(msg1, expected16_32[i], bus.read_ua32(start + i * 4) & 0xffffffffL);
}
long[] expected16_64 = {
0xcdef89ab45670123L, 0xdef99abc56781234L,
0x0123cdef89ab4567L, 0x9abc56781234def9L,
};
for (int i = 0; i < expected16_64.length; i++) {
Assert.assertEquals(msg1, expected16_64[i], bus.read_ua64(start + i * 8));
}
}
public void unalignedAccess32(long start, Bus bus) throws Exception {
String msg1 = "Bus unaligned access 32bits failed.";
int[] actual32 = {
0x01234567, 0x89abcdef, 0x12345678, 0x9abcdef9,
0x23456789, 0xabcdef12, 0x3456789a, 0xbcdef9ba,
};
for (int i = 0; i < actual32.length; i++) {
bus.write_ua32(start + i * 4, actual32[i]);
}
long[] expected32_8 = {
0x67L, 0x45L, 0x23L, 0x01L, 0xefL, 0xcdL, 0xabL, 0x89L,
0x78L, 0x56L, 0x34L, 0x12L, 0xf9L, 0xdeL, 0xbcL, 0x9aL,
0x89L, 0x67L, 0x45L, 0x23L, 0x12L, 0xefL, 0xcdL, 0xabL,
0x9aL, 0x78L, 0x56L, 0x34L, 0xbaL, 0xf9L, 0xdeL, 0xbcL,
};
for (int i = 0; i < expected32_8.length; i++) {
Assert.assertEquals(msg1, expected32_8[i], bus.read8(start + i) & 0xffL);
}
long[] expected32_16 = {
0x4567L, 0x0123L, 0xcdefL, 0x89abL,
0x5678L, 0x1234L, 0xdef9L, 0x9abcL,
0x6789L, 0x2345L, 0xef12L, 0xabcdL,
0x789aL, 0x3456L, 0xf9baL, 0xbcdeL,
};
for (int i = 0; i < expected32_16.length; i++) {
Assert.assertEquals(msg1, expected32_16[i], bus.read_ua16(start + i * 2) & 0xffffL);
}
long[] expected32_32 = {
0x01234567L, 0x89abcdefL, 0x12345678L, 0x9abcdef9L,
0x23456789L, 0xabcdef12L, 0x3456789aL, 0xbcdef9baL,
};
for (int i = 0; i < expected32_32.length; i++) {
Assert.assertEquals(msg1, expected32_32[i], bus.read_ua32(start + i * 4) & 0xffffffffL);
}
long[] expected32_64 = {
0x89abcdef01234567L, 0x9abcdef912345678L,
0xabcdef1223456789L, 0xbcdef9ba3456789aL,
};
for (int i = 0; i < expected32_64.length; i++) {
Assert.assertEquals(msg1, expected32_64[i], bus.read_ua64(start + i * 8));
}
}
public void unalignedAccess64(long start, Bus bus) throws Exception {
String msg1 = "Bus unaligned access 64bits failed.";
long[] actual64 = {
0x0123456789abcdefL, 0x89abcdeffedcba98L,
0x23456789abcdef89L, 0xabcdeffedcba9801L,
};
for (int i = 0; i < actual64.length; i++) {
bus.write_ua64(start + i * 8, actual64[i]);
}
long[] expected64_8 = {
0xefL, 0xcdL, 0xabL, 0x89L, 0x67L, 0x45L, 0x23L, 0x01L,
0x98L, 0xbaL, 0xdcL, 0xfeL, 0xefL, 0xcdL, 0xabL, 0x89L,
0x89L, 0xefL, 0xcdL, 0xabL, 0x89L, 0x67L, 0x45L, 0x23L,
0x01L, 0x98L, 0xbaL, 0xdcL, 0xfeL, 0xefL, 0xcdL, 0xabL,
};
for (int i = 0; i < expected64_8.length; i++) {
Assert.assertEquals(msg1, expected64_8[i], bus.read8(start + i) & 0xffL);
}
long[] expected64_16 = {
0xcdefL, 0x89abL, 0x4567L, 0x0123L,
0xba98L, 0xfedcL, 0xcdefL, 0x89abL,
0xef89L, 0xabcdL, 0x6789L, 0x2345L,
0x9801L, 0xdcbaL, 0xeffeL, 0xabcdL,
};
for (int i = 0; i < expected64_16.length; i++) {
Assert.assertEquals(msg1, expected64_16[i], bus.read_ua16(start + i * 2) & 0xffffL);
}
long[] expected64_32 = {
0x89abcdefL, 0x01234567L, 0xfedcba98L, 0x89abcdefL,
0xabcdef89L, 0x23456789L, 0xdcba9801L, 0xabcdeffeL,
};
for (int i = 0; i < expected64_32.length; i++) {
Assert.assertEquals(msg1, expected64_32[i], bus.read_ua32(start + i * 4) & 0xffffffffL);
}
long[] expected64_64 = {
0x0123456789abcdefL, 0x89abcdeffedcba98L,
0x23456789abcdef89L, 0xabcdeffedcba9801L,
};
for (int i = 0; i < expected64_64.length; i++) {
Assert.assertEquals(msg1, expected64_64[i], bus.read_ua64(start + i * 8));
}
}
} |
package com.docker.utils;
import chat.main.ServerStart;
import com.docker.file.adapters.GridFSFileHandler;
import com.docker.server.OnlineServer;
import com.docker.storage.DBException;
import com.docker.storage.mongodb.MongoHelper;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFileFilter;
import script.file.FileAdapter;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class DeployServiceUtils {
public static void main(String[] args) throws Exception {
CommandLineParser parser = new PosixParser();
Options opt = new Options();
opt.addOption("h", "help", false, "help")
.addOption("p",true, "Service path")
// .addOption("a",true, "async servlet map")
.addOption("l",true, "Dependency library path")
.addOption("x",true, "Prefix name")
.addOption("d",true, "Docker name")
.addOption("s",true, "Service name")
.addOption("f",true, "Mongodb GridFS host, or other dfs host")
.addOption("v",true, "Version");
org.apache.commons.cli.CommandLine line = parser.parse(opt, args);
System.out.println("commandLine " + Arrays.toString(args));
List<String> argList = line.getArgList();
if (line.hasOption('h') || line.hasOption("help")) {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("DeployServiceUtils[options:]", opt, false);
return;
}
String prefix = null;
String servicePath = null;
String dockerName = null;
String serviceName = null;
String gridfsHost = null;
String versionStr = null;
String libPath = null;
if(line.hasOption('x')){
prefix = line.getOptionValue('x');
}
if(line.hasOption('p')){
servicePath = line.getOptionValue('p');
}else{
HelpFormatter hf = new HelpFormatter();
hf.printHelp("DeployServiceUtils[options:]", opt, false);
return;
}
if(line.hasOption('l')){
libPath = line.getOptionValue('l');
}
if(line.hasOption('d')){
dockerName = line.getOptionValue('d');
} else {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("DeployServiceUtils[options:]", opt, false);
return;
}
if(line.hasOption('s')){
serviceName = line.getOptionValue('s');
} else {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("DeployServiceUtils[options:]", opt, false);
return;
}
if(line.hasOption('f')){
gridfsHost = line.getOptionValue('f');
}else {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("DeployServiceUtils[options:]", opt, false);
return;
}
Integer version = null;
if(line.hasOption('v')){
versionStr = line.getOptionValue('v');
try {
version = Integer.valueOf(versionStr);
} catch(Exception e) {}
}
deploy(prefix, servicePath, dockerName, serviceName, gridfsHost, version, libPath);
}
public static void deploy(String prefix, String servicePath, String dockerName, String serviceName, String gridfsHost, Integer version) throws Exception {
deploy(prefix, servicePath, dockerName, serviceName, gridfsHost, version, null);
}
public static void deploy(String prefix, String servicePath, String dockerName, String serviceName, String gridfsHost, Integer version, String libPath) throws Exception {
File deploy = new File(servicePath + "/build/deploy/classes");
File root = new File(servicePath + "/build/deploy");
FileUtils.deleteDirectory(root);
//copy libs
if(libPath != null) {
// List<String> libPathList = new ArrayList<>();
String[] libPaths = libPath.split(",");
for(String libP : libPaths) {
File libGroovyFile = new File(libP + "/src/main/groovy");
if(libGroovyFile.isDirectory() && libGroovyFile.exists())
FileUtils.copyDirectory(libGroovyFile, deploy);
File libResourceFile = new File(libP + "/src/main/resources");
if(libResourceFile.exists() && libResourceFile.isDirectory())
FileUtils.copyDirectory(libResourceFile, deploy);
}
}
//copy source
File groovyFile = new File(servicePath + "/src/main/groovy");
if(groovyFile.isDirectory() && groovyFile.exists()) {
FileUtils.copyDirectory(groovyFile, deploy);
}
File resourceFile = new File(servicePath + "/src/main/resources");
if(resourceFile.exists() && resourceFile.isDirectory()) {
FileUtils.copyDirectory(resourceFile, deploy);
}
if(version != null)
serviceName = serviceName + "_v" + version;
doZip(new File(FilenameUtils.separatorsToUnix(root.getAbsolutePath()) + (prefix != null ? "/" + prefix : "") + "/" + dockerName + "/" + serviceName + "/groovy.zip"), deploy);
// clean(deploy, ".zip");
FileUtils.deleteQuietly(deploy);
File[] toRemoveEmptyFolders = root.listFiles();
for(File findEmptyFolder : toRemoveEmptyFolders) {
if(getAllEmptyFoldersOfDir(findEmptyFolder)) {
FileUtils.deleteDirectory(findEmptyFolder);
}
}
// if(true)
// return;
MongoHelper helper = new MongoHelper();
helper.setHost(gridfsHost);
helper.setDbName("gridfiles");
// helper.setUsername("socialshopsim");
// helper.setPassword("eDANviLHQtjwmFlywyKu");
helper.init();
// helper.setUsername();
GridFSFileHandler fileHandler = new GridFSFileHandler();
fileHandler.setResourceHelper(helper);
fileHandler.setBucketName("imfs");
fileHandler.init();
File directory = new File(servicePath + "/build/deploy");
// File directory = new File("/home/aplomb/dev/github/DiscoveryService/deploy");
Collection<File> files = FileUtils.listFiles(directory, new String[]{"zip"}, true);
if(files != null) {
for(File file : files) {
String filePath = FilenameUtils.separatorsToUnix(file.getAbsolutePath());
String dirPath = FilenameUtils.separatorsToUnix(directory.getAbsolutePath());
String thePath = filePath.substring(dirPath.length());
// System.out.println("file " + thePath);
FileAdapter.PathEx path = new FileAdapter.PathEx(thePath);
fileHandler.saveFile(FileUtils.openInputStream(new File(filePath)), path, FileAdapter.FileReplaceStrategy.REPLACE);
System.out.println("File " + thePath + " saved!");
}
}
}
static boolean getAllEmptyFoldersOfDir(File current){
if(current.isDirectory()){
File[] files = current.listFiles();
if(files.length == 0){ //There is no file in this folder - safe to delete
System.out.println("Safe to delete - empty folder: " + FilenameUtils.separatorsToUnix(current.getAbsolutePath()));
return true;
} else {
int totalFolderCount = 0;
int emptyFolderCount = 0;
for(File f : files){
if(f.isDirectory()){
totalFolderCount++;
if(getAllEmptyFoldersOfDir(f)){ //safe to delete
emptyFolderCount++;
}
}
}
if(totalFolderCount == files.length && emptyFolderCount == totalFolderCount){ //only if all folders are safe to delete then this folder is also safe to delete
System.out.println("Safe to delete - all subfolders are empty: " + FilenameUtils.separatorsToUnix(current.getAbsolutePath()));
return true;
}
}
}
return false;
}
public static void clean(File folder, String endWith) {
Collection<File> fList = FileUtils.listFiles(folder, null, true);
for (File file : fList) {
if (file.isFile() && !file.getName().endsWith(endWith)) {
// file.delete();
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtils.listFiles(folder, new FileFileFilter(){}, new DirectoryFileFilter(){
public boolean accept(File file) {
if(file.isDirectory()) {
Collection<File> hasFiles = FileUtils.listFiles(file, null, true);
if(hasFiles == null || hasFiles.isEmpty()) {
// file.delete();
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
});
}
public static void doZip(File zipFile, File zipDirectory){//zipDirectoryPath:
File file;
File zipDir;
zipDir = zipDirectory;
try{
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(FileUtils.openOutputStream(zipFile)));
handleDir(zipDir, zipDir, zipOut, zipFile);
zipOut.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//doZip,
private static void handleDir(File root, File dir , ZipOutputStream zipOut, File zipFile)throws IOException{
FileInputStream fileIn;
File[] files;
files = dir.listFiles();
if(files.length == 0){
//ZipEntryisDirectory(),"/".
zipOut.putNextEntry(new ZipEntry(dir.toString() + "/"));
zipOut.closeEntry();
}
else{
for(File fileName : files){
//System.out.println(fileName);
int readedBytes;
byte[] buf = new byte[64 * 1024];
if(fileName.isDirectory()){
handleDir(root, fileName , zipOut, zipFile);
}
else if(!fileName.getAbsolutePath().equals(zipFile.getAbsolutePath())){
fileIn = new FileInputStream(fileName);
String zipPath = FilenameUtils.separatorsToUnix(fileName.getAbsolutePath()).substring(FilenameUtils.separatorsToUnix(root.getAbsolutePath()).length());
if(zipPath.startsWith("/"))
zipPath = zipPath.substring(1);
zipOut.putNextEntry(new ZipEntry(zipPath));
while((readedBytes = fileIn.read(buf))>0){
zipOut.write(buf , 0 , readedBytes);
}
zipOut.closeEntry();
}
}
}
}
} |
package com.jme3.renderer;
import com.jme3.bounding.BoundingBox;
import com.jme3.bounding.BoundingVolume;
import com.jme3.export.*;
import com.jme3.math.*;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>Camera</code> is a standalone, purely mathematical class for doing
* camera-related computations.
*
* <p>
* Given input data such as location, orientation (direction, left, up),
* and viewport settings, it can compute data necessary to render objects
* with the graphics library. Two matrices are generated, the view matrix
* transforms objects from world space into eye space, while the projection
* matrix transforms objects from eye space into clip space.
* </p>
* <p>Another purpose of the camera class is to do frustum culling operations,
* defined by six planes which define a 3D frustum shape, it is possible to
* test if an object bounded by a mathematically defined volume is inside
* the camera frustum, and thus to avoid rendering objects that are outside
* the frustum
* </p>
*
* @author Mark Powell
* @author Joshua Slack
*/
public class Camera implements Savable, Cloneable {
private static final Logger logger = Logger.getLogger(Camera.class.getName());
/**
* The <code>FrustumIntersect</code> enum is returned as a result
* of a culling check operation,
* see {@link #contains(com.jme3.bounding.BoundingVolume) }
*/
public enum FrustumIntersect {
/**
* defines a constant assigned to spatials that are completely outside
* of this camera's view frustum.
*/
Outside,
/**
* defines a constant assigned to spatials that are completely inside
* the camera's view frustum.
*/
Inside,
/**
* defines a constant assigned to spatials that are intersecting one of
* the six planes that define the view frustum.
*/
Intersects;
}
/**
* LEFT_PLANE represents the left plane of the camera frustum.
*/
private static final int LEFT_PLANE = 0;
/**
* RIGHT_PLANE represents the right plane of the camera frustum.
*/
private static final int RIGHT_PLANE = 1;
/**
* BOTTOM_PLANE represents the bottom plane of the camera frustum.
*/
private static final int BOTTOM_PLANE = 2;
/**
* TOP_PLANE represents the top plane of the camera frustum.
*/
private static final int TOP_PLANE = 3;
/**
* FAR_PLANE represents the far plane of the camera frustum.
*/
private static final int FAR_PLANE = 4;
/**
* NEAR_PLANE represents the near plane of the camera frustum.
*/
private static final int NEAR_PLANE = 5;
/**
* FRUSTUM_PLANES represents the number of planes of the camera frustum.
*/
private static final int FRUSTUM_PLANES = 6;
/**
* MAX_WORLD_PLANES holds the maximum planes allowed by the system.
*/
private static final int MAX_WORLD_PLANES = 6;
/**
* Camera's location
*/
protected Vector3f location;
/**
* The orientation of the camera.
*/
protected Quaternion rotation;
/**
* Distance from camera to near frustum plane.
*/
protected float frustumNear;
/**
* Distance from camera to far frustum plane.
*/
protected float frustumFar;
/**
* Distance from camera to left frustum plane.
*/
protected float frustumLeft;
/**
* Distance from camera to right frustum plane.
*/
protected float frustumRight;
/**
* Distance from camera to top frustum plane.
*/
protected float frustumTop;
/**
* Distance from camera to bottom frustum plane.
*/
protected float frustumBottom;
//Temporary values computed in onFrustumChange that are needed if a
//call is made to onFrameChange.
protected float[] coeffLeft;
protected float[] coeffRight;
protected float[] coeffBottom;
protected float[] coeffTop;
//view port coordinates
/**
* Percent value on display where horizontal viewing starts for this camera.
* Default is 0.
*/
protected float viewPortLeft;
/**
* Percent value on display where horizontal viewing ends for this camera.
* Default is 1.
*/
protected float viewPortRight;
/**
* Percent value on display where vertical viewing ends for this camera.
* Default is 1.
*/
protected float viewPortTop;
/**
* Percent value on display where vertical viewing begins for this camera.
* Default is 0.
*/
protected float viewPortBottom;
/**
* Array holding the planes that this camera will check for culling.
*/
protected Plane[] worldPlane;
/**
* A mask value set during contains() that allows fast culling of a Node's
* children.
*/
private int planeState;
protected int width;
protected int height;
protected boolean viewportChanged = true;
/**
* store the value for field parallelProjection
*/
private boolean parallelProjection = true;
protected Matrix4f projectionMatrixOverride;
protected Matrix4f viewMatrix = new Matrix4f();
protected Matrix4f projectionMatrix = new Matrix4f();
protected Matrix4f viewProjectionMatrix = new Matrix4f();
private BoundingBox guiBounding = new BoundingBox();
/** The camera's name. */
protected String name;
/**
* Serialization only. Do not use.
*/
public Camera() {
worldPlane = new Plane[MAX_WORLD_PLANES];
for (int i = 0; i < MAX_WORLD_PLANES; i++) {
worldPlane[i] = new Plane();
}
}
/**
* Constructor instantiates a new <code>Camera</code> object. All
* values of the camera are set to default.
*/
public Camera(int width, int height) {
this();
location = new Vector3f();
rotation = new Quaternion();
frustumNear = 1.0f;
frustumFar = 2.0f;
frustumLeft = -0.5f;
frustumRight = 0.5f;
frustumTop = 0.5f;
frustumBottom = -0.5f;
coeffLeft = new float[2];
coeffRight = new float[2];
coeffBottom = new float[2];
coeffTop = new float[2];
viewPortLeft = 0.0f;
viewPortRight = 1.0f;
viewPortTop = 1.0f;
viewPortBottom = 0.0f;
this.width = width;
this.height = height;
onFrustumChange();
onViewPortChange();
onFrameChange();
logger.log(Level.INFO, "Camera created (W: {0}, H: {1})", new Object[]{width, height});
}
@Override
public Camera clone() {
try {
Camera cam = (Camera) super.clone();
cam.viewportChanged = true;
cam.planeState = 0;
cam.worldPlane = new Plane[MAX_WORLD_PLANES];
for (int i = 0; i < worldPlane.length; i++) {
cam.worldPlane[i] = worldPlane[i].clone();
}
cam.coeffLeft = new float[2];
cam.coeffRight = new float[2];
cam.coeffBottom = new float[2];
cam.coeffTop = new float[2];
cam.location = location.clone();
cam.rotation = rotation.clone();
if (projectionMatrixOverride != null) {
cam.projectionMatrixOverride = projectionMatrixOverride.clone();
}
cam.viewMatrix = viewMatrix.clone();
cam.projectionMatrix = projectionMatrix.clone();
cam.viewProjectionMatrix = viewProjectionMatrix.clone();
cam.guiBounding = (BoundingBox) guiBounding.clone();
cam.update();
return cam;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
/**
* This method copise the settings of the given camera.
*
* @param cam
* the camera we copy the settings from
*/
public void copyFrom(Camera cam) {
location.set(cam.location);
rotation.set(cam.rotation);
frustumNear = cam.frustumNear;
frustumFar = cam.frustumFar;
frustumLeft = cam.frustumLeft;
frustumRight = cam.frustumRight;
frustumTop = cam.frustumTop;
frustumBottom = cam.frustumBottom;
coeffLeft[0] = cam.coeffLeft[0];
coeffLeft[1] = cam.coeffLeft[1];
coeffRight[0] = cam.coeffRight[0];
coeffRight[1] = cam.coeffRight[1];
coeffBottom[0] = cam.coeffBottom[0];
coeffBottom[1] = cam.coeffBottom[1];
coeffTop[0] = cam.coeffTop[0];
coeffTop[1] = cam.coeffTop[1];
viewPortLeft = cam.viewPortLeft;
viewPortRight = cam.viewPortRight;
viewPortTop = cam.viewPortTop;
viewPortBottom = cam.viewPortBottom;
this.width = cam.width;
this.height = cam.height;
this.planeState = cam.planeState;
this.viewportChanged = cam.viewportChanged;
for (int i = 0; i < MAX_WORLD_PLANES; ++i) {
worldPlane[i].setNormal(cam.worldPlane[i].getNormal());
worldPlane[i].setConstant(cam.worldPlane[i].getConstant());
}
this.parallelProjection = cam.parallelProjection;
if(cam.projectionMatrixOverride != null) {
if(this.projectionMatrixOverride == null) {
this.projectionMatrixOverride = cam.projectionMatrixOverride.clone();
} else {
this.projectionMatrixOverride.set(cam.projectionMatrixOverride);
}
} else {
this.projectionMatrixOverride = null;
}
this.viewMatrix.set(cam.viewMatrix);
this.projectionMatrix.set(cam.projectionMatrix);
this.viewProjectionMatrix.set(cam.viewProjectionMatrix);
this.guiBounding.setXExtent(cam.guiBounding.getXExtent());
this.guiBounding.setYExtent(cam.guiBounding.getYExtent());
this.guiBounding.setZExtent(cam.guiBounding.getZExtent());
this.guiBounding.setCenter(cam.guiBounding.getCenter());
this.guiBounding.setCheckPlane(cam.guiBounding.getCheckPlane());
this.name = cam.name;
}
/**
* This method sets the cameras name.
* @param name the cameras name
*/
public void setName(String name) {
this.name = name;
}
/**
* This method returns the cameras name.
* @return the cameras name
*/
public String getName() {
return name;
}
public void setClipPlane(Plane clipPlane, Plane.Side side) {
float sideFactor = 1;
if (side == Plane.Side.Negative) {
sideFactor = -1;
}
//we are on the other side of the plane no need to clip anymore.
if (clipPlane.whichSide(location) == side) {
return;
}
Matrix4f p = projectionMatrix.clone();
Matrix4f ivm = viewMatrix.clone();
Vector3f point = clipPlane.getNormal().mult(clipPlane.getConstant());
Vector3f pp = ivm.mult(point);
Vector3f pn = ivm.multNormal(clipPlane.getNormal(), null);
Vector4f clipPlaneV = new Vector4f(pn.x * sideFactor, pn.y * sideFactor, pn.z * sideFactor, -(pp.dot(pn)) * sideFactor);
Vector4f v = new Vector4f(0, 0, 0, 0);
v.x = (Math.signum(clipPlaneV.x) + p.m02) / p.m00;
v.y = (Math.signum(clipPlaneV.y) + p.m12) / p.m11;
v.z = -1.0f;
v.w = (1.0f + p.m22) / p.m23;
float dot = clipPlaneV.dot(v);//clipPlaneV.x * v.x + clipPlaneV.y * v.y + clipPlaneV.z * v.z + clipPlaneV.w * v.w;
Vector4f c = clipPlaneV.mult(2.0f / dot);
p.m20 = c.x - p.m30;
p.m21 = c.y - p.m31;
p.m22 = c.z - p.m32;
p.m23 = c.w - p.m33;
setProjectionMatrix(p);
}
public void setClipPlane(Plane clipPlane) {
setClipPlane(clipPlane, clipPlane.whichSide(location));
}
/**
* Resizes this camera's view with the given width and height. This is
* similar to constructing a new camera, but reusing the same Object. This
* method is called by an associated {@link RenderManager} to notify the camera of
* changes in the display dimensions.
*
* @param width the view width
* @param height the view height
* @param fixAspect If true, the camera's aspect ratio will be recomputed.
* Recomputing the aspect ratio requires changing the frustum values.
*/
public void resize(int width, int height, boolean fixAspect) {
this.width = width;
this.height = height;
onViewPortChange();
if (fixAspect /*&& !parallelProjection*/) {
frustumRight = frustumTop * ((float) width / height);
frustumLeft = -frustumRight;
onFrustumChange();
}
}
/**
* <code>getFrustumBottom</code> returns the value of the bottom frustum
* plane.
*
* @return the value of the bottom frustum plane.
*/
public float getFrustumBottom() {
return frustumBottom;
}
/**
* <code>setFrustumBottom</code> sets the value of the bottom frustum
* plane.
*
* @param frustumBottom the value of the bottom frustum plane.
*/
public void setFrustumBottom(float frustumBottom) {
this.frustumBottom = frustumBottom;
onFrustumChange();
}
/**
* <code>getFrustumFar</code> gets the value of the far frustum plane.
*
* @return the value of the far frustum plane.
*/
public float getFrustumFar() {
return frustumFar;
}
/**
* <code>setFrustumFar</code> sets the value of the far frustum plane.
*
* @param frustumFar the value of the far frustum plane.
*/
public void setFrustumFar(float frustumFar) {
this.frustumFar = frustumFar;
onFrustumChange();
}
/**
* <code>getFrustumLeft</code> gets the value of the left frustum plane.
*
* @return the value of the left frustum plane.
*/
public float getFrustumLeft() {
return frustumLeft;
}
/**
* <code>setFrustumLeft</code> sets the value of the left frustum plane.
*
* @param frustumLeft the value of the left frustum plane.
*/
public void setFrustumLeft(float frustumLeft) {
this.frustumLeft = frustumLeft;
onFrustumChange();
}
/**
* <code>getFrustumNear</code> gets the value of the near frustum plane.
*
* @return the value of the near frustum plane.
*/
public float getFrustumNear() {
return frustumNear;
}
/**
* <code>setFrustumNear</code> sets the value of the near frustum plane.
*
* @param frustumNear the value of the near frustum plane.
*/
public void setFrustumNear(float frustumNear) {
this.frustumNear = frustumNear;
onFrustumChange();
}
/**
* <code>getFrustumRight</code> gets the value of the right frustum plane.
*
* @return frustumRight the value of the right frustum plane.
*/
public float getFrustumRight() {
return frustumRight;
}
/**
* <code>setFrustumRight</code> sets the value of the right frustum plane.
*
* @param frustumRight the value of the right frustum plane.
*/
public void setFrustumRight(float frustumRight) {
this.frustumRight = frustumRight;
onFrustumChange();
}
/**
* <code>getFrustumTop</code> gets the value of the top frustum plane.
*
* @return the value of the top frustum plane.
*/
public float getFrustumTop() {
return frustumTop;
}
/**
* <code>setFrustumTop</code> sets the value of the top frustum plane.
*
* @param frustumTop the value of the top frustum plane.
*/
public void setFrustumTop(float frustumTop) {
this.frustumTop = frustumTop;
onFrustumChange();
}
/**
* <code>getLocation</code> retrieves the location vector of the camera.
*
* @return the position of the camera.
* @see Camera#getLocation()
*/
public Vector3f getLocation() {
return location;
}
/**
* <code>getRotation</code> retrieves the rotation quaternion of the camera.
*
* @return the rotation of the camera.
*/
public Quaternion getRotation() {
return rotation;
}
/**
* <code>getDirection</code> retrieves the direction vector the camera is
* facing.
*
* @return the direction the camera is facing.
* @see Camera#getDirection()
*/
public Vector3f getDirection() {
return rotation.getRotationColumn(2);
}
/**
* <code>getLeft</code> retrieves the left axis of the camera.
*
* @return the left axis of the camera.
* @see Camera#getLeft()
*/
public Vector3f getLeft() {
return rotation.getRotationColumn(0);
}
/**
* <code>getUp</code> retrieves the up axis of the camera.
*
* @return the up axis of the camera.
* @see Camera#getUp()
*/
public Vector3f getUp() {
return rotation.getRotationColumn(1);
}
/**
* <code>getDirection</code> retrieves the direction vector the camera is
* facing.
*
* @return the direction the camera is facing.
* @see Camera#getDirection()
*/
public Vector3f getDirection(Vector3f store) {
return rotation.getRotationColumn(2, store);
}
/**
* <code>getLeft</code> retrieves the left axis of the camera.
*
* @return the left axis of the camera.
* @see Camera#getLeft()
*/
public Vector3f getLeft(Vector3f store) {
return rotation.getRotationColumn(0, store);
}
/**
* <code>getUp</code> retrieves the up axis of the camera.
*
* @return the up axis of the camera.
* @see Camera#getUp()
*/
public Vector3f getUp(Vector3f store) {
return rotation.getRotationColumn(1, store);
}
/**
* <code>setLocation</code> sets the position of the camera.
*
* @param location the position of the camera.
*/
public void setLocation(Vector3f location) {
this.location.set(location);
onFrameChange();
}
/**
* <code>setRotation</code> sets the orientation of this camera.
* This will be equivelant to setting each of the axes:
* <code><br>
* cam.setLeft(rotation.getRotationColumn(0));<br>
* cam.setUp(rotation.getRotationColumn(1));<br>
* cam.setDirection(rotation.getRotationColumn(2));<br>
* </code>
*
* @param rotation the rotation of this camera
*/
public void setRotation(Quaternion rotation) {
this.rotation.set(rotation);
onFrameChange();
}
/**
* <code>lookAtDirection</code> sets the direction the camera is facing
* given a direction and an up vector.
*
* @param direction the direction this camera is facing.
*/
public void lookAtDirection(Vector3f direction, Vector3f up) {
this.rotation.lookAt(direction, up);
onFrameChange();
}
/**
* <code>setAxes</code> sets the axes (left, up and direction) for this
* camera.
*
* @param left the left axis of the camera.
* @param up the up axis of the camera.
* @param direction the direction the camera is facing.
*
* @see Camera#setAxes(com.jme3.math.Quaternion)
*/
public void setAxes(Vector3f left, Vector3f up, Vector3f direction) {
this.rotation.fromAxes(left, up, direction);
onFrameChange();
}
/**
* <code>setAxes</code> uses a rotational matrix to set the axes of the
* camera.
*
* @param axes the matrix that defines the orientation of the camera.
*/
public void setAxes(Quaternion axes) {
this.rotation.set(axes);
onFrameChange();
}
/**
* normalize normalizes the camera vectors.
*/
public void normalize() {
this.rotation.normalizeLocal();
onFrameChange();
}
/**
* <code>setFrustum</code> sets the frustum of this camera object.
*
* @param near the near plane.
* @param far the far plane.
* @param left the left plane.
* @param right the right plane.
* @param top the top plane.
* @param bottom the bottom plane.
* @see Camera#setFrustum(float, float, float, float,
* float, float)
*/
public void setFrustum(float near, float far, float left, float right,
float top, float bottom) {
frustumNear = near;
frustumFar = far;
frustumLeft = left;
frustumRight = right;
frustumTop = top;
frustumBottom = bottom;
onFrustumChange();
}
/**
* <code>setFrustumPerspective</code> defines the frustum for the camera. This
* frustum is defined by a viewing angle, aspect ratio, and near/far planes
*
* @param fovY Frame of view angle along the Y in degrees.
* @param aspect Width:Height ratio
* @param near Near view plane distance
* @param far Far view plane distance
*/
public void setFrustumPerspective(float fovY, float aspect, float near,
float far) {
if (Float.isNaN(aspect) || Float.isInfinite(aspect)) {
// ignore.
logger.log(Level.WARNING, "Invalid aspect given to setFrustumPerspective: {0}", aspect);
return;
}
float h = FastMath.tan(fovY * FastMath.DEG_TO_RAD * .5f) * near;
float w = h * aspect;
frustumLeft = -w;
frustumRight = w;
frustumBottom = -h;
frustumTop = h;
frustumNear = near;
frustumFar = far;
// Camera is no longer parallel projection even if it was before
parallelProjection = false;
onFrustumChange();
}
/**
* <code>setFrame</code> sets the orientation and location of the camera.
*
* @param location the point position of the camera.
* @param left the left axis of the camera.
* @param up the up axis of the camera.
* @param direction the facing of the camera.
* @see Camera#setFrame(com.jme3.math.Vector3f,
* com.jme3.math.Vector3f, com.jme3.math.Vector3f, com.jme3.math.Vector3f)
*/
public void setFrame(Vector3f location, Vector3f left, Vector3f up,
Vector3f direction) {
this.location = location;
this.rotation.fromAxes(left, up, direction);
onFrameChange();
}
/**
* <code>lookAt</code> is a convienence method for auto-setting the frame
* based on a world position the user desires the camera to look at. It
* repoints the camera towards the given position using the difference
* between the position and the current camera location as a direction
* vector and the worldUpVector to compute up and left camera vectors.
*
* @param pos where to look at in terms of world coordinates
* @param worldUpVector a normalized vector indicating the up direction of the world.
* (typically {0, 1, 0} in jME.)
*/
public void lookAt(Vector3f pos, Vector3f worldUpVector) {
TempVars vars = TempVars.get();
Vector3f newDirection = vars.vect1;
Vector3f newUp = vars.vect2;
Vector3f newLeft = vars.vect3;
newDirection.set(pos).subtractLocal(location).normalizeLocal();
newUp.set(worldUpVector).normalizeLocal();
if (newUp.equals(Vector3f.ZERO)) {
newUp.set(Vector3f.UNIT_Y);
}
newLeft.set(newUp).crossLocal(newDirection).normalizeLocal();
if (newLeft.equals(Vector3f.ZERO)) {
if (newDirection.x != 0) {
newLeft.set(newDirection.y, -newDirection.x, 0f);
} else {
newLeft.set(0f, newDirection.z, -newDirection.y);
}
}
newUp.set(newDirection).crossLocal(newLeft).normalizeLocal();
this.rotation.fromAxes(newLeft, newUp, newDirection);
this.rotation.normalizeLocal();
vars.release();
onFrameChange();
}
/**
* <code>setFrame</code> sets the orientation and location of the camera.
*
* @param location
* the point position of the camera.
* @param axes
* the orientation of the camera.
*/
public void setFrame(Vector3f location, Quaternion axes) {
this.location = location;
this.rotation.set(axes);
onFrameChange();
}
/**
* <code>update</code> updates the camera parameters by calling
* <code>onFrustumChange</code>,<code>onViewPortChange</code> and
* <code>onFrameChange</code>.
*
* @see Camera#update()
*/
public void update() {
onFrustumChange();
onViewPortChange();
onFrameChange();
}
/**
* <code>getPlaneState</code> returns the state of the frustum planes. So
* checks can be made as to which frustum plane has been examined for
* culling thus far.
*
* @return the current plane state int.
*/
public int getPlaneState() {
return planeState;
}
/**
* <code>setPlaneState</code> sets the state to keep track of tested
* planes for culling.
*
* @param planeState the updated state.
*/
public void setPlaneState(int planeState) {
this.planeState = planeState;
}
/**
* <code>getViewPortLeft</code> gets the left boundary of the viewport
*
* @return the left boundary of the viewport
*/
public float getViewPortLeft() {
return viewPortLeft;
}
/**
* <code>setViewPortLeft</code> sets the left boundary of the viewport
*
* @param left the left boundary of the viewport
*/
public void setViewPortLeft(float left) {
viewPortLeft = left;
onViewPortChange();
}
/**
* <code>getViewPortRight</code> gets the right boundary of the viewport
*
* @return the right boundary of the viewport
*/
public float getViewPortRight() {
return viewPortRight;
}
/**
* <code>setViewPortRight</code> sets the right boundary of the viewport
*
* @param right the right boundary of the viewport
*/
public void setViewPortRight(float right) {
viewPortRight = right;
onViewPortChange();
}
/**
* <code>getViewPortTop</code> gets the top boundary of the viewport
*
* @return the top boundary of the viewport
*/
public float getViewPortTop() {
return viewPortTop;
}
/**
* <code>setViewPortTop</code> sets the top boundary of the viewport
*
* @param top the top boundary of the viewport
*/
public void setViewPortTop(float top) {
viewPortTop = top;
onViewPortChange();
}
/**
* <code>getViewPortBottom</code> gets the bottom boundary of the viewport
*
* @return the bottom boundary of the viewport
*/
public float getViewPortBottom() {
return viewPortBottom;
}
/**
* <code>setViewPortBottom</code> sets the bottom boundary of the viewport
*
* @param bottom the bottom boundary of the viewport
*/
public void setViewPortBottom(float bottom) {
viewPortBottom = bottom;
onViewPortChange();
}
/**
* <code>setViewPort</code> sets the boundaries of the viewport
*
* @param left the left boundary of the viewport (default: 0)
* @param right the right boundary of the viewport (default: 1)
* @param bottom the bottom boundary of the viewport (default: 0)
* @param top the top boundary of the viewport (default: 1)
*/
public void setViewPort(float left, float right, float bottom, float top) {
this.viewPortLeft = left;
this.viewPortRight = right;
this.viewPortBottom = bottom;
this.viewPortTop = top;
onViewPortChange();
}
/**
* Returns the pseudo distance from the given position to the near
* plane of the camera. This is used for render queue sorting.
* @param pos The position to compute a distance to.
* @return Distance from the far plane to the point.
*/
public float distanceToNearPlane(Vector3f pos) {
return worldPlane[NEAR_PLANE].pseudoDistance(pos);
}
/**
* <code>contains</code> tests a bounding volume against the planes of the
* camera's frustum. The frustums planes are set such that the normals all
* face in towards the viewable scene. Therefore, if the bounding volume is
* on the negative side of the plane is can be culled out.
*
* NOTE: This method is used internally for culling, for public usage,
* the plane state of the bounding volume must be saved and restored, e.g:
* <code>BoundingVolume bv;<br/>
* Camera c;<br/>
* int planeState = bv.getPlaneState();<br/>
* bv.setPlaneState(0);<br/>
* c.contains(bv);<br/>
* bv.setPlaneState(plateState);<br/>
* </code>
*
* @param bound the bound to check for culling
* @return See enums in <code>FrustumIntersect</code>
*/
public FrustumIntersect contains(BoundingVolume bound) {
if (bound == null) {
return FrustumIntersect.Inside;
}
int mask;
FrustumIntersect rVal = FrustumIntersect.Inside;
for (int planeCounter = FRUSTUM_PLANES; planeCounter >= 0; planeCounter
if (planeCounter == bound.getCheckPlane()) {
continue; // we have already checked this plane at first iteration
}
int planeId = (planeCounter == FRUSTUM_PLANES) ? bound.getCheckPlane() : planeCounter;
// int planeId = planeCounter;
mask = 1 << (planeId);
if ((planeState & mask) == 0) {
Plane.Side side = bound.whichSide(worldPlane[planeId]);
if (side == Plane.Side.Negative) {
//object is outside of frustum
bound.setCheckPlane(planeId);
return FrustumIntersect.Outside;
} else if (side == Plane.Side.Positive) {
//object is visible on *this* plane, so mark this plane
//so that we don't check it for sub nodes.
planeState |= mask;
} else {
rVal = FrustumIntersect.Intersects;
}
}
}
return rVal;
}
/**
* <code>containsGui</code> tests a bounding volume against the ortho
* bounding box of the camera. A bounding box spanning from
* 0, 0 to Width, Height. Constrained by the viewport settings on the
* camera.
*
* @param bound the bound to check for culling
* @return True if the camera contains the gui element bounding volume.
*/
public boolean containsGui(BoundingVolume bound) {
return guiBounding.intersects(bound);
}
/**
* @return the view matrix of the camera.
* The view matrix transforms world space into eye space.
* This matrix is usually defined by the position and
* orientation of the camera.
*/
public Matrix4f getViewMatrix() {
return viewMatrix;
}
/**
* Overrides the projection matrix used by the camera. Will
* use the matrix for computing the view projection matrix as well.
* Use null argument to return to normal functionality.
*
* @param projMatrix
*/
public void setProjectionMatrix(Matrix4f projMatrix) {
projectionMatrixOverride = projMatrix;
updateViewProjection();
}
/**
* @return the projection matrix of the camera.
* The view projection matrix transforms eye space into clip space.
* This matrix is usually defined by the viewport and perspective settings
* of the camera.
*/
public Matrix4f getProjectionMatrix() {
if (projectionMatrixOverride != null) {
return projectionMatrixOverride;
}
return projectionMatrix;
}
/**
* Updates the view projection matrix.
*/
public void updateViewProjection() {
if (projectionMatrixOverride != null) {
viewProjectionMatrix.set(projectionMatrixOverride).multLocal(viewMatrix);
} else {
//viewProjectionMatrix.set(viewMatrix).multLocal(projectionMatrix);
viewProjectionMatrix.set(projectionMatrix).multLocal(viewMatrix);
}
}
/**
* @return The result of multiplying the projection matrix by the view
* matrix. This matrix is required for rendering an object. It is
* precomputed so as to not compute it every time an object is rendered.
*/
public Matrix4f getViewProjectionMatrix() {
return viewProjectionMatrix;
}
/**
* @return True if the viewport (width, height, left, right, bottom, up)
* has been changed. This is needed in the renderer so that the proper
* viewport can be set-up.
*/
public boolean isViewportChanged() {
return viewportChanged;
}
/**
* Clears the viewport changed flag once it has been updated inside
* the renderer.
*/
public void clearViewportChanged() {
viewportChanged = false;
}
/**
* Called when the viewport has been changed.
*/
public void onViewPortChange() {
viewportChanged = true;
setGuiBounding();
}
private void setGuiBounding() {
float sx = width * viewPortLeft;
float ex = width * viewPortRight;
float sy = height * viewPortBottom;
float ey = height * viewPortTop;
float xExtent = Math.max(0f, (ex - sx) / 2f);
float yExtent = Math.max(0f, (ey - sy) / 2f);
guiBounding.setCenter(new Vector3f(sx + xExtent, sy + yExtent, 0));
guiBounding.setXExtent(xExtent);
guiBounding.setYExtent(yExtent);
guiBounding.setZExtent(Float.MAX_VALUE);
}
/**
* <code>onFrustumChange</code> updates the frustum to reflect any changes
* made to the planes. The new frustum values are kept in a temporary
* location for use when calculating the new frame. The projection
* matrix is updated to reflect the current values of the frustum.
*/
public void onFrustumChange() {
if (!isParallelProjection()) {
float nearSquared = frustumNear * frustumNear;
float leftSquared = frustumLeft * frustumLeft;
float rightSquared = frustumRight * frustumRight;
float bottomSquared = frustumBottom * frustumBottom;
float topSquared = frustumTop * frustumTop;
float inverseLength = FastMath.invSqrt(nearSquared + leftSquared);
coeffLeft[0] = -frustumNear * inverseLength;
coeffLeft[1] = -frustumLeft * inverseLength;
inverseLength = FastMath.invSqrt(nearSquared + rightSquared);
coeffRight[0] = frustumNear * inverseLength;
coeffRight[1] = frustumRight * inverseLength;
inverseLength = FastMath.invSqrt(nearSquared + bottomSquared);
coeffBottom[0] = frustumNear * inverseLength;
coeffBottom[1] = -frustumBottom * inverseLength;
inverseLength = FastMath.invSqrt(nearSquared + topSquared);
coeffTop[0] = -frustumNear * inverseLength;
coeffTop[1] = frustumTop * inverseLength;
} else {
coeffLeft[0] = 1;
coeffLeft[1] = 0;
coeffRight[0] = -1;
coeffRight[1] = 0;
coeffBottom[0] = 1;
coeffBottom[1] = 0;
coeffTop[0] = -1;
coeffTop[1] = 0;
}
projectionMatrix.fromFrustum(frustumNear, frustumFar, frustumLeft, frustumRight, frustumTop, frustumBottom, parallelProjection);
// projectionMatrix.transposeLocal();
// The frame is effected by the frustum values
// update it as well
onFrameChange();
}
/**
* <code>onFrameChange</code> updates the view frame of the camera.
*/
public void onFrameChange() {
TempVars vars = TempVars.get();
Vector3f left = getLeft(vars.vect1);
Vector3f direction = getDirection(vars.vect2);
Vector3f up = getUp(vars.vect3);
float dirDotLocation = direction.dot(location);
// left plane
Vector3f leftPlaneNormal = worldPlane[LEFT_PLANE].getNormal();
leftPlaneNormal.x = left.x * coeffLeft[0];
leftPlaneNormal.y = left.y * coeffLeft[0];
leftPlaneNormal.z = left.z * coeffLeft[0];
leftPlaneNormal.addLocal(direction.x * coeffLeft[1], direction.y
* coeffLeft[1], direction.z * coeffLeft[1]);
worldPlane[LEFT_PLANE].setConstant(location.dot(leftPlaneNormal));
// right plane
Vector3f rightPlaneNormal = worldPlane[RIGHT_PLANE].getNormal();
rightPlaneNormal.x = left.x * coeffRight[0];
rightPlaneNormal.y = left.y * coeffRight[0];
rightPlaneNormal.z = left.z * coeffRight[0];
rightPlaneNormal.addLocal(direction.x * coeffRight[1], direction.y
* coeffRight[1], direction.z * coeffRight[1]);
worldPlane[RIGHT_PLANE].setConstant(location.dot(rightPlaneNormal));
// bottom plane
Vector3f bottomPlaneNormal = worldPlane[BOTTOM_PLANE].getNormal();
bottomPlaneNormal.x = up.x * coeffBottom[0];
bottomPlaneNormal.y = up.y * coeffBottom[0];
bottomPlaneNormal.z = up.z * coeffBottom[0];
bottomPlaneNormal.addLocal(direction.x * coeffBottom[1], direction.y
* coeffBottom[1], direction.z * coeffBottom[1]);
worldPlane[BOTTOM_PLANE].setConstant(location.dot(bottomPlaneNormal));
// top plane
Vector3f topPlaneNormal = worldPlane[TOP_PLANE].getNormal();
topPlaneNormal.x = up.x * coeffTop[0];
topPlaneNormal.y = up.y * coeffTop[0];
topPlaneNormal.z = up.z * coeffTop[0];
topPlaneNormal.addLocal(direction.x * coeffTop[1], direction.y
* coeffTop[1], direction.z * coeffTop[1]);
worldPlane[TOP_PLANE].setConstant(location.dot(topPlaneNormal));
if (isParallelProjection()) {
worldPlane[LEFT_PLANE].setConstant(worldPlane[LEFT_PLANE].getConstant() + frustumLeft);
worldPlane[RIGHT_PLANE].setConstant(worldPlane[RIGHT_PLANE].getConstant() - frustumRight);
worldPlane[TOP_PLANE].setConstant(worldPlane[TOP_PLANE].getConstant() - frustumTop);
worldPlane[BOTTOM_PLANE].setConstant(worldPlane[BOTTOM_PLANE].getConstant() + frustumBottom);
}
// far plane
worldPlane[FAR_PLANE].setNormal(left);
worldPlane[FAR_PLANE].setNormal(-direction.x, -direction.y, -direction.z);
worldPlane[FAR_PLANE].setConstant(-(dirDotLocation + frustumFar));
// near plane
worldPlane[NEAR_PLANE].setNormal(direction.x, direction.y, direction.z);
worldPlane[NEAR_PLANE].setConstant(dirDotLocation + frustumNear);
viewMatrix.fromFrame(location, direction, up, left);
vars.release();
// viewMatrix.transposeLocal();
updateViewProjection();
}
/**
* @return true if parallel projection is enable, false if in normal perspective mode
* @see #setParallelProjection(boolean)
*/
public boolean isParallelProjection() {
return this.parallelProjection;
}
/**
* Enable/disable parallel projection.
*
* @param value true to set up this camera for parallel projection is enable, false to enter normal perspective mode
*/
public void setParallelProjection(final boolean value) {
this.parallelProjection = value;
onFrustumChange();
}
public float getViewToProjectionZ(float viewZPos) {
float far = getFrustumFar();
float near = getFrustumNear();
float a = far / (far - near);
float b = far * near / (near - far);
return a + b / viewZPos;
}
public Vector3f getWorldCoordinates(Vector2f screenPos, float projectionZPos) {
return getWorldCoordinates(screenPos, projectionZPos, null);
}
/**
* @see Camera#getWorldCoordinates
*/
public Vector3f getWorldCoordinates(Vector2f screenPosition,
float projectionZPos, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
Matrix4f inverseMat = new Matrix4f(viewProjectionMatrix);
inverseMat.invertLocal();
store.set(
(screenPosition.x / getWidth() - viewPortLeft) / (viewPortRight - viewPortLeft) * 2 - 1,
(screenPosition.y / getHeight() - viewPortBottom) / (viewPortTop - viewPortBottom) * 2 - 1,
projectionZPos * 2 - 1);
float w = inverseMat.multProj(store, store);
store.multLocal(1f / w);
return store;
}
/**
* Converts the given position from world space to screen space.
*
* @see Camera#getScreenCoordinates
*/
public Vector3f getScreenCoordinates(Vector3f worldPos) {
return getScreenCoordinates(worldPos, null);
}
/**
* Converts the given position from world space to screen space.
*
* @see Camera#getScreenCoordinates(Vector3f, Vector3f)
*/
public Vector3f getScreenCoordinates(Vector3f worldPosition, Vector3f store) {
if (store == null) {
store = new Vector3f();
}
// TempVars vars = vars.lock();
// Quaternion tmp_quat = vars.quat1;
// tmp_quat.set( worldPosition.x, worldPosition.y, worldPosition.z, 1 );
// viewProjectionMatrix.mult(tmp_quat, tmp_quat);
// tmp_quat.multLocal( 1.0f / tmp_quat.getW() );
// store.x = ( ( tmp_quat.getX() + 1 ) * ( viewPortRight - viewPortLeft ) / 2 + viewPortLeft ) * getWidth();
// store.y = ( ( tmp_quat.getY() + 1 ) * ( viewPortTop - viewPortBottom ) / 2 + viewPortBottom ) * getHeight();
// store.z = ( tmp_quat.getZ() + 1 ) / 2;
// vars.release();
float w = viewProjectionMatrix.multProj(worldPosition, store);
store.divideLocal(w);
store.x = ((store.x + 1f) * (viewPortRight - viewPortLeft) / 2f + viewPortLeft) * getWidth();
store.y = ((store.y + 1f) * (viewPortTop - viewPortBottom) / 2f + viewPortBottom) * getHeight();
store.z = (store.z + 1f) / 2f;
return store;
}
/**
* @return the width/resolution of the display.
*/
public int getWidth() {
return width;
}
/**
* @return the height/resolution of the display.
*/
public int getHeight() {
return height;
}
@Override
public String toString() {
return "Camera[location=" + location + "\n, direction=" + getDirection() + "\n"
+ "res=" + width + "x" + height + ", parallel=" + parallelProjection + "\n"
+ "near=" + frustumNear + ", far=" + frustumFar + "]";
}
public void write(JmeExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(location, "location", Vector3f.ZERO);
capsule.write(rotation, "rotation", Quaternion.DIRECTION_Z);
capsule.write(frustumNear, "frustumNear", 1);
capsule.write(frustumFar, "frustumFar", 2);
capsule.write(frustumLeft, "frustumLeft", -0.5f);
capsule.write(frustumRight, "frustumRight", 0.5f);
capsule.write(frustumTop, "frustumTop", 0.5f);
capsule.write(frustumBottom, "frustumBottom", -0.5f);
capsule.write(coeffLeft, "coeffLeft", new float[2]);
capsule.write(coeffRight, "coeffRight", new float[2]);
capsule.write(coeffBottom, "coeffBottom", new float[2]);
capsule.write(coeffTop, "coeffTop", new float[2]);
capsule.write(viewPortLeft, "viewPortLeft", 0);
capsule.write(viewPortRight, "viewPortRight", 1);
capsule.write(viewPortTop, "viewPortTop", 1);
capsule.write(viewPortBottom, "viewPortBottom", 0);
capsule.write(width, "width", 0);
capsule.write(height, "height", 0);
capsule.write(name, "name", null);
}
public void read(JmeImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
location = (Vector3f) capsule.readSavable("location", Vector3f.ZERO.clone());
rotation = (Quaternion) capsule.readSavable("rotation", Quaternion.DIRECTION_Z.clone());
frustumNear = capsule.readFloat("frustumNear", 1);
frustumFar = capsule.readFloat("frustumFar", 2);
frustumLeft = capsule.readFloat("frustumLeft", -0.5f);
frustumRight = capsule.readFloat("frustumRight", 0.5f);
frustumTop = capsule.readFloat("frustumTop", 0.5f);
frustumBottom = capsule.readFloat("frustumBottom", -0.5f);
coeffLeft = capsule.readFloatArray("coeffLeft", new float[2]);
coeffRight = capsule.readFloatArray("coeffRight", new float[2]);
coeffBottom = capsule.readFloatArray("coeffBottom", new float[2]);
coeffTop = capsule.readFloatArray("coeffTop", new float[2]);
viewPortLeft = capsule.readFloat("viewPortLeft", 0);
viewPortRight = capsule.readFloat("viewPortRight", 1);
viewPortTop = capsule.readFloat("viewPortTop", 1);
viewPortBottom = capsule.readFloat("viewPortBottom", 0);
width = capsule.readInt("width", 1);
height = capsule.readInt("height", 1);
name = capsule.readString("name", null);
onFrustumChange();
onViewPortChange();
onFrameChange();
}
} |
package com.jme3.util;
import com.jme3.asset.AssetManager;
import com.jme3.asset.TextureKey;
import com.jme3.bounding.BoundingSphere;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Sphere;
import com.jme3.texture.Image;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture;
import com.jme3.texture.TextureCubeMap;
public class SkyFactory {
public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap){
return createSky(assetManager, texture, normalScale, sphereMap, 10);
}
public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap, int sphereRadius){
if (texture == null)
throw new IllegalArgumentException("texture cannot be null");
final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true);
Geometry sky = new Geometry("Sky", sphereMesh);
sky.setQueueBucket(Bucket.Sky);
sky.setCullHint(Spatial.CullHint.Never);
sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO));
Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md");
skyMat.setVector3("NormalScale", normalScale);
if (sphereMap){
skyMat.setBoolean("SphereMap", sphereMap);
}else if (!(texture instanceof TextureCubeMap)){
// make sure its a cubemap
Image img = texture.getImage();
texture = new TextureCubeMap();
texture.setImage(img);
}
skyMat.setTexture("Texture", texture);
sky.setMaterial(skyMat);
return sky;
}
private static void checkImage(Image image){
// if (image.getDepth() != 1)
if (image.getWidth() != image.getHeight())
throw new IllegalArgumentException("Image width and height must be the same");
if (image.getMultiSamples() != 1)
throw new IllegalArgumentException("Multisample textures not allowed");
}
private static void checkImagesForCubeMap(Image ... images){
if (images.length == 1) return;
Format fmt = images[0].getFormat();
int width = images[0].getWidth();
int size = images[0].getData(0).capacity();
checkImage(images[0]);
for (int i = 1; i < images.length; i++){
Image image = images[i];
checkImage(images[i]);
if (image.getFormat() != fmt) throw new IllegalArgumentException("Images must have same format");
if (image.getWidth() != width) throw new IllegalArgumentException("Images must have same resolution");
if (image.getData(0).capacity() != size) throw new IllegalArgumentException("Images must have same size");
}
}
public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale){
return createSky(assetManager, west, east, north, south, up, down, normalScale, 10);
}
public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale, int sphereRadius){
final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true);
Geometry sky = new Geometry("Sky", sphereMesh);
sky.setQueueBucket(Bucket.Sky);
sky.setCullHint(Spatial.CullHint.Never);
sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO));
Image westImg = west.getImage();
Image eastImg = east.getImage();
Image northImg = north.getImage();
Image southImg = south.getImage();
Image upImg = up.getImage();
Image downImg = down.getImage();
checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg);
Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null);
cubeImage.addData(westImg.getData(0));
cubeImage.addData(eastImg.getData(0));
cubeImage.addData(downImg.getData(0));
cubeImage.addData(upImg.getData(0));
cubeImage.addData(southImg.getData(0));
cubeImage.addData(northImg.getData(0));
TextureCubeMap cubeMap = new TextureCubeMap(cubeImage);
cubeMap.setAnisotropicFilter(0);
cubeMap.setMagFilter(Texture.MagFilter.Bilinear);
cubeMap.setMinFilter(Texture.MinFilter.NearestNoMipMaps);
cubeMap.setWrap(Texture.WrapMode.EdgeClamp);
Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md");
skyMat.setTexture("Texture", cubeMap);
skyMat.setVector3("NormalScale", normalScale);
sky.setMaterial(skyMat);
return sky;
}
public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down){
return createSky(assetManager, west, east, north, south, up, down, Vector3f.UNIT_XYZ);
}
public static Spatial createSky(AssetManager assetManager, Texture texture, boolean sphereMap){
return createSky(assetManager, texture, Vector3f.UNIT_XYZ, sphereMap);
}
public static Spatial createSky(AssetManager assetManager, String textureName, boolean sphereMap){
TextureKey key = new TextureKey(textureName, true);
key.setGenerateMips(true);
key.setAsCube(!sphereMap);
Texture tex = assetManager.loadTexture(key);
return createSky(assetManager, tex, sphereMap);
}
} |
package com.beans;
import banner.crud.BannerMethos;
import banner.map.PersonaBanner;
import com.util.LazyCasoDataModel;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.model.LazyDataModel;
import procuradoria.map.Uzatcaso;
import procuradoria.crud.ProcuradoriaMethods;
import procuradoria.map.Uzatactor;
import procuradoria.map.UzatinvCa;
import procuradoria.map.UzatinvCaId;
import procuradoria.map.Uzatjudi;
import procuradoria.map.Uzatmateri;
/**
*
* @author FANNY
*/
@ManagedBean
@ViewScoped
public class ResumenAboBean{
/**
* Creates a new instance of ResumenProcuBean
*/
private String idCaso;
private String cedulaActor;
private String tipoActor;
private String cajaTextoSeleccionarActor="Por favor, Seleccione un actor";
private String botonAgregarActor = "Agregar Actor";
private LazyDataModel<Uzatcaso> lazyModelCasosAsignados;
private String idocedula;
private String numeroocedula;
private String valorbusqueda;
private Uzatcaso selectedCaso;
private Uzatactor selectedActor;
private ArrayList<SelectItem> ItemsMaterias;
private ArrayList<SelectItem> ItemsJudicaturas;
private BigDecimal idMateria;
private BigDecimal idJudicatura;
private String textoBotonVincular;
private Uzatcaso findCaso;
private String nombreActorAnterior;
private String cedulaActorAnterior;
private Uzatjudi vincuJudi;
private Uzatmateri vincuMateria;
public ResumenAboBean() {
lazyModelCasosAsignados = new LazyCasoDataModel(this.getUserAttribute(), new BigDecimal(2));
selectedCaso = new Uzatcaso();
findCaso = new Uzatcaso();
this.selectedActor = new Uzatactor();
this.idCaso = "vacio";
this.idocedula = "vacio";
this.cedulaActor= "";
this.ItemsJudicaturas = new ArrayList<SelectItem>();
this.ItemsMaterias = new ArrayList<SelectItem>();
this.textoBotonVincular = "Buscar";
this.loadlistMaterias();
this.ItemsJudicaturas.clear();
vincuMateria = new Uzatmateri();
vincuJudi = new Uzatjudi();
}
private BigDecimal getUserAttribute() {
String UserAttribute = "";
BigDecimal id = new BigDecimal(BigInteger.ZERO);
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
if (session == null) {
} else {
Object IdBanner = session.getAttribute("uzatfuncionarioId");
UserAttribute = IdBanner.toString();
id = new BigDecimal(UserAttribute);
}
return id;
}
public void findCasobyid(String id)
{
this.idCaso = id ;
this.selectedCaso = ProcuradoriaMethods.findCasobyId(new BigDecimal(idCaso));
}
public void findActorbycedula()
{
if(!cedulaActor.equals("Ingrese número de cédula")){
ValidateFuncionario(cedulaActor);
System.out.println(this.selectedActor.getUzatactorNombres());
this.botonAgregarActor = "Ver Datos Actor";
this.cajaTextoSeleccionarActor = this.selectedActor.getUzatactorNombres() + " " + this.selectedActor.getUzatactorApellidos();
}
}
public void botonActualizarActor()
{
updateActor();
}
public void botonActualizarCaso()
{
if(this.selectedCaso.getUzatcasoVincu() == null)
this.selectedCaso.setUzatcasoVincu(this.selectedCaso.getUzatcasoId());
System.out.println("");
updateCaso();
asignarActoraCaso();
}
public void buttonAction(ActionEvent actionEvent) {
addMessage("Welcome to Primefaces!!");
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
private void updateActor() {
if(ProcuradoriaMethods.UpdateActor(selectedActor))
{
addMessage("Se han actualizado los Datos de Actor");
}
}
private void updateCaso() {
this.selectedCaso.setUzatcasoFlag(new BigDecimal(1));
if(ProcuradoriaMethods.UpdateCaso(selectedCaso))
{
addMessage("Se han actualizado los Datos del Caso");
}else
{
addMessage("Ha ocurrido un error");
}
}
private void asignarActoraCaso() {
UzatinvCa involucrado = new UzatinvCa();
UzatinvCaId idinvolucrado = new UzatinvCaId(this.selectedActor.getUzatactorId(), this.selectedCaso.getUzatcasoId());
involucrado.setId(idinvolucrado);
involucrado.setUzatinvTipo(tipoActor);
involucrado.setUzatinvolCa(getDate());
involucrado.setUzatcaso(selectedCaso);
involucrado.setUzatactor(selectedActor);
if(ProcuradoriaMethods.InsertInvolCa(involucrado))
{
addMessage("Se ha asignado corretamente el caso");
}else
{
addMessage("Ha ocurrido un error");
}
}
public static String getDate() {
SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
//Busqueda de actor en banner
private Boolean ValidateFuncionario(String claveFuncionario) {
Boolean exito = false;
PersonaBanner find = null;
String mdatoCli = claveFuncionario.trim();
claveFuncionario = mdatoCli.toUpperCase();
if (!findFuncionarioProcuaradoria(claveFuncionario, idocedula)) {
if(idocedula.equals("0")){
find = BannerMethos.FindPersonBannerByCedula(claveFuncionario);
}else if(idocedula.equals("1"))
{
find = BannerMethos.FindPersonBannerByIdBanner(claveFuncionario);
}
if (find != null) {
SendDataFuncionario(find);
addMessage("Se ha ingresado Actor en Base de Datos");
exito = true;
}
}else
{
addMessage("Se ha encontrado Actor en Base de Datos");
}
return exito;
}
public Boolean findFuncionarioProcuaradoria(String claveFuncionario, String idocedula) {
Boolean exito = false;
if(idocedula.equals("0"))
{
this.selectedActor = ProcuradoriaMethods.findActorbyCedula(claveFuncionario);
}
else
{
this.selectedActor = ProcuradoriaMethods.findActorbyIDBanner(claveFuncionario);
}
if (this.selectedActor != null) {
exito = true;
} else {
this.selectedActor = new Uzatactor();
}
return exito;
}
public void SendDataFuncionario(PersonaBanner Funcionario) {
this.selectedActor.setUzatactorApellidos(Funcionario.getApellidos());
this.selectedActor.setUzatactorCedula(Funcionario.getCedula());
this.selectedActor.setUzatactorEmail(Funcionario.getEmail());
this.selectedActor.setUzatactorNombres(Funcionario.getNombres());
this.selectedActor.setUzatactorIdbanner(Funcionario.getIdBanner());
this.selectedActor.setUzatactorId(new BigDecimal(1111));
Boolean exito = ProcuradoriaMethods.insertActor(this.selectedActor);
if (exito) {
this.selectedActor = ProcuradoriaMethods.findActorbyCedula(this.selectedActor.getUzatactorCedula());
}
else
{
addMessage("A ocurrido un error, no se han Grabado los Datos en el Registro");
}
}
public void loadlistMaterias() {
ArrayList<Uzatmateri> selectItemsMat = ProcuradoriaMethods.ListMaterias();
this.ItemsMaterias.clear();
SelectItem si;
for (int i = 0; i < selectItemsMat.size(); i++) {
si = new SelectItem(selectItemsMat.get(i).getUzatmateriaId(),selectItemsMat.get(i).getUzatmateriaDescripcion());
this.ItemsMaterias.add(si);
}
this.ItemsMaterias.remove(0);
}
public void loadlistJudi() {
BigDecimal idmateri = this.getIdMateria();
ArrayList<Uzatjudi> selectItemsJud = ProcuradoriaMethods.findjudibyMateriId(idmateri);
if(!(selectItemsJud == null))
{
this.ItemsJudicaturas.clear();
SelectItem si;
for (int i = 0; i < selectItemsJud.size(); i++) {
si = new SelectItem(selectItemsJud.get(i).getId().getUzatjudiId(),selectItemsJud.get(i).getUzatjudiDescripcion());
this.ItemsJudicaturas.add(si);
}
}
else
{
this.ItemsJudicaturas.clear();
SelectItem si;
si = new SelectItem("100","No existe Judicatura");
this.ItemsJudicaturas.add(si);
}
}
public void findCasos()
{
this.findCaso = ProcuradoriaMethods.FindCasobyNumCausa(this.valorbusqueda);
if(this.findCaso != null)
{
this.vincuJudi = this.findCaso.getUzatjudi();
this.vincuMateria = ProcuradoriaMethods.findMateribyJudiId(this.vincuJudi.getId().getUzatjudiId());
addMessage("Se ha encontrado el Caso Solicitado");
}else{
addMessage("No se ha encontrado Caso con el número de Causa ingresado");
}
}
public void vincular()
{
this.textoBotonVincular = "Cambiar";
this.selectedCaso.setUzatcasoVincu(this.findCaso.getUzatcasoId());
addMessage("Se ha vinculado el caso");
}
// <editor-fold defaultstate="collapsed" desc=" Getters and Setters ">
public Uzatcaso getSelectedCaso() {
return selectedCaso;
}
public void setSelectedCaso(Uzatcaso selectedCaso) {
this.selectedCaso = selectedCaso;
}
public LazyDataModel<Uzatcaso> getLazyModelCasosAsignados() {
return lazyModelCasosAsignados;
}
public void setLazyModelCasosAsignados(LazyDataModel<Uzatcaso> lazyModelCasosAsignados) {
this.lazyModelCasosAsignados = lazyModelCasosAsignados;
}
public String getIdCaso() {
return idCaso;
}
public void setIdCaso(String idCaso) {
this.idCaso = idCaso;
}
public String getTipoActor() {
return tipoActor;
}
public void setTipoActor(String tipoActor) {
this.tipoActor = tipoActor;
}
public Uzatactor getSelectedActor() {
return selectedActor;
}
public void setSelectedActor(Uzatactor selectedActor) {
this.selectedActor = selectedActor;
}
public String getCedulaActor() {
return cedulaActor;
}
public void setCedulaActor(String cedulaActor) {
this.cedulaActor = cedulaActor;
}
public String getBotonAgregarActor() {
return botonAgregarActor;
}
public void setBotonAgregarActor(String botonAgregarActor) {
this.botonAgregarActor = botonAgregarActor;
}
public String getCajaTextoSeleccionarActor() {
return cajaTextoSeleccionarActor;
}
public void setCajaTextoSeleccionarActor(String cajaTextoSeleccionarActor) {
this.cajaTextoSeleccionarActor = cajaTextoSeleccionarActor;
}
public String getIdocedula() {
return idocedula;
}
public void setIdocedula(String idocedula) {
this.idocedula = idocedula;
}
public ArrayList<SelectItem> getItemsMaterias() {
return ItemsMaterias;
}
public void setItemsMaterias(ArrayList<SelectItem> ItemsMaterias) {
this.ItemsMaterias = ItemsMaterias;
}
public ArrayList<SelectItem> getItemsJudicaturas() {
return ItemsJudicaturas;
}
public void setItemsJudicaturas(ArrayList<SelectItem> ItemsJudicaturas) {
this.ItemsJudicaturas = ItemsJudicaturas;
}
public String getTextoBotonVincular() {
return textoBotonVincular;
}
public void setTextoBotonVincular(String textoBotonVincular) {
this.textoBotonVincular = textoBotonVincular;
}
public String getNumeroocedula() {
return numeroocedula;
}
public void setNumeroocedula(String numeroocedula) {
this.numeroocedula = numeroocedula;
}
public String getValorbusqueda() {
return valorbusqueda;
}
public void setValorbusqueda(String valorbusqueda) {
this.valorbusqueda = valorbusqueda;
}
public Uzatcaso getFindCaso() {
return findCaso;
}
public void setFindCaso(Uzatcaso findCaso) {
this.findCaso = findCaso;
}
public String getNombreActorAnterior() {
return nombreActorAnterior;
}
public void setNombreActorAnterior(String nombreActorAnterior) {
this.nombreActorAnterior = nombreActorAnterior;
}
public String getCedulaActorAnterior() {
return cedulaActorAnterior;
}
public void setCedulaActorAnterior(String cedulaActorAnterior) {
this.cedulaActorAnterior = cedulaActorAnterior;
}
public Uzatjudi getVincuJudi() {
return vincuJudi;
}
public void setVincuJudi(Uzatjudi vincuJudi) {
this.vincuJudi = vincuJudi;
}
public Uzatmateri getVincuMateria() {
return vincuMateria;
}
public void setVincuMateria(Uzatmateri vincuMateria) {
this.vincuMateria = vincuMateria;
}
// </editor-fold>
public BigDecimal getIdMateria() {
return idMateria;
}
public void setIdMateria(BigDecimal idMateria) {
this.idMateria = idMateria;
}
public BigDecimal getIdJudicatura() {
return idJudicatura;
}
public void setIdJudicatura(BigDecimal idJudicatura) {
this.idJudicatura = idJudicatura;
}
} |
// BUI - a user interface library for the JME 3D engine
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.jmex.bui;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.jme.image.Image;
import com.jme.renderer.ColorRGBA;
import com.jme.util.TextureManager;
import com.jmex.bui.background.BBackground;
import com.jmex.bui.background.BlankBackground;
import com.jmex.bui.background.ImageBackground;
import com.jmex.bui.background.TintedBackground;
import com.jmex.bui.border.BBorder;
import com.jmex.bui.border.EmptyBorder;
import com.jmex.bui.border.LineBorder;
import com.jmex.bui.icon.BIcon;
import com.jmex.bui.icon.BlankIcon;
import com.jmex.bui.icon.ImageIcon;
import com.jmex.bui.text.AWTTextFactory;
import com.jmex.bui.text.BKeyMap;
import com.jmex.bui.text.BTextFactory;
import com.jmex.bui.text.DefaultKeyMap;
import com.jmex.bui.util.Dimension;
import com.jmex.bui.util.Insets;
/**
* Defines a stylesheet which is used to configure the style (font family, font
* size, foreground and background color, etc.) of components in the BUI
* library. The BUI stylesheets syntax is a subset of the Cascading Style Sheet
* sytnax and follows its semantic conventions as well where possible.
*
* <p> A basic stylesheet enumerating most usable values is as follows:
* <pre>
* style_class {
* // foreground and background properties
* color: 0 0 0;
* background: solid #00000088; // note the 50% alpha
* background: image monkey.png XX; // XX = centerx|centery|centerxy|
* // scalex|scaley|scalexy|
* // tilex|tiley|tilexy|
* // framex|framey|framexy
*
* // text properties
* font: Helvetica XX 12; // XX = normal|bold|italic|bolditalic
* text-align: XX; // XX = left|center|right
* vertical-align: XX; // XX = top|center|bottom
* text-effect: XX; // XX = none|outline|shadow
*
* // box properties
* padding: top; // right=top, bottom=top, left=top
* padding: top, right; // bottom=top, left=right
* padding: top, right, bottom, left;
* border: 1 solid #FFCC99;
* border: 1 blank;
* size: 250 100; // overrrides component preferred size
*
* // explicit inheritance
* parent: other_class; // other_class must be defined *before* this one
* }
* </pre>
*
* Each component is identified by its default stylesheet class, which are
* derived from the component's Java class name: <code>window, label,
* textfield, component, popupmenu, etc.</code> The component's stylesheet
* class can be overridden with a call to {@link BComponent#setStyleClass}.
*
* <p> A component's style is resolved in the following manner:
* <ul>
* <li> First by looking up the property using the component's stylesheet
* class.
* <li> <em>For certain properties</em>, the interface hierarchy is then
* climbed and each parents' stylesheet class is checked for the property in
* question. The properties for which that applies are: <code>color, font,
* text-align, vertical-align</code>.
*
* <li> Lastly the <code>root</code> stylesheet class is checked (for all
* properties, not just those for which we climb the interface hierarchy).
* </ul>
*
* <p> This resolution process is followed at the time the component is added
* to the interface hierarchy and the result is used to configure the
* component. We tradeoff the relative expense of doing the lookup every time
* the component is rendered (every frame) with the memory expense of storing
* the style of every component in memory.
*/
public class BStyleSheet
{
/** An interface used by the stylesheet to obtain font and image
* resources. */
public interface ResourceProvider
{
/**
* Creates a factory that will render text using the specified font.
*/
public BTextFactory createTextFactory (
String family, String style, int size);
/**
* Loads the image with the specified path.
*/
public Image loadImage (String path) throws IOException;
}
/** A default implementation of the stylesheet resource provider. */
public static class DefaultResourceProvider implements ResourceProvider
{
public BTextFactory createTextFactory (
String family, String style, int size) {
int nstyle = Font.PLAIN;
if (style.equals(BOLD)) {
nstyle = Font.BOLD;
} else if (style.equals(ITALIC)) {
nstyle = Font.ITALIC;
} else if (style.equals(BOLD_ITALIC)) {
nstyle = Font.ITALIC|Font.BOLD;
}
return new AWTTextFactory(new Font(family, nstyle, size), true);
}
public Image loadImage (String path) throws IOException {
if (!path.startsWith("/")) {
path = "/" + path;
}
URL url = getClass().getResource(path);
if (url == null) {
throw new IOException("Can't locate image '" + path + "'.");
}
return TextureManager.loadImage(url, true);
}
}
/** A font style constant. */
public static final String PLAIN = "plain";
/** A font style constant. */
public static final String BOLD = "bold";
/** A font style constant. */
public static final String ITALIC = "italic";
/** A font style constant. */
public static final String BOLD_ITALIC = "bolditalic";
public static void main (String[] args)
{
// load up the default BUI stylesheet
BStyleSheet style = null;
try {
style = new BStyleSheet(new InputStreamReader(
BStyleSheet.class.getClassLoader().
getResourceAsStream("rsrc/style.bss")),
new DefaultResourceProvider());
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
/**
* Creates a stylesheet from the specified textual source.
*/
public BStyleSheet (Reader reader, ResourceProvider rsrcprov)
throws IOException
{
_rsrcprov = rsrcprov;
StreamTokenizer tok = new StreamTokenizer(new BufferedReader(reader));
tok.lowerCaseMode(true);
tok.slashSlashComments(true);
tok.slashStarComments(true);
tok.eolIsSignificant(false);
tok.wordChars('
tok.wordChars('_', '_');
parse(tok);
}
public ColorRGBA getColor (BComponent component, String pseudoClass)
{
return (ColorRGBA)findProperty(component, pseudoClass, "color", true);
}
public BBackground getBackground (BComponent component, String pseudoClass)
{
return (BBackground)findProperty(
component, pseudoClass, "background", false);
}
public BIcon getIcon (BComponent component, String pseudoClass)
{
return (BIcon)findProperty(component, pseudoClass, "icon", false);
}
public BTextFactory getTextFactory (
BComponent component, String pseudoClass)
{
return (BTextFactory)findProperty(component, pseudoClass, "font", true);
}
public int getTextAlignment (BComponent component, String pseudoClass)
{
Integer value = (Integer)
findProperty(component, pseudoClass, "text-align", true);
return (value == null) ? BConstants.LEFT : value.intValue();
}
public int getVerticalAlignment (BComponent component, String pseudoClass)
{
Integer value = (Integer)
findProperty(component, pseudoClass, "vertical-align", true);
return (value == null) ? BConstants.CENTER : value.intValue();
}
public int getTextEffect (BComponent component, String pseudoClass)
{
Integer value = (Integer)
findProperty(component, pseudoClass, "text-effect", true);
return (value == null) ? BConstants.NORMAL : value.intValue();
}
public ColorRGBA getEffectColor (BComponent component, String pseudoClass)
{
return (ColorRGBA)findProperty(
component, pseudoClass, "effect-color", true);
}
public Insets getInsets (BComponent component, String pseudoClass)
{
Insets insets = (Insets)
findProperty(component, pseudoClass, "padding", false);
return (insets == null) ? Insets.ZERO_INSETS : insets;
}
public BBorder getBorder (BComponent component, String pseudoClass)
{
return (BBorder)findProperty(component, pseudoClass, "border", false);
}
public Dimension getSize (BComponent component, String pseudoClass)
{
return (Dimension)findProperty(component, pseudoClass, "size", false);
}
public BKeyMap getKeyMap (BComponent component, String pseudoClass)
{
return new DefaultKeyMap();
}
protected Object findProperty (BComponent component, String pseudoClass,
String property, boolean climb)
{
Object value;
// first try this component's configured style class
String styleClass = component.getStyleClass();
String fqClass = makeFQClass(styleClass, pseudoClass);
if ((value = getProperty(fqClass, property)) != null) {
return value;
}
// next fall back to its un-qualified configured style
if (pseudoClass != null) {
if ((value = getProperty(styleClass, property)) != null) {
return value;
}
}
// if applicable climb up the hierarch to its parent and try there
if (climb) {
BComponent parent = component.getParent();
if (parent != null) {
return findProperty(parent, pseudoClass, property, climb);
}
}
// finally check the "root" class
fqClass = makeFQClass("root", pseudoClass);
if ((value = getProperty(fqClass, property)) != null) {
return value;
}
if (pseudoClass != null) {
return getProperty("root", property);
}
return null;
}
protected Object getProperty (String fqClass, String property)
{
Rule rule = (Rule)_rules.get(fqClass);
if (rule == null) {
return null;
}
// we need to lazily resolve certain properties at this time
Object prop = rule.get(_rules, property);
if (prop instanceof Property) {
prop = ((Property)prop).resolve(_rsrcprov);
rule.properties.put(property, prop);
}
return prop;
}
protected void parse (StreamTokenizer tok)
throws IOException
{
while (tok.nextToken() != StreamTokenizer.TT_EOF) {
Rule rule = startRule(tok);
while (parseProperty(tok, rule)) {}
_rules.put(makeFQClass(rule.styleClass, rule.pseudoClass), rule);
}
}
protected Rule startRule (StreamTokenizer tok)
throws IOException
{
if (tok.ttype != StreamTokenizer.TT_WORD) {
fail(tok, "style-class");
}
Rule rule = new Rule();
rule.styleClass = tok.sval;
switch (tok.nextToken()) {
case '{':
return rule;
case ':':
if (tok.nextToken() != StreamTokenizer.TT_WORD) {
fail(tok, "pseudo-class");
}
rule.pseudoClass = tok.sval;
if (tok.nextToken() != '{') {
fail(tok, "{");
}
return rule;
default:
fail(tok, "{ or :");
return null; // not reachable
}
}
protected boolean parseProperty (StreamTokenizer tok, Rule rule)
throws IOException
{
if (tok.nextToken() == '}') {
return false;
} else if (tok.ttype != StreamTokenizer.TT_WORD) {
fail(tok, "property-name");
}
int sline = tok.lineno();
String name = tok.sval;
if (tok.nextToken() != ':') {
fail(tok, ":");
}
ArrayList args = new ArrayList();
while (tok.nextToken() != ';' && tok.ttype != '}') {
switch (tok.ttype) {
case '\'':
case '"':
case StreamTokenizer.TT_WORD:
args.add(tok.sval);
break;
case StreamTokenizer.TT_NUMBER:
args.add(new Double(tok.nval));
break;
default:
System.err.println("Unexpected token: '" + (char)tok.ttype +
"'. Line " + tok.lineno() + ".");
break;
}
}
try {
rule.properties.put(name, createProperty(name, args));
// System.out.println(" " + name + " -> " + rule.get(name));
} catch (Exception e) {
System.err.println("Failure parsing property '" + name +
"' line " + sline + ": " + e.getMessage());
if (!(e instanceof IllegalArgumentException)) {
e.printStackTrace(System.err);
}
}
return true;
}
protected Object createProperty (String name, ArrayList args)
{
if (name.equals("color") || name.equals("effect-color")) {
return parseColor((String)args.get(0));
} else if (name.equals("background")) {
BackgroundProperty bprop = new BackgroundProperty();
bprop.type = (String)args.get(0);
if (bprop.type.equals("solid")) {
bprop.color = parseColor((String)args.get(1));
} else if (bprop.type.equals("image")) {
bprop.ipath = (String)args.get(1);
if (args.size() > 2) {
String scale = (String)args.get(2);
Integer scval = (Integer)_ibconsts.get(scale);
if (scval == null) {
throw new IllegalArgumentException(
"Unknown background scaling type: '" + scale + "'");
}
bprop.scale = scval.intValue();
}
} else if (bprop.type.equals("blank")) {
// nothing to do
} else {
throw new IllegalArgumentException(
"Unknown background type: '" + bprop.type + "'");
}
return bprop;
} else if (name.equals("icon")) {
IconProperty iprop = new IconProperty();
iprop.type = (String)args.get(0);
if (iprop.type.equals("image")) {
iprop.ipath = (String)args.get(1);
} else if (iprop.type.equals("blank")) {
iprop.width = parseInt(args.get(1));
iprop.height = parseInt(args.get(2));
} else {
throw new IllegalArgumentException(
"Unknown icon type: '" + iprop.type + "'");
}
return iprop;
} else if (name.equals("font")) {
try {
FontProperty fprop = new FontProperty();
fprop.family = (String)args.get(0);
fprop.style = (String)args.get(1);
if (!fprop.style.equals(PLAIN) && !fprop.style.equals(BOLD) &&
!fprop.style.equals(ITALIC) &&
!fprop.style.equals(BOLD_ITALIC)) {
throw new IllegalArgumentException(
"Unknown font style: '" + fprop.style + "'");
}
fprop.size = parseInt(args.get(2));
return fprop;
} catch (Exception e) {
e.printStackTrace(System.err);
throw new IllegalArgumentException(
"Fonts must be specified as: " +
"\"Font name\" plain|bold|italic|bolditalic point-size");
}
} else if (name.equals("text-align")) {
String type = (String)args.get(0);
Object value = _taconsts.get(type);
if (value == null) {
throw new IllegalArgumentException(
"Unknown text-align type '" + type + "'");
}
return value;
} else if (name.equals("vertical-align")) {
String type = (String)args.get(0);
Object value = _vaconsts.get(type);
if (value == null) {
throw new IllegalArgumentException(
"Unknown vertical-align type '" + type + "'");
}
return value;
} else if (name.equals("text-effect")) {
String type = (String)args.get(0);
Object value = _teconsts.get(type);
if (value == null) {
throw new IllegalArgumentException(
"Unknown text-effect type '" + type + "'");
}
return value;
} else if (name.equals("padding")) {
Insets insets = new Insets();
insets.top = parseInt(args.get(0));
insets.right = (args.size() > 1) ?
parseInt(args.get(1)) : insets.top;
insets.bottom = (args.size() > 2) ?
parseInt(args.get(2)) : insets.top;
insets.left = (args.size() > 3) ?
parseInt(args.get(3)) : insets.right;
return insets;
} else if (name.equals("border")) {
int thickness = parseInt(args.get(0));
String type = (String)args.get(1);
if (type.equals("blank")) {
return new EmptyBorder(
thickness, thickness, thickness, thickness);
} else if (type.equals("solid")) {
// TODO: use thickness
return new LineBorder(parseColor((String)args.get(2)));
} else {
throw new IllegalArgumentException(
"Unknown border type '" + type + "'");
}
} else if (name.equals("size")) {
Dimension size = new Dimension();
size.width = parseInt(args.get(0));
size.height = parseInt(args.get(1));
return size;
} else if (name.equals("parent")) {
Rule parent = (Rule)_rules.get(args.get(0));
if (parent == null) {
throw new IllegalArgumentException(
"Unknown parent class '" + args.get(0) + "'");
}
return parent;
} else {
throw new IllegalArgumentException(
"Unknown property '" + name + "'");
}
}
protected void fail (StreamTokenizer tok, String expected)
throws IOException
{
String err = "Parse failure line: " + tok.lineno() +
" expected: '" + expected + "' found: '";
switch (tok.ttype) {
case StreamTokenizer.TT_WORD: err += tok.sval; break;
case StreamTokenizer.TT_NUMBER: err += tok.nval; break;
case StreamTokenizer.TT_EOF: err += "EOF"; break;
default: err += (char)tok.ttype;
}
throw new IOException(err + "'");
}
protected ColorRGBA parseColor (String hex)
{
if (!hex.startsWith("
(hex.length() != 7 && hex.length() != 9)) {
String errmsg = "Color must be #RRGGBB or #RRGGBBAA: " + hex;
throw new IllegalArgumentException(errmsg);
}
float r = Integer.parseInt(hex.substring(1, 3), 16) / 255f;
float g = Integer.parseInt(hex.substring(3, 5), 16) / 255f;
float b = Integer.parseInt(hex.substring(5, 7), 16) / 255f;
float a = 1f;
if (hex.length() == 9) {
a = Integer.parseInt(hex.substring(7, 9), 16) / 255f;
}
return new ColorRGBA(r, g, b, a);
}
protected int parseInt (Object arg)
{
return (int)((Double)arg).doubleValue();
}
protected static String makeFQClass (String styleClass, String pseudoClass)
{
return (pseudoClass == null) ? styleClass :
(styleClass + ":" + pseudoClass);
}
protected static class Rule
{
public String styleClass;
public String pseudoClass;
public HashMap properties = new HashMap();
public Object get (HashMap rules, String key)
{
Object value = properties.get(key);
if (value != null) {
return value;
}
Rule prule = (Rule)properties.get("parent");
return (prule != null) ? prule.get(rules, key) : null;
}
public String toString () {
return "[class=" + styleClass + ", pclass=" + pseudoClass + "]";
}
}
protected static abstract class Property
{
public abstract Object resolve (ResourceProvider rsrcprov);
}
protected static class FontProperty extends Property
{
String family;
String style;
int size;
public Object resolve (ResourceProvider rsrcprov) {
// System.out.println("Resolving text factory [family=" + family +
// ", style=" + style + ", size=" + size + "].");
return rsrcprov.createTextFactory(family, style, size);
}
}
protected static class BackgroundProperty extends Property
{
String type;
ColorRGBA color;
String ipath;
int scale = ImageBackground.SCALE_XY;
public Object resolve (ResourceProvider rsrcprov) {
if (type.equals("solid")) {
return new TintedBackground(color);
} else if (type.equals("image")) {
Image image;
try {
image = rsrcprov.loadImage(ipath);
} catch (IOException ioe) {
System.err.println("Failed to load background image '" +
ipath + "': " + ioe);
return new BlankBackground();
}
// TODO: parse stretching/centering/tiling rule
return new ImageBackground(scale, image);
} else {
return new BlankBackground();
}
}
}
protected static class IconProperty extends Property
{
public String type;
public String ipath;
public int width, height;
public Object resolve (ResourceProvider rsrcprov) {
if (type.equals("image")) {
Image image;
try {
image = rsrcprov.loadImage(ipath);
} catch (IOException ioe) {
System.err.println("Failed to load icon image '" +
ipath + "': " + ioe);
return new BlankBackground();
}
return new ImageIcon(image);
} else if (type.equals("blank")) {
return new BlankIcon(width, height);
} else {
return new BlankIcon(10, 10);
}
}
}
protected ResourceProvider _rsrcprov;
protected HashMap _rules = new HashMap();
protected static HashMap _taconsts = new HashMap();
protected static HashMap _vaconsts = new HashMap();
protected static HashMap _teconsts = new HashMap();
protected static HashMap _ibconsts = new HashMap();
static {
// alignment constants
_taconsts.put("left", new Integer(BConstants.LEFT));
_taconsts.put("right", new Integer(BConstants.RIGHT));
_taconsts.put("center", new Integer(BConstants.CENTER));
_vaconsts.put("center", new Integer(BConstants.CENTER));
_vaconsts.put("top", new Integer(BConstants.TOP));
_vaconsts.put("bottom", new Integer(BConstants.BOTTOM));
// effect constants
_teconsts.put("none", new Integer(BConstants.NORMAL));
_teconsts.put("shadow", new Integer(BConstants.SHADOW));
_teconsts.put("outline", new Integer(BConstants.OUTLINE));
// background image constants
_ibconsts.put("centerxy", new Integer(ImageBackground.CENTER_XY));
_ibconsts.put("centerx", new Integer(ImageBackground.CENTER_X));
_ibconsts.put("centery", new Integer(ImageBackground.CENTER_Y));
_ibconsts.put("scalexy", new Integer(ImageBackground.SCALE_XY));
_ibconsts.put("scalex", new Integer(ImageBackground.SCALE_X));
_ibconsts.put("scaley", new Integer(ImageBackground.SCALE_Y));
_ibconsts.put("tilexy", new Integer(ImageBackground.TILE_XY));
_ibconsts.put("tilex", new Integer(ImageBackground.TILE_X));
_ibconsts.put("tiley", new Integer(ImageBackground.TILE_Y));
_ibconsts.put("framexy", new Integer(ImageBackground.FRAME_XY));
_ibconsts.put("framex", new Integer(ImageBackground.FRAME_X));
_ibconsts.put("framey", new Integer(ImageBackground.FRAME_Y));
}
} |
package shadow.pgsql;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class PreparedSQL implements AutoCloseable {
private final static TypeHandler[] NO_COLUMNS = new TypeHandler[0];
protected final Connection pg;
protected final String statementId;
protected final SQL sql;
protected final ColumnInfo[] columnInfos;
protected final TypeHandler[] typeDecoders;
private final ResultBuilder resultBuilder;
private final RowBuilder rowBuilder;
protected final TypeHandler[] typeEncoders;
final Timer executeTimer;
// statement
PreparedSQL(Connection pg, String statementId, TypeHandler[] typeEncoders, SQL sql) {
this(pg, statementId, typeEncoders, sql, null, null, null, null);
}
// query
PreparedSQL(Connection pg, String statementId, TypeHandler[] typeEncoders, SQL sql, ColumnInfo[] columnInfos, TypeHandler[] typeDecoders, ResultBuilder resultBuilder, RowBuilder rowBuilder) {
this.pg = pg;
this.statementId = statementId;
this.typeEncoders = typeEncoders;
this.executeTimer = getExecuteTimer(pg, sql.getName());
this.sql = sql;
this.columnInfos = columnInfos;
this.typeDecoders = typeDecoders;
this.resultBuilder = resultBuilder;
this.rowBuilder = rowBuilder;
pg.db.preparedCounter.inc();
}
public SQL getSQL() {
return sql;
}
public StatementResult executeWith(Object... queryParams) throws IOException {
return execute(Arrays.asList(queryParams));
}
public StatementResult execute(List queryParams) throws IOException {
if (sql.expectsData()) {
throw new IllegalStateException("SQL expects data, use query");
}
Timer.Context timerContext = executeTimer.time();
// flow -> B/E/S
executeWithParams(NO_COLUMNS, queryParams);
// flow <- 2/C/Z
final StatementResult result = pg.input.readStatementResult(sql.getSQLString());
pg.db.metricCollector.collectExecuteTime(sql.getName(), sql.getSQLString(), timerContext.stop());
return result;
}
public Object queryWith(Object... params) throws IOException {
return query(Arrays.asList(params));
}
public Object query(final List queryParams) throws IOException {
if (!sql.expectsData()) {
throw new IllegalStateException("SQL expects no data, use execute");
}
final Timer.Context timerContext = executeTimer.time();
executeWithParams(typeDecoders, queryParams);
Object queryResult = resultBuilder.init();
Map<String, String> errorData = null;
boolean complete = false;
// flow <- 2/D*/n?/C/Z
RESULT_LOOP:
while (true) {
final char type = pg.input.readNextCommand();
switch (type) {
case '2': // BindComplete
{
pg.input.checkSize("BindComplete", 0);
break;
}
case 'D': // DataRow
{
queryResult = resultBuilder.add(queryResult, readRow());
break;
}
case 'C': { // CommandComplete
final String tag = pg.input.readString();
complete = true;
// FIXME: losing information (tag)
break;
}
case 'Z': // ReadyForQuery
{
pg.input.readReadyForQuery();
break RESULT_LOOP;
}
case 'E': {
errorData = pg.input.readMessages();
break;
}
default: {
throw new IllegalStateException(String.format("invalid protocol action while reading query results: '%s'", type));
}
}
}
if (errorData != null) {
throw new CommandException(String.format("Failed to execute Query\nsql: %s\n", sql.getSQLString()), errorData);
}
if (!complete) {
throw new IllegalStateException("Command did not complete");
}
final Object result = resultBuilder.complete(queryResult);
pg.db.metricCollector.collectExecuteTime(sql.getName(), sql.getSQLString(), timerContext.stop());
return result;
}
private Object readRow() throws IOException {
final int cols = pg.input.getShort();
if (cols != columnInfos.length) {
throw new IllegalStateException(
String.format("backend said to expect %d columns, but data had %d", columnInfos.length, cols)
);
}
Object row = rowBuilder.init();
for (int i = 0; i < columnInfos.length; i++) {
final ColumnInfo field = columnInfos[i];
final TypeHandler decoder = typeDecoders[i];
final int colSize = pg.input.getInt();
Object columnValue = null;
if (colSize != -1) {
columnValue = readColumnValue(field, decoder, colSize);
}
row = rowBuilder.add(row, field, i, columnValue);
}
return rowBuilder.complete(row);
}
private Object readColumnValue(ColumnInfo field, TypeHandler decoder, int colSize) throws IOException {
try {
Object columnValue;
if (decoder.supportsBinary()) {
int mark = pg.input.current.position();
columnValue = decoder.decodeBinary(pg, field, pg.input.current, colSize);
if (pg.input.current.position() != mark + colSize) {
throw new IllegalStateException(String.format("Field:[%s ,%s] did not consume all bytes", field.name, decoder));
}
} else {
byte[] bytes = new byte[colSize];
pg.input.getBytes(bytes);
// FIXME: assumes UTF-8
final String stringValue = new String(bytes);
columnValue = decoder.decodeString(pg, field, stringValue);
}
return columnValue;
} catch (Exception e) {
throw new IllegalStateException(
String.format("Failed parsing field \"%s\" of table \"%s\"",
field.name,
field.tableOid > 0 ? pg.db.oid2name.get(field.tableOid) : "--unknown
), e);
}
}
protected void writeBind(TypeHandler[] typeDecoders, List<Object> queryParams, String portalId) {
// Bind
pg.output.beginCommand('B');
pg.output.string(portalId); // portal name (might be null)
pg.output.string(statementId); // statement name (should not be null)
// format codes for params
pg.output.int16((short) typeEncoders.length);
for (TypeHandler t : typeEncoders) {
pg.output.int16((short) (t.supportsBinary() ? 1 : 0)); // format code 0 = text, 1 = binary
}
pg.output.int16((short) typeEncoders.length);
for (int i = 0; i < typeEncoders.length; i++) {
TypeHandler encoder = typeEncoders[i];
Object param = queryParams.get(i);
try {
if (param == null) {
pg.output.int32(-1);
} else if (encoder.supportsBinary()) {
pg.output.beginExclusive();
encoder.encodeBinary(pg, pg.output, param);
pg.output.complete();
} else {
String paramString = encoder.encodeToString(pg, param);
// FIXME: assumes UTF-8
byte[] bytes = paramString.getBytes();
pg.output.int32(bytes.length);
if (bytes.length > 0) {
pg.output.bytea(bytes);
}
}
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Failed to encode parameter $%d [%s -> \"%s\"]\nsql: %s", i + 1, encoder.getClass().getName(), param, sql.getSQLString()), e);
}
}
pg.output.int16((short) typeDecoders.length);
for (TypeHandler t : typeDecoders) {
pg.output.int16((short) (t.supportsBinary() ? 1 : 0));
}
pg.output.complete();
}
protected void writeExecute(String portalId, int limit) {
pg.output.beginCommand('E');
pg.output.string(portalId); // portal name
pg.output.int32(limit); // max rows, zero = no limit
pg.output.complete();
}
protected void writeSync() {
// Sync
pg.output.simpleCommand('S');
}
protected void executeWithParams(TypeHandler[] typeDecoders, List queryParams) throws IOException {
if (queryParams.size() != typeEncoders.length) {
throw new IllegalArgumentException(String.format("Incorrect params provided to Statement, expected %d got %d", typeEncoders.length, queryParams.size()));
}
pg.checkReady();
pg.output.checkReset();
// flow -> B/E/H
try {
writeBind(typeDecoders, queryParams, null);
writeExecute(null, 0);
writeSync();
pg.output.flushAndReset();
pg.state = ConnectionState.QUERY_RESULT;
} catch (Exception e) {
// nothing on the wire, no harm done
pg.output.reset();
pg.state = ConnectionState.READY;
throw e;
}
}
public void close() throws IOException {
pg.closeStatement(statementId);
pg.db.preparedCounter.dec();
}
static Timer getExecuteTimer(Connection pg, String metricsName) {
// FIXME: don't like that this is constructed every time, Query/Statement maybe a better place to keep these?
if (metricsName != null) {
return pg.db.metricRegistry.timer(MetricRegistry.name("shadow-pgsql", "query", metricsName, "execute"));
} else {
return pg.db.unnamedExecuteTimer;
}
}
} |
package jmetest.effects;
import jmetest.renderer.TestBoxColor;
import jmetest.renderer.TestEnvMap;
import com.jme.app.SimpleGame;
import com.jme.bounding.BoundingBox;
import com.jme.bounding.BoundingSphere;
import com.jme.image.Texture;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.math.FastMath;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.scene.Spatial;
import com.jme.scene.Text;
import com.jme.scene.Spatial.CullHint;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.shape.Box;
import com.jme.scene.shape.Sphere;
import com.jme.scene.state.BlendState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.util.TextureManager;
import com.jme.util.Timer;
import com.jmex.effects.TrailMesh;
/**
* <code>TestTrailMesh</code>
*
* @author Rikard Herlitz (MrCoder)
*/
public class TestTrailMesh extends SimpleGame {
private Sphere sphere;
private TrailMesh trailMesh;
private Vector3f tangent = new Vector3f();
private boolean updateTrail = true;
private boolean variableWidth = false;
public static void main(String[] args) {
TestTrailMesh app = new TestTrailMesh();
app.setConfigShowMode(ConfigShowMode.AlwaysShow);
app.start();
}
protected void simpleUpdate() {
if (KeyBindingManager.getKeyBindingManager().isValidCommand("1", false)) {
trailMesh.setFacingMode(TrailMesh.FacingMode.Tangent);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("2", false)) {
trailMesh.setFacingMode(TrailMesh.FacingMode.Billboard);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("3", false)) {
trailMesh.setUpdateMode(TrailMesh.UpdateMode.Step);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("4", false)) {
trailMesh.setUpdateMode(TrailMesh.UpdateMode.Interpolate);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("5", false)) {
trailMesh.setUpdateSpeed(trailMesh.getUpdateSpeed() * 2.0f);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("6", false)) {
trailMesh.setUpdateSpeed(trailMesh.getUpdateSpeed() * 0.5f);
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("freeze",
false)) {
updateTrail = !updateTrail;
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("width",
false)) {
variableWidth = !variableWidth;
}
if (KeyBindingManager.getKeyBindingManager().isValidCommand("reset",
false)) {
trailMesh.resetPosition(sphere.getWorldTranslation());
}
// Update the trail front position
if (updateTrail) {
// Do some crappy moving around
float speed = timer.getTimeInSeconds() * 4.0f;
float xPos = FastMath.sin(speed)
* (FastMath.sin(speed * 0.7f) * 80.0f + 0.0f);
float yPos = FastMath.sin(speed * 1.5f) * 20.0f + 20.0f;
float zPos = FastMath.cos(speed * 1.2f)
* (FastMath.sin(speed) * 80.0f + 0.0f);
sphere.getLocalTranslation().set(xPos, yPos, zPos);
sphere.updateGeometricState(0.0f, true);
// Create a spin for tangent mode
tangent.set(xPos, yPos, zPos);
tangent.normalizeLocal();
// Setup width
float width = 7.0f;
if (variableWidth) {
width = FastMath.sin(speed * 3.7f) * 10.0f + 15.0f;
}
// If you use the Tangent mode you have to send a tangent vector as
// well (spin), otherwise you can just drop that variable like this:
// trailMesh.setTrailFront(sphere.getWorldTranslation(), width,
// Timer
// .getTimer().getTimePerFrame());
trailMesh.setTrailFront(sphere.getWorldTranslation(), tangent,
width, Timer.getTimer().getTimePerFrame());
}
// Update the mesh
trailMesh.update(cam.getLocation());
}
protected void simpleInitGame() {
display.setTitle("TestTrailMesh");
cam.getLocation().set(new Vector3f(140, 140, 140));
cam.lookAt(new Vector3f(), Vector3f.UNIT_Y);
// Create the trail
trailMesh = new TrailMesh("TrailMesh", 100);
trailMesh.setUpdateSpeed(60.0f);
trailMesh.setFacingMode(TrailMesh.FacingMode.Billboard);
trailMesh.setUpdateMode(TrailMesh.UpdateMode.Step);
// Try out some additive blending etc
trailMesh.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
trailMesh.setCullHint(CullHint.Never);
TextureState ts = display.getRenderer().createTextureState();
ts.setEnabled(true);
Texture t1 = TextureManager.loadTexture(
TestBoxColor.class.getClassLoader().getResource(
"jmetest/data/texture/trail.png"),
Texture.MinificationFilter.Trilinear,
Texture.MagnificationFilter.Bilinear);
ts.setTexture(t1);
trailMesh.setRenderState(ts);
BlendState bs = display.getRenderer().createBlendState();
bs.setBlendEnabled(true);
bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
bs.setDestinationFunction(BlendState.DestinationFunction.One);
bs.setTestEnabled(true);
trailMesh.setRenderState(bs);
ZBufferState zs = display.getRenderer().createZBufferState();
zs.setWritable(false);
trailMesh.setRenderState(zs);
CullState cs = display.getRenderer().createCullState();
cs.setCullFace(CullState.Face.None);
cs.setEnabled(true);
trailMesh.setRenderState(cs);
rootNode.attachChild(trailMesh);
// Create a background floor
Box floor = new Box("Floor", new Vector3f(), 200, 1, 200);
floor.setModelBound(new BoundingBox());
floor.updateModelBound();
floor.getLocalTranslation().y = -20;
ts = display.getRenderer().createTextureState();
Texture t0 = TextureManager.loadTexture(TestEnvMap.class
.getClassLoader().getResource("jmetest/data/texture/top.jpg"),
Texture.MinificationFilter.Trilinear,
Texture.MagnificationFilter.Bilinear);
t0.setWrap(Texture.WrapMode.Repeat);
ts.setTexture(t0);
floor.setRenderState(ts);
floor.scaleTextureCoordinates(0, 5);
rootNode.attachChild(floor);
// Create a sphere as trail guide
sphere = new Sphere("Sphere", 16, 16, 4);
sphere.setModelBound(new BoundingSphere());
sphere.updateModelBound();
ts = display.getRenderer().createTextureState();
ts.setEnabled(true);
t1 = TextureManager.loadTexture(TestBoxColor.class.getClassLoader()
.getResource("jmetest/data/texture/post.jpg"),
Texture.MinificationFilter.Trilinear,
Texture.MagnificationFilter.Bilinear);
ts.setTexture(t1);
sphere.setRenderState(ts);
rootNode.attachChild(sphere);
// No lighting for clarity
rootNode.setLightCombineMode(LightCombineMode.Off);
rootNode.setRenderQueueMode(com.jme.renderer.Renderer.QUEUE_OPAQUE);
// Setup some keys for playing around with settings
setupKeyBindings();
}
private void setupKeyBindings() {
KeyBindingManager.getKeyBindingManager().set("freeze", KeyInput.KEY_F);
KeyBindingManager.getKeyBindingManager().set("width", KeyInput.KEY_G);
KeyBindingManager.getKeyBindingManager().set("1", KeyInput.KEY_1);
KeyBindingManager.getKeyBindingManager().set("2", KeyInput.KEY_2);
KeyBindingManager.getKeyBindingManager().set("3", KeyInput.KEY_3);
KeyBindingManager.getKeyBindingManager().set("4", KeyInput.KEY_4);
KeyBindingManager.getKeyBindingManager().set("5", KeyInput.KEY_5);
KeyBindingManager.getKeyBindingManager().set("6", KeyInput.KEY_6);
KeyBindingManager.getKeyBindingManager().set("reset", KeyInput.KEY_E);
Text t = Text.createDefaultTextLabel("Text", "1/2: Tangent/Billboard");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 120, 1));
statNode.attachChild(t);
t = Text.createDefaultTextLabel("Text", "3/4: Step/Interpolate");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 100, 1));
statNode.attachChild(t);
t = Text
.createDefaultTextLabel("Text", "5/6: Raise/Lower update speed");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 80, 1));
statNode.attachChild(t);
t = Text.createDefaultTextLabel("Text", "F: Freeze");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 60, 1));
statNode.attachChild(t);
t = Text.createDefaultTextLabel("Text",
"G: Enable/Disable variable width");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 40, 1));
statNode.attachChild(t);
t = Text.createDefaultTextLabel("Text", "E: Reset position");
t.setRenderQueueMode(Renderer.QUEUE_ORTHO);
t.setLightCombineMode(Spatial.LightCombineMode.Off);
t.setLocalTranslation(new Vector3f(0, 20, 1));
statNode.attachChild(t);
}
} |
package jp.isisredirect.tts;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.util.TiActivityResultHandler;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.Engine;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.text.TextUtils;
import android.os.Build;
@Kroll.module(name="Tts", id="jp.isisredirect.tts")
public class TtsModule extends KrollModule implements OnInitListener, OnUtteranceCompletedListener, TiActivityResultHandler
{
private static final String LCAT = "TtsModule";
private static final boolean DBG = TiConfig.LOGD;
@Kroll.constant
public static final String TTS_ERROR = "error";
@Kroll.constant
public static final String TTS_CHKOK = "checkok";
@Kroll.constant
public static final String TTS_INITOK = "initok";
@Kroll.constant
public static final String TTS_INSTALL_START = "ttsinstallstart";
@Kroll.constant
public static final String TTS_UTTERANCE_ID = "utteranceid";
@Kroll.constant
public static final String TTS_UTTERANCE_COMPLETE = "utterancecomplete";
@Kroll.constant
public static final String TTS_MESSAGE = "message";
@Kroll.constant
public static final String TTS_VOICES = "voices";
private boolean initialized = false;
private TextToSpeech tts;
private float pitch = 1.0f;
private float rate = 1.0f;
private static final int CHECK_TTS = 682730934;
public TtsModule() {
super();
}
@Kroll.onAppCreate
public static void onAppCreate(TiApplication app)
{
if (DBG) Log.d(LCAT, "inside onAppCreate");
// put module init code that needs to run when the application is created
}
@Override
public void onStart(Activity activity) {
super.onStart(activity);
}
@Override
public void onResume(Activity activity) {
super.onResume(activity);
}
@Override
public void onPause(Activity activity) {
super.onPause(activity);
}
@Override
public void onStop(Activity activity) {
super.onStop(activity);
}
@Override
public void onDestroy(Activity activity) {
super.onDestroy(activity);
shutdown();
}
@Override
public void onInit(int status) {
if (DBG) Log.d(LCAT, "onInit " + status);
if(status == TextToSpeech.SUCCESS) {
initialized = true;
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
fireEvent(TTS_INITOK, data);
}else{
if (DBG) Log.e("TTS", "Init error.");
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
fireEvent(TTS_ERROR, data);
}
}
private static class MyEngineInfo {
public String name;
public String label;
@Override
public String toString() {
return "MyEngineInfo{name=" + name + "}";
}
}
private MyEngineInfo getEngineInfo(ResolveInfo resolve, PackageManager pm) {
ServiceInfo service = resolve.serviceInfo;
if (service != null) {
MyEngineInfo engine = new MyEngineInfo();
engine.name = service.packageName;
CharSequence label = service.loadLabel(pm);
engine.label = TextUtils.isEmpty(label) ? engine.name : label
.toString();
return engine;
}
return null;
}
@Kroll.method
public KrollDict getEngines() {
KrollDict data = new KrollDict();
PackageManager pm = TiApplication.getInstance().getPackageManager();
Intent intent = new Intent(Engine.INTENT_ACTION_TTS_SERVICE);
List<ResolveInfo> resolveInfos = pm.queryIntentServices(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfos == null)
return data;
for (ResolveInfo resolveInfo : resolveInfos) {
MyEngineInfo engine = getEngineInfo(resolveInfo, pm);
if (engine != null) {
data.put(engine.label, engine.name);
}
}
return data;
}
private boolean isPackageInstalled(String packageName) {
PackageManager pm = TiApplication.getInstance().getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi != null;
} catch (NameNotFoundException e) {
return false;
}
}
@Kroll.method
public boolean initTTS(
@Kroll.argument(optional = true) String enginepackangename) {
shutdown();
if (enginepackangename != null) {
if (DBG) Log.d(LCAT, "initTTS engine:"+enginepackangename);
if (isPackageInstalled(enginepackangename)) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2) {
tts = new TextToSpeech(TiApplication.getInstance(), this);
tts.setEngineByPackageName(enginepackangename);
} else {
tts = new TextToSpeech(TiApplication.getInstance(), this, enginepackangename);
}
return true;
} else {
if (DBG) Log.d(LCAT, "initTTS engine not found");
return false;
}
} else {
tts = new TextToSpeech(TiApplication.getInstance(), this);
return true;
}
}
@Kroll.method
public void checkTTS(
@Kroll.argument(optional = true) String enginepackangename) {
shutdown();
TiBaseActivity activity = TiApplication.getInstance().getRootActivity();
Intent intent;
if (enginepackangename != null) {
intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
intent.setPackage(enginepackangename);
}else{
intent = new Intent();
}
intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
activity.launchActivityForResult(intent, CHECK_TTS, this);
}
// implements TiActivityResultHandler
@Override
public void onError(Activity activity, int requestCode, Exception e) {
if (CHECK_TTS == requestCode) {
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
data.put(TTS_MESSAGE, e.getLocalizedMessage());
fireEvent(TTS_ERROR, data);
}
}
//implements TiActivityResultHandler
@Override
public void onResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (CHECK_TTS == requestCode) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
ArrayList<String> voices= data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
if (voices != null) {
if (DBG) Log.d(LCAT, "voices:" + voices.toString());
}
KrollDict resultdata = new KrollDict();
resultdata.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
resultdata.put(TTS_VOICES, voices.toArray(new String[voices.size()]));
fireEvent(TTS_CHKOK, resultdata);
} else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
activity.startActivity(install);
KrollDict resultdata = new KrollDict();
resultdata.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
fireEvent(TTS_INSTALL_START, resultdata);
}
}
}
@Kroll.method
public boolean isSupportedLang(String localeString)
{
if (localeString == null || localeString.isEmpty()) {
return false;
}
if (!initialized) {
return false;
}
Locale locale = makeLocaleByString(localeString);
return (TextToSpeech.LANG_AVAILABLE <= tts.isLanguageAvailable(locale));
}
@Kroll.method
public boolean setLanguage(String localeString)
{
if (localeString == null || localeString.isEmpty()) {
return false;
}
if (!initialized) {
return false;
}
if (isSupportedLang(localeString)) {
if (DBG) Log.d(LCAT, "setLanguage:" + localeString);
Locale locale = makeLocaleByString(localeString);
if (DBG) Log.d(LCAT, "setLanguage getVariant():"+ locale.getVariant());
switch (tts.setLanguage(locale)) {
case TextToSpeech.LANG_AVAILABLE:
if (DBG) Log.d(LCAT, "setLanguage supported LANG_AVAILABLE:" + localeString);
return true;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
if (DBG) Log.d(LCAT, "setLanguage supported LANG_COUNTRY_AVAILABLE:" + localeString);
return true;
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
if (DBG) Log.d(LCAT, "setLanguage supported LANG_COUNTRY_VAR_AVAILABLE:" + localeString);
return true;
case TextToSpeech.LANG_MISSING_DATA:
case TextToSpeech.LANG_NOT_SUPPORTED:
default:
break;
}
}
if (DBG) Log.d(LCAT, "setLanguage not supported:" + localeString);
return false;
}
private Locale makeLocaleByString(String localeString) {
Locale locale;
String[] elememts = localeString.replaceAll("-", "_").split("_", -1);
switch (elememts.length) {
case 3:
locale = new Locale(elememts[0], elememts[1], elememts[2]);
break;
case 2:
locale = new Locale(elememts[0], elememts[1]);
break;
case 1:
default:
locale = new Locale(localeString);
break;
}
return locale;
}
@Kroll.method
public String getLanguage()
{
if (!initialized) {
return "";
}
Locale locale = tts.getLanguage();
if (DBG) Log.d(LCAT, "getLanguage:" + locale.toString());
return locale.toString();
}
@Kroll.method
public boolean isSpeaking() {
if (DBG) Log.d(LCAT, "isSpeaking" );
if (initialized) {
return tts.isSpeaking();
}
return false;
}
@Kroll.method
public boolean speak(String text, @Kroll.argument(optional = true) String utteranceId) {
if (DBG) Log.d(LCAT, "speak " + text);
if (initialized) {
if (0 < text.length()) {
if (tts.setPitch(getPitch()) == TextToSpeech.ERROR) {
if (DBG) Log.e("TTS", "Ptich(" + getPitch() + ") set error.");
}
if (tts.setSpeechRate(getRate()) == TextToSpeech.ERROR) {
if (DBG) Log.e("TTS", "Speech rate(" + getRate() + ") set error.");
}
stopSpeaking();
tts.setOnUtteranceCompletedListener(this);
HashMap<String, String> options = new HashMap<String, String>();
//myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
// String.valueOf(AudioManager.STREAM_ALARM));
options.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
utteranceId);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, options);
}
}
return true;
}
// implements OnUtteranceCompletedListener
@Override
public void onUtteranceCompleted(String utteranceId) {
KrollDict data = new KrollDict();
data.put(TiC.EVENT_PROPERTY_SOURCE, TtsModule.this);
data.put(TTS_UTTERANCE_ID, utteranceId);
fireEvent(TTS_UTTERANCE_COMPLETE, data);
}
@Kroll.method
public void stopSpeaking() {
if (DBG) Log.d(LCAT, "stopSpeaking ");
if (initialized) {
if (isSpeaking()) {
tts.stop();
}
}
}
// @Kroll.method
@Kroll.getProperty
public boolean getIsInitialized() {
return initialized;
}
@Kroll.method
@Kroll.setProperty
public void setPitch(float pitch) {
this.pitch = pitch;
}
@Kroll.method
@Kroll.getProperty
public float getPitch() {
return pitch;
}
@Kroll.method
@Kroll.setProperty
public void setRate(float rate) {
this.rate = rate;
}
@Kroll.method
@Kroll.getProperty
public float getRate() {
return rate;
}
@Kroll.method
public void shutdown() {
if (tts != null) {
tts.shutdown();
tts = null;
initialized = false;
}
}
@Kroll.method
public void showTTSSettings() {
Intent intent = new Intent();
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2) {
ComponentName componentToLaunch = new ComponentName(
"com.android.settings",
"com.android.settings.TextToSpeechSettings");
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(componentToLaunch);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
intent = new Intent();
intent.setAction("com.android.settings.TTS_SETTINGS");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
try {
if (DBG) Log.i(LCAT, "startActivity : TextToSpeechSettings");
TiApplication.getInstance().getRootActivity().startActivity(intent);
} catch (ActivityNotFoundException e) {
if (DBG) Log.e(LCAT, "ActivityNotFoundException");
}
}
} |
package edu.umd.cs.piccolo;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.event.EventListenerList;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import edu.umd.cs.piccolo.activities.PActivity;
import edu.umd.cs.piccolo.activities.PColorActivity;
import edu.umd.cs.piccolo.activities.PInterpolatingActivity;
import edu.umd.cs.piccolo.activities.PTransformActivity;
import edu.umd.cs.piccolo.event.PInputEventListener;
import edu.umd.cs.piccolo.util.PAffineTransform;
import edu.umd.cs.piccolo.util.PAffineTransformException;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PNodeFilter;
import edu.umd.cs.piccolo.util.PObjectOutputStream;
import edu.umd.cs.piccolo.util.PPaintContext;
import edu.umd.cs.piccolo.util.PPickPath;
import edu.umd.cs.piccolo.util.PUtil;
/**
* <b>PNode</b> is the central abstraction in Piccolo. All objects that are
* visible on the screen are instances of the node class. All nodes may have
* other "child" nodes added to them.
* <p>
* See edu.umd.piccolo.examples.NodeExample.java for demonstrations of how nodes
* can be used and how new types of nodes can be created.
* <P>
*
* @version 1.0
* @author Jesse Grosjean
*/
public class PNode implements Cloneable, Serializable, Printable {
/**
* Allows for future serialization code to understand versioned binary
* formats.
*/
private static final long serialVersionUID = 1L;
/**
* The property name that identifies a change in this node's client
* propertie (see {@link #getClientProperty getClientProperty}). In an
* property change event the new value will be a reference to the map of
* client properties but old value will always be null.
*/
public static final String PROPERTY_CLIENT_PROPERTIES = "clientProperties";
public static final int PROPERTY_CODE_CLIENT_PROPERTIES = 1 << 0;
/**
* The property name that identifies a change of this node's bounds (see
* {@link #getBounds getBounds}, {@link #getBoundsReference
* getBoundsReference}). In any property change event the new value will be
* a reference to this node's bounds, but old value will always be null.
*/
public static final String PROPERTY_BOUNDS = "bounds";
public static final int PROPERTY_CODE_BOUNDS = 1 << 1;
/**
* The property name that identifies a change of this node's full bounds
* (see {@link #getFullBounds getFullBounds},
* {@link #getFullBoundsReference getFullBoundsReference}). In any property
* change event the new value will be a reference to this node's full bounds
* cache, but old value will always be null.
*/
public static final String PROPERTY_FULL_BOUNDS = "fullBounds";
public static final int PROPERTY_CODE_FULL_BOUNDS = 1 << 2;
/**
* The property name that identifies a change of this node's transform (see
* {@link #getTransform getTransform}, {@link #getTransformReference
* getTransformReference}). In any property change event the new value will
* be a reference to this node's transform, but old value will always be
* null.
*/
public static final String PROPERTY_TRANSFORM = "transform";
public static final int PROPERTY_CODE_TRANSFORM = 1 << 3;
/**
* The property name that identifies a change of this node's visibility (see
* {@link #getVisible getVisible}). Both old value and new value will be
* null in any property change event.
*/
public static final String PROPERTY_VISIBLE = "visible";
public static final int PROPERTY_CODE_VISIBLE = 1 << 4;
/**
* The property name that identifies a change of this node's paint (see
* {@link #getPaint getPaint}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final String PROPERTY_PAINT = "paint";
public static final int PROPERTY_CODE_PAINT = 1 << 5;
/**
* The property name that identifies a change of this node's transparency
* (see {@link #getTransparency getTransparency}). Both old value and new
* value will be null in any property change event.
*/
public static final String PROPERTY_TRANSPARENCY = "transparency";
public static final int PROPERTY_CODE_TRANSPARENCY = 1 << 6;
/**
* The property name that identifies a change of this node's pickable status
* (see {@link #getPickable getPickable}). Both old value and new value will
* be null in any property change event.
*/
public static final String PROPERTY_PICKABLE = "pickable";
public static final int PROPERTY_CODE_PICKABLE = 1 << 7;
/**
* The property name that identifies a change of this node's children
* pickable status (see {@link #getChildrenPickable getChildrenPickable}).
* Both old value and new value will be null in any property change event.
*/
public static final String PROPERTY_CHILDREN_PICKABLE = "childrenPickable";
public static final int PROPERTY_CODE_CHILDREN_PICKABLE = 1 << 8;
/**
* The property name that identifies a change in the set of this node's
* direct children (see {@link #getChildrenReference getChildrenReference},
* {@link #getChildrenIterator getChildrenIterator}). In any property change
* event the new value will be a reference to this node's children, but old
* value will always be null.
*/
public static final String PROPERTY_CHILDREN = "children";
public static final int PROPERTY_CODE_CHILDREN = 1 << 9;
/**
* The property name that identifies a change of this node's parent (see
* {@link #getParent getParent}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final String PROPERTY_PARENT = "parent";
public static final int PROPERTY_CODE_PARENT = 1 << 10;
private static final PBounds TEMP_REPAINT_BOUNDS = new PBounds();
/**
* The single scene graph delegate that recives low level node events.
*/
public static PSceneGraphDelegate SCENE_GRAPH_DELEGATE = null;
/**
* <b>PSceneGraphDelegate</b> is an interface to recive low level node
* events. It together with PNode.SCENE_GRAPH_DELEGATE gives Piccolo users
* an efficient way to learn about low level changes in Piccolo's scene
* graph. Most users will not need to use this.
*/
public interface PSceneGraphDelegate {
public void nodePaintInvalidated(PNode node);
public void nodeFullBoundsInvalidated(PNode node);
}
private transient PNode parent;
private List children;
private final PBounds bounds;
private PAffineTransform transform;
private Paint paint;
private float transparency;
private MutableAttributeSet clientProperties;
private PBounds fullBoundsCache;
private int propertyChangeParentMask = 0;
private transient SwingPropertyChangeSupport changeSupport;
private transient EventListenerList listenerList;
private boolean pickable;
private boolean childrenPickable;
private boolean visible;
private boolean childBoundsVolatile;
private boolean paintInvalid;
private boolean childPaintInvalid;
private boolean boundsChanged;
private boolean fullBoundsInvalid;
private boolean childBoundsInvalid;
private boolean occluded;
private String name;
public void setName(final String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
* Calls {@link PNode} followed by {@link PNode#setName(String)}.
*/
public PNode(final String name) {
this();
setName(name);
}
/**
* Constructs a new PNode.
* <P>
* By default a node's paint is null, and bounds are empty. These values
* must be set for the node to show up on the screen once it's added to a
* scene graph.
*/
public PNode() {
bounds = new PBounds();
fullBoundsCache = new PBounds();
transparency = 1.0f;
pickable = true;
childrenPickable = true;
visible = true;
}
// Animation - Methods to animate this node.
// Note that animation is implemented by activities (PActivity),
// so if you need more control over your animation look at the
// activities package. Each animate method creates an animation that
// will animate the node from its current state to the new state
// specified over the given duration. These methods will try to
// automatically schedule the new activity, but if the node does not
// descend from the root node when the method is called then the
// activity will not be scheduled and you must schedule it manually.
/**
* Animate this node's bounds from their current location when the activity
* starts to the specified bounds. If this node descends from the root then
* the activity will be scheduled, else the returned activity should be
* scheduled manually. If two different transform activities are scheduled
* for the same node at the same time, they will both be applied to the
* node, but the last one scheduled will be applied last on each frame, so
* it will appear to have replaced the original. Generally you will not want
* to do that. Note this method animates the node's bounds, but does not
* change the node's transform. Use animateTransformToBounds() to animate
* the node's transform instead.
*
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToBounds(final double x, final double y, final double width,
final double height, final long duration) {
if (duration == 0) {
setBounds(x, y, width, height);
return null;
}
else {
final PBounds dst = new PBounds(x, y, width, height);
final PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) {
private PBounds src;
protected void activityStarted() {
src = getBounds();
startResizeBounds();
super.activityStarted();
}
public void setRelativeTargetValue(final float zeroToOne) {
PNode.this.setBounds(src.x + zeroToOne * (dst.x - src.x), src.y + zeroToOne * (dst.y - src.y),
src.width + zeroToOne * (dst.width - src.width), src.height + zeroToOne
* (dst.height - src.height));
}
protected void activityFinished() {
super.activityFinished();
endResizeBounds();
}
};
addActivity(ta);
return ta;
}
}
/**
* Animate this node from it's current transform when the activity starts a
* new transform that will fit the node into the given bounds. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that. Note this method
* animates the node's transform, but does not directly change the node's
* bounds rectangle. Use animateToBounds() to animate the node's bounds
* rectangle instead.
*
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PTransformActivity animateTransformToBounds(final double x, final double y, final double width,
final double height, final long duration) {
final PAffineTransform t = new PAffineTransform();
t.setToScale(width / getWidth(), height / getHeight());
final double scale = t.getScale();
t.setOffset(x - getX() * scale, y - getY() * scale);
return animateToTransform(t, duration);
}
/**
* Animate this node's transform from its current location when the activity
* starts to the specified location, scale, and rotation. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param duration amount of time that the animation should take
* @param theta final theta value (in radians) for the animation
* @return the newly scheduled activity
*/
public PTransformActivity animateToPositionScaleRotation(final double x, final double y, final double scale,
final double theta, final long duration) {
final PAffineTransform t = getTransform();
t.setOffset(x, y);
t.setScale(scale);
t.setRotation(theta);
return animateToTransform(t, duration);
}
/**
* Animate this node's transform from its current values when the activity
* starts to the new values specified in the given transform. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param destTransform the final transform value
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PTransformActivity animateToTransform(final AffineTransform destTransform, final long duration) {
if (duration == 0) {
setTransform(destTransform);
return null;
}
else {
final PTransformActivity.Target t = new PTransformActivity.Target() {
public void setTransform(final AffineTransform aTransform) {
PNode.this.setTransform(aTransform);
}
public void getSourceMatrix(final double[] aSource) {
PNode.this.getTransformReference(true).getMatrix(aSource);
}
};
final PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t,
destTransform);
addActivity(ta);
return ta;
}
}
/**
* Animate this node's color from its current value to the new value
* specified. This meathod assumes that this nodes paint property is of type
* color. If this node descends from the root then the activity will be
* scheduled, else the returned activity should be scheduled manually. If
* two different color activities are scheduled for the same node at the
* same time, they will both be applied to the node, but the last one
* scheduled will be applied last on each frame, so it will appear to have
* replaced the original. Generally you will not want to do that.
*
* @param destColor final color value.
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToColor(final Color destColor, final long duration) {
if (duration == 0) {
setPaint(destColor);
return null;
}
else {
final PColorActivity.Target t = new PColorActivity.Target() {
public Color getColor() {
return (Color) getPaint();
}
public void setColor(final Color color) {
setPaint(color);
}
};
final PColorActivity ca = new PColorActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destColor);
addActivity(ca);
return ca;
}
}
/**
* Animate this node's transparency from its current value to the new value
* specified. Transparency values must range from zero to one. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transparency activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param zeroToOne final transparency value.
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToTransparency(final float zeroToOne, final long duration) {
if (duration == 0) {
setTransparency(zeroToOne);
return null;
}
else {
final float dest = zeroToOne;
final PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) {
private float source;
protected void activityStarted() {
source = getTransparency();
super.activityStarted();
}
public void setRelativeTargetValue(final float zeroToOne) {
PNode.this.setTransparency(source + zeroToOne * (dest - source));
}
};
addActivity(ta);
return ta;
}
}
/**
* Schedule the given activity with the root, note that only scheduled
* activities will be stepped. If the activity is successfully added true is
* returned, else false.
*
* @param activity new activity to schedule
* @return true if the activity is successfully scheduled.
*/
public boolean addActivity(final PActivity activity) {
final PRoot r = getRoot();
if (r != null) {
return r.addActivity(activity);
}
return false;
}
// Client Properties - Methods for managing client properties for
// this node.
// Client properties provide a way for programmers to attach
// extra information to a node without having to subclass it and
// add new instance variables.
/**
* Return mutable attributed set of client properites associated with this
* node.
*/
public MutableAttributeSet getClientProperties() {
if (clientProperties == null) {
clientProperties = new SimpleAttributeSet();
}
return clientProperties;
}
/**
* Returns the value of the client attribute with the specified key. Only
* attributes added with <code>addAttribute</code> will return a non-null
* value.
*
* @return the value of this attribute or null
*/
public Object getAttribute(final Object key) {
if (clientProperties == null || key == null) {
return null;
}
else {
return clientProperties.getAttribute(key);
}
}
public void addAttribute(final Object key, final Object value) {
if (value == null && clientProperties == null) {
return;
}
final Object oldValue = getAttribute(key);
if (value != oldValue) {
if (clientProperties == null) {
clientProperties = new SimpleAttributeSet();
}
if (value == null) {
clientProperties.removeAttribute(key);
}
else {
clientProperties.addAttribute(key, value);
}
if (clientProperties.getAttributeCount() == 0 && clientProperties.getResolveParent() == null) {
clientProperties = null;
}
firePropertyChange(PROPERTY_CODE_CLIENT_PROPERTIES, PROPERTY_CLIENT_PROPERTIES, null, clientProperties);
firePropertyChange(PROPERTY_CODE_CLIENT_PROPERTIES, key.toString(), oldValue, value);
}
}
/**
* Returns an enumeration of all keys maped to attribute values values.
*
* @return an Enumeration over attribute keys
*/
public Enumeration getClientPropertyKeysEnumeration() {
if (clientProperties == null) {
return PUtil.NULL_ENUMERATION;
}
else {
return clientProperties.getAttributeNames();
}
}
// convenience methods for attributes
public Object getAttribute(final Object key, final Object def) {
final Object o = getAttribute(key);
return o == null ? def : o;
}
public boolean getBooleanAttribute(final Object key, final boolean def) {
final Boolean b = (Boolean) getAttribute(key);
return b == null ? def : b.booleanValue();
}
public int getIntegerAttribute(final Object key, final int def) {
final Number n = (Number) getAttribute(key);
return n == null ? def : n.intValue();
}
public double getDoubleAttribute(final Object key, final double def) {
final Number n = (Number) getAttribute(key);
return n == null ? def : n.doubleValue();
}
/**
* @deprecated use getAttribute(Object key)instead.
*/
public Object getClientProperty(final Object key) {
return getAttribute(key);
}
/**
* @deprecated use addAttribute(Object key, Object value)instead.
*/
public void addClientProperty(final Object key, final Object value) {
addAttribute(key, value);
}
/**
* @deprecated use getClientPropertyKeysEnumerator() instead.
*/
public Iterator getClientPropertyKeysIterator() {
final Enumeration enumeration = getClientPropertyKeysEnumeration();
return new Iterator() {
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public Object next() {
return enumeration.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// Copying - Methods for copying this node and its descendants.
// Copying is implemened in terms of serialization.
/**
* The copy method copies this node and all of its descendents. Note that
* copying is implemented in terms of java serialization. See the
* serialization notes for more information.
*
* @return new copy of this node or null if the node was not serializable
*/
public Object clone() {
try {
final byte[] ser = PObjectOutputStream.toByteArray(this);
return new ObjectInputStream(new ByteArrayInputStream(ser)).readObject();
}
catch (final IOException e) {
return null;
}
catch (final ClassNotFoundException e) {
return null;
}
}
// Coordinate System Conversions - Methods for converting
// geometry between this nodes local coordinates and the other
// major coordinate systems.
// Each nodes has an affine transform that it uses to define its
// own coordinate system. For example if you create a new node and
// add it to the canvas it will appear in the upper right corner. Its
// coordinate system matches the coordinate system of its parent
// (the root node) at this point. But if you move this node by calling
// node.translate() the nodes affine transform will be modified and the
// node will appear at a different location on the screen. The node
// coordinate system no longer matches the coordinate system of its
// parent.
// This is useful because it means that the node's methods for
// rendering and picking don't need to worry about the fact that
// the node has been moved to another position on the screen, they
// keep working just like they did when it was in the upper right
// hand corner of the screen.
// The problem is now that each node defines its own coordinate
// system it is difficult to compare the positions of two node with
// each other. These methods are all meant to help solve that problem.
// The terms used in the methods are as follows:
// local - The local or base coordinate system of a node.
// parent - The coordinate system of a node's parent
// global - The topmost coordinate system, above the root node.
// Normally when comparing the positions of two nodes you will
// convert the local position of each node to the global coordinate
// system, and then compare the positions in that common coordinate
// system.
/**
* Transform the given point from this node's local coordinate system to its
* parent's local coordinate system. Note that this will modify the point
* parameter.
*
* @param localPoint point in local coordinate system to be transformed.
* @return point in parent's local coordinate system
*/
public Point2D localToParent(final Point2D localPoint) {
if (transform == null) {
return localPoint;
}
return transform.transform(localPoint, localPoint);
}
/**
* Transform the given dimension from this node's local coordinate system to
* its parent's local coordinate system. Note that this will modify the
* dimension parameter.
*
* @param localDimension dimension in local coordinate system to be
* transformed.
* @return dimension in parent's local coordinate system
*/
public Dimension2D localToParent(final Dimension2D localDimension) {
if (transform == null) {
return localDimension;
}
return transform.transform(localDimension, localDimension);
}
/**
* Transform the given rectangle from this node's local coordinate system to
* its parent's local coordinate system. Note that this will modify the
* rectangle parameter.
*
* @param localRectangle rectangle in local coordinate system to be
* transformed.
* @return rectangle in parent's local coordinate system
*/
public Rectangle2D localToParent(final Rectangle2D localRectangle) {
if (transform == null) {
return localRectangle;
}
return transform.transform(localRectangle, localRectangle);
}
/**
* Transform the given point from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the point parameter.
*
* @param parentPoint point in parent's coordinate system to be transformed.
* @return point in this node's local coordinate system
*/
public Point2D parentToLocal(final Point2D parentPoint) {
if (transform == null) {
return parentPoint;
}
return transform.inverseTransform(parentPoint, parentPoint);
}
/**
* Transform the given dimension from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the dimension parameter.
*
* @param parentDimension dimension in parent's coordinate system to be
* transformed.
* @return dimension in this node's local coordinate system
*/
public Dimension2D parentToLocal(final Dimension2D parentDimension) {
if (transform == null) {
return parentDimension;
}
return transform.inverseTransform(parentDimension, parentDimension);
}
/**
* Transform the given rectangle from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the rectangle parameter.
*
* @param parentRectangle rectangle in parent's coordinate system to be
* transformed.
* @return rectangle in this node's local coordinate system
*/
public Rectangle2D parentToLocal(final Rectangle2D parentRectangle) {
if (transform == null) {
return parentRectangle;
}
return transform.inverseTransform(parentRectangle, parentRectangle);
}
/**
* Transform the given point from this node's local coordinate system to the
* global coordinate system. Note that this will modify the point parameter.
*
* @param localPoint point in local coordinate system to be transformed.
* @return point in global coordinates
*/
public Point2D localToGlobal(Point2D localPoint) {
PNode n = this;
while (n != null) {
localPoint = n.localToParent(localPoint);
n = n.parent;
}
return localPoint;
}
/**
* Transform the given dimension from this node's local coordinate system to
* the global coordinate system. Note that this will modify the dimension
* parameter.
*
* @param localDimension dimension in local coordinate system to be
* transformed.
* @return dimension in global coordinates
*/
public Dimension2D localToGlobal(Dimension2D localDimension) {
PNode n = this;
while (n != null) {
localDimension = n.localToParent(localDimension);
n = n.parent;
}
return localDimension;
}
/**
* Transform the given rectangle from this node's local coordinate system to
* the global coordinate system. Note that this will modify the rectangle
* parameter.
*
* @param localRectangle rectangle in local coordinate system to be
* transformed.
* @return rectangle in global coordinates
*/
public Rectangle2D localToGlobal(Rectangle2D localRectangle) {
PNode n = this;
while (n != null) {
localRectangle = n.localToParent(localRectangle);
n = n.parent;
}
return localRectangle;
}
/**
* Transform the given point from global coordinates to this node's local
* coordinate system. Note that this will modify the point parameter.
*
* @param globalPoint point in global coordinates to be transformed.
* @return point in this node's local coordinate system.
*/
public Point2D globalToLocal(Point2D globalPoint) {
if (parent != null) {
globalPoint = parent.globalToLocal(globalPoint);
}
return parentToLocal(globalPoint);
}
/**
* Transform the given dimension from global coordinates to this node's
* local coordinate system. Note that this will modify the dimension
* parameter.
*
* @param globalDimension dimension in global coordinates to be transformed.
* @return dimension in this node's local coordinate system.
*/
public Dimension2D globalToLocal(Dimension2D globalDimension) {
if (parent != null) {
globalDimension = parent.globalToLocal(globalDimension);
}
return parentToLocal(globalDimension);
}
/**
* Transform the given rectangle from global coordinates to this node's
* local coordinate system. Note that this will modify the rectangle
* parameter.
*
* @param globalRectangle rectangle in global coordinates to be transformed.
* @return rectangle in this node's local coordinate system.
*/
public Rectangle2D globalToLocal(Rectangle2D globalRectangle) {
if (parent != null) {
globalRectangle = parent.globalToLocal(globalRectangle);
}
return parentToLocal(globalRectangle);
}
/**
* Return the transform that converts local coordinates at this node to the
* global coordinate system.
*
* @return The concatenation of transforms from the top node down to this
* node.
*/
public PAffineTransform getLocalToGlobalTransform(PAffineTransform dest) {
if (parent != null) {
dest = parent.getLocalToGlobalTransform(dest);
if (transform != null) {
dest.concatenate(transform);
}
}
else {
if (dest == null) {
dest = getTransform();
}
else {
if (transform != null) {
dest.setTransform(transform);
}
else {
dest.setToIdentity();
}
}
}
return dest;
}
/**
* Return the transform that converts global coordinates to local
* coordinates of this node.
*
* @return The inverse of the concatenation of transforms from the root down
* to this node.
*/
public PAffineTransform getGlobalToLocalTransform(PAffineTransform dest) {
dest = getLocalToGlobalTransform(dest);
try {
dest.setTransform(dest.createInverse());
}
catch (final NoninvertibleTransformException e) {
throw new PAffineTransformException(e, dest);
}
return dest;
}
// Event Listeners - Methods for adding and removing event listeners
// from a node.
// Here methods are provided to add property change listeners and
// input event listeners. The property change listeners are notified
// when certain properties of this node change, and the input event
// listeners are notified when the nodes receives new key and mouse
// events.
/**
* Return the list of event listeners associated with this node.
*
* @return event listener list or null
*/
public EventListenerList getListenerList() {
return listenerList;
}
/**
* Adds the specified input event listener to receive input events from this
* node.
*
* @param listener the new input listener
*/
public void addInputEventListener(final PInputEventListener listener) {
if (listenerList == null) {
listenerList = new EventListenerList();
}
getListenerList().add(PInputEventListener.class, listener);
}
/**
* Removes the specified input event listener so that it no longer receives
* input events from this node.
*
* @param listener the input listener to remove
*/
public void removeInputEventListener(final PInputEventListener listener) {
if (listenerList == null) {
return;
}
getListenerList().remove(PInputEventListener.class, listener);
if (listenerList.getListenerCount() == 0) {
listenerList = null;
}
}
/**
* Add a PropertyChangeListener to the listener list. The listener is
* registered for all properties. See the fields in PNode and subclasses
* that start with PROPERTY_ to find out which properties exist.
*
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(final PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/**
* Add a PropertyChangeListener for a specific property. The listener will
* be invoked only when a call on firePropertyChange names that specific
* property. See the fields in PNode and subclasses that start with
* PROPERTY_ to find out which properties are supported.
*
* @param propertyName The name of the property to listen on.
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
if (listener == null) {
return;
}
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* Remove a PropertyChangeListener from the listener list. This removes a
* PropertyChangeListener that was registered for all properties.
*
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(final PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
/**
* Remove a PropertyChangeListener for a specific property.
*
* @param propertyName The name of the property that was listened on.
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
if (listener == null) {
return;
}
if (changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(propertyName, listener);
}
/**
* Return the propertyChangeParentMask that determines which property change
* events are forwared to this nodes parent so that its property change
* listeners will also be notified.
*/
public int getPropertyChangeParentMask() {
return propertyChangeParentMask;
}
/**
* Set the propertyChangeParentMask that determines which property change
* events are forwared to this nodes parent so that its property change
* listeners will also be notified.
*/
public void setPropertyChangeParentMask(final int propertyChangeParentMask) {
this.propertyChangeParentMask = propertyChangeParentMask;
}
/**
* Report a bound property update to any registered listeners. No event is
* fired if old and new are equal and non-null. If the propertyCode exists
* in this node's propertyChangeParentMask then a property change event will
* also be fired on this nodes parent.
*
* @param propertyCode The code of the property changed.
* @param propertyName The programmatic name of the property that was
* changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
*/
protected void firePropertyChange(final int propertyCode, final String propertyName, final Object oldValue,
final Object newValue) {
PropertyChangeEvent event = null;
if (changeSupport != null) {
event = new PropertyChangeEvent(this, propertyName, oldValue, newValue);
changeSupport.firePropertyChange(event);
}
if (parent != null && (propertyCode & propertyChangeParentMask) != 0) {
if (event == null) {
event = new PropertyChangeEvent(this, propertyName, oldValue, newValue);
}
parent.fireChildPropertyChange(event, propertyCode);
}
}
/**
* Called by child node to forward property change events up the node tree
* so that property change listeners registered with this node will be
* notified of property changes of its children nodes. For performance
* reason only propertyCodes listed in the propertyChangeParentMask are
* forwarded.
*
* @param event The property change event containing source node and changed
* values.
* @param propertyCode The code of the property changed.
*/
protected void fireChildPropertyChange(final PropertyChangeEvent event, final int propertyCode) {
if (changeSupport != null) {
changeSupport.firePropertyChange(event);
}
if (parent != null && (propertyCode & propertyChangeParentMask) != 0) {
parent.fireChildPropertyChange(event, propertyCode);
}
}
// Bounds Geometry - Methods for setting and querying the bounds
// of this node.
// The bounds of a node store the node's position and size in
// the nodes local coordinate system. Many node subclasses will need
// to override the setBounds method so that they can update their
// internal state appropriately. See PPath for an example.
// Since the bounds are stored in the local coordinate system
// they WILL NOT change if the node is scaled, translated, or rotated.
// The bounds may be accessed with either getBounds, or
// getBoundsReference. The former returns a copy of the bounds
// the latter returns a reference to the nodes bounds that should
// normally not be modified. If a node is marked as volatile then
// it may modify its bounds before returning them from getBoundsReference,
// otherwise it may not.
/**
* Return a copy of this node's bounds. These bounds are stored in the local
* coordinate system of this node and do not include the bounds of any of
* this node's children.
*/
public PBounds getBounds() {
return (PBounds) getBoundsReference().clone();
}
/**
* Return a direct reference to this node's bounds. These bounds are stored
* in the local coordinate system of this node and do not include the bounds
* of any of this node's children. The value returned should not be
* modified.
*/
public PBounds getBoundsReference() {
return bounds;
}
/**
* Notify this node that you will begin to repeatedly call <code>setBounds
* </code>. When you
* are done call <code>endResizeBounds</code> to let the node know that you
* are done.
*/
public void startResizeBounds() {
}
/**
* Notify this node that you have finished a resize bounds sequence.
*/
public void endResizeBounds() {
}
public boolean setX(final double x) {
return setBounds(x, getY(), getWidth(), getHeight());
}
public boolean setY(final double y) {
return setBounds(getX(), y, getWidth(), getHeight());
}
public boolean setWidth(final double width) {
return setBounds(getX(), getY(), width, getHeight());
}
public boolean setHeight(final double height) {
return setBounds(getX(), getY(), getWidth(), height);
}
/**
* Set the bounds of this node to the given value. These bounds are stored
* in the local coordinate system of this node.
*
* @return true if the bounds changed.
*/
public boolean setBounds(final Rectangle2D newBounds) {
return setBounds(newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight());
}
/**
* Set the bounds of this node to the given value. These bounds are stored
* in the local coordinate system of this node.
*
* If the width or height is less then or equal to zero then the bound's
* emtpy bit will be set to true.
*
* Subclasses must call the super.setBounds() method.
*
* @return true if the bounds changed.
*/
public boolean setBounds(final double x, final double y, final double width, final double height) {
if (bounds.x != x || bounds.y != y || bounds.width != width || bounds.height != height) {
bounds.setRect(x, y, width, height);
if (width <= 0 || height <= 0) {
bounds.reset();
}
internalUpdateBounds(x, y, width, height);
invalidatePaint();
signalBoundsChanged();
return true;
}
// Don't put any invalidating code here or else nodes with volatile
// bounds will
// create a soft infinite loop (calling Swing.invokeLater()) when they
// validate
// their bounds.
return false;
}
/**
* Gives nodes a chance to update their internal structure before bounds
* changed notifications are sent. When this message is recived the nodes
* bounds field will contain the new value.
*
* See PPath for an example that uses this method.
*/
protected void internalUpdateBounds(final double x, final double y, final double width, final double height) {
}
/**
* Set the empty bit of this bounds to true.
*/
public void resetBounds() {
setBounds(0, 0, 0, 0);
}
/**
* Return the x position (in local coords) of this node's bounds.
*/
public double getX() {
return getBoundsReference().getX();
}
/**
* Return the y position (in local coords) of this node's bounds.
*/
public double getY() {
return getBoundsReference().getY();
}
/**
* Return the width (in local coords) of this node's bounds.
*/
public double getWidth() {
return getBoundsReference().getWidth();
}
/**
* Return the height (in local coords) of this node's bounds.
*/
public double getHeight() {
return getBoundsReference().getHeight();
}
/**
* Return a copy of the bounds of this node in the global coordinate system.
*
* @return the bounds in global coordinate system.
*/
public PBounds getGlobalBounds() {
return (PBounds) localToGlobal(getBounds());
}
/**
* Center the bounds of this node so that they are centered on the given
* point specified on the local coords of this node. Note that this meathod
* will modify the nodes bounds, while centerFullBoundsOnPoint will modify
* the nodes transform.
*
* @return true if the bounds changed.
*/
public boolean centerBoundsOnPoint(final double localX, final double localY) {
final double dx = localX - bounds.getCenterX();
final double dy = localY - bounds.getCenterY();
return setBounds(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height);
}
/**
* Center the ffull bounds of this node so that they are centered on the
* given point specified on the local coords of this nodes parent. Note that
* this meathod will modify the nodes transform, while centerBoundsOnPoint
* will modify the nodes bounds.
*/
public void centerFullBoundsOnPoint(final double parentX, final double parentY) {
final double dx = parentX - getFullBoundsReference().getCenterX();
final double dy = parentY - getFullBoundsReference().getCenterY();
offset(dx, dy);
}
/**
* Return true if this node intersects the given rectangle specified in
* local bounds. If the geometry of this node is complex this method can
* become expensive, it is therefore recommended that
* <code>fullIntersects</code> is used for quick rejects before calling this
* method.
*
* @param localBounds the bounds to test for intersection against
* @return true if the given rectangle intersects this nodes geometry.
*/
public boolean intersects(final Rectangle2D localBounds) {
if (localBounds == null) {
return true;
}
return getBoundsReference().intersects(localBounds);
}
// Full Bounds - Methods for computing and querying the
// full bounds of this node.
// The full bounds of a node store the nodes bounds
// together with the union of the bounds of all the
// node's descendents. The full bounds are stored in the parent
// coordinate system of this node, the full bounds DOES change
// when you translate, scale, or rotate this node.
// The full bounds may be accessed with either getFullBounds, or
// getFullBoundsReference. The former returns a copy of the full bounds
// the latter returns a reference to the node's full bounds that should
// not be modified.
/**
* Return a copy of this node's full bounds. These bounds are stored in the
* parent coordinate system of this node and they include the union of this
* node's bounds and all the bounds of it's descendents.
*
* @return a copy of this node's full bounds.
*/
public PBounds getFullBounds() {
return (PBounds) getFullBoundsReference().clone();
}
/**
* Return a reference to this node's full bounds cache. These bounds are
* stored in the parent coordinate system of this node and they include the
* union of this node's bounds and all the bounds of it's descendents. The
* bounds returned by this method should not be modified.
*
* @return a reference to this node's full bounds cache.
*/
public PBounds getFullBoundsReference() {
validateFullBounds();
return fullBoundsCache;
}
/**
* Compute and return the full bounds of this node. If the dstBounds
* parameter is not null then it will be used to return the results instead
* of creating a new PBounds.
*
* @param dstBounds if not null the new bounds will be stored here
* @return the full bounds in the parent coordinate system of this node
*/
public PBounds computeFullBounds(final PBounds dstBounds) {
final PBounds result = getUnionOfChildrenBounds(dstBounds);
result.add(getBoundsReference());
localToParent(result);
return result;
}
/**
* Compute and return the union of the full bounds of all the children of
* this node. If the dstBounds parameter is not null then it will be used to
* return the results instead of creating a new PBounds.
*
* @param dstBounds if not null the new bounds will be stored here
*/
public PBounds getUnionOfChildrenBounds(PBounds dstBounds) {
if (dstBounds == null) {
dstBounds = new PBounds();
}
else {
dstBounds.resetToZero();
}
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
dstBounds.add(each.getFullBoundsReference());
}
return dstBounds;
}
/**
* Return a copy of the full bounds of this node in the global coordinate
* system.
*
* @return the full bounds in global coordinate system.
*/
public PBounds getGlobalFullBounds() {
final PBounds b = getFullBounds();
if (parent != null) {
parent.localToGlobal(b);
}
return b;
}
/**
* Return true if the full bounds of this node intersects with the specified
* bounds.
*
* @param parentBounds the bounds to test for intersection against
* (specified in parent's coordinate system)
* @return true if this nodes full bounds intersect the given bounds.
*/
public boolean fullIntersects(final Rectangle2D parentBounds) {
if (parentBounds == null) {
return true;
}
return getFullBoundsReference().intersects(parentBounds);
}
// Bounds Damage Management - Methods used to invalidate and validate
// the bounds of nodes.
/**
* Return true if this nodes bounds may change at any time. The default
* behavior is to return false, subclasses that override this method to
* return true should also override getBoundsReference() and compute their
* volatile bounds there before returning the reference.
*
* @return true if this node has volatile bounds
*/
protected boolean getBoundsVolatile() {
return false;
}
/**
* Return true if this node has a child with volatile bounds.
*
* @return true if this node has a child with volatile bounds
*/
protected boolean getChildBoundsVolatile() {
return childBoundsVolatile;
}
/**
* Set if this node has a child with volatile bounds. This should normally
* be managed automatically by the bounds validation process.
*
* @param childBoundsVolatile true if this node has a descendent with
* volatile bounds
*/
protected void setChildBoundsVolatile(final boolean childBoundsVolatile) {
this.childBoundsVolatile = childBoundsVolatile;
}
/**
* Return true if this node's bounds have recently changed. This flag will
* be reset on the next call of validateFullBounds.
*
* @return true if this node's bounds have changed.
*/
protected boolean getBoundsChanged() {
return boundsChanged;
}
/**
* Set the bounds chnaged flag. This flag will be reset on the next call of
* validateFullBounds.
*
* @param boundsChanged true if this nodes bounds have changed.
*/
protected void setBoundsChanged(final boolean boundsChanged) {
this.boundsChanged = boundsChanged;
}
/**
* Return true if the full bounds of this node are invalid. This means that
* the full bounds of this node have changed and need to be recomputed.
*
* @return true if the full bounds of this node are invalid
*/
protected boolean getFullBoundsInvalid() {
return fullBoundsInvalid;
}
/**
* Set the full bounds invalid flag. This flag is set when the full bounds
* of this node need to be recomputed as is the case when this node is
* transformed or when one of this node's children changes geometry.
*/
protected void setFullBoundsInvalid(final boolean fullBoundsInvalid) {
this.fullBoundsInvalid = fullBoundsInvalid;
}
/**
* Return true if one of this node's descendents has invalid bounds.
*/
protected boolean getChildBoundsInvalid() {
return childBoundsInvalid;
}
/**
* Set the flag indicating that one of this node's descendents has invalid
* bounds.
*/
protected void setChildBoundsInvalid(final boolean childBoundsInvalid) {
this.childBoundsInvalid = childBoundsInvalid;
}
/**
* This method should be called when the bounds of this node are changed. It
* invalidates the full bounds of this node, and also notifies each of this
* nodes children that their parent's bounds have changed. As a result of
* this method getting called this nodes layoutChildren will be called.
*/
public void signalBoundsChanged() {
invalidateFullBounds();
setBoundsChanged(true);
firePropertyChange(PROPERTY_CODE_BOUNDS, PROPERTY_BOUNDS, null, bounds);
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.parentBoundsChanged();
}
}
/**
* Invalidate this node's layout, so that later layoutChildren will get
* called.
*/
public void invalidateLayout() {
invalidateFullBounds();
}
/**
* A notification that the bounds of this node's parent have changed.
*/
protected void parentBoundsChanged() {
}
/**
* Invalidates the full bounds of this node, and sets the child bounds
* invalid flag on each of this node's ancestors.
*/
public void invalidateFullBounds() {
setFullBoundsInvalid(true);
PNode n = parent;
while (n != null && !n.getChildBoundsInvalid()) {
n.setChildBoundsInvalid(true);
n = n.parent;
}
if (SCENE_GRAPH_DELEGATE != null) {
SCENE_GRAPH_DELEGATE.nodeFullBoundsInvalidated(this);
}
}
/**
* This method is called to validate the bounds of this node and all of its
* descendents. It returns true if this nodes bounds or the bounds of any of
* its descendents are marked as volatile.
*
* @return true if this node or any of its descendents have volatile bounds
*/
protected boolean validateFullBounds() {
final boolean boundsVolatile = getBoundsVolatile();
// 1. Only compute new bounds if invalid flags are set.
if (fullBoundsInvalid || childBoundsInvalid || boundsVolatile || childBoundsVolatile) {
// 2. If my bounds are volatile and they have not been changed then
// signal a change.
// For most cases this will do nothing, but if a nodes bounds depend
// on its model, then
// validate bounds has the responsibility of making the bounds match
// the models value.
// For example PPaths validateBounds method makes sure that the
// bounds are equal to the
// bounds of the GeneralPath model.
if (boundsVolatile && !boundsChanged) {
signalBoundsChanged();
}
// 3. If the bounds of on of my decendents are invalidate then
// validate the bounds of all of my children.
if (childBoundsInvalid || childBoundsVolatile) {
childBoundsVolatile = false;
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
childBoundsVolatile |= each.validateFullBounds();
}
}
// 4. Now that my children's bounds are valid and my own bounds are
// valid run any layout algorithm here. Note that if you try to
// layout volatile
// children piccolo will most likely start a "soft" infinite loop.
// It won't freeze
// your program, but it will make an infinite number of calls to
// SwingUtilities
// invoke later. You don't want to do that.
layoutChildren();
// 5. If the full bounds cache is invalid then recompute the full
// bounds cache here after our own bounds and the children's bounds
// have been computed above.
if (fullBoundsInvalid) {
final double oldX = fullBoundsCache.x;
final double oldY = fullBoundsCache.y;
final double oldWidth = fullBoundsCache.width;
final double oldHeight = fullBoundsCache.height;
final boolean oldEmpty = fullBoundsCache.isEmpty();
// 6. This will call getFullBoundsReference on all of the
// children. So if the above
// layoutChildren method changed the bounds of any of the
// children they will be
// validated again here.
fullBoundsCache = computeFullBounds(fullBoundsCache);
final boolean fullBoundsChanged = fullBoundsCache.x != oldX || fullBoundsCache.y != oldY
|| fullBoundsCache.width != oldWidth || fullBoundsCache.height != oldHeight
|| fullBoundsCache.isEmpty() != oldEmpty;
// 7. If the new full bounds cache differs from the previous
// cache then
// tell our parent to invalidate their full bounds. This is how
// bounds changes
// deep in the tree percolate up.
if (fullBoundsChanged) {
if (parent != null) {
parent.invalidateFullBounds();
}
firePropertyChange(PROPERTY_CODE_FULL_BOUNDS, PROPERTY_FULL_BOUNDS, null, fullBoundsCache);
// 8. If our paint was invalid make sure to repaint our old
// full bounds. The
// new bounds will be computed later in the validatePaint
// pass.
if (paintInvalid && !oldEmpty) {
TEMP_REPAINT_BOUNDS.setRect(oldX, oldY, oldWidth, oldHeight);
repaintFrom(TEMP_REPAINT_BOUNDS, this);
}
}
}
// 9. Clear the invalid bounds flags.
boundsChanged = false;
fullBoundsInvalid = false;
childBoundsInvalid = false;
}
return boundsVolatile || childBoundsVolatile;
}
/**
* Nodes that apply layout constraints to their children should override
* this method and do the layout there.
*/
protected void layoutChildren() {
}
// Node Transform - Methods to manipulate the node's transform.
// Each node has a transform that is used to define the nodes
// local coordinate system. IE it is applied before picking and
// rendering the node.
// The usual way to move nodes about on the canvas is to manipulate
// this transform, as opposed to changing the bounds of the
// node.
// Since this transform defines the local coordinate system of this
// node the following methods with affect the global position both
// this node and all of its descendents.
/**
* Returns the rotation applied by this node's transform in radians. This
* rotation affects this node and all its descendents. The value returned
* will be between 0 and 2pi radians.
*
* @return rotation in radians.
*/
public double getRotation() {
if (transform == null) {
return 0;
}
return transform.getRotation();
}
/**
* Sets the rotation of this nodes transform in radians. This will affect
* this node and all its descendents.
*
* @param theta rotation in radians
*/
public void setRotation(final double theta) {
rotate(theta - getRotation());
}
/**
* Rotates this node by theta (in radians) about the 0,0 point. This will
* affect this node and all its descendents.
*
* @param theta the amount to rotate by in radians
*/
public void rotate(final double theta) {
rotateAboutPoint(theta, 0, 0);
}
/**
* Rotates this node by theta (in radians), and then translates the node so
* that the x, y position of its fullBounds stays constant.
*
* @param theta the amount to rotate by in radians
*/
public void rotateInPlace(final double theta) {
PBounds b = getFullBoundsReference();
final double px = b.x;
final double py = b.y;
rotateAboutPoint(theta, 0, 0);
b = getFullBoundsReference();
offset(px - b.x, py - b.y);
}
/**
* Rotates this node by theta (in radians) about the given point. This will
* affect this node and all its descendents.
*
* @param theta the amount to rotate by in radians
*/
public void rotateAboutPoint(final double theta, final Point2D point) {
rotateAboutPoint(theta, point.getX(), point.getY());
}
/**
* Rotates this node by theta (in radians) about the given point. This will
* affect this node and all its descendents.
*
* @param theta the amount to rotate by in radians
*/
public void rotateAboutPoint(final double theta, final double x, final double y) {
getTransformReference(true).rotate(theta, x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the total amount of rotation applied to this node by its own
* transform together with the transforms of all its ancestors. The value
* returned will be between 0 and 2pi radians.
*
* @return the total amount of rotation applied to this node in radians
*/
public double getGlobalRotation() {
return getLocalToGlobalTransform(null).getRotation();
}
/**
* Set the global rotation (in radians) of this node. This is implemented by
* rotating this nodes transform the required amount so that the nodes
* global rotation is as requested.
*
* @param theta the amount to rotate by in radians relative to the global
* coord system.
*/
public void setGlobalRotation(final double theta) {
if (parent != null) {
setRotation(theta - parent.getGlobalRotation());
}
else {
setRotation(theta);
}
}
/**
* Return the scale applied by this node's transform. The scale is effecting
* this node and all its descendents.
*
* @return scale applied by this nodes transform.
*/
public double getScale() {
if (transform == null) {
return 1;
}
return transform.getScale();
}
/**
* Set the scale of this node's transform. The scale will affect this node
* and all its descendents.
*
* @param scale the scale to set the transform to
*/
public void setScale(final double scale) {
if (scale == 0) {
throw new RuntimeException("Can't set scale to 0");
}
scale(scale / getScale());
}
/**
* Scale this nodes transform by the given amount. This will affect this
* node and all of its descendents.
*
* @param scale the amount to scale by
*/
public void scale(final double scale) {
scaleAboutPoint(scale, 0, 0);
}
/**
* Scale this nodes transform by the given amount about the specified point.
* This will affect this node and all of its descendents.
*
* @param scale the amount to scale by
* @param point the point to scale about
*/
public void scaleAboutPoint(final double scale, final Point2D point) {
scaleAboutPoint(scale, point.getX(), point.getY());
}
/**
* Scale this nodes transform by the given amount about the specified point.
* This will affect this node and all of its descendents.
*
* @param scale the amount to scale by
*/
public void scaleAboutPoint(final double scale, final double x, final double y) {
getTransformReference(true).scaleAboutPoint(scale, x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the global scale that is being applied to this node by its
* transform together with the transforms of all its ancestors.
*/
public double getGlobalScale() {
return getLocalToGlobalTransform(null).getScale();
}
/**
* Set the global scale of this node. This is implemented by scaling this
* nodes transform the required amount so that the nodes global scale is as
* requested.
*
* @param scale the desired global scale
*/
public void setGlobalScale(final double scale) {
if (parent != null) {
setScale(scale / parent.getGlobalScale());
}
else {
setScale(scale);
}
}
public double getXOffset() {
if (transform == null) {
return 0;
}
return transform.getTranslateX();
}
public double getYOffset() {
if (transform == null) {
return 0;
}
return transform.getTranslateY();
}
/**
* Return the offset that is being applied to this node by its transform.
* This offset effects this node and all of its descendents and is specified
* in the parent coordinate system. This returns the values that are in the
* m02 and m12 positions in the affine transform.
*
* @return a point representing the x and y offset
*/
public Point2D getOffset() {
if (transform == null) {
return new Point2D.Double();
}
return new Point2D.Double(transform.getTranslateX(), transform.getTranslateY());
}
/**
* Set the offset that is being applied to this node by its transform. This
* offset effects this node and all of its descendents and is specified in
* the nodes parent coordinate system. This directly sets the values of the
* m02 and m12 positions in the affine transform. Unlike "PNode.translate()"
* it is not effected by the transforms scale.
*
* @param point a point representing the x and y offset
*/
public void setOffset(final Point2D point) {
setOffset(point.getX(), point.getY());
}
/**
* Set the offset that is being applied to this node by its transform. This
* offset effects this node and all of its descendents and is specified in
* the nodes parent coordinate system. This directly sets the values of the
* m02 and m12 positions in the affine transform. Unlike "PNode.translate()"
* it is not effected by the transforms scale.
*
* @param x amount of x offset
* @param y amount of y offset
*/
public void setOffset(final double x, final double y) {
getTransformReference(true).setOffset(x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Offset this node relative to the parents coordinate system, and is NOT
* effected by this nodes current scale or rotation. This is implemented by
* directly adding dx to the m02 position and dy to the m12 position in the
* affine transform.
*/
public void offset(final double dx, final double dy) {
getTransformReference(true);
setOffset(transform.getTranslateX() + dx, transform.getTranslateY() + dy);
}
/**
* Translate this node's transform by the given amount, using the standard
* affine transform translate method. This translation effects this node and
* all of its descendents.
*/
public void translate(final double dx, final double dy) {
getTransformReference(true).translate(dx, dy);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the global translation that is being applied to this node by its
* transform together with the transforms of all its ancestors.
*/
public Point2D getGlobalTranslation() {
final Point2D p = getOffset();
if (parent != null) {
parent.localToGlobal(p);
}
return p;
}
/**
* Set the global translation of this node. This is implemented by
* translating this nodes transform the required amount so that the nodes
* global scale is as requested.
*
* @param globalPoint the desired global translation
*/
public void setGlobalTranslation(final Point2D globalPoint) {
if (parent != null) {
parent.getGlobalToLocalTransform(null).transform(globalPoint, globalPoint);
}
setOffset(globalPoint);
}
/**
* Transform this nodes transform by the given transform.
*
* @param aTransform the transform to apply.
*/
public void transformBy(final AffineTransform aTransform) {
getTransformReference(true).concatenate(aTransform);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Linearly interpolates between a and b, based on t. Specifically, it
* computes lerp(a, b, t) = a + t*(b - a). This produces a result that
* changes from a (when t = 0) to b (when t = 1).
*
* @param a from point
* @param b to Point
* @param t variable 'time' parameter
*/
static public double lerp(final double t, final double a, final double b) {
return a + t * (b - a);
}
/**
* This will calculate the necessary transform in order to make this node
* appear at a particular position relative to the specified bounding box.
* The source point specifies a point in the unit square (0, 0) - (1, 1)
* that represents an anchor point on the corresponding node to this
* transform. The destination point specifies an anchor point on the
* reference node. The position method then computes the transform that
* results in transforming this node so that the source anchor point
* coincides with the reference anchor point. This can be useful for layout
* algorithms as it is straightforward to position one object relative to
* another.
* <p>
* For example, If you have two nodes, A and B, and you call
*
* <PRE>
* Point2D srcPt = new Point2D.Double(1.0, 0.0);
* Point2D destPt = new Point2D.Double(0.0, 0.0);
* A.position(srcPt, destPt, B.getGlobalBounds(), 750, null);
* </PRE>
*
* The result is that A will move so that its upper-right corner is at the
* same place as the upper-left corner of B, and the transition will be
* smoothly animated over a period of 750 milliseconds.
*
* @param srcPt The anchor point on this transform's node (normalized to a
* unit square)
* @param destPt The anchor point on destination bounds (normalized to a
* unit square)
* @param destBounds The bounds (in global coordinates) used to calculate
* this transform's node
* @param millis Number of milliseconds over which to perform the animation
*/
public PActivity animateToRelativePosition(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds,
final int millis) {
double srcx, srcy;
double destx, desty;
double dx, dy;
Point2D pt1, pt2;
if (parent == null) {
return null;
}
else {
// First compute translation amount in global coordinates
final Rectangle2D srcBounds = getGlobalFullBounds();
srcx = lerp(srcPt.getX(), srcBounds.getX(), srcBounds.getX() + srcBounds.getWidth());
srcy = lerp(srcPt.getY(), srcBounds.getY(), srcBounds.getY() + srcBounds.getHeight());
destx = lerp(destPt.getX(), destBounds.getX(), destBounds.getX() + destBounds.getWidth());
desty = lerp(destPt.getY(), destBounds.getY(), destBounds.getY() + destBounds.getHeight());
// Convert vector to local coordinates
pt1 = new Point2D.Double(srcx, srcy);
globalToLocal(pt1);
pt2 = new Point2D.Double(destx, desty);
globalToLocal(pt2);
dx = pt2.getX() - pt1.getX();
dy = pt2.getY() - pt1.getY();
// Finally, animate change
final PAffineTransform at = new PAffineTransform(getTransformReference(true));
at.translate(dx, dy);
return animateToTransform(at, millis);
}
}
/**
* @deprecated in favor of animateToRelativePosition
*
* It will calculate the necessary transform in order to make
* this node appear at a particular position relative to the
* specified bounding box. The source point specifies a point in
* the unit square (0, 0) - (1, 1) that represents an anchor
* point on the corresponding node to this transform. The
* destination point specifies an anchor point on the reference
* node. The position method then computes the transform that
* results in transforming this node so that the source anchor
* point coincides with the reference anchor point. This can be
* useful for layout algorithms as it is straightforward to
* position one object relative to another.
* <p>
* For example, If you have two nodes, A and B, and you call
*
* <PRE>
* Point2D srcPt = new Point2D.Double(1.0, 0.0);
* Point2D destPt = new Point2D.Double(0.0, 0.0);
* A.position(srcPt, destPt, B.getGlobalBounds(), 750, null);
* </PRE>
*
* The result is that A will move so that its upper-right corner
* is at the same place as the upper-left corner of B, and the
* transition will be smoothly animated over a period of 750
* milliseconds.
*
* @param srcPt The anchor point on this transform's node (normalized to a
* unit square)
* @param destPt The anchor point on destination bounds (normalized to a
* unit square)
* @param destBounds The bounds (in global coordinates) used to calculate
* this transform's node
* @param millis Number of milliseconds over which to perform the animation
*/
public void position(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds, final int millis) {
animateToRelativePosition(srcPt, destPt, destBounds, millis);
};
/**
* Return a copy of the transform associated with this node.
*
* @return copy of this node's transform
*/
public PAffineTransform getTransform() {
if (transform == null) {
return new PAffineTransform();
}
else {
return (PAffineTransform) transform.clone();
}
}
/**
* Return a reference to the transform associated with this node. This
* returned transform should not be modified. PNode transforms are created
* lazily when needed. If you access the transform reference before the
* transform has been created it may return null. The
* createNewTransformIfNull parameter is used to specify that the PNode
* should create a new transform (and assign that transform to the nodes
* local transform variable) instead of returning null.
*
* @return reference to this node's transform
*/
public PAffineTransform getTransformReference(final boolean createNewTransformIfNull) {
if (transform == null && createNewTransformIfNull) {
transform = new PAffineTransform();
}
return transform;
}
/**
* Return an inverted copy of the transform associated with this node.
*
* @return inverted copy of this node's transform
*/
public PAffineTransform getInverseTransform() {
if (transform == null) {
return new PAffineTransform();
}
try {
return new PAffineTransform(transform.createInverse());
}
catch (final NoninvertibleTransformException e) {
throw new PAffineTransformException(e, transform);
}
}
/**
* Set the transform applied to this node.
*
* @param newTransform the new transform value
*/
public void setTransform(final AffineTransform newTransform) {
if (newTransform == null) {
transform = null;
}
else {
getTransformReference(true).setTransform(newTransform);
}
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
// Paint Damage Management - Methods used to invalidate the areas of
// the screen that this node appears in so that they will later get
// painted.
// Generally you will not need to call these invalidate methods
// when starting out with Piccolo because methods such as setPaint
// already automatically call them for you. You will need to call
// them when you start creating your own nodes.
// When you do create you own nodes the only method that you will
// normally need to call is invalidatePaint. This method marks the
// nodes as having invalid paint, the root node's UI cycle will then
// later discover this damage and report it to the Java repaint manager.
// Repainting is normally done with PNode.invalidatePaint() instead of
// directly calling PNode.repaint() because PNode.repaint() requires
// the nodes bounds to be computed right away. But with invalidatePaint
// the bounds computation can be delayed until the end of the root's UI
// cycle, and this can add up to a bit savings when modifying a
// large number of nodes all at once.
// The other methods here will rarely be called except internally
// from the framework.
/**
* Return true if this nodes paint is invalid, in which case the node needs
* to be repainted.
*
* @return true if this node needs to be repainted
*/
public boolean getPaintInvalid() {
return paintInvalid;
}
/**
* Mark this node as having invalid paint. If this is set the node will
* later be repainted. Node this method is most often used internally.
*
* @param paintInvalid true if this node should be repainted
*/
public void setPaintInvalid(final boolean paintInvalid) {
this.paintInvalid = paintInvalid;
}
/**
* Return true if this node has a child with invalid paint.
*
* @return true if this node has a child with invalid paint
*/
public boolean getChildPaintInvalid() {
return childPaintInvalid;
}
/**
* Mark this node as having a child with invalid paint.
*
* @param childPaintInvalid true if this node has a child with invalid paint
*/
public void setChildPaintInvalid(final boolean childPaintInvalid) {
this.childPaintInvalid = childPaintInvalid;
}
/**
* Invalidate this node's paint, and mark all of its ancestors as having a
* node with invalid paint.
*/
public void invalidatePaint() {
setPaintInvalid(true);
PNode n = parent;
while (n != null && !n.getChildPaintInvalid()) {
n.setChildPaintInvalid(true);
n = n.parent;
}
if (SCENE_GRAPH_DELEGATE != null) {
SCENE_GRAPH_DELEGATE.nodePaintInvalidated(this);
}
}
/**
* Repaint this node and any of its descendents if they have invalid paint.
*/
public void validateFullPaint() {
if (getPaintInvalid()) {
repaint();
setPaintInvalid(false);
}
if (getChildPaintInvalid()) {
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.validateFullPaint();
}
setChildPaintInvalid(false);
}
}
/**
* Mark the area on the screen represented by this nodes full bounds as
* needing a repaint.
*/
public void repaint() {
TEMP_REPAINT_BOUNDS.setRect(getFullBoundsReference());
repaintFrom(TEMP_REPAINT_BOUNDS, this);
}
/**
* Pass the given repaint request up the tree, so that any cameras can
* invalidate that region on their associated canvas.
*
* @param localBounds the bounds to repaint
* @param childOrThis if childOrThis does not equal this then this nodes
* transform will be applied to the localBounds param
*/
public void repaintFrom(final PBounds localBounds, final PNode childOrThis) {
if (parent != null) {
if (childOrThis != this) {
localToParent(localBounds);
}
else if (!getVisible()) {
return;
}
parent.repaintFrom(localBounds, this);
}
}
// Occluding - Methods to support occluding optimization. Not yet
// complete.
public boolean isOpaque(final Rectangle2D boundary) {
return false;
}
public boolean getOccluded() {
return occluded;
}
public void setOccluded(final boolean isOccluded) {
occluded = isOccluded;
}
// Painting - Methods for painting this node and its children
// Painting is how a node defines its visual representation on the
// screen, and is done in the local coordinate system of the node.
// The default painting behavior is to first paint the node, and
// then paint the node's children on top of the node. If a node
// needs wants specialized painting behavior it can override:
// paint() - Painting here will happen before the children
// are painted, so the children will be painted on top of painting done
// here.
// paintAfterChildren() - Painting here will happen after the children
// are painted, so it will paint on top of them.
// Note that you should not normally need to override fullPaint().
// The visible flag can be used to make a node invisible so that
// it will never get painted.
/**
* Return true if this node is visible, that is if it will paint itself and
* descendents.
*
* @return true if this node and its descendents are visible.
*/
public boolean getVisible() {
return visible;
}
/**
* Set the visibility of this node and its descendents.
*
* @param isVisible true if this node and its descendents are visible
*/
public void setVisible(final boolean isVisible) {
if (getVisible() != isVisible) {
if (!isVisible) {
repaint();
}
visible = isVisible;
firePropertyChange(PROPERTY_CODE_VISIBLE, PROPERTY_VISIBLE, null, null);
invalidatePaint();
}
}
/**
* Return the paint used to paint this node. This value may be null.
*/
public Paint getPaint() {
return paint;
}
/**
* Set the paint used to paint this node. This value may be set to null.
*/
public void setPaint(final Paint newPaint) {
if (paint == newPaint) {
return;
}
final Paint old = paint;
paint = newPaint;
invalidatePaint();
firePropertyChange(PROPERTY_CODE_PAINT, PROPERTY_PAINT, old, paint);
}
/**
* Return the transparency used when painting this node. Note that this
* transparency is also applied to all of the node's descendents.
*/
public float getTransparency() {
return transparency;
}
/**
* Set the transparency used to paint this node. Note that this transparency
* applies to this node and all of its descendents.
*/
public void setTransparency(final float zeroToOne) {
if (transparency == zeroToOne) {
return;
}
transparency = zeroToOne;
invalidatePaint();
firePropertyChange(PROPERTY_CODE_TRANSPARENCY, PROPERTY_TRANSPARENCY, null, null);
}
/**
* Paint this node behind any of its children nodes. Subclasses that define
* a different appearance should override this method and paint themselves
* there.
*
* @param paintContext the paint context to use for painting the node
*/
protected void paint(final PPaintContext paintContext) {
if (paint != null) {
final Graphics2D g2 = paintContext.getGraphics();
g2.setPaint(paint);
g2.fill(getBoundsReference());
}
}
/**
* Paint this node and all of its descendents. Most subclasses do not need
* to override this method, they should override <code>paint</code> or
* <code>paintAfterChildren</code> instead.
*
* @param paintContext the paint context to use for painting this node and
* its children
*/
public void fullPaint(final PPaintContext paintContext) {
if (getVisible() && fullIntersects(paintContext.getLocalClip())) {
paintContext.pushTransform(transform);
paintContext.pushTransparency(transparency);
if (!getOccluded()) {
paint(paintContext);
}
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.fullPaint(paintContext);
}
paintAfterChildren(paintContext);
paintContext.popTransparency(transparency);
paintContext.popTransform(transform);
}
}
/**
* Subclasses that wish to do additional painting after their children are
* painted should override this method and do that painting here.
*
* @param paintContext the paint context to sue for painting after the
* children are painted
*/
protected void paintAfterChildren(final PPaintContext paintContext) {
}
/**
* Return a new Image representing this node and all of its children. The
* image size will be equal to the size of this nodes full bounds.
*
* @return a new image representing this node and its descendents
*/
public Image toImage() {
final PBounds b = getFullBoundsReference();
return toImage((int) Math.ceil(b.getWidth()), (int) Math.ceil(b.getHeight()), null);
}
/**
* Return a new Image of the requested size representing this node and all
* of its children. If backGroundPaint is null the resulting image will have
* transparent regions, otherwise those regions will be filled with the
* backgroundPaint.
*
* @param width pixel width of the resulting image
* @param height pixel height of the resulting image
* @return a new image representing this node and its descendents
*/
public Image toImage(final int width, final int height, final Paint backGroundPaint) {
BufferedImage result;
if (GraphicsEnvironment.isHeadless()) {
result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
else {
final GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
result = graphicsConfiguration.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
return toImage(result, backGroundPaint);
}
/**
* Paint a representation of this node into the specified buffered image. If
* background, paint is null, then the image will not be filled with a color
* prior to rendering
*
* @return a rendering of this image and its descendents into the specified
* image
*/
public Image toImage(final BufferedImage image, final Paint backGroundPaint) {
final int width = image.getWidth();
final int height = image.getHeight();
final Graphics2D g2 = image.createGraphics();
if (backGroundPaint != null) {
g2.setPaint(backGroundPaint);
g2.fillRect(0, 0, width, height);
}
// reuse print method
final Paper paper = new Paper();
paper.setSize(width, height);
paper.setImageableArea(0, 0, width, height);
final PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
print(g2, pageFormat, 0);
return image;
}
/**
* Constructs a new PrinterJob, allows the user to select which printer to
* print to, And then prints the node.
*/
public void print() {
final PrinterJob printJob = PrinterJob.getPrinterJob();
final PageFormat pageFormat = printJob.defaultPage();
final Book book = new Book();
book.append(this, pageFormat);
printJob.setPageable(book);
if (printJob.printDialog()) {
try {
printJob.print();
}
catch (final PrinterException e) {
System.out.println("Error Printing");
e.printStackTrace();
}
}
}
/**
* Prints the node into the given Graphics context using the specified
* format. The zero based index of the requested page is specified by
* pageIndex. If the requested page does not exist then this method returns
* NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned. If the printable object
* aborts the print job then it throws a PrinterException.
*
* @param graphics the context into which the node is drawn
* @param pageFormat the size and orientation of the page
* @param pageIndex the zero based index of the page to be drawn
*/
public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
final Graphics2D g2 = (Graphics2D) graphics;
final PBounds imageBounds = getFullBounds();
imageBounds.expandNearestIntegerDimensions();
g2.setClip(0, 0, (int) pageFormat.getWidth(), (int) pageFormat.getHeight());
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// scale the graphics so node's full bounds fit in the imageable bounds.
double scale = pageFormat.getImageableWidth() / imageBounds.getWidth();
if (pageFormat.getImageableHeight() / imageBounds.getHeight() < scale) {
scale = pageFormat.getImageableHeight() / imageBounds.getHeight();
}
g2.scale(scale, scale);
g2.translate(-imageBounds.x, -imageBounds.y);
final PPaintContext pc = new PPaintContext(g2);
pc.setRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING);
fullPaint(pc);
return PAGE_EXISTS;
}
// Picking - Methods for picking this node and its children.
// Picking is used to determine the node that intersects a point or
// rectangle on the screen. It is most frequently used by the
// PInputManager to determine the node that the cursor is over.
// The intersects() method is used to determine if a node has
// been picked or not. The default implementation just test to see
// if the pick bounds intersects the bounds of the node. Subclasses
// whose geometry (a circle for example) does not match up exactly with
// the bounds should override the intersects() method.
// The default picking behavior is to first try to pick the nodes
// children, and then try to pick the nodes own bounds. If a node
// wants specialized picking behavior it can override:
// pick() - Pick nodes here that should be picked before the nodes
// children are picked.
// pickAfterChildren() - Pick nodes here that should be picked after the
// node's children are picked.
// Note that fullPick should not normally be overridden.
// The pickable and childrenPickable flags can be used to make a
// node or it children not pickable even if their geometry does
// intersect the pick bounds.
/**
* Return true if this node is pickable. Only pickable nodes can receive
* input events. Nodes are pickable by default.
*
* @return true if this node is pickable
*/
public boolean getPickable() {
return pickable;
}
/**
* Set the pickable flag for this node. Only pickable nodes can receive
* input events. Nodes are pickable by default.
*
* @param isPickable true if this node is pickable
*/
public void setPickable(final boolean isPickable) {
if (getPickable() != isPickable) {
pickable = isPickable;
firePropertyChange(PROPERTY_CODE_PICKABLE, PROPERTY_PICKABLE, null, null);
}
}
/**
* Return true if the children of this node should be picked. If this flag
* is false then this node will not try to pick its children. Children are
* pickable by default.
*
* @return true if this node tries to pick its children
*/
public boolean getChildrenPickable() {
return childrenPickable;
}
/**
* Set the children pickable flag. If this flag is false then this node will
* not try to pick its children. Children are pickable by default.
*
* @param areChildrenPickable true if this node tries to pick its children
*/
public void setChildrenPickable(final boolean areChildrenPickable) {
if (getChildrenPickable() != areChildrenPickable) {
childrenPickable = areChildrenPickable;
firePropertyChange(PROPERTY_CODE_CHILDREN_PICKABLE, PROPERTY_CHILDREN_PICKABLE, null, null);
}
}
/**
* Try to pick this node before its children have had a chance to be picked.
* Nodes that paint on top of their children may want to override this
* method to if the pick path intersects that paint.
*
* @param pickPath the pick path used for the pick operation
* @return true if this node was picked
*/
protected boolean pick(final PPickPath pickPath) {
return false;
}
/**
* Try to pick this node and all of its descendents. Most subclasses should
* not need to override this method. Instead they should override
* <code>pick</code> or <code>pickAfterChildren</code>.
*
* @param pickPath the pick path to add the node to if its picked
* @return true if this node or one of its descendents was picked.
*/
public boolean fullPick(final PPickPath pickPath) {
if ((getPickable() || getChildrenPickable()) && fullIntersects(pickPath.getPickBounds())) {
pickPath.pushNode(this);
pickPath.pushTransform(transform);
final boolean thisPickable = getPickable() && pickPath.acceptsNode(this);
if (thisPickable && pick(pickPath)) {
return true;
}
if (getChildrenPickable()) {
final int count = getChildrenCount();
for (int i = count - 1; i >= 0; i
final PNode each = (PNode) children.get(i);
if (each.fullPick(pickPath)) {
return true;
}
}
}
if (thisPickable && pickAfterChildren(pickPath)) {
return true;
}
pickPath.popTransform(transform);
pickPath.popNode(this);
}
return false;
}
public void findIntersectingNodes(final Rectangle2D fullBounds, final ArrayList results) {
if (fullIntersects(fullBounds)) {
final Rectangle2D localBounds = parentToLocal((Rectangle2D) fullBounds.clone());
if (intersects(localBounds)) {
results.add(this);
}
final int count = getChildrenCount();
for (int i = count - 1; i >= 0; i
final PNode each = (PNode) children.get(i);
each.findIntersectingNodes(localBounds, results);
}
}
}
/**
* Try to pick this node after its children have had a chance to be picked.
* Most subclasses the define a different geometry will need to override
* this method.
*
* @param pickPath the pick path used for the pick operation
* @return true if this node was picked
*/
protected boolean pickAfterChildren(final PPickPath pickPath) {
if (intersects(pickPath.getPickBounds())) {
return true;
}
return false;
}
// Structure - Methods for manipulating and traversing the
// parent child relationship
// Most of these methods won't need to be overridden by subclasses
// but you will use them frequently to build up your node structures.
/**
* Add a node to be a new child of this node. The new node is added to the
* end of the list of this node's children. If child was previously a child
* of another node, it is removed from that first.
*
* @param child the new child to add to this node
*/
public void addChild(final PNode child) {
int insertIndex = getChildrenCount();
if (child.parent == this) {
insertIndex
}
addChild(insertIndex, child);
}
/**
* Add a node to be a new child of this node at the specified index. If
* child was previously a child of another node, it is removed from that
* node first.
*
* @param child the new child to add to this node
*/
public void addChild(final int index, final PNode child) {
final PNode oldParent = child.getParent();
if (oldParent != null) {
oldParent.removeChild(child);
}
child.setParent(this);
getChildrenReference().add(index, child);
child.invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
}
/**
* Add a collection of nodes to be children of this node. If these nodes
* already have parents they will first be removed from those parents.
*
* @param nodes a collection of nodes to be added to this node
*/
public void addChildren(final Collection nodes) {
final Iterator i = nodes.iterator();
while (i.hasNext()) {
final PNode each = (PNode) i.next();
addChild(each);
}
}
/**
* Return true if this node is an ancestor of the parameter node.
*
* @param node a possible descendent node
* @return true if this node is an ancestor of the given node
*/
public boolean isAncestorOf(final PNode node) {
PNode p = node.parent;
while (p != null) {
if (p == this) {
return true;
}
p = p.parent;
}
return false;
}
/**
* Return true if this node is a descendent of the parameter node.
*
* @param node a possible ancestor node
* @return true if this nodes descends from the given node
*/
public boolean isDescendentOf(final PNode node) {
PNode p = parent;
while (p != null) {
if (p == node) {
return true;
}
p = p.parent;
}
return false;
}
/**
* Return true if this node descends from the root.
*/
public boolean isDescendentOfRoot() {
return getRoot() != null;
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in back of all of its other sibling nodes.
*/
public void moveToBack() {
final PNode p = parent;
if (p != null) {
p.removeChild(this);
p.addChild(0, this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in front of all of its other sibling nodes.
*/
public void moveInBackOf(final PNode sibling) {
final PNode p = parent;
if (p != null && p == sibling.getParent()) {
p.removeChild(this);
final int index = p.indexOfChild(sibling);
p.addChild(index, this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw after the given sibling node.
*/
public void moveToFront() {
final PNode p = parent;
if (p != null) {
p.removeChild(this);
p.addChild(this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw before the given sibling node.
*/
public void moveInFrontOf(final PNode sibling) {
final PNode p = parent;
if (p != null && p == sibling.getParent()) {
p.removeChild(this);
final int index = p.indexOfChild(sibling);
p.addChild(index + 1, this);
}
}
/**
* Return the parent of this node. This will be null if this node has not
* been added to a parent yet.
*
* @return this nodes parent or null
*/
public PNode getParent() {
return parent;
}
/**
* Set the parent of this node. Note this is set automatically when adding
* and removing children.
*/
public void setParent(final PNode newParent) {
final PNode old = parent;
parent = newParent;
firePropertyChange(PROPERTY_CODE_PARENT, PROPERTY_PARENT, old, parent);
}
/**
* Return the index where the given child is stored.
*/
public int indexOfChild(final PNode child) {
if (children == null) {
return -1;
}
return children.indexOf(child);
}
/**
* Remove the given child from this node's children list. Any subsequent
* children are shifted to the left (one is subtracted from their indices).
* The removed child's parent is set to null.
*
* @param child the child to remove
* @return the removed child
*/
public PNode removeChild(final PNode child) {
final int index = indexOfChild(child);
if (index == -1) {
return null;
}
return removeChild(index);
}
/**
* Remove the child at the specified position of this group node's children.
* Any subsequent children are shifted to the left (one is subtracted from
* their indices). The removed child's parent is set to null.
*
* @param index the index of the child to remove
* @return the removed child
*/
public PNode removeChild(final int index) {
if (children == null) {
return null;
}
final PNode child = (PNode) children.remove(index);
if (children.size() == 0) {
children = null;
}
child.repaint();
child.setParent(null);
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
return child;
}
/**
* Remove all the children in the given collection from this node's list of
* children. All removed nodes will have their parent set to null.
*
* @param childrenNodes the collection of children to remove
*/
public void removeChildren(final Collection childrenNodes) {
final Iterator i = childrenNodes.iterator();
while (i.hasNext()) {
final PNode each = (PNode) i.next();
removeChild(each);
}
}
/**
* Remove all the children from this node. Node this method is more
* efficient then removing each child individually.
*/
public void removeAllChildren() {
if (children != null) {
final int count = children.size();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.setParent(null);
}
children = null;
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
}
}
/**
* Delete this node by removing it from its parent's list of children.
*/
public void removeFromParent() {
if (parent != null) {
parent.removeChild(this);
}
}
/**
* Set the parent of this node, and transform the node in such a way that it
* doesn't move in global coordinates.
*
* @param newParent The new parent of this node.
*/
public void reparent(final PNode newParent) {
final AffineTransform originalTransform = getLocalToGlobalTransform(null);
final AffineTransform newTransform = newParent.getGlobalToLocalTransform(null);
newTransform.concatenate(originalTransform);
removeFromParent();
setTransform(newTransform);
newParent.addChild(this);
computeFullBounds(fullBoundsCache);
}
/**
* Swaps this node out of the scene graph tree, and replaces it with the
* specified replacement node. This node is left dangling, and it is up to
* the caller to manage it. The replacement node will be added to this
* node's parent in the same position as this was. That is, if this was the
* 3rd child of its parent, then after calling replaceWith(), the
* replacement node will also be the 3rd child of its parent. If this node
* has no parent when replace is called, then nothing will be done at all.
*
* @param replacementNode the new node that replaces the current node in the
* scene graph tree.
*/
public void replaceWith(final PNode replacementNode) {
if (parent != null) {
final PNode p = parent;
final int index = p.getChildrenReference().indexOf(this);
p.removeChild(this);
p.addChild(index, replacementNode);
}
}
/**
* Return the number of children that this node has.
*
* @return the number of children
*/
public int getChildrenCount() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Return the child node at the specified index.
*
* @param index a child index
* @return the child node at the specified index
*/
public PNode getChild(final int index) {
return (PNode) children.get(index);
}
/**
* Return a reference to the list used to manage this node's children. This
* list should not be modified.
*
* @return reference to the children list
*/
public List getChildrenReference() {
if (children == null) {
children = new ArrayList();
}
return children;
}
/**
* Return an iterator over this node's direct descendent children.
*
* @return iterator over this nodes children
*/
public ListIterator getChildrenIterator() {
if (children == null) {
return Collections.EMPTY_LIST.listIterator();
}
return Collections.unmodifiableList(children).listIterator();
}
/**
* Return the root node (instance of PRoot). If this node does not descend
* from a PRoot then null will be returned.
*/
public PRoot getRoot() {
if (parent != null) {
return parent.getRoot();
}
return null;
}
/**
* Return a collection containing this node and all of its descendent nodes.
*
* @return a new collection containing this node and all descendents
*/
public Collection getAllNodes() {
return getAllNodes(null, null);
}
/**
* Return a collection containing the subset of this node and all of its
* descendent nodes that are accepted by the given node filter. If the
* filter is null then all nodes will be accepted. If the results parameter
* is not null then it will be used to collect this subset instead of
* creating a new collection.
*
* @param filter the filter used to determine the subset
* @return a collection containing this node and all descendents
*/
public Collection getAllNodes(final PNodeFilter filter, Collection results) {
if (results == null) {
results = new ArrayList();
}
if (filter == null || filter.accept(this)) {
results.add(this);
}
if (filter == null || filter.acceptChildrenOf(this)) {
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.getAllNodes(filter, results);
}
}
return results;
}
// Serialization - Nodes conditionally serialize their parent.
// This means that only the parents that were unconditionally
// (using writeObject) serialized by someone else will be restored
// when the node is unserialized.
/**
* Write this node and all of its descendent nodes to the given outputsteam.
* This stream must be an instance of PObjectOutputStream or serialization
* will fail. This nodes parent is written out conditionally, that is it
* will only be written out if someone else writes it out unconditionally.
*
* @param out the output stream to write to, must be an instance of
* PObjectOutputStream
*/
private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
((PObjectOutputStream) out).writeConditionalObject(parent);
}
/**
* Read this node and all of its descendents in from the given input stream.
*
* @param in the stream to read from
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
parent = (PNode) in.readObject();
}
// Debugging - methods for debugging
/**
* Returns a string representation of this object for debugging purposes.
*/
public String toString() {
final String result = super.toString().replaceAll(".*\\.", "");
return result + "[" + paramString() + "]";
}
/**
* Returns a string representing the state of this node. This method is
* intended to be used only for debugging purposes, and the content and
* format of the returned string may vary between implementations. The
* returned string may be empty but may not be <code>null</code>.
*
* @return a string representation of this node's state
*/
protected String paramString() {
final StringBuffer result = new StringBuffer();
result.append("bounds=" + (bounds == null ? "null" : bounds.toString()));
result.append(",fullBounds=" + (fullBoundsCache == null ? "null" : fullBoundsCache.toString()));
result.append(",transform=" + (transform == null ? "null" : transform.toString()));
result.append(",paint=" + (paint == null ? "null" : paint.toString()));
result.append(",transparency=" + transparency);
result.append(",childrenCount=" + getChildrenCount());
if (fullBoundsInvalid) {
result.append(",fullBoundsInvalid");
}
if (pickable) {
result.append(",pickable");
}
if (childrenPickable) {
result.append(",childrenPickable");
}
if (visible) {
result.append(",visible");
}
return result.toString();
}
public PInputEventListener[] getInputEventListeners() {
if (listenerList == null || listenerList.getListenerCount() == 0) {
return new PInputEventListener[] {};
}
final EventListener[] listeners = listenerList.getListeners(PInputEventListener.class);
final PInputEventListener[] result = new PInputEventListener[listeners.length];
for (int i = 0; i < listeners.length; i++) {
result[i] = (PInputEventListener) listeners[i];
}
return result;
}
} |
package hudson.model;
import hudson.model.Descriptor.FormException;
import hudson.node_monitors.NodeMonitor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.io.IOException;
/**
* Serves as the top of {@link Computer}s in the URL hierarchy.
* <p>
* Getter methods are prefixed with '_' to avoid collision with computer names.
*
* @author Kohsuke Kawaguchi
*/
public final class ComputerSet implements ModelObject {
private static volatile List<NodeMonitor> monitors = Collections.emptyList();
public ComputerSet() {
if(monitors.isEmpty()) {
// create all instances when requested for the first time.
ArrayList<NodeMonitor> r = new ArrayList<NodeMonitor>();
for (Descriptor<NodeMonitor> d : NodeMonitor.LIST)
try {
r.add(d.newInstance(null,null));
} catch (FormException e) {
// so far impossible. TODO: report
}
monitors = r;
}
}
public String getDisplayName() {
return "nodes";
}
public static List<NodeMonitor> get_monitors() {
return monitors;
}
public Computer[] get_all() {
return Hudson.getInstance().getComputers();
}
public Computer getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
return Hudson.getInstance().getComputer(token);
}
public void do_launchAll(StaplerRequest req, StaplerResponse rsp) throws IOException {
for(Computer c : get_all()) {
if(c.isJnlpAgent())
continue;
c.launch();
}
rsp.sendRedirect(".");
}
} |
package hudson.scm;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.Util;
import static hudson.Util.fixNull;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.FormFieldValidator;
import hudson.util.Scrambler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNInfo;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import org.tmatesoft.svn.core.wc.xml.SVNXMLLogHandler;
import org.xml.sax.helpers.LocatorImpl;
import javax.servlet.ServletException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SubversionSCM extends SCM implements Serializable {
private final String modules;
private boolean useUpdate;
private String username;
/**
* @deprecated
* No longer in use but left for serialization compatibility.
*/
private transient String otherOptions;
SubversionSCM(String modules, boolean useUpdate, String username) {
StringBuilder normalizedModules = new StringBuilder();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
if(normalizedModules.length()>0) normalizedModules.append(' ');
String m = tokens.nextToken();
if(m.endsWith("/"))
// the normalized name is always without the trailing '/'
m = m.substring(0,m.length()-1);
normalizedModules.append(m);
}
this.modules = normalizedModules.toString();
this.useUpdate = useUpdate;
this.username = nullify(username);
}
/**
* Whitespace-separated list of SVN URLs that represent
* modules to be checked out.
*/
public String getModules() {
return modules;
}
public boolean isUseUpdate() {
return useUpdate;
}
public String getUsername() {
return username;
}
private Collection<String> getModuleDirNames() {
List<String> dirs = new ArrayList<String>();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
dirs.add(getLastPathComponent(tokens.nextToken()));
}
return dirs;
}
private boolean calcChangeLog(AbstractBuild<?, ?> build, File changelogFile, BuildListener listener) throws IOException {
if(build.getPreviousBuild()==null) {
// nothing to compare against
return createEmptyChangeLog(changelogFile, listener, "log");
}
PrintStream logger = listener.getLogger();
Map<String,Long> previousRevisions = parseRevisionFile(build.getPreviousBuild());
Map<String,Long> thisRevisions = parseRevisionFile(build);
boolean changelogFileCreated = false;
SVNLogClient svnlc = createSvnClientManager(getDescriptor().createAuthenticationProvider()).getLogClient();
TransformerHandler th = createTransformerHandler();
th.setResult(new StreamResult(changelogFile));
SVNXMLLogHandler logHandler = new SVNXMLLogHandler(th);
th.setDocumentLocator(DUMMY_LOCATOR);
logHandler.startDocument();
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
String url = tokens.nextToken();
Long prevRev = previousRevisions.get(url);
if(prevRev==null) {
logger.println("no revision recorded for "+url+" in the previous build");
continue;
}
Long thisRev = thisRevisions.get(url);
if(thisRev.equals(prevRev)) {
logger.println("no change for "+url+" since the previous build");
continue;
}
try {
svnlc.doLog(SVNURL.parseURIEncoded(url),null,
SVNRevision.create(prevRev), SVNRevision.create(prevRev+1),
SVNRevision.create(thisRev),
false, true, Long.MAX_VALUE, logHandler);
} catch (SVNException e) {
e.printStackTrace(listener.error("revision check failed on "+url));
}
changelogFileCreated = true;
}
if(changelogFileCreated) {
logHandler.endDocument();
}
if(!changelogFileCreated)
createEmptyChangeLog(changelogFile, listener, "log");
return true;
}
/**
* Creates an identity transformer.
*/
private static TransformerHandler createTransformerHandler() {
try {
return ((SAXTransformerFactory) SAXTransformerFactory.newInstance()).newTransformerHandler();
} catch (TransformerConfigurationException e) {
throw new Error(e); // impossible
}
}
/*package*/ static Map<String,Long> parseRevisionFile(AbstractBuild build) throws IOException {
Map<String,Long> revisions = new HashMap<String,Long>(); // module -> revision
{// read the revision file of the last build
File file = getRevisionFile(build);
if(!file.exists())
// nothing to compare against
return revisions;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line=br.readLine())!=null) {
int index = line.lastIndexOf('/');
if(index<0) {
continue; // invalid line?
}
try {
revisions.put(line.substring(0,index), Long.parseLong(line.substring(index+1)));
} catch (NumberFormatException e) {
// perhaps a corrupted line. ignore
}
}
}
return revisions;
}
public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, final BuildListener listener, File changelogFile) throws IOException, InterruptedException {
if(!checkout(launcher,workspace, listener))
return false;
// write out the revision file
PrintWriter w = new PrintWriter(new FileOutputStream(getRevisionFile(build)));
try {
Map<String,SvnInfo> revMap = buildRevisionMap(workspace, listener);
for (Entry<String,SvnInfo> e : revMap.entrySet()) {
w.println( e.getKey() +'/'+ e.getValue().revision );
}
} finally {
w.close();
}
return calcChangeLog(build, changelogFile, listener);
}
public boolean checkout(Launcher launcher, FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
if(useUpdate && isUpdatable(workspace, listener)) {
return update(launcher,workspace,listener);
} else {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Boolean>() {
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
Util.deleteContentsRecursive(ws);
SVNUpdateClient svnuc = createSvnClientManager(authProvider).getUpdateClient();
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener));
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
try {
SVNURL url = SVNURL.parseURIEncoded(tokens.nextToken());
listener.getLogger().println("Checking out "+url);
svnuc.doCheckout(url, new File(ws, getLastPathComponent(url.getPath())), SVNRevision.HEAD, SVNRevision.HEAD, true );
} catch (SVNException e) {
e.printStackTrace(listener.error("Error in subversion"));
return false;
}
}
return true;
}
});
}
}
/**
* Creates {@link SVNClientManager}.
*
* <p>
* This method must be executed on the slave where svn operations are performed.
*
* @param authProvider
* The value obtained from {@link DescriptorImpl#createAuthenticationProvider()}.
* If the operation runs on slaves,
* (and properly remoted, if the svn operations run on slaves.)
*/
private static SVNClientManager createSvnClientManager(ISVNAuthenticationProvider authProvider) {
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(authProvider);
return SVNClientManager.newInstance(SVNWCUtil.createDefaultOptions(true),sam);
}
public static final class SvnInfo implements Serializable {
/**
* Decoded repository URL.
*/
final String url;
final long revision;
public SvnInfo(String url, long revision) {
this.url = url;
this.revision = revision;
}
public SvnInfo(SVNInfo info) {
this( info.getURL().toDecodedString(), info.getCommittedRevision().getNumber() );
}
public SVNURL getSVNURL() throws SVNException {
return SVNURL.parseURIDecoded(url);
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the SVN metadata for the given local workspace.
*
* @param workspace
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(File workspace, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(workspace,SVNRevision.WORKING);
}
/**
* Gets the SVN metadata for the remote repository.
*
* @param remoteUrl
* The target to run "svn info".
*/
private SVNInfo parseSvnInfo(SVNURL remoteUrl, ISVNAuthenticationProvider authProvider) throws SVNException {
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
return svnWc.doInfo(remoteUrl, SVNRevision.HEAD, SVNRevision.HEAD);
}
/**
* Checks .svn files in the workspace and finds out revisions of the modules
* that the workspace has.
*
* @return
* null if the parsing somehow fails. Otherwise a map from the repository URL to revisions.
*/
private Map<String,SvnInfo> buildRevisionMap(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Map<String,SvnInfo>>() {
public Map<String,SvnInfo> invoke(File ws, VirtualChannel channel) throws IOException {
Map<String/*module name*/,SvnInfo> revisions = new HashMap<String,SvnInfo>();
SVNWCClient svnWc = createSvnClientManager(authProvider).getWCClient();
// invoke the "svn info"
for( String module : getModuleDirNames() ) {
try {
SvnInfo info = new SvnInfo(svnWc.doInfo(new File(ws,module),SVNRevision.WORKING));
revisions.put(info.url,info);
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to parse svn info for "+module));
}
}
return revisions;
}
});
}
/**
* Gets the file that stores the revision.
*/
private static File getRevisionFile(AbstractBuild build) {
return new File(build.getRootDir(),"revision.txt");
}
public boolean update(Launcher launcher, FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Boolean>() {
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
SVNUpdateClient svnuc = createSvnClientManager(authProvider).getUpdateClient();
svnuc.setEventHandler(new SubversionUpdateEventHandler(listener));
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
try {
String url = tokens.nextToken();
listener.getLogger().println("Updating "+url);
svnuc.doUpdate(new File(ws, getLastPathComponent(url)), SVNRevision.HEAD, true );
} catch (SVNException e) {
e.printStackTrace(listener.error("Error in subversion"));
return false;
}
}
return true;
}
});
}
/**
* Returns true if we can use "svn update" instead of "svn checkout"
*/
private boolean isUpdatable(FilePath workspace, final TaskListener listener) throws IOException, InterruptedException {
final ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
return workspace.act(new FileCallable<Boolean>() {
public Boolean invoke(File ws, VirtualChannel channel) throws IOException {
StringTokenizer tokens = new StringTokenizer(modules);
while(tokens.hasMoreTokens()) {
String url = tokens.nextToken();
String moduleName = getLastPathComponent(url);
File module = new File(ws,moduleName);
if(!module.exists()) {
listener.getLogger().println("Checking out a fresh workspace because "+module+" doesn't exist");
return false;
}
try {
SvnInfo svnInfo = new SvnInfo(parseSvnInfo(module,authProvider));
if(!svnInfo.url.equals(url)) {
listener.getLogger().println("Checking out a fresh workspace because the workspace is not "+url);
return false;
}
} catch (SVNException e) {
listener.getLogger().println("Checking out a fresh workspace because Hudson failed to detect the current workspace "+module);
e.printStackTrace(listener.error(e.getMessage()));
return false;
}
}
return true;
}
});
}
public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
// current workspace revision
Map<String,SvnInfo> wsRev = buildRevisionMap(workspace, listener);
ISVNAuthenticationProvider authProvider = getDescriptor().createAuthenticationProvider();
// check the corresponding remote revision
for (SvnInfo localInfo : wsRev.values()) {
try {
SvnInfo remoteInfo = new SvnInfo(parseSvnInfo(localInfo.getSVNURL(),authProvider));
listener.getLogger().println("Revision:"+remoteInfo.revision);
if(remoteInfo.revision > localInfo.revision)
return true; // change found
} catch (SVNException e) {
e.printStackTrace(listener.error("Failed to check repository revision for "+localInfo.url));
}
}
return false; // no change
}
public ChangeLogParser createChangeLogParser() {
return new SubversionChangeLogParser();
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public void buildEnvVars(Map<String,String> env) {
// no environment variable
}
public FilePath getModuleRoot(FilePath workspace) {
String s;
// if multiple URLs are specified, pick the first one
int idx = modules.indexOf(' ');
if(idx>=0) s = modules.substring(0,idx);
else s = modules;
return workspace.child(getLastPathComponent(s));
}
private static String getLastPathComponent(String s) {
String[] tokens = s.split("/");
return tokens[tokens.length-1]; // return the last token
}
public static final class DescriptorImpl extends SCMDescriptor {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
/**
* Path to <tt>svn.exe</tt>. Null to default.
*
* @deprecated
* No longer in use.
*/
private volatile String svnExe;
/**
* SVN authentication realm to its associated credentials.
*/
private final Map<String,Credential> credentials = new Hashtable<String,Credential>();
/**
* Stores {@link SVNAuthentication} for a single realm.
*/
private static abstract class Credential implements Serializable {
abstract SVNAuthentication createSVNAuthentication();
}
private static final class PasswordCredential extends Credential {
private final String userName;
private final String password; // scrambled by base64
public PasswordCredential(String userName, String password) {
this.userName = userName;
this.password = Scrambler.scramble(password);
}
@Override
SVNPasswordAuthentication createSVNAuthentication() {
return new SVNPasswordAuthentication(userName,Scrambler.descramble(password),false);
}
}
/**
* Remoting interface that allows remote {@link ISVNAuthenticationProvider}
* to read from local {@link DescriptorImpl#credentials}.
*/
private interface RemotableSVNAuthenticationProvider {
Credential getCredential(String realm);
}
private final class RemotableSVNAuthenticationProviderImpl implements RemotableSVNAuthenticationProvider, Serializable {
public Credential getCredential(String realm) {
return credentials.get(realm);
}
/**
* When sent to the remote node, send a proxy.
*/
private Object writeReplace() {
return Channel.current().export(RemotableSVNAuthenticationProvider.class, this);
}
}
/**
* See {@link DescriptorImpl#createAuthenticationProvider()}.
*/
private static final class SVNAuthenticationProviderImpl implements ISVNAuthenticationProvider, Serializable {
private final RemotableSVNAuthenticationProvider source;
public SVNAuthenticationProviderImpl(RemotableSVNAuthenticationProvider source) {
this.source = source;
}
public SVNAuthentication requestClientAuthentication(String kind, SVNURL url, String realm, SVNErrorMessage errorMessage, SVNAuthentication previousAuth, boolean authMayBeStored) {
Credential cred = source.getCredential(realm);
if(cred==null) return null;
return cred.createSVNAuthentication();
}
public int acceptServerAuthentication(SVNURL url, String realm, Object certificate, boolean resultMayBeStored) {
return ACCEPTED_TEMPORARY;
}
private static final long serialVersionUID = 1L;
}
private DescriptorImpl() {
super(SubversionSCM.class,SubversionRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Subversion";
}
public SCM newInstance(StaplerRequest req) {
return new SubversionSCM(
req.getParameter("svn_modules"),
req.getParameter("svn_use_update")!=null,
req.getParameter("svn_username")
);
}
/**
* Creates {@link ISVNAuthenticationProvider} backed by {@link #credentials}.
* This method must be invoked on the master, but the returned object is remotable.
*/
public ISVNAuthenticationProvider createAuthenticationProvider() {
return new SVNAuthenticationProviderImpl(new RemotableSVNAuthenticationProviderImpl());
}
/**
* Used in the job configuration page to check if authentication for the SVN URLs
* are available.
*/
public void doAuthenticationCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
new FormFieldValidator(req,rsp,true) {
protected void check() throws IOException, ServletException {
StringTokenizer tokens = new StringTokenizer(fixNull(request.getParameter("value")));
String message="";
while(tokens.hasMoreTokens()) {
String url = tokens.nextToken();
try {
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(createAuthenticationProvider());
repository.setAuthenticationManager(sam);
repository.testConnection();
} catch (SVNException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
message += "Unable to access "+url+" : "+Util.escape( e.getErrorMessage().getFullMessage());
message += " <a href='#' id=svnerrorlink onclick='javascript:" +
"document.getElementById(\"svnerror\").style.display=\"block\";" +
"document.getElementById(\"svnerrorlink\").style.display=\"none\";" +
"return false;'>(show details)</a>";
message += "<pre id=svnerror style='display:none'>"+sw+"</pre>";
message += " (Maybe you need to <a href='"+req.getContextPath()+"/scm/SubversionSCM/enterCredential?"+url+"'>enter credential</a>?)";
message += "<br>";
logger.log(Level.INFO, "Failed to access subversion repository "+url,e);
}
}
if(message.length()==0)
ok();
else
error(message);
}
}.process();
}
/**
* Submits the authentication info.
*/
public void doPostCredential(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
final String url = req.getParameter("url");
final String username = req.getParameter("username");
final String password = req.getParameter("password");
try {
// the way it works with SVNKit is that
// 1) svnkit calls AuthenticationManager asking for a credential.
// this is when we can see the 'realm', which identifies the user domain.
// 2) DefaultSVNAuthenticationManager returns the username and password we set below
// 3) if the authentication is successful, svnkit calls back acknowledgeAuthentication
// (so we store the password info here)
SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
repository.setAuthenticationManager(new DefaultSVNAuthenticationManager(SVNWCUtil.getDefaultConfigurationDirectory(),true,username,password) {
public void acknowledgeAuthentication(boolean accepted, String kind, String realm, SVNErrorMessage errorMessage, SVNAuthentication authentication) throws SVNException {
if(accepted) {
credentials.put(realm,new PasswordCredential(username,password));
save();
}
super.acknowledgeAuthentication(accepted, kind, realm, errorMessage, authentication);
}
});
repository.testConnection();
rsp.sendRedirect("credentialOK");
} catch (SVNException e) {
req.setAttribute("message",e.getErrorMessage());
rsp.forward(Hudson.getInstance(),"error",req);
}
}
static { new Initializer(); }
}
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SubversionSCM.class.getName());
private static final LocatorImpl DUMMY_LOCATOR = new LocatorImpl();
static {
new Initializer();
DUMMY_LOCATOR.setLineNumber(-1);
DUMMY_LOCATOR.setColumnNumber(-1);
}
private static final class Initializer {
static {
DAVRepositoryFactory.setup(); // http, https
SVNRepositoryFactoryImpl.setup(); // svn, svn+xxx
FSRepositoryFactory.setup(); // file
}
}
} |
package net.novucs.ftop;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import net.novucs.ftop.hook.VaultEconomyHook;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
public class Settings {
private static final int LATEST_VERSION = 1;
private static final String HEADER = "FactionsTop configuration.\n";
private final FactionsTopPlugin plugin;
private FileConfiguration config;
private File configFile;
// General settings.
private List<String> commandAliases;
private List<String> ignoredFactionIds;
private int factionsPerPage;
private int liquidUpdateTicks;
private int chunkQueueSize;
private long chunkRecalculateMillis;
private HikariConfig hikariConfig;
private Map<WorthType, Boolean> enabled;
private Map<WorthType, Boolean> detailed;
private Map<RecalculateReason, Boolean> performRecalculate;
private Map<RecalculateReason, Boolean> bypassRecalculateDelay;
private Map<EntityType, Double> spawnerPrices;
private Map<Material, Double> blockPrices;
public Settings(FactionsTopPlugin plugin) {
this.plugin = plugin;
}
public List<String> getCommandAliases() {
return commandAliases;
}
public List<String> getIgnoredFactionIds() {
return ignoredFactionIds;
}
public int getFactionsPerPage() {
return factionsPerPage;
}
public int getLiquidUpdateTicks() {
return liquidUpdateTicks;
}
public int getChunkQueueSize() {
return chunkQueueSize;
}
public long getChunkRecalculateMillis() {
return chunkRecalculateMillis;
}
public HikariConfig getHikariConfig() {
return hikariConfig;
}
public boolean isEnabled(WorthType worthType) {
return enabled.getOrDefault(worthType, false);
}
public boolean isDetailed(WorthType worthType) {
return detailed.getOrDefault(worthType, false);
}
public boolean isPerformRecalculate(RecalculateReason reason) {
return performRecalculate.getOrDefault(reason, false);
}
public boolean isBypassRecalculateDelay(RecalculateReason reason) {
return bypassRecalculateDelay.getOrDefault(reason, false);
}
public double getSpawnerPrice(EntityType entityType) {
return spawnerPrices.getOrDefault(entityType, 0d);
}
public double getBlockPrice(Material material) {
return blockPrices.getOrDefault(material, 0d);
}
private void set(String path, Object val) {
config.set(path, val);
}
private boolean getBoolean(String path, boolean def) {
config.addDefault(path, def);
return config.getBoolean(path);
}
private int getInt(String path, int def) {
config.addDefault(path, def);
return config.getInt(path);
}
private long getLong(String path, long def) {
config.addDefault(path, def);
return config.getLong(path);
}
private double getDouble(String path, double def) {
config.addDefault(path, def);
return config.getDouble(path);
}
private String getString(String path, String def) {
config.addDefault(path, def);
return config.getString(path);
}
private ConfigurationSection getOrCreateSection(String key) {
return config.getConfigurationSection(key) == null ?
config.createSection(key) : config.getConfigurationSection(key);
}
private ConfigurationSection getOrDefaultSection(String key) {
return config.getConfigurationSection(key).getKeys(false).isEmpty() ?
config.getDefaults().getConfigurationSection(key) : config.getConfigurationSection(key);
}
private <T> List<?> getList(String key, List<T> def) {
config.addDefault(key, def);
return config.getList(key, config.getList(key));
}
private <E> List<E> getList(String key, List<E> def, Class<E> type) {
try {
return castList(type, getList(key, def));
} catch (ClassCastException e) {
return def;
}
}
private <E> List<E> castList(Class<? extends E> type, List<?> toCast) throws ClassCastException {
return toCast.stream().map(type::cast).collect(Collectors.toList());
}
private <T extends Enum<T>> EnumMap<T, Boolean> parseStateMap(Class<T> type, String key, boolean def) {
EnumMap<T, Boolean> target = new EnumMap<>(type);
ConfigurationSection section = getOrDefaultSection(key);
for (String name : section.getKeys(false)) {
// Warn user if unable to parse enum.
Optional<T> parsed = StringUtils.parseEnum(type, name);
if (!parsed.isPresent()) {
plugin.getLogger().warning("Invalid " + type.getSimpleName() + ": " + name);
continue;
}
// Add the parsed enum and value to the target map.
target.put(parsed.get(), section.getBoolean(name, def));
}
return target;
}
private <T extends Enum<T>> void addDefaults(Class<T> type, String key, boolean def, List<T> exempt) {
ConfigurationSection section = getOrCreateSection(key);
for (T target : type.getEnumConstants()) {
section.addDefault(target.name(), exempt.contains(target) != def);
}
}
private <T extends Enum<T>> EnumMap<T, Double> parsePriceMap(Class<T> type, String key, double def) {
EnumMap<T, Double> target = new EnumMap<>(type);
ConfigurationSection section = getOrDefaultSection(key);
for (String name : section.getKeys(false)) {
// Warn user if unable to parse enum.
Optional<T> parsed = StringUtils.parseEnum(type, name);
if (!parsed.isPresent()) {
plugin.getLogger().warning("Invalid " + type.getSimpleName() + ": " + name);
continue;
}
// Add the parsed enum and value to the target map.
target.put(parsed.get(), section.getDouble(name, def));
}
return target;
}
private <T extends Enum<T>> void addDefaults(String key, Map<T, Double> prices) {
ConfigurationSection section = getOrCreateSection(key);
prices.forEach((type, price) -> section.addDefault(type.name(), price));
}
private <T extends Enum<T>> EnumMap<T, Double> parseDefPrices(Class<T> type, Map<String, Double> def) {
EnumMap<T, Double> target = new EnumMap<>(type);
def.forEach((name, price) -> {
Optional<T> parsed = StringUtils.parseEnum(type, name);
if (parsed.isPresent()) {
target.put(parsed.get(), price);
}
});
return target;
}
private HikariConfig loadHikariConfig() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(getString("settings.database.jdbc-url", "jdbc:h2:./plugins/FactionsTop/database"));
hikariConfig.setUsername(getString("settings.database.username", "root"));
hikariConfig.setPassword(getString("settings.database.password", "pa$$w0rd"));
hikariConfig.setMaximumPoolSize(getInt("settings.database.maximum-pool-size", 10));
hikariConfig.setMaxLifetime(getLong("settings.database.max-lifetime", 5000));
hikariConfig.setIdleTimeout(getLong("settings.database.idle-timeout", 5000));
hikariConfig.setConnectionTimeout(getLong("settings.database.connection-timeout", 5000));
hikariConfig.setThreadFactory(new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("factions-top-sql-pool-%d").build());
return hikariConfig;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void load() throws IOException, InvalidConfigurationException {
// Create then load the configuration and file.
configFile = new File(plugin.getDataFolder() + File.separator + "config.yml");
configFile.getParentFile().mkdirs();
configFile.createNewFile();
config = new YamlConfiguration();
config.load(configFile);
// Load all configuration values into memory.
int version = getInt("config-version", 0);
commandAliases = getList("settings.command-aliases", Collections.singletonList("f top"), String.class);
ignoredFactionIds = getList("settings.ignored-faction-ids", Arrays.asList("none", "safezone", "warzone", "0", "-1", "-2"), String.class);
factionsPerPage = getInt("settings.factions-per-page", 9);
liquidUpdateTicks = getInt("settings.liquid-update-ticks", 100);
if (plugin.getEconomyHook() instanceof VaultEconomyHook) {
((VaultEconomyHook) plugin.getEconomyHook()).setLiquidUpdateTicks(liquidUpdateTicks);
}
chunkQueueSize = getInt("settings.chunk-queue-size", 200);
chunkRecalculateMillis = getLong("settings.chunk-recalculate-millis", 120000);
hikariConfig = loadHikariConfig();
addDefaults(WorthType.class, "settings.enabled", true, Collections.singletonList(WorthType.CHEST));
enabled = parseStateMap(WorthType.class, "settings.enabled", false);
plugin.getEconomyHook().setFactionEnabled(isEnabled(WorthType.FACTION_BALANCE));
plugin.getEconomyHook().setPlayerEnabled(isEnabled(WorthType.PLAYER_BALANCE));
addDefaults(WorthType.class, "settings.detailed", true, Collections.emptyList());
detailed = parseStateMap(WorthType.class, "settings.detailed", false);
addDefaults(RecalculateReason.class, "settings.perform-recalculate", true, Collections.singletonList(RecalculateReason.CHEST));
performRecalculate = parseStateMap(RecalculateReason.class, "settings.perform-recalculate", false);
addDefaults(RecalculateReason.class, "settings.bypass-recalculate-delay", false, Arrays.asList(RecalculateReason.UNLOAD, RecalculateReason.CLAIM));
bypassRecalculateDelay = parseStateMap(RecalculateReason.class, "settings.bypass-recalculate-delay", false);
Map<String, Double> prices = ImmutableMap.of(
"SLIME", 75_000.00,
"SKELETON", 30_000.00,
"ZOMBIE", 25_000.00
);
addDefaults("settings.spawner-prices", parseDefPrices(EntityType.class, prices));
spawnerPrices = parsePriceMap(EntityType.class, "settings.spawner-prices", 0);
prices = ImmutableMap.of(
"EMERALD_BLOCK", 1_250.00,
"DIAMOND_BLOCK", 1_000.00,
"GOLD_BLOCK", 250.00,
"IRON_BLOCK", 75.00,
"COAL_BLOCK", 25.00
);
addDefaults("settings.block-prices", parseDefPrices(Material.class, prices));
blockPrices = parsePriceMap(Material.class, "settings.block-prices", 0);
// Update the configuration file if it is outdated.
if (version < LATEST_VERSION) {
// Update header and all config values.
config.options().header(HEADER);
config.options().copyDefaults(true);
set("config-version", LATEST_VERSION);
// Save the config.
config.save(configFile);
plugin.getLogger().info("Configuration file has been successfully updated.");
}
}
} |
package scorer.termproject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.galagosearch.core.index.PositionIndexReader;
import org.galagosearch.core.retrieval.structured.CountIterator;
import org.galagosearch.core.retrieval.structured.RequiredStatistics;
import org.galagosearch.core.retrieval.structured.ScoringFunctionIterator;
import org.galagosearch.core.types.DocumentFeature;
import org.galagosearch.core.util.ExtentArray;
import org.galagosearch.tupleflow.Parameters;
@RequiredStatistics(statistics = {"collectionLength", "documentCount"})
public class IntappScorer extends ScoringFunctionIterator {
double inverseDocumentFrequency;
double documentFrequency;
double documentCount;
double avgDocumentLength;
double collectionLength;
HashMap<Integer, ArrayList<Integer>> termPositionsMap = new HashMap<Integer, ArrayList<Integer>>();
HashMap<Integer, Long> byteLengthMap = new HashMap<Integer, Long>();
HashMap<Integer, ArrayList<String>> termListMap = new HashMap<Integer, ArrayList<String>>();
public IntappScorer(Parameters parameters, CountIterator iterator) throws IOException {
super(iterator);
// here you write your scoring function needed for a query
// = new int[extentArray.getPosition()];
// k_1 = parameters.get("k_1", 1);
// b = parameters.get("b", 1);
documentFrequency = 0;
documentCount = parameters.get("documentCount", 100000);
collectionLength = parameters.get("collectionLength", 1000000);
avgDocumentLength = collectionLength / documentCount;
// System.out.println(((PositionIndexReader.Iterator) iterator).getRecordString());
if(iterator instanceof PositionIndexReader.Iterator) {
while(!iterator.isDone()) {
ArrayList<String> termList = new ArrayList<String>();
int document = iterator.document();
ExtentArray extentArray = ((PositionIndexReader.Iterator) iterator).extents();
ArrayList<Integer> termPositions = new ArrayList<Integer>();
for (int i = 0; i < extentArray.getPosition(); ++i) {
termPositions.add(extentArray.getBuffer()[i].begin);
}
termPositionsMap.put(document, termPositions);
byteLengthMap.put(document, ((PositionIndexReader.Iterator) iterator).getDocumentByteLength());
iterator.nextDocument();
}
}
iterator.reset();
while (!iterator.isDone()) {
documentFrequency += 1;
iterator.nextDocument();
}
iterator.reset();
computeInverseDocumentFrequency();
}
public void computeInverseDocumentFrequency() {
double numerator = documentCount - documentFrequency + 0.5;
double denominator = documentFrequency + 0.5;
inverseDocumentFrequency = Math.log(numerator / denominator);
}
public double score(int document, int length) {
int count = 0;
if (iterator.document() == document) {
count = iterator.count();
}
return scoreCount(count, length);
}
public double scoreCount(int count, int length) {
double score=0;
int document = iterator.document();
ArrayList<Integer> termPositions = termPositionsMap.get(document);
// POSSIBLE FEATURES
// documentFrequency: number of documents that contains the query term
// documentCount: total number of documents in the collection
// collectionLength: length of collection
// avgDocumentLength: average document length
// termPositions: positions in the document for the query term
// count: number of term occurrence in the document for the query term
// length: length of current document
double termPosWeightSum = 0;
if(termPositions != null && count != 0) {
for(int i = 0; i < termPositions.size(); i++) {
// term
double value = Math.pow(((double)(length - termPositions.get(i)) / (double)length + 0.5), 2.0);
//document_length.xls 200
if (length < avgDocumentLength) {
if(termPositions.get(i)/(double)length < 0.25) {
value += value * 0.8;
} else if(termPositions.get(i)/(double)length < 0.35) {
value += value * 0.5;
} else if(termPositions.get(i)/(double)length > 0.70) {
value += value * 0.5;
}
} else {
if(termPositions.get(i)/(double)length < 0.15) {
value += value * 0.75;
} if(termPositions.get(i)/(double)length < 0.30) {
value += value * 0.5;
} else if(termPositions.get(i)/(double)length > 0.80) {
value += value * 0.5;
}
}
termPosWeightSum += value;
}
termPosWeightSum = termPosWeightSum * Math.pow(count, 1.5);
}
//foundation_bm25_review.pdf 30p b, k_1
double k_1 = 1.6;
double b = 0.8;
double numerator = termPosWeightSum * (k_1 + 1);
double denominator = termPosWeightSum + (k_1 * (1.0 - b + b * (length/avgDocumentLength)));
// IDF
score = Math.pow(inverseDocumentFrequency, 2.0) * numerator / denominator;
return score;
}
} |
import log.Logger;
import path.Path;
import path.RedirectableNode;
import path.RedirectablePath;
import wiki_api.RedirectedException;
import wiki_api.WikipediaApi;
import java.io.IOException;
import java.util.*;
public class WikipediaPathFinder implements PathFinder {
private WikipediaLinkSource linkSource;
private WikipediaBacklinkSource backlinkSource;
private WikipediaApi api;
private Logger logger;
public WikipediaPathFinder(WikipediaApi api) {
this.api = api;
linkSource = new WikipediaLinkSource(api);
backlinkSource = new WikipediaBacklinkSource(api);
logger = Logger.getInstance();
}
@Override
public RedirectablePath getPath(String from, String to) throws Exception {
Map<String, String> frontParents = new HashMap<>();
Map<String, String> backParents = new HashMap<>();
Queue<String> frontNextQueue = new LinkedList<>();
Queue<String> backNextQueue = new LinkedList<>();
frontNextQueue.add(from);
frontParents.put(from, null);
backNextQueue.add(to);
backParents.put(to, null);
int step = 0;
String result = null;
boolean lastStepSkipped = false;
while (true) {
step++;
Queue<String> nextQueue;
Map<String, String> parents;
Map<String, String> targets;
LinkSource source;
if (step % 2 == 1) {
// search from front
nextQueue = frontNextQueue;
parents = frontParents;
targets = backParents;
source = linkSource;
} else {
// search from back
nextQueue = backNextQueue;
parents = backParents;
targets = frontParents;
source = backlinkSource;
}
if (!nextQueue.isEmpty()) {
logStep(nextQueue, step);
nextQueue = search(nextQueue, parents, targets, source);
} else {
// if both queue is empty, stop the searching
if (lastStepSkipped) {
break;
} else {
lastStepSkipped = true;
}
}
// update queue
if (step % 2 == 1) {
frontNextQueue = nextQueue;
} else {
backNextQueue = nextQueue;
}
// front and back is connected by result
result = checkResult(frontParents, backParents);
if (result != null) {
break;
}
}
if (result == null) {
return null;
}
// concat both results
ArrayList<String> frontResult = getResult(frontParents, from, result);
ArrayList<String> backResult = getResult(backParents, to, result);
backResult.remove(backResult.size() - 1); // remove duplicated result
Collections.reverse(backResult);
frontResult.addAll(backResult);
return new RedirectablePath(toRedirectableList(frontResult));
}
// return the key contained by both maps. If not found, return null
private String checkResult(Map<String, String> frontParents, Map<String, String> backParents) {
Set<String> copiedSet = new HashSet<>(frontParents.keySet());
copiedSet.retainAll(backParents.keySet());
if (copiedSet.isEmpty()) {
return null;
}
return copiedSet.iterator().next();
}
// get links from queue and add them to the parents map
private Queue<String> search(Queue<String> queue, Map<String, String> parents,
Map<String, String> targets, LinkSource source) throws Exception {
Queue<String> nextQueue = new LinkedList<>();
boolean stopSearching = false;
while (!queue.isEmpty() & !stopSearching) {
String currentNode = queue.poll();
logCurrentNode(currentNode);
Set<String> connectedLinks = null;
try {
connectedLinks = source.getLinks(currentNode);
} catch (RedirectedException ignored) {
// do special job to redirected link
String redirected = api.resolve(currentNode);
if (!parents.containsKey(redirected)) {
parents.put(redirected, currentNode);
nextQueue.add(redirected);
continue;
}
}
if (connectedLinks == null) {
continue;
}
// add links to the parents map if they're not added yet.
for (String connectedNode : connectedLinks) {
if (!parents.containsKey(connectedNode)) {
parents.put(connectedNode, currentNode);
nextQueue.add(connectedNode);
}
if (targets.containsKey(connectedNode)) {
stopSearching = true;
break;
}
}
}
return nextQueue;
}
// follow parents from 'to' until it reaches 'from'
private ArrayList<String> getResult(Map<String, String> parents, String from, String to) {
ArrayList<String> path = new ArrayList<>();
String current = to;
while (!current.equals(from)) {
path.add(current);
current = parents.get(current);
}
path.add(current);
Collections.reverse(path);
return path;
}
// transform string list to redirectable list
private ArrayList<RedirectableNode> toRedirectableList(ArrayList<String> original) throws IOException {
ArrayList<RedirectableNode> result = new ArrayList<>();
for (String s : original) {
result.add(new RedirectableNode(api.resolve(s) != null, s));
}
return result;
}
private void logCurrentNode(String currentNode) {
logger.debug(String.format("%s", currentNode));
}
private void logStep(Queue<String> queue, int step) {
logger.info(String.format("Step %d, Queue size: %d", step, queue.size()));
}
} |
package de.fosd.jdime.gui;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.apache.commons.io.IOUtils;
/**
* A simple JavaFX GUI for JDime.
*/
public class GUI extends Application {
private static final String TITLE = "JDime";
@FXML
private TextArea output;
@FXML
private TextField left;
@FXML
private TextField base;
@FXML
private TextField right;
@FXML
private TextField jDime;
@FXML
private TextField cmdArgs;
@FXML
private Button leftBtn;
@FXML
private Button baseBtn;
@FXML
private Button rightBtn;
@FXML
private Button runBtn;
@FXML
private Button jDimeBtn;
private File lastChooseDir;
private List<TextField> textFields;
private List<Button> buttons;
/**
* Launches the GUI with the given <code>args</code>.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource(getClass().getSimpleName() + ".fxml"));
loader.setController(this);
Parent root = loader.load();
Scene scene = new Scene(root);
textFields = Arrays.asList(left, base, right, jDime, cmdArgs);
buttons = Arrays.asList(leftBtn, baseBtn, rightBtn, runBtn, jDimeBtn);
primaryStage.setTitle(TITLE);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* Shows a <code>FileChooser</code> and returns the chosen <code>File</code>. Sets <code>lastChooseDir</code>
* to the parent file of the returned <code>File</code>.
*
* @param event the <code>ActionEvent</code> that occurred in the action listener
* @return the chosen <code>File</code> or <code>null</code> if the dialog was closed
*/
private File getChosenFile(ActionEvent event) {
FileChooser chooser = new FileChooser();
Window window = ((Node) event.getTarget()).getScene().getWindow();
if (lastChooseDir != null && lastChooseDir.isDirectory()) {
chooser.setInitialDirectory(lastChooseDir);
}
return chooser.showOpenDialog(window);
}
/**
* Called when the 'Choose' button for the left file is clicked.
*
* @param event the <code>ActionEvent</code> that occurred
*/
public void chooseLeft(ActionEvent event) {
File leftArtifact = getChosenFile(event);
if (leftArtifact != null) {
lastChooseDir = leftArtifact.getParentFile();
left.setText(leftArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the base file is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseBase(ActionEvent event) {
File baseArtifact = getChosenFile(event);
if (baseArtifact != null) {
lastChooseDir = baseArtifact.getParentFile();
base.setText(baseArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the right file is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseRight(ActionEvent event) {
File rightArtifact = getChosenFile(event);
if (rightArtifact != null) {
lastChooseDir = rightArtifact.getParentFile();
right.setText(rightArtifact.getAbsolutePath());
}
}
/**
* Called when the 'Choose' button for the JDime executable is clicked.
*
* @param event
* the <code>ActionEvent</code> that occurred
*/
public void chooseJDime(ActionEvent event) {
File jDimeBinary = getChosenFile(event);
if (jDimeBinary != null) {
lastChooseDir = jDimeBinary.getParentFile();
jDime.setText(jDimeBinary.getAbsolutePath());
}
}
/**
* Called when the 'Run' button is clicked.
*/
public void runClicked() {
boolean valid = textFields.stream().allMatch(tf -> {
if (tf == cmdArgs) {
return true;
}
if (tf == base) {
return tf.getText().trim().isEmpty() || new File(tf.getText()).exists();
}
return new File(tf.getText()).exists();
});
if (!valid) {
return;
}
textFields.forEach(textField -> textField.setDisable(true));
buttons.forEach(button -> button.setDisable(true));
Task<String> jDimeExec = new Task<String>() {
@Override
protected String call() throws Exception {
ProcessBuilder builder = new ProcessBuilder();
List<String> command = new ArrayList<>();
command.add(jDime.getText());
command.addAll(Arrays.asList(cmdArgs.getText().split("\\s+")));
command.add(left.getText());
command.add(base.getText());
command.add(right.getText());
builder.command(command);
File workingDir = new File(jDime.getText()).getParentFile();
if (workingDir != null && workingDir.exists()) {
builder.directory(workingDir);
}
Process process = builder.start();
process.waitFor();
StringWriter writer = new StringWriter();
IOUtils.copy(process.getInputStream(), writer, Charset.defaultCharset());
return writer.toString();
}
};
jDimeExec.setOnSucceeded(event -> {
output.setText(jDimeExec.getValue());
textFields.forEach(textField -> textField.setDisable(false));
buttons.forEach(button -> button.setDisable(false));
});
new Thread(jDimeExec).start();
}
} |
package accepting;
import java.util.HashMap;
public class Timelines {
private HashMap<String, Timeline> timelines = new HashMap<>();
public Timeline getPostsFor(String user) {
return timelines.getOrDefault(user, new Timeline());
}
public void post(String user, Post post) {
Timeline timeline = timelines.getOrDefault(user, new Timeline());
timeline.addPost(post);
timelines.put(user, timeline);
}
} |
package app.tests;
import app.login.RegisterController;
import app.login.User;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.JVM)
public class LoginTest {
@Test
public void nameTester() {
RegisterController tester = new RegisterController();
Boolean name=true;
Boolean name2=false;
String name3="Pieter";
// assert statements
Boolean result2 = tester.multiplyString(name);
Assert.assertEquals(name, result2);
Boolean result3 = tester.multiplyString(name);
Assert.assertEquals(name, result3);
}
@Test
public void zcreateAdressTester() {
User tester = new User();
String name="2";
String name2="Toos";
String name3="Pieter";
String name4="city";
// assert statements
String result = tester.createAdress(name, name2, name3, name, name3);
Assert.assertEquals("insert into adress(adressid, city, postalcode ,street, housenumber) values('"+name+"', '"+name2+"', '"+name3+"', '"+name+"', '"+name3+"');", result);
String result1 = tester.alterAdress(name4, name2, name3);
Assert.assertEquals("city", result1);
String result2 = tester.deleteAdress(name);
Assert.assertEquals(name, result2);
}
@Test
public void createCustomerTester() {
User tester = new User();
String name="02-12-2016";
String name2="Toos";
String name3="Pieter";
String name4="userlevel";
// assert statements
Boolean result = tester.createCustomer(name3, name2, name3, name2, name3,name,name3,name);
Assert.assertEquals(true, result);
String result1 = tester.alterCustomer(name4, name2, name3);
Assert.assertEquals("userlevel", result1);
String result2 = tester.deleteCustomer(name3);
Assert.assertEquals(name3, result2);
}
@Test
public void wishlistTester() {
User tester = new User();
String name="02-12-2016";
String name2="Toos";
String name3="2";
// assert statements
String result = tester.addWishproduct(name3, name2, name3);
Assert.assertEquals("insert into wishlistproducts(productid, wishlistid, quantity) values('"+name3+"', '"+name2+"', '"+name3+"');", result);
}
} |
package ch.uzh.csg.p2p;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.sound.sampled.LineUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.uzh.csg.p2p.controller.LoginWindowController;
import ch.uzh.csg.p2p.helper.LoginHelper;
import ch.uzh.csg.p2p.model.Friend;
import ch.uzh.csg.p2p.model.Message;
import ch.uzh.csg.p2p.model.User;
import ch.uzh.csg.p2p.model.request.BootstrapRequest;
import ch.uzh.csg.p2p.model.request.MessageRequest;
import ch.uzh.csg.p2p.model.request.Request;
import ch.uzh.csg.p2p.model.request.RequestHandler;
import ch.uzh.csg.p2p.model.request.RequestListener;
import ch.uzh.csg.p2p.model.request.RequestType;
import ch.uzh.csg.p2p.model.request.UserRequest;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import net.tomp2p.connection.Bindings;
import net.tomp2p.dht.FutureGet;
import net.tomp2p.dht.PeerBuilderDHT;
import net.tomp2p.dht.PeerDHT;
import net.tomp2p.futures.BaseFutureListener;
import net.tomp2p.p2p.PeerBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.replication.IndirectReplication;
import net.tomp2p.rpc.ObjectDataReply;
public class Node extends Observable{
protected final String BOOTSTRAPNODE = "Bootstrapnode";
private final int DEFAULTPORT = 54000;
private Logger log;
private User user;
private ObservableList<Friend> friendList = FXCollections.observableList(new ArrayList<Friend>());
protected PeerDHT peer;
public Node(int nodeId, String ip, String username, String password, Observer nodeReadyObserver)
throws IOException, LineUnavailableException, ClassNotFoundException {
log = LoggerFactory.getLogger("Node of user " + username);
user = new User(username, password, null);
int id = ((Long) System.currentTimeMillis()).intValue();
if(nodeReadyObserver != null) {
addObserver(nodeReadyObserver);
}
// if not a BootstrapNode
if (ip != null) {
createPeer(id, username, password, false);
connectToNode(ip);
} else {
createPeer(nodeId, username, password, true);
}
initiateUser(username, password);
}
private void nodeReady() {
setChanged();
notifyObservers(this);
}
public void loadStoredDataFromDHT()
throws UnsupportedEncodingException, LineUnavailableException {
// TODO load messages, calls, friendrequests...
loadFriendlistFromDHT();
}
private void initiateUser(final String username, final String password)
throws ClassNotFoundException, LineUnavailableException, IOException {
RequestListener<User> userExistsListener = new RequestListener<User>(this) {
@Override
public void operationComplete(FutureGet futureGet) throws Exception {
if (futureGet != null && futureGet.isSuccess() && futureGet.data() != null) {
// user already exist --> only update address
LoginHelper.updatePeerAddress(this.node, username);
} else {
// user does not exist --> add user
LoginHelper.saveUsernamePassword(this.node, username, password);
User newUser = new User(username, password, this.node.getPeer().peerAddress());
this.node.setUser(newUser);
}
nodeReady();
}
};
LoginHelper.retrieveUser(username, this, userExistsListener);
}
private void loadFriendlistFromDHT()
throws UnsupportedEncodingException, LineUnavailableException {
for (String friendName : user.getFriendStorage()) {
User user = new User(friendName, null, null);
RequestListener<User> requestListener = new RequestListener<User>(this) {
@Override
public void operationComplete(FutureGet futureGet) throws Exception {
if (futureGet != null && futureGet.isSuccess() && futureGet.data() != null) {
User user = (User) futureGet.data().object();
Friend friend = new Friend(user.getPeerAddress(), user.getUsername());
this.node.friendList.add(friend);
}
}
};
LoginHelper.retrieveUser(friendName, this, requestListener);
}
}
public void registerForFriendListUpdates(ListChangeListener<Friend> listener) {
friendList.addListener(listener);
}
protected void createPeer(int nodeId, String username, String password, Boolean isBootstrapNode)
throws IOException, ClassNotFoundException, LineUnavailableException {
Bindings b = new Bindings().listenAny();
peer = new PeerBuilderDHT(
new PeerBuilder(new Number160(nodeId)).ports(getPort()).bindings(b).start())
.start();
if (isBootstrapNode) {
BootstrapRequest request = new BootstrapRequest(RequestType.STORE);
RequestHandler.handleRequest(request, this);
}
peer.peer().objectDataReply(new ObjectDataReply() {
public Object reply(PeerAddress peerAddress, Object object) throws Exception {
return handleReceivedData(peerAddress, object);
}
});
// TODO: Indirect Replication or direct? Replication factor?
new IndirectReplication(peer).autoReplication(true).replicationFactor(3).start();
}
protected Object handleReceivedData(PeerAddress peerAddress, Object object)
throws IOException, LineUnavailableException, ClassNotFoundException {
log.info("received message: " + object.toString() + " from: " + peerAddress.toString());
if (object instanceof Message) {
MessageRequest messageRequest = new MessageRequest();
messageRequest.setType(RequestType.RECEIVE);
messageRequest.setMessage((Message) object);
RequestHandler.handleRequest(messageRequest, this);
}
/*
* if (object instanceof AudioMessage) { messageRequest.setType(RequestType.RECEIVE);
* messageRequest.setMessage((AudioMessage) object);
* RequestHandler.handleRequest(messageRequest, this); } else if (object instanceof
* ChatMessage) { messageRequest.setType(RequestType.RECEIVE);
* messageRequest.setMessage((ChatMessage) object);
* RequestHandler.handleRequest(messageRequest, this);}
*/
/*
* else if (object instanceof AudioRequest) { AudioRequest audioRequest = (AudioRequest)
* object; audioRequest.setType(RequestType.RECEIVE);
* RequestHandler.handleRequest(audioRequest, this); }
*/
else if (object instanceof Request) {
Request r = (Request) object;
r.setType(RequestType.RECEIVE);
RequestHandler.handleRequest(r, this);
} else {
System.out.println("else");
}
return 0;
}
private void connectToNode(String knownIP) throws ClassNotFoundException, IOException {
BootstrapRequest request =
new BootstrapRequest(RequestType.SEND, user.getPeerAddress(), knownIP);
RequestHandler.handleRequest(request, this);
}
private int getPort() {
int port = DEFAULTPORT;
while (portIsOpen("127.0.0.1", port, 200)) {
port++;
}
log.info("Free port found, port is: " + port);
return port;
}
private boolean portIsOpen(String ip, int port, int timeout) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, port), timeout);
socket.close();
return true;
} catch (Exception ex) {
return false;
}
}
public PeerDHT getPeer() {
return peer;
}
public User getUser() {
return user;
}
public void setUser(User user) {
if (user != null) {
this.user = user;
} else {
User newUser = new User(this.user.getUsername(), this.user.getPassword(),
this.getPeer().peerAddress());
this.user = newUser;
}
}
public List<Friend> getFriendList() {
return friendList;
}
public void shutdown() {
log.info("Shutting down gracefully.");
if (peer != null) {
peer.shutdown();
}
}
public Friend getFriend(String currentChatPartner) {
for (Friend f : friendList) {
if (f.getName().equals(currentChatPartner)) {
return f;
}
}
return null;
}
public void addFriend(Friend friend) {
friendList.add(friend);
}
} |
package com.bugsnag;
import com.bugsnag.callbacks.Callback;
import com.bugsnag.delivery.Delivery;
import com.bugsnag.delivery.HttpDelivery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.Proxy;
public class Bugsnag {
private static final Logger LOGGER = LoggerFactory.getLogger(Bugsnag.class);
private Configuration config;
// Constructors
/**
* Initialize a Bugsnag client and automatically send uncaught exceptions.
*
* @param apiKey your Bugsnag API key from your Bugsnag dashboard
*/
public Bugsnag(String apiKey) {
this(apiKey, true);
}
/**
* Initialize a Bugsnag client.
*
* @param apiKey your Bugsnag API key
* @param sendUncaughtExceptions should we send uncaught exceptions to Bugsnag
*/
public Bugsnag(String apiKey, boolean sendUncaughtExceptions) {
if (apiKey == null) {
throw new NullPointerException("You must provide a Bugsnag API key");
}
config = new Configuration(apiKey);
// Automatically send unhandled exceptions to Bugsnag using this Bugsnag
if (sendUncaughtExceptions) {
ExceptionHandler.enable(this);
}
}
// Configuration
/**
* Add a callback to execute code before/after every notification to Bugsnag.
*
* <p>You can use this to add or modify information attached to an error
* before it is sent to your dashboard. You can also stop any reports being
* sent to Bugsnag completely.
*
* @param callback a callback to run before sending errors to Bugsnag
* @see Callback
*/
public void addCallback(Callback callback) {
config.addCallback(callback);
}
/**
* Get the method of delivery for Bugsnag error reports.
*
* @see Delivery
*/
public Delivery getDelivery() {
return config.delivery;
}
/**
* Set the application type sent to Bugsnag.
*
* @param appType the app type to send, eg. spring, gradleTask
*/
public void setAppType(String appType) {
config.appType = appType;
}
/**
* Set the application version sent to Bugsnag.
*
* @param appVersion the app version to send
*/
public void setAppVersion(String appVersion) {
config.appVersion = appVersion;
}
public void setDelivery(Delivery delivery) {
config.delivery = delivery;
}
/**
* Set the endpoint to deliver Bugsnag errors report to. This is a convenient
* shorthand for bugsnag.getDelivery().setEndpoint();
*
* @param endpoint the endpoint to send reports to
* @see #setDelivery
*/
public void setEndpoint(String endpoint) {
if (config.delivery instanceof HttpDelivery) {
((HttpDelivery) config.delivery).setEndpoint(endpoint);
}
}
/**
* Set which keys should be filtered when sending metaData to Bugsnag.
* Use this when you want to ensure sensitive information, such as passwords
* or credit card information is stripped from metaData you send to Bugsnag.
* Any keys in metaData which contain these strings will be marked as
* [FILTERED] when send to Bugsnag.
*
* @param filters a list of String keys to filter from metaData
*/
public void setFilters(String... filters) {
config.filters = filters;
}
/**
* Set which exception classes should be ignored (not sent) by Bugsnag.
*
* @param ignoreClasses a list of exception classes to ignore
*/
public void setIgnoreClasses(String... ignoreClasses) {
config.ignoreClasses = ignoreClasses;
}
/**
* Set for which releaseStages errors should be sent to Bugsnag.
* Use this to stop errors from development builds being sent.
*
* @param notifyReleaseStages a list of releaseStages to notify for
* @see #setReleaseStage
*/
public void setNotifyReleaseStages(String... notifyReleaseStages) {
config.notifyReleaseStages = notifyReleaseStages;
}
/**
* Set which packages should be considered part of your application.
* Bugsnag uses this to help with error grouping, and stacktrace display.
*
* @param projectPackages a list of package names
*/
public void setProjectPackages(String... projectPackages) {
config.projectPackages = projectPackages;
}
/**
* Set a proxy to use when delivering Bugsnag error reports. This is a convenient
* shorthand for bugsnag.getDelivery().setProxy();
*
* @param proxy the proxy to use to send reports
*/
public void setProxy(Proxy proxy) {
if (config.delivery instanceof HttpDelivery) {
((HttpDelivery) config.delivery).setProxy(proxy);
}
}
/**
* Set the current "release stage" of your application.
*
* @param releaseStage the release stage of the app
* @see #setNotifyReleaseStages
*/
public void setReleaseStage(String releaseStage) {
config.releaseStage = releaseStage;
}
/**
* Set whether Bugsnag should capture and report thread-state for all
* running threads. This is often not useful for Java web apps, since
* there could be thousands of active threads depending on your
* environment.
*
* @param sendThreads should we send thread state with error reports
* @see #setNotifyReleaseStages
*/
public void setSendThreads(boolean sendThreads) {
config.sendThreads = sendThreads;
}
/**
* Set a timeout (in ms) to use when delivering Bugsnag error reports.
* This is a convenient shorthand for bugsnag.getDelivery().setTimeout();
*
* @param timeout the timeout to set (in ms)
* @see #setDelivery
*/
public void setTimeout(int timeout) {
if (config.delivery instanceof HttpDelivery) {
((HttpDelivery) config.delivery).setTimeout(timeout);
}
}
// Notification
/**
* Build an Report object to send to Bugsnag.
*
* @param throwable the exception to send to Bugsnag
* @return the report object
* @see Report
* @see #notify(com.bugsnag.Report)
*/
public Report buildReport(Throwable throwable) {
return new Report(config, throwable);
}
/**
* Notify Bugsnag of a handled exception.
*
* @param throwable the exception to send to Bugsnag
* @return true unless the error report was ignored
*/
public boolean notify(Throwable throwable) {
return notify(buildReport(throwable));
}
/**
* Notify Bugsnag of a handled exception.
*
* @param throwable the exception to send to Bugsnag
* @param callback the {@link Callback} object to run for this Report
* @return true unless the error report was ignored
*/
public boolean notify(Throwable throwable, Callback callback) {
return notify(buildReport(throwable), callback);
}
/**
* Notify Bugsnag of a handled exception - with a severity.
*
* @param throwable the exception to send to Bugsnag
* @param severity the severity of the error, one of {#link Severity#ERROR},
* {@link Severity#WARNING} or {@link Severity#INFO}
* @return true unless the error report was ignored
*/
public boolean notify(Throwable throwable, Severity severity) {
if (throwable == null) {
LOGGER.warn("Tried to notify with a null Throwable");
return false;
}
Report report = buildReport(throwable);
report.setSeverity(severity);
return notify(report);
}
/**
* Notify Bugsnag of an exception and provide custom diagnostic data
* for this particular error report.
*
* @param report the {@link Report} object to send to Bugsnag
* @return true unless the error report was ignored
* @see Report
* @see #buildReport
*/
public boolean notify(Report report) {
return notify(report, null);
}
/**
* Notify Bugsnag of an exception and provide custom diagnostic data
* for this particular error report.
*
* @param report the {@link Report} object to send to Bugsnag
* @param reportCallback the {@link Callback} object to run for this Report
* @return false if the error report was ignored
* @see Report
* @see #buildReport
*/
public boolean notify(Report report, Callback reportCallback) {
if (report == null) {
LOGGER.warn("Tried to call notify with a null Report");
return false;
}
// Don't notify if this error class should be ignored
if (config.shouldIgnoreClass(report.getExceptionName())) {
LOGGER.debug("Error not reported to Bugsnag - {} is in 'ignoreClasses'",
report.getExceptionName());
return false;
}
// Don't notify unless releaseStage is in notifyReleaseStages
if (!config.shouldNotifyForReleaseStage()) {
LOGGER.debug("Error not reported to Bugsnag - {} is not in 'notifyReleaseStages'",
config.releaseStage);
return false;
}
// Run all client-wide beforeNotify callbacks
for (Callback callback : config.callbacks) {
try {
// Run the callback
callback.beforeNotify(report);
// Check if callback cancelled delivery
if (report.getShouldCancel()) {
LOGGER.debug("Error not reported to Bugsnag - "
+ "cancelled by a client-wide beforeNotify callback");
return false;
}
} catch (Throwable ex) {
LOGGER.warn("Callback threw an exception", ex);
}
}
// Run the report-specific beforeNotify callback, if given
if (reportCallback != null) {
try {
// Run the callback
reportCallback.beforeNotify(report);
// Check if callback cancelled delivery
if (report.getShouldCancel()) {
LOGGER.debug(
"Error not reported to Bugsnag - cancelled by a report-specific callback");
return false;
}
} catch (Throwable ex) {
LOGGER.warn("Callback threw an exception", ex);
}
}
if (config.delivery == null) {
LOGGER.debug("Error not reported to Bugsnag - no delivery is set");
return false;
}
// Build the notification
Notification notification = new Notification(config, report);
// Deliver the notification
LOGGER.debug("Reporting error to Bugsnag");
config.delivery.deliver(config.serializer, notification);
return true;
}
} |
package com.togocms.pns;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.clickntap.tool.types.Datetime;
import com.togocms.pns.api.AndroidNotification;
import com.togocms.pns.api.IOSNotification;
import com.togocms.pns.api.PushNotification;
import com.togocms.pns.api.PushNotificationService;
import com.togocms.pns.bo.Channel;
import com.togocms.pns.bo.Device;
import com.togocms.pns.bo.Message;
import com.togocms.pns.bo.Push;
public class App extends com.clickntap.hub.App implements PushNotificationService {
private Resource resourcesDir;
public Resource getResourcesDir() {
return resourcesDir;
}
public void setResourcesDir(Resource resourcesDir) {
this.resourcesDir = resourcesDir;
}
public List<Channel> getChannels() throws Exception {
return getBOListByClass(Channel.class, "all");
}
public Long sendBroadcastNotification(String apiKey, PushNotification notification) throws Exception {
Long id = createMessage(apiKey, notification);
return id;
}
public Long sendNotification(String apiKey, PushNotification notification, Long userId) throws Exception {
Long id = createMessage(apiKey, notification);
return id;
}
public Long sendGroupNotification(String apiKey, PushNotification notification, List<Long> userIds) throws Exception {
Long id = createMessage(apiKey, notification);
return id;
}
public void init() throws Exception {
exportKeyStores();
}
public void exportKeyStores() throws Exception {
for (Channel channel : getChannels()) {
if (channel.getKeyStore() != null) {
File f = geyKeyStorePath(channel);
FileUtils.writeByteArrayToFile(f, Base64.decodeBase64(channel.getKeyStore()));
}
}
}
private File geyKeyStorePath(Channel channel) throws IOException {
return new File(getResourcesDir().getFile().getCanonicalPath() + "/" + channel.getId() + "_" + channel.getProduction() + ".p12");
}
public void sync() throws Exception {
executeTransaction(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
Message message = new Message();
message.setApp(App.this);
message.read("next");
if (message.getId() != null) {
message.read();
if (message.getWorkflow().intValue() == 0) {
Channel channel = message.getChannel();
List<String> addedTokens = new ArrayList<String>();
for (Device device : channel.getDevices()) {
if (!addedTokens.contains(device.getToken())) {
addedTokens.add(device.getToken());
Push item = new Push();
item.setApp(App.this);
item.setToken(device.getToken());
item.setPlatform(device.getPlatform());
item.setMessageId(message.getId());
item.setCreationTime(new Datetime());
item.setLastModified(item.getCreationTime());
item.create();
}
}
message.setLastModified(new Datetime());
message.execute("queued");
} else if (message.getWorkflow().intValue() == 1) {
message.setAndroidSent(0);
message.setAndroidFails(0);
message.setIosSent(0);
message.setIosFails(0);
{ // android
List<Push> androidDevices = message.getNextAndroidPushes();
while (androidDevices.size() != 0) {
AndroidNotification notification = new AndroidNotification();
notification.setSecretKey(message.getChannel().getSecretKey());
notification.setTitle(message.getTitle());
notification.setAlert(message.getAlert());
for (Push push : androidDevices) {
notification.addToken(push.getToken());
push.delete();
}
status.createSavepoint();
int androidSent = androidDevices.size();
int androidFails = 0;
for (String badToken : notification.send()) {
disableDevice(badToken);
androidSent
androidFails++;
}
message.setAndroidSent(message.getAndroidSent().intValue() + androidSent);
message.setAndroidFails(message.getAndroidFails().intValue() + androidFails);
androidDevices = message.getNextAndroidPushes();
}
}
{ // apple
List<Push> iosDevices = message.getNextIosPushes();
while (iosDevices.size() != 0) {
IOSNotification notification = new IOSNotification();
notification.setKeyStorePath(geyKeyStorePath(message.getChannel()).getCanonicalPath());
notification.setKeyStorePassword(message.getChannel().getKeyStorePassword());
notification.setAlert(message.getAlert());
for (Push push : iosDevices) {
notification.addToken(push.getToken());
push.delete();
}
status.createSavepoint();
int iosSent = iosDevices.size();
int iosFails = 0;
for (String badToken : notification.send()) {
disableDevice(badToken);
iosSent
iosFails++;
}
message.setIosSent(message.getIosSent().intValue() + iosSent);
message.setIosFails(message.getIosFails().intValue() + iosFails);
iosDevices = message.getNextIosPushes();
}
}
message.setLastModified(new Datetime());
message.execute("sent");
}
}
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
}
return null;
}
private void disableDevice(String badToken) {
try {
Device device = new Device();
device.setApp(App.this);
device.setToken(badToken);
device.read("token");
device.execute("disable");
} catch (Exception e) {
}
}
});
}
private Number findChannelId(String apiKey) throws Exception {
Channel channel = new Channel();
channel.setApp(this);
channel.setApiKey(apiKey);
channel.read("apiKey");
return channel.getId();
}
private Long createMessage(String apiKey, PushNotification notification) throws Exception {
Message message = new Message();
message.setApp(this);
message.setTitle(notification.getTitle());
message.setAlert(notification.getAlert());
message.setChannelId(findChannelId(apiKey));
message.setCreationTime(new Datetime());
message.setLastModified(message.getCreationTime());
message.setWorkflow(0);
message.create();
return message.getId().longValue();
}
} |
package dk.ekot.ibm;
import dk.ekot.misc.Bitmap;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Jan2019 {
private static Log log = LogFactory.getLog(Jan2019.class);
public static void main(String[] args) {
new Jan2019().run();
}
private void run() {
final int maxElement = 100_000;
final int minALength = 4;
final int minBLength = 4;
final int maxResults = 5;
//fixedA2(maxElement, minBLength);
long startNS = System.nanoTime();
earlyElimination(maxElement, minALength, minBLength, maxResults);
}
private void earlyElimination(int maxElement, int minALength, int minBLength, int maxResults) {
System.out.println("Early eliminationwith maxElement=" + maxElement + ", min-A-size=" + minALength +
", min-B-size=" + minBLength);
final Bitmap validProducts = generateValidProducts(maxElement*2);
Bitmap validDeltas = getValidDeltas(validProducts, maxElement, minBLength);
final int[] as = new int[minALength];
final Bitmap[] candidateBs = new Bitmap[minALength];
final Bitmap[] validBs = new Bitmap[minALength];
for (int i = 0 ; i < minALength ; i++) {
candidateBs[i] = new Bitmap(validProducts.size());
validBs[i] = new Bitmap(validProducts.size());
}
earlyElimination(validProducts, validDeltas, maxElement, minALength, minBLength, as, candidateBs, validBs, 0,
new AtomicInteger(maxResults), new AtomicInteger(1), new AtomicInteger(1),
System.nanoTime());
}
private void earlyElimination(
Bitmap validProducts, Bitmap validDeltas, int maxElement, int minALength, int minBLength,
int[] as, Bitmap[] candidateBs, Bitmap[] validBs, final int level,
AtomicInteger resultsLeft, AtomicInteger printedA, AtomicInteger printedB, long startTime) {
if (level == minALength) {
System.out.print(toString(as) + " " + toString(validBs[level-1].getIntegers()));
System.out.println(" " + (System.nanoTime() - startTime)/1000000/1000 + " seconds");
resultsLeft.decrementAndGet();
return;
}
final int previousIndex = level == 0 ? 0 : as[level-1];
int delta = level == 0 ? 1 : validDeltas.thisOrNext(1);
as[level] = previousIndex+delta;
while (as[level] <= maxElement) {
if (level == 0) {
System.out.print(as[level] + " ");
if ((as[level] & 31) == 0) {
System.out.println();
}
}
validProducts.shift(-as[level], candidateBs[level]);
if (level == 0) {
candidateBs[level].copy(validBs[level]);
} else {
Bitmap.and(validBs[level-1], candidateBs[level], validBs[level]);
}
if (validBs[level].cardinality() >= minBLength) {
if (level > printedA.get()) {
System.out.print(toString(as) + " " + toString(validBs[level].getIntegers()));
System.out.println(" " + (System.nanoTime() - startTime) / 1000000 / 1000 + " seconds");
printedA.set(level);
printedB.set(1);
} else if (level == printedA.get() && validBs[level].cardinality() > printedB.get()) {
System.out.print(toString(as) + " " + toString(validBs[level].getIntegers()));
System.out.println(" " + (System.nanoTime() - startTime) / 1000000 / 1000 + " seconds");
printedB.set(validBs[level].cardinality());
}
earlyElimination(validProducts, validDeltas, maxElement, minALength, minBLength, as, candidateBs, validBs, level + 1,
resultsLeft, printedA, printedB, startTime);
if (resultsLeft.get() <= 0) {
break;
}
}
delta = level == 0 ? delta+1 : validDeltas.thisOrNext(delta+1);
if (delta == Integer.MAX_VALUE) {
break;
}
as[level] = previousIndex+delta;
}
as[level] = 0;
}
// Calculate deltas from 1 that has >= minBLength valids
private Bitmap getValidDeltas(Bitmap validProducts, int maxElement, int minBLength) {
final Bitmap validDeltas = new Bitmap(maxElement+1);
final Bitmap reuse = new Bitmap(validProducts.size());
for (int delta = 1 ; delta < maxElement ; delta++) {
validProducts.shift(-delta, reuse);
Bitmap.and(validProducts, reuse, reuse);
if (reuse.cardinality() >= minBLength) {
validDeltas.set(delta);
}
}
System.out.println("Calculated valid deltas: " + validDeltas.cardinality() + "/" + maxElement);
return validDeltas;
}
private void fixedA2(int maxElement, int minBLength) {
final int minALength = 2;
final Bitmap validProducts = generateValidProducts(maxElement*2);
final long[] as = new long[minALength];
final Bitmap validB1s = new Bitmap(validProducts.size());
final Bitmap candidateB2s = new Bitmap(validProducts.size());
final Bitmap validB2s = new Bitmap(validProducts.size());
int results = 0;
for (as[0] = 1 ; as[0] <= maxElement ; as[0]++) {
validProducts.shift((int) -as[0], validB1s);
for (as[1] = as[0]+1; as[1] <= maxElement; as[1]++) {
validProducts.shift((int) -as[1], candidateB2s);
Bitmap.and(validB1s, candidateB2s, validB2s);
if (validB2s.cardinality() < minBLength) {
continue;
}
System.out.println(toString(as) + " " + toString(validB2s.getIntegers()));
results++;
if (results >= 10) {
return;
}
}
}
}
// Simple brute
private void findGroups2(boolean[] validProducts) {
final int max = 200;
int[] A = new int[2];
int[] B = new int[2];
for (A[0] = 1 ; A[0] <= max ; A[0]++) {
for (A[1] = A[0]+1 ; A[1] <= max ; A[1]++) {
for (B[0] = 1; B[0] <= max; B[0]++) {
for (B[1] = B[0]+1 ; B[1] <= max; B[1]++) {
if (check(validProducts, A, B)) {
System.out.println(toString(A) + " " + toString(B));
}
}
}
}
}
}
// Simple brute
private void findGroups3(boolean[] validProducts) {
final int max = 200;
int[] A = new int[3];
int[] B = new int[3];
for (A[0] = 1 ; A[0] <= max ; A[0]++) {
System.out.print("\n/");
for (A[1] = A[0]+1 ; A[1] <= max ; A[1]++) {
System.out.print(".");
for (A[2] = A[1]+1 ; A[2] <= max ; A[2]++) {
for (B[0] = 1; B[0] <= max; B[0]++) {
for (B[1] = B[0]+1 ; B[1] <= max; B[1]++) {
for (B[2] = B[1]+1 ; B[2] <= max; B[2]++) {
if (check(validProducts, A, B)) {
System.out.println(toString(A) + " " + toString(B));
}
}
}
}
}
}
}
}
private String toString(Bitmap b) {
return toString(b.getIntegers());
}
private String toString(Bitmap as, Bitmap bs) {
return toString(as.getBacking()) + " " + toString(bs.getBacking());
}
private String toString(int[] ints) {
StringBuilder sb = new StringBuilder(ints.length*4);
sb.append("[");
for (int i: ints) {
if (sb.length() != 1) {
sb.append(", ");
}
sb.append(Integer.toString(i));
}
sb.append("]");
return sb.toString();
}
private String toString(long[] longs) {
StringBuilder sb = new StringBuilder(longs.length*4);
sb.append("[");
for (long l: longs) {
if (sb.length() != 1) {
sb.append(", ");
}
sb.append(Long.toString(l));
}
sb.append("]");
return sb.toString();
}
private boolean check(int[] validProducts, int[] A, int[] B) {
for (int ai = 0 ; ai < A.length ; ai++) {
for (int bi = 0 ; bi < B.length ; bi++) {
if (Arrays.binarySearch(validProducts, A[ai] + B[bi]) < 0) {
return false;
}
}
}
return true;
}
private boolean check(boolean[] validProducts, int[] A, int[] B) {
for (int ai = 0 ; ai < A.length ; ai++) {
for (int bi = 0 ; bi < B.length ; bi++) {
if (!validProducts[A[ai] + B[bi]]) {
return false;
}
}
}
return true;
}
private Bitmap toBitmap(int[] ints) {
Bitmap b = new Bitmap(ints[ints.length-1]+1);
Arrays.stream(ints).forEach(b::set);
return b;
}
private boolean[] toBool(int[] ints) {
boolean[] result = new boolean[ints[ints.length-1]+1];
for (int i: ints) {
result[i] = true;
}
return result;
}
private Bitmap generateValidProducts(final int maxValid) {
int primePairs = 0;
while (Math.pow(4, primePairs) < maxValid) { // 4 is smallest possible valid
primePairs++;
}
// All prime-pairs up to at most maxPrime^2
final Bitmap bResult = new Bitmap(maxValid+1);
final GrowableInts result = new GrowableInts(); // For efficient iteration
result.add(2*2); bResult.set(2*2);
for (int i = 3 ; i*i <= maxValid ; i+=2) {
if (isPrime(i)) {
int pow = i*i;
result.add(pow); bResult.set(pow);
}
}
for (int pp = 1; pp < primePairs ; pp++) {
final int prevPos = result.size();
for (int startPos = 0 ; startPos < prevPos ; startPos++) {
for (int multiplierPos = startPos ; multiplierPos < prevPos ; multiplierPos++) {
final long newValid = 1L*result.get(startPos)*result.get(multiplierPos);
if (newValid <= maxValid && !bResult.get((int) newValid)) {
result.add((int) newValid); bResult.set((int) newValid);
}
}
}
}
System.out.println("Valid prime pair sums up to maxValid: " + bResult.cardinality());
return bResult;
}
private class GrowableInts {
int[] ints = new int[100];
int pos = 0;
public void add(int v) {
if (pos == ints.length) {
int[] newInts = new int[ints.length*2];
System.arraycopy(ints, 0, newInts, 0, ints.length);
ints = newInts;
}
ints[pos++] = v;
}
public int get(int index) {
return ints[index];
}
public int size() {
return pos;
}
public int[] getInts() {
int[] result = new int[pos];
System.arraycopy(ints, 0, result, 0, pos);
return result;
}
}
private static int val2(int n) {
int m = 0;
if ((n&0xffff) == 0) {
n >>= 16;
m += 16;
}
if ((n&0xff) == 0) {
n >>= 8;
m += 8;
}
if ((n&0xf) == 0) {
n >>= 4;
m += 4;
}
if ((n&0x3) == 0) {
n >>= 2;
m += 2;
}
if (n > 1) {
m++;
}
return m;
}
// For convenience, handle modular exponentiation via BigInteger.
private static int modPow(int base, int exponent, int m) {
BigInteger bigB = BigInteger.valueOf(base);
BigInteger bigE = BigInteger.valueOf(exponent);
BigInteger bigM = BigInteger.valueOf(m);
BigInteger bigR = bigB.modPow(bigE, bigM);
return bigR.intValue();
}
// Basic implementation.
private static boolean isStrongProbablePrime(int n, int base) {
int s = val2(n-1);
int d = modPow(base, n>>s, n);
if (d == 1) {
return true;
}
for (int i=1; i < s; i++) {
if (d+1 == n) {
return true;
}
d = d*d % n;
}
return d+1 == n;
}
public static boolean isPrime(int n) {
if ((n&1) == 0) {
return n == 2;
}
if (n < 9) {
return n > 1;
}
return isStrongProbablePrime(n, 2) && isStrongProbablePrime(n, 7) && isStrongProbablePrime(n, 61);
}
} |
package graph;
import javafx.util.Pair;
import parser.GfaParser;
import parser.Tuple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Our own Graph Class.
* This class is the SequenceGraph.
* A Graph handling a Directed-Acyclic-Graph.
* This is our own data structure we will use to draw the eventual graph.
*/
public class SequenceGraph {
private HashMap<Integer, SequenceNode> nodes;
private ArrayList<Edge> edges;
private ArrayList<ArrayList<SequenceNode>> columns;
/**
* The constructor initializes the SequenceGraph with it's basic values.
*/
public SequenceGraph() {
this.nodes = new HashMap<Integer, SequenceNode>();
this.edges = new ArrayList<Edge>();
}
public int size() {
return nodes.size();
}
public void createSubGraph(int centerNodeID, int range, int[] parentArray, int[] childArray, int counter) {
int upperBoundID = childArray[counter-1];
int lowerBoundID = 1;
if(centerNodeID + range <= upperBoundID) {
upperBoundID = centerNodeID + range;
}
if(centerNodeID - range >= lowerBoundID) {
lowerBoundID = centerNodeID - range;
}
for(int i = lowerBoundID-1; i < counter; i++) {
int parentID = parentArray[i];
int childID = childArray[i];
if(parentID >= lowerBoundID && childID <= upperBoundID) {
SequenceNode parentNode = new SequenceNode(parentID);
parentNode.addChild(childID);
SequenceNode childNode = new SequenceNode(childID);
this.addNode(parentNode);
this.addNode(childNode);
Edge edge = new Edge(parentID, childID);
this.getEdges().add(edge);
}
}
initialize();
layerizeGraph(lowerBoundID);
}
/**
* Getter for the column list
* @return the column arraylist with an arraylist with nodes.
*/
public ArrayList<ArrayList<SequenceNode>> getColumns() {
return this.columns;
}
/**
* Returns all the edges contained in the graph.
* @return a arrayList of Edges containing all the edges of the graph.
*/
public ArrayList<Edge> getEdges() {
return this.edges;
}
public void setEdges(ArrayList<Edge> allEdges) {
this.edges = allEdges;
}
/**
* Add a node to the ArrayList of Nodes.
* @param node The node to be added.
*/
public void addNode(SequenceNode node) {
this.nodes.put(node.getId(), node);
}
/**
* Get a specific Node.
* @param id The Id of the Node to get.
* @return The Node with the given Id.
*/
public SequenceNode getNode(Integer id) {
return nodes.get(id);
}
/**
* Returns all nodes contained in the graph.
* @return A HashMap of all nodes and their IDs contained in the graph.
*/
public HashMap<Integer, SequenceNode> getNodes() {
return this.nodes;
}
public void setNodes(HashMap<Integer, SequenceNode> hash) {
this.nodes = hash;
}
/**
* Add a child to each Node.
*/
public void initialize() {
for (Edge edge : getEdges()) {
// aan elke parent de child toevoegen
this.getNode(edge.getParent()).addChild(edge.getChild());
}
}
/**
* Will add columns to all the nodes and to all the edges.
*/
public void layerizeGraph(int lowerBoundID) {
createColumns(lowerBoundID);
createEdgeColumns();
this.columns = createColumnList();
createIndex();
}
/**
* assigns indices to all nodes in the column list.
*/
private void createIndex() {
for (ArrayList<SequenceNode> column : columns) {
for (int j = 0; j < column.size(); j++) {
column.get(j).setIndex(j);
}
}
}
/**
* Gives each node a column where it should be built.
*/
private void createColumns(int lowerBoundID) {
for (int i = lowerBoundID; i <= nodes.size() + lowerBoundID - 1; i++) {
SequenceNode parent = nodes.get(i); // Start at first node
ArrayList<Integer> children = parent.getChildren(); // Get all children
for (Integer child : children) {
this.getNode(child).incrementColumn(parent.getColumn());
}
}
}
/**
* Gives each edge it's ghost nodes.
*/
private void createEdgeColumns() {
for (Edge edge : edges) {
int parColumn = nodes.get(edge.getParent()).getColumn();
int childColumn = nodes.get(edge.getChild()).getColumn();
edge.setEntireColumnSpan(parColumn, childColumn);
}
}
//TODO: rework placement of nodes and dummy nodes
/**
* Get the List of all Columns.
* @return The List of Columns.
*/
private ArrayList<ArrayList<SequenceNode>> createColumnList() {
ArrayList<ArrayList<SequenceNode>> columns = new ArrayList<ArrayList<SequenceNode>>();
for (Object o : nodes.entrySet()) {
Map.Entry pair = (Map.Entry) o;
SequenceNode node = (SequenceNode) pair.getValue();
while (columns.size() <= node.getColumn()) {
columns.add(new ArrayList<SequenceNode>());
}
columns.get(node.getColumn()).add(node);
//it.remove();
}
int counter = nodes.size()+1;
for (Edge edge : edges) {
for (int i : edge.getColumnSpan()) {
SequenceNode dummyNode = new SequenceNode(counter);
dummyNode.setDummy(true);
columns.get(i).add(0, dummyNode);
counter++;
}
}
return columns;
}
} |
package leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Problem354 {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes.length == 0) {
return 0;
}
Arrays.sort(envelopes, (a, b) -> {
int cmp = Integer.compare(a[0], b[0]);
if (cmp == 0) {
return Integer.compare(a[1], b[1]);
}
return cmp;
});
int max = 0;
Map<Integer, Integer> memo = new HashMap<>();
for (int i = 0; i < envelopes.length; i++) {
max = Math.max(max, maxEnvelops(envelopes, i, memo) + 1);
}
return max;
}
private static int maxEnvelops(int[][] envelops, int idx, Map<Integer, Integer> memo) {
if (idx >= envelops.length) {
return 0;
}
int max = 0;
if (memo.containsKey(idx)) {
return memo.get(idx);
}
for (int i = idx + 1; i < envelops.length; i++) {
if (envelops[idx][0] < envelops[i][0] && envelops[idx][1] < envelops[i][1]) {
max = Math.max(max, maxEnvelops(envelops, i, memo) + 1);
}
}
memo.put(idx, max);
return max;
}
public static void main(String[] args) {
Problem354 prob = new Problem354();
System.out.println(prob.maxEnvelopes(new int[][]{
{2, 3},
{6, 4},
{6, 7}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{5, 4},
{6, 4},
{6, 7},
{2, 3}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{2, 3},
{5, 10},
{6, 4},
{7, 8}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{2, 3},
{5, 10},
{6, 4},
{7, 8}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{2, 3},
{3, 10},
{4, 4},
{5, 6},
{9, 9}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{2, 3},
{4, 5},
{6, 7}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{46, 89},
{50, 53},
{52, 68},
{72, 45},
{77, 81}
}));
System.out.println(prob.maxEnvelopes(new int[][]{
{856, 533}, {583, 772}, {980, 524}, {203, 666}, {987, 151}, {274, 802}, {982, 85}, {359, 160}, {58, 823}, {512, 381}, {796, 655}, {341, 427}, {145, 114}, {76, 306}, {760, 929}, {836, 751}, {922, 678}, {128, 317}, {185, 953}, {115, 845}, {829, 991}, {93, 694}, {317, 434}, {818, 571}, {352, 638}, {926, 780}, {819, 995}, {54, 69}, {191, 392}, {377, 180}, {669, 952}, {588, 920}, {335, 316}, {48, 769}, {188, 661}, {916, 933}, {674, 308}, {356, 556}, {350, 249}, {686, 851}, {600, 178}, {849, 439}, {597, 181}, {80, 382}, {647, 105}, {4, 836}, {901, 907}, {595, 347}, {214, 335}, {956, 382}, {77, 979}, {489, 365}, {80, 220}, {859, 270}, {676, 665}, {636, 46}, {906, 457}, {522, 769}, {2, 758}, {206, 586}, {444, 904}, {912, 370}, {64, 871}, {59, 409}, {599, 238}, {437, 58}, {309, 767}, {258, 440}, {922, 369}, {848, 650}, {478, 76}, {84, 704}, {314, 207}, {138, 823}, {994, 764}, {604, 595}, {537, 876}, {877, 253}, {945, 185}, {623, 497}, {968, 633}, {172, 705}, {577, 388}, {819, 763}, {409, 905}, {275, 532}, {729, 593}, {547, 226}, {445, 495}, {398, 544}, {243, 500}, {308, 24}, {652, 452}, {93, 885}, {75, 884}, {243, 113}, {600, 555}, {756, 596}, {892, 762}, {402, 653}, {916, 975}, {770, 220}, {455, 579}, {889, 68}, {306, 899}, {567, 290}, {809, 653}, {92, 329}, {370, 861}, {632, 754}, {321, 689}, {190, 812}, {88, 701}, {79, 310}, {917, 91}, {751, 480}, {750, 39}, {781, 978}, {778, 912}, {946, 559}, {529, 621}, {55, 295}, {473, 748}, {646, 854}, {930, 913}, {116, 734}, {647, 812}, {426, 172}, {122, 14}, {522, 843}, {88, 308}, {719, 602}, {712, 928}, {303, 890}, {973, 886}, {276, 354}, {660, 720}, {708, 387}, {776, 605}, {653, 815}, {448, 285}, {549, 959}, {139, 365}, {74, 952}, {372, 424}, {642, 504}, {361, 901}, {620, 612}, {313, 301}, {397, 225}, {446, 716}, {17, 361}, {160, 812}, {171, 529}, {180, 482}, {454, 600}, {228, 872}, {204, 492}, {607, 889}, {86, 79}, {494, 78}, {442, 404}, {462, 127}, {935, 402}, {509, 649}, {458, 941}, {219, 444}, {306, 57}, {674, 617}, {79, 652}, {73, 735}, {900, 756}, {649, 294}, {982, 754}, {521, 439}, {356, 265}, {240, 533}, {865, 44}, {744, 379}, {97, 454}, {65, 480}, {544, 191}, {18, 191}, {503, 38}, {696, 658}, {61, 884}, {793, 984}, {383, 364}, {280, 467}, {888, 662}, {133, 643}, {365, 512}, {610, 975}, {98, 584}, {40, 177}, {548, 102}, {80, 98}, {986, 951}, {264, 258}, {583, 734}, {353, 322}, {427, 551}, {80, 660}, {273, 609}, {980, 871}, {739, 802}, {366, 836}, {55, 509}, {889, 720}, {857, 661}, {48, 489}, {119, 26}, {31, 180}, {472, 673}, {960, 951}, {383, 500}, {928, 351}, {848, 705}, {969, 766}, {311, 714}, {861, 230}, {34, 596}, {38, 642}, {1, 955}, {698, 846}, {784, 791}, {760, 344}, {677, 239}, {969, 191}, {539, 644}, {470, 418}, {289, 357}, {269, 446}, {668, 245}, {293, 719}, {937, 103}, {575, 297}, {874, 656}, {714, 257}, {934, 396}, {109, 904}, {89, 635}, {374, 545}, {316, 587}, {158, 121}, {901, 969}, {284, 564}, {666, 568}, {993, 409}, {370, 637}, {443, 694}, {576, 160}, {262, 357}, {590, 729}, {194, 976}, {743, 376}, {348, 80}, {669, 527}, {338, 953}, {236, 785}, {144, 460}, {438, 457}, {517, 951}, {545, 647}, {158, 556}, {905, 591}, {793, 609}, {571, 643}, {9, 850}, {581, 490}, {804, 394}, {635, 483}, {457, 30}, {42, 621}, {65, 137}, {424, 864}, {536, 455}, {59, 492}, {645, 734}, {892, 571}, {762, 593}, {608, 384}, {558, 257}, {692, 420}, {973, 203}, {531, 51}, {349, 861}, {804, 649}, {3, 611}, {6, 468}, {298, 568}, {651, 767}, {251, 142}, {173, 974}, {117, 728}, {326, 562}, {894, 288}, {814, 555}, {420, 771}, {20, 775}, {445, 247}, {243, 592}, {186, 173}, {101, 800}, {590, 876}, {515, 534}, {73, 540}, {333, 215}, {902, 394}, {640, 787}, {596, 298}, {984, 712}, {307, 378}, {540, 646}, {473, 743}, {340, 387}, {756, 217}, {139, 493}, {9, 742}, {195, 25}, {763, 823}, {451, 693}, {24, 298}, {645, 595}, {224, 770}, {976, 41}, {832, 78}, {599, 705}, {487, 734}, {818, 134}, {225, 431}, {380, 566}, {395, 680}, {294, 320}, {915, 201}, {553, 480}, {318, 42}, {627, 94}, {164, 959}, {92, 715}, {588, 689}, {734, 983}, {976, 334}, {846, 573}, {676, 521}, {449, 69}, {745, 810}, {961, 722}, {416, 409}, {135, 406}, {234, 357}, {873, 61}, {20, 521}, {525, 31}, {659, 688}, {424, 554}, {203, 315}, {16, 240}, {288, 273}, {281, 623}, {651, 659}, {939, 32}, {732, 373}, {778, 728}, {340, 432}, {335, 80}, {33, 835}, {835, 651}, {317, 156}, {284, 119}, {543, 159}, {719, 820}, {961, 424}, {88, 178}, {621, 146}, {594, 649}, {659, 433}, {527, 441}, {118, 160}, {92, 217}, {489, 38}, {18, 359}, {833, 136}, {470, 897}, {106, 123}, {831, 674}, {181, 191}, {892, 780}, {377, 779}, {608, 618}, {618, 423}, {180, 323}, {390, 803}, {562, 412}, {107, 905}, {902, 281}, {718, 540}, {16, 966}, {678, 455}, {597, 135}, {840, 7}, {886, 45}, {719, 937}, {890, 173}
}));
}
} |
/*
$Log$
Revision 1.13 1998/12/01 23:33:19 rimassa
Completely rewritten (again!) to use new Agent class API for DF
access. Now all DF actions are carried on by means of suitable Agent
class methods. This results in blocking interactions. Still missing
search constraints.
Revision 1.12 1998/11/30 00:12:23 rimassa
Almost completely rewritten; now it correctly supports a complete DF
interaction, search action included. Still missing some detail, such
as search constraints.
Revision 1.11 1998/11/23 00:11:58 rimassa
Fixed a little bug: an instance variable vas not reset after each
message received.
Revision 1.10 1998/11/18 22:56:49 Giovanni
Reading input from the standard input has been moved from setup()
method to an agent Behaviour. Besides, a suitable reset() method was
added to mainBehaviour, in order to make dfTester agent perform an
endless loop of requests to the DF, asking for different parameters
each time.
Revision 1.9 1998/10/18 17:33:53 rimassa
Added support for 'search' DF operation.
Revision 1.8 1998/10/18 16:10:39 rimassa
Some code changes to avoid deprecated APIs.
- Agent.parse() is now deprecated. Use ACLMessage.fromText(Reader r) instead.
- ACLMessage() constructor is now deprecated. Use ACLMessage(String type)
instead.
- ACLMessage.dump() is now deprecated. Use ACLMessage.toText(Writer w)
instead.
Revision 1.7 1998/10/11 19:09:17 rimassa
Removed old,commented out code.
Revision 1.6 1998/10/04 18:00:32 rimassa
Added a 'Log:' field to every source file.
*/
package examples.ex5;
// This agent allows a comprehensive testing of Directory Facilitator
// agent.
import java.io.*;
import java.util.Vector;
import jade.core.*;
import jade.lang.acl.*;
import jade.domain.SearchDFBehaviour;
import jade.domain.AgentManagementOntology;
import jade.domain.FIPAException;
public class dfTester extends Agent {
private AgentManagementOntology.DFSearchResult searchResult;
protected void setup() {
ComplexBehaviour mainBehaviour = new SequentialBehaviour(this) {
protected void postAction() {
reset();
}
};
mainBehaviour.addBehaviour(new OneShotBehaviour(this) {
public void action() {
int len = 0;
byte[] buffer = new byte[1024];
try {
System.out.println("Enter DF agent action to perform: (register, deregister, modify, search) ");
len = System.in.read(buffer);
AgentManagementOntology.DFAgentDescriptor dfd = new AgentManagementOntology.DFAgentDescriptor();
String actionName = new String(buffer,0,len-1);
System.out.println("Enter values for parameters (ENTER leaves them blank)");
String name = null;
String address = null;
System.out.print(":agent-name (e.g. Peter; mandatory for 'register') ");
len = System.in.read(buffer);
if(len > 1)
name = new String(buffer,0,len-1);
System.out.println(":agent-address (e.g. iiop://fipa.org:50/acc)");
System.out.print(" (mandatory for 'register') ");
len = System.in.read(buffer);
if(len > 1)
address = new String(buffer,0,len-1);
if(address != null) {
if(name != null)
dfd.setName(name + "@" + address);
dfd.addAddress(address);
}
System.out.print(":agent-type (mandatory for 'register') ");
len = System.in.read(buffer);
if(len > 1)
dfd.setType(new String(buffer,0,len-1));
System.out.println(":interaction-protocols ");
System.out.print(" protocol name (ENTER to end) ");
len = System.in.read(buffer);
while(len > 1) {
dfd.addInteractionProtocol(new String(buffer,0,len-1));
System.out.print(" protocol name (ENTER to end) ");
len = System.in.read(buffer);
}
System.out.print(":ontology ");
len = System.in.read(buffer);
if(len > 1)
dfd.setOntology(new String(buffer,0,len-1));
System.out.print(":ownership (mandatory for 'register') ");
len = System.in.read(buffer);
if(len > 1)
dfd.setOwnership(new String(buffer,0,len-1));
System.out.print(":df-state (active, suspended, retired; mandatory for 'register') ");
len = System.in.read(buffer);
if(len > 1)
dfd.setDFState(new String(buffer,0,len-1));
System.out.println(":agent-services ");
System.out.println(":service-description (leave name blank to end)");
System.out.print(" :service-name ");
len = System.in.read(buffer);
while(len > 1) {
AgentManagementOntology.ServiceDescriptor sd = new AgentManagementOntology.ServiceDescriptor();
sd.setName(new String(buffer,0,len-1));
System.out.print(" :service-type ");
len = System.in.read(buffer);
if(len > 1)
sd.setType(new String(buffer,0,len-1));
System.out.print(" :service-ontology ");
len = System.in.read(buffer);
if(len > 1)
sd.setOntology(new String(buffer,0,len-1));
System.out.print(" :fixed-properties ");
len = System.in.read(buffer);
if(len > 1)
sd.setFixedProps(new String(buffer,0,len-1));
System.out.print(" :negotiable-properties ");
len = System.in.read(buffer);
if(len > 1)
sd.setNegotiableProps(new String(buffer,0,len-1));
System.out.print(" :communication-properties ");
len = System.in.read(buffer);
if(len > 1)
sd.setCommunicationProps(new String(buffer,0,len-1));
dfd.addAgentService(sd);
System.out.println(":service-description (leave name blank to end)");
System.out.print(" :service-name ");
len = System.in.read(buffer);
}
System.out.println("");
if(actionName.equalsIgnoreCase("search")) {
AgentManagementOntology.DFSearchResult agents = null;
System.out.println("Calling searchDF()");
try {
agents = searchDF("df", dfd, null);
}
catch(FIPAException fe) {
System.out.println("Caught a FIPA exception: " + fe.getMessage());
}
try {
Writer w = new BufferedWriter(new OutputStreamWriter(System.out));
agents.toText(w);
System.out.println("");
}
catch(FIPAException fe) {
System.out.println("Caught a FIPA exception: " + fe.getMessage());
}
}
else if(actionName.equalsIgnoreCase("register")) {
System.out.println("Calling registerWithDF()");
try {
registerWithDF("df", dfd);
}
catch(FIPAException fe) {
System.out.println("Caught a FIPA exception: " + fe.getMessage());
}
}
else if(actionName.equalsIgnoreCase("deregister")) {
System.out.println("Calling deregisterWithDF()");
try {
deregisterWithDF("df", dfd);
}
catch(FIPAException fe) {
System.out.println("Caught a FIPA exception: " + fe.getMessage());
}
}
else if(actionName.equalsIgnoreCase("modify")) {
System.out.println("Calling modifyDFData()");
try {
modifyDFData("df", dfd);
}
catch(FIPAException fe) {
System.out.println("Caught a FIPA exception: " + fe.getMessage());
}
}
else {
System.out.println("Invalid action name.");
}
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
});
addBehaviour(mainBehaviour);
} // End of setup()
} |
package leetcode;
public class Problem430 {
private static class Node {
public int val;
public Node prev;
public Node next;
public Node child;
public Node() {
}
public Node(int _val, Node _prev, Node _next, Node _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
}
public Node flatten(Node head) {
for (Node n = head; n != null; n = n.next) {
if (n.child != null) {
Node tmp = n.next;
n.next = n.child;
Node cn = n.child;
while (cn.next != null) {
cn = cn.next;
}
cn.next = tmp;
}
}
return head;
}
private static void print(Node head) {
for (Node n = head; n != null; n = n.next) {
System.out.print(n.val + ' ');
}
System.out.println();
}
public static void main(String[] args) {
Problem430 prob = new Problem430();
}
} |
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Problem506 {
public String[] findRelativeRanks(int[] nums) {
int[] copy = Arrays.copyOf(nums, nums.length);
List<Integer> list = new ArrayList<>();
for (int i = 0; i < copy.length; i++) {
list.add(copy[i]);
}
Collections.sort(list, (a, b) -> Integer.compare(b, a));
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i), i + 1);
}
String[] result = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
int position = map.get(nums[i]);
if (position == 1) {
result[i] = "Gold Medal";
} else if (position == 2) {
result[i] = "Silver Medal";
} else if (position == 3) {
result[i] = "Bronze Medal";
} else {
result[i] = Integer.toString(position);
}
}
return result;
}
} |
package liquidrods;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A parsed template that can be rendered using {@link Template#render(Object, java.io.Writer)}
*/
public class Template {
private List<LiquidrodsNode> rootNodes;
private Config config;
/**
* Creates a template. You shouldn't be using this most of the time, but rather {@link Liquidrods#parse(java.io.Reader)} or {@link Liquidrods#parse(String)} to create a template.
*
* @param rootNodes the top level nodes of the template
* @param config the liquidrods instance to be used with this template.
*/
public Template(List<LiquidrodsNode> rootNodes, Config config) {
this.rootNodes = rootNodes;
this.config = config;
processIncludes();
processExtends();
}
private void processIncludes() {
List<LiquidrodsNode> mergedNodes = new ArrayList<LiquidrodsNode>(rootNodes.size());
for (LiquidrodsNode node : rootNodes) {
if (node instanceof LiquidrodsNode.Block) {
LiquidrodsNode.Block block = (LiquidrodsNode.Block) node;
if ("include".equals(block.getName())) {
final Template included = Liquidrods.parse(block.getArg(), config);
mergedNodes.addAll(included.getRootNodes());
} else {
mergedNodes.add(block);
}
} else {
mergedNodes.add(node);
}
}
this.rootNodes = mergedNodes;
}
private void processExtends() {
String parentTemplate = null;
boolean nonText = false;
Map<String, LiquidrodsNode.Block> blocks = new HashMap<String, LiquidrodsNode.Block>();
for (LiquidrodsNode node : rootNodes) {
if (node instanceof LiquidrodsNode.Variable) {
nonText = true;
if (parentTemplate != null) {
throw new RuntimeException("Invalid template: it extends another template yet it defines a top level variable (should be in a block tag)" + node);
}
} else if (node instanceof LiquidrodsNode.Block) {
LiquidrodsNode.Block block = (LiquidrodsNode.Block) node;
if ("extends".equals(block.getName())) {
if (parentTemplate != null) {
throw new RuntimeException("Invalid template: multiple extends directives: found " + node + " while and extend with" + parentTemplate + " was already defined");
} else if (nonText) {
throw new RuntimeException("Invalid template: it extends another template yet it defines a top level variable or block");
} else {
parentTemplate = block.getArg();
}
} else if ("block".equals(block.getName())) {
blocks.put(block.getArg(), block);
} else {
nonText = true;
if (parentTemplate != null) {
throw new RuntimeException("Invalid template: it extends another template yet it defines a top level block " + node);
}
}
}
}
if (parentTemplate != null) {
Template parent = Liquidrods.parse(parentTemplate, config);
List<LiquidrodsNode> mergedNodes = new ArrayList<LiquidrodsNode>(parent.rootNodes.size());
for (LiquidrodsNode node : parent.rootNodes) {
if (node instanceof LiquidrodsNode.Block) {
final LiquidrodsNode.Block block = (LiquidrodsNode.Block) node;
if ("block".equals(block.getName())) {
LiquidrodsNode.Block toInsert = blocks.get(block.getArg());
if (toInsert != null) {
mergedNodes.add(toInsert);
} else {
mergedNodes.add(block);
}
} else {
mergedNodes.add(block);
}
} else {
mergedNodes.add(node);
}
}
this.rootNodes = mergedNodes;
}
}
public List<LiquidrodsNode> getRootNodes() {
return rootNodes;
}
/**
* Render this template using the specified model into the specified writer
*
* @param model the model object to resolve properties against
* @param out where to write the result
*/
public void render(Object model, Writer out) {
Context context = new Context(null, model);
try {
for (LiquidrodsNode node : rootNodes) {
config.defaultRenderer().render(node, context, config, out);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return "Template " + rootNodes;
}
} |
package me.pagar.model;
import com.google.gson.JsonObject;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import me.pagar.util.JSONUtils;
import org.joda.time.DateTime;
import javax.ws.rs.HttpMethod;
public class Card extends PagarMeModel<String> {
@Expose(deserialize = false)
@SerializedName("card_hash")
private String hash;
@Expose(serialize = false)
private Brand brand;
@Expose
@SerializedName("holder_name")
private String holderName;
@Expose(deserialize = false)
@SerializedName("card_number")
private String number;
@Expose(serialize = false)
@SerializedName("first_digits")
private String firstDigits;
@Expose(serialize = false)
@SerializedName("last_digits")
private String lastDigits;
@Expose(serialize = false)
private String fingerprint;
@Expose(serialize = false)
private String country;
@Expose(deserialize = false)
@SerializedName("customer_id")
private Integer customerId;
@Expose(serialize = false)
private Boolean valid;
@Expose
@SerializedName("expiration_date")
private String expiresAt;
@Expose(serialize = false)
@SerializedName("date_updated")
private DateTime updatedAt;
@Expose(serialize = false)
@SerializedName("cvv")
private Integer cvv;
@Expose(serialize = false)
private Customer customer;
public Brand getBrand() {
return brand;
}
public String getHolderName() {
return holderName;
}
public String getFirstDigits() {
return firstDigits;
}
public String getLastDigits() {
return lastDigits;
}
public Integer getCvv() {
return cvv;
}
public void setCvv(Integer cvv) {
this.cvv = cvv;
}
public String getFingerprint() {
return fingerprint;
}
public String getCountry() {
return country;
}
public Boolean getValid() {
return valid;
}
public DateTime getUpdatedAt() {
return updatedAt;
}
public Customer getCustomer() {
return customer;
}
public String getExpiresAt(){
return expiresAt;
}
public String getNumber(){
return number;
}
public void setHash(String hash) {
this.hash = hash;
addUnsavedProperty("hash");
}
public void setHolderName(String holderName) {
this.holderName = holderName;
addUnsavedProperty("holderName");
}
public void setNumber(String number) {
this.number = number;
addUnsavedProperty("number");
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
addUnsavedProperty("customerId");
}
public void setExpiresAt(String expiresAt) {
this.expiresAt = expiresAt;
addUnsavedProperty("expiresAt");
}
public Card save() throws PagarMeException {
final Card saved = super.save(getClass());
copy(saved);
return saved;
}
public Card find(String id) throws PagarMeException {
final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET,
String.format("/%s/%s", getClassName(), id));
final Card other = JSONUtils.getAsObject((JsonObject) request.execute(), Card.class);
copy(other);
flush();
return other;
}
public Card refresh() throws PagarMeException {
final Card other = JSONUtils.getAsObject(refreshModel(), Card.class);
copy(other);
flush();
return other;
}
private void copy(Card other) {
super.copy(other);
this.updatedAt = other.updatedAt;
this.brand = other.brand;
this.holderName = other.holderName;
this.firstDigits = other.firstDigits;
this.lastDigits = other.lastDigits;
this.fingerprint = other.fingerprint;
this.country = other.country;
this.valid = other.valid;
this.expiresAt = other.expiresAt;
}
public enum Brand {
@SerializedName("amex")
AMEX,
@SerializedName("aura")
AURA,
@SerializedName("discover")
DISCOVER,
@SerializedName("diners")
DINERS,
@SerializedName("elo")
ELO,
@SerializedName("hipercard")
HIPERCARD,
@SerializedName("jcb")
JCB,
@SerializedName("visa")
VISA,
@SerializedName("mastercard")
MASTERCARD
}
} |
package org.dockfx;
import java.util.Stack;
import com.sun.javafx.css.StyleManager;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.css.PseudoClass;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Popup;
import javafx.util.Duration;
/**
* Base class for a dock pane that provides the layout of the dock nodes. Stacking the dock nodes to
* the center in a TabPane will be added in a future release. For now the DockPane uses the relative
* sizes of the dock nodes and lays them out in a tree of SplitPanes.
*
* @since DockFX 0.1
*/
public class DockPane extends StackPane implements EventHandler<DockEvent> {
/**
* The current root node of this dock pane's layout.
*/
private Node root;
/**
* Whether a DOCK_ENTER event has been received by this dock pane since the last DOCK_EXIT event
* was received.
*/
private boolean receivedEnter = false;
/**
* The current node in this dock pane that we may be dragging over.
*/
private Node dockNodeDrag;
/**
* The docking area of the current dock indicator button if any is selected. This is either the
* root or equal to dock node drag.
*/
private Node dockAreaDrag;
/**
* The docking position of the current dock indicator button if any is selected.
*/
private DockPos dockPosDrag;
/**
* The docking area shape with a dotted animated border on the indicator overlay popup.
*/
private Rectangle dockAreaIndicator;
/**
* The timeline used to animate the borer of the docking area indicator shape. Because JavaFX has
* no CSS styling for timelines/animations yet we will make this private and offer an accessor for
* the user to programmatically modify the animation or disable it.
*/
private Timeline dockAreaStrokeTimeline;
/**
* The popup used to display the root dock indicator buttons and the docking area indicator.
*/
private Popup dockIndicatorOverlay;
/**
* The grid pane used to lay out the local dock indicator buttons. This is the grid used to lay
* out the buttons in the circular indicator.
*/
private GridPane dockPosIndicator;
/**
* The popup used to display the local dock indicator buttons. This allows these indicator buttons
* to be displayed outside the window of this dock pane.
*/
private Popup dockIndicatorPopup;
/**
* Base class for a dock indicator button that allows it to be displayed during a dock event and
* continue to receive input.
*
* @since DockFX 0.1
*/
public class DockPosButton extends Button {
/**
* Whether this dock indicator button is used for docking a node relative to the root of the
* dock pane.
*/
private boolean dockRoot = true;
/**
* The docking position indicated by this button.
*/
private DockPos dockPos = DockPos.CENTER;
/**
* Creates a new dock indicator button.
*/
public DockPosButton(boolean dockRoot, DockPos dockPos) {
super();
this.dockRoot = dockRoot;
this.dockPos = dockPos;
}
/**
* Whether this dock indicator button is used for docking a node relative to the root of the
* dock pane.
*
* @param dockRoot Whether this indicator button is used for docking a node relative to the root
* of the dock pane.
*/
public final void setDockRoot(boolean dockRoot) {
this.dockRoot = dockRoot;
}
/**
* The docking position indicated by this button.
*
* @param dockPos The docking position indicated by this button.
*/
public final void setDockPos(DockPos dockPos) {
this.dockPos = dockPos;
}
/**
* The docking position indicated by this button.
*
* @return The docking position indicated by this button.
*/
public final DockPos getDockPos() {
return dockPos;
}
/**
* Whether this dock indicator button is used for docking a node relative to the root of the
* dock pane.
*
* @return Whether this indicator button is used for docking a node relative to the root of the
* dock pane.
*/
public final boolean isDockRoot() {
return dockRoot;
}
}
/**
* A collection used to manage the indicator buttons and automate hit detection during DOCK_OVER
* events.
*/
private ObservableList<DockPosButton> dockPosButtons;
/**
* Creates a new DockPane adding event handlers for dock events and creating the indicator
* overlays.
*/
public DockPane() {
super();
this.addEventHandler(DockEvent.ANY, this);
this.addEventFilter(DockEvent.ANY, new EventHandler<DockEvent>() {
@Override
public void handle(DockEvent event) {
if (event.getEventType() == DockEvent.DOCK_ENTER) {
DockPane.this.receivedEnter = true;
} else if (event.getEventType() == DockEvent.DOCK_OVER) {
DockPane.this.dockNodeDrag = null;
}
}
});
dockIndicatorPopup = new Popup();
dockIndicatorPopup.setAutoFix(false);
dockIndicatorOverlay = new Popup();
dockIndicatorOverlay.setAutoFix(false);
StackPane dockRootPane = new StackPane();
dockRootPane.prefWidthProperty().bind(this.widthProperty());
dockRootPane.prefHeightProperty().bind(this.heightProperty());
dockAreaIndicator = new Rectangle();
dockAreaIndicator.setManaged(false);
dockAreaIndicator.setMouseTransparent(true);
dockAreaStrokeTimeline = new Timeline();
dockAreaStrokeTimeline.setCycleCount(Timeline.INDEFINITE);
// 12 is the cumulative offset of the stroke dash array in the Default.css style sheet
// RFE filed for CSS styled timelines/animations:
KeyValue kv = new KeyValue(dockAreaIndicator.strokeDashOffsetProperty(), 12);
KeyFrame kf = new KeyFrame(Duration.millis(500), kv);
dockAreaStrokeTimeline.getKeyFrames().add(kf);
dockAreaStrokeTimeline.play();
DockPosButton dockCenter = new DockPosButton(false, DockPos.CENTER);
dockCenter.getStyleClass().add("dock-center");
DockPosButton dockTop = new DockPosButton(false, DockPos.TOP);
dockTop.getStyleClass().add("dock-top");
DockPosButton dockRight = new DockPosButton(false, DockPos.RIGHT);
dockRight.getStyleClass().add("dock-right");
DockPosButton dockBottom = new DockPosButton(false, DockPos.BOTTOM);
dockBottom.getStyleClass().add("dock-bottom");
DockPosButton dockLeft = new DockPosButton(false, DockPos.LEFT);
dockLeft.getStyleClass().add("dock-left");
DockPosButton dockTopRoot = new DockPosButton(true, DockPos.TOP);
StackPane.setAlignment(dockTopRoot, Pos.TOP_CENTER);
dockTopRoot.getStyleClass().add("dock-top-root");
DockPosButton dockRightRoot = new DockPosButton(true, DockPos.RIGHT);
StackPane.setAlignment(dockRightRoot, Pos.CENTER_RIGHT);
dockRightRoot.getStyleClass().add("dock-right-root");
DockPosButton dockBottomRoot = new DockPosButton(true, DockPos.BOTTOM);
StackPane.setAlignment(dockBottomRoot, Pos.BOTTOM_CENTER);
dockBottomRoot.getStyleClass().add("dock-bottom-root");
DockPosButton dockLeftRoot = new DockPosButton(true, DockPos.LEFT);
StackPane.setAlignment(dockLeftRoot, Pos.CENTER_LEFT);
dockLeftRoot.getStyleClass().add("dock-left-root");
// TODO: dockCenter goes first when tabs are added in a future version
dockPosButtons = FXCollections.observableArrayList(dockTop, dockRight, dockBottom, dockLeft,
dockTopRoot, dockRightRoot, dockBottomRoot, dockLeftRoot);
dockPosIndicator = new GridPane();
dockPosIndicator.add(dockTop, 1, 0);
dockPosIndicator.add(dockRight, 2, 1);
dockPosIndicator.add(dockBottom, 1, 2);
dockPosIndicator.add(dockLeft, 0, 1);
// dockPosIndicator.add(dockCenter, 1, 1);
dockRootPane.getChildren().addAll(dockAreaIndicator, dockTopRoot, dockRightRoot, dockBottomRoot,
dockLeftRoot);
dockIndicatorOverlay.getContent().add(dockRootPane);
dockIndicatorPopup.getContent().addAll(dockPosIndicator);
this.getStyleClass().add("dock-pane");
dockRootPane.getStyleClass().add("dock-root-pane");
dockPosIndicator.getStyleClass().add("dock-pos-indicator");
dockAreaIndicator.getStyleClass().add("dock-area-indicator");
}
/**
* The Timeline used to animate the docking area indicator in the dock indicator overlay for this
* dock pane.
*
* @return The Timeline used to animate the docking area indicator in the dock indicator overlay
* for this dock pane.
*/
public final Timeline getDockAreaStrokeTimeline() {
return dockAreaStrokeTimeline;
}
/**
* Helper function to retrieve the URL of the default style sheet used by DockFX.
*
* @return The URL of the default style sheet used by DockFX.
*/
public final static String getDefaultUserAgentStyleheet() {
return DockPane.class.getResource("Default.css").toExternalForm();
}
/**
* Helper function to add the default style sheet of DockFX to the user agent style sheets.
*/
public final static void initializeDefaultUserAgentStylesheet() {
StyleManager.getInstance()
.addUserAgentStylesheet(DockPane.class.getResource("Default.css").toExternalForm());
}
/**
* A cache of all dock node event handlers that we have created for tracking the current docking
* area.
*/
private ObservableMap<Node, DockNodeEventHandler> dockNodeEventFilters =
FXCollections.observableHashMap();
/**
* A wrapper to the type parameterized generic EventHandler that allows us to remove it from its
* listener when the dock node becomes detached. It is specifically used to monitor which dock
* node in this dock pane's layout we are currently dragging over.
*
* @since DockFX 0.1
*/
private class DockNodeEventHandler implements EventHandler<DockEvent> {
/**
* The node associated with this event handler that reports to the encapsulating dock pane.
*/
private Node node = null;
/**
* Creates a default dock node event handler that will help this dock pane track the current
* docking area.
*
* @param node The node that is to listen for docking events and report to the encapsulating
* docking pane.
*/
public DockNodeEventHandler(Node node) {
this.node = node;
}
@Override
public void handle(DockEvent event) {
DockPane.this.dockNodeDrag = node;
}
}
/**
* Dock the node into this dock pane at the given docking position relative to the sibling in the
* layout. This is used to relatively position the dock nodes to other nodes given their preferred
* size.
*
* @param node The node that is to be docked into this dock pane.
* @param dockPos The docking position of the node relative to the sibling.
* @param sibling The sibling of this node in the layout.
*/
public void dock(Node node, DockPos dockPos, Node sibling) {
DockNodeEventHandler dockNodeEventHandler = new DockNodeEventHandler(node);
dockNodeEventFilters.put(node, dockNodeEventHandler);
node.addEventFilter(DockEvent.DOCK_OVER, dockNodeEventHandler);
SplitPane split = (SplitPane) root;
if (split == null) {
split = new SplitPane();
split.getItems().add(node);
root = split;
this.getChildren().add(root);
return;
}
// find the parent of the sibling
if (sibling != null && sibling != root) {
Stack<Parent> stack = new Stack<Parent>();
stack.push((Parent) root);
while (!stack.isEmpty()) {
Parent parent = stack.pop();
ObservableList<Node> children = parent.getChildrenUnmodifiable();
if (parent instanceof SplitPane) {
SplitPane splitPane = (SplitPane) parent;
children = splitPane.getItems();
}
for (int i = 0; i < children.size(); i++) {
if (children.get(i) == sibling) {
split = (SplitPane) parent;
} else if (children.get(i) instanceof Parent) {
stack.push((Parent) children.get(i));
}
}
}
}
Orientation requestedOrientation = (dockPos == DockPos.LEFT || dockPos == DockPos.RIGHT)
? Orientation.HORIZONTAL : Orientation.VERTICAL;
// if the orientation is different then reparent the split pane
if (split.getOrientation() != requestedOrientation) {
if (split.getItems().size() > 1) {
SplitPane splitPane = new SplitPane();
if (split == root && sibling == root) {
this.getChildren().set(this.getChildren().indexOf(root), splitPane);
splitPane.getItems().add(split);
root = splitPane;
} else {
split.getItems().set(split.getItems().indexOf(sibling), splitPane);
splitPane.getItems().add(sibling);
}
split = splitPane;
}
split.setOrientation(requestedOrientation);
}
// finally dock the node to the correct split pane
ObservableList<Node> splitItems = split.getItems();
double magnitude = 0;
if (splitItems.size() > 0) {
if (split.getOrientation() == Orientation.HORIZONTAL) {
for (Node splitItem : splitItems) {
magnitude += splitItem.prefWidth(0);
}
} else {
for (Node splitItem : splitItems) {
magnitude += splitItem.prefHeight(0);
}
}
}
if (dockPos == DockPos.LEFT || dockPos == DockPos.TOP) {
int relativeIndex = 0;
if (sibling != null && sibling != root) {
relativeIndex = splitItems.indexOf(sibling);
}
splitItems.add(relativeIndex, node);
if (splitItems.size() > 1) {
if (split.getOrientation() == Orientation.HORIZONTAL) {
split.setDividerPosition(relativeIndex,
node.prefWidth(0) / (magnitude + node.prefWidth(0)));
} else {
split.setDividerPosition(relativeIndex,
node.prefHeight(0) / (magnitude + node.prefHeight(0)));
}
}
} else if (dockPos == DockPos.RIGHT || dockPos == DockPos.BOTTOM) {
int relativeIndex = splitItems.size();
if (sibling != null && sibling != root) {
relativeIndex = splitItems.indexOf(sibling) + 1;
}
splitItems.add(relativeIndex, node);
if (splitItems.size() > 1) {
if (split.getOrientation() == Orientation.HORIZONTAL) {
split.setDividerPosition(relativeIndex - 1,
1 - node.prefWidth(0) / (magnitude + node.prefWidth(0)));
} else {
split.setDividerPosition(relativeIndex - 1,
1 - node.prefHeight(0) / (magnitude + node.prefHeight(0)));
}
}
}
}
/**
* Dock the node into this dock pane at the given docking position relative to the root in the
* layout. This is used to relatively position the dock nodes to other nodes given their preferred
* size.
*
* @param node The node that is to be docked into this dock pane.
* @param dockPos The docking position of the node relative to the sibling.
*/
public void dock(Node node, DockPos dockPos) {
dock(node, dockPos, root);
}
/**
* Detach the node from this dock pane removing it from the layout.
*
* @param node The node that is to be removed from this dock pane.
*/
public void undock(DockNode node) {
DockNodeEventHandler dockNodeEventHandler = dockNodeEventFilters.get(node);
node.removeEventFilter(DockEvent.DOCK_OVER, dockNodeEventHandler);
dockNodeEventFilters.remove(node);
// depth first search to find the parent of the node
Stack<Parent> findStack = new Stack<Parent>();
findStack.push((Parent) root);
while (!findStack.isEmpty()) {
Parent parent = findStack.pop();
ObservableList<Node> children = parent.getChildrenUnmodifiable();
if (parent instanceof SplitPane) {
SplitPane split = (SplitPane) parent;
children = split.getItems();
}
for (int i = 0; i < children.size(); i++) {
if (children.get(i) == node) {
children.remove(i);
// start from the root again and remove any SplitPane's with no children in them
Stack<Parent> clearStack = new Stack<Parent>();
clearStack.push((Parent) root);
while (!clearStack.isEmpty()) {
parent = clearStack.pop();
children = parent.getChildrenUnmodifiable();
if (parent instanceof SplitPane) {
SplitPane split = (SplitPane) parent;
children = split.getItems();
}
for (i = 0; i < children.size(); i++) {
if (children.get(i) instanceof SplitPane) {
SplitPane split = (SplitPane) children.get(i);
if (split.getItems().size() < 1) {
children.remove(i);
continue;
} else {
clearStack.push(split);
}
}
}
}
return;
} else if (children.get(i) instanceof Parent) {
findStack.push((Parent) children.get(i));
}
}
}
}
@Override
public void handle(DockEvent event) {
if (event.getEventType() == DockEvent.DOCK_ENTER) {
if (!dockIndicatorOverlay.isShowing()) {
Point2D topLeft = DockPane.this.localToScreen(0, 0);
dockIndicatorOverlay.show(DockPane.this, topLeft.getX(), topLeft.getY());
}
} else if (event.getEventType() == DockEvent.DOCK_OVER) {
this.receivedEnter = false;
dockPosDrag = null;
dockAreaDrag = dockNodeDrag;
for (DockPosButton dockIndicatorButton : dockPosButtons) {
if (dockIndicatorButton
.contains(dockIndicatorButton.screenToLocal(event.getScreenX(), event.getScreenY()))) {
dockPosDrag = dockIndicatorButton.getDockPos();
if (dockIndicatorButton.isDockRoot()) {
dockAreaDrag = root;
}
dockIndicatorButton.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), true);
break;
} else {
dockIndicatorButton.pseudoClassStateChanged(PseudoClass.getPseudoClass("focused"), false);
}
}
if (dockPosDrag != null) {
Point2D originToScene = dockAreaDrag.localToScene(0, 0);
dockAreaIndicator.setVisible(true);
dockAreaIndicator.relocate(originToScene.getX(), originToScene.getY());
if (dockPosDrag == DockPos.RIGHT) {
dockAreaIndicator.setTranslateX(dockAreaDrag.getLayoutBounds().getWidth() / 2);
} else {
dockAreaIndicator.setTranslateX(0);
}
if (dockPosDrag == DockPos.BOTTOM) {
dockAreaIndicator.setTranslateY(dockAreaDrag.getLayoutBounds().getHeight() / 2);
} else {
dockAreaIndicator.setTranslateY(0);
}
if (dockPosDrag == DockPos.LEFT || dockPosDrag == DockPos.RIGHT) {
dockAreaIndicator.setWidth(dockAreaDrag.getLayoutBounds().getWidth() / 2);
} else {
dockAreaIndicator.setWidth(dockAreaDrag.getLayoutBounds().getWidth());
}
if (dockPosDrag == DockPos.TOP || dockPosDrag == DockPos.BOTTOM) {
dockAreaIndicator.setHeight(dockAreaDrag.getLayoutBounds().getHeight() / 2);
} else {
dockAreaIndicator.setHeight(dockAreaDrag.getLayoutBounds().getHeight());
}
} else {
dockAreaIndicator.setVisible(false);
}
if (dockNodeDrag != null) {
Point2D originToScreen = dockNodeDrag.localToScreen(0, 0);
double posX = originToScreen.getX() + dockNodeDrag.getLayoutBounds().getWidth() / 2
- dockPosIndicator.getWidth() / 2;
double posY = originToScreen.getY() + dockNodeDrag.getLayoutBounds().getHeight() / 2
- dockPosIndicator.getHeight() / 2;
if (!dockIndicatorPopup.isShowing()) {
dockIndicatorPopup.show(DockPane.this, posX, posY);
} else {
dockIndicatorPopup.setX(posX);
dockIndicatorPopup.setY(posY);
}
// set visible after moving the popup
dockPosIndicator.setVisible(true);
} else {
dockPosIndicator.setVisible(false);
}
}
if (event.getEventType() == DockEvent.DOCK_RELEASED && event.getContents() != null) {
if (dockPosDrag != null && dockIndicatorOverlay.isShowing()) {
DockNode dockNode = (DockNode) event.getContents();
dockNode.dock(this, dockPosDrag, dockAreaDrag);
}
}
if ((event.getEventType() == DockEvent.DOCK_EXIT && !this.receivedEnter)
|| event.getEventType() == DockEvent.DOCK_RELEASED) {
if (dockIndicatorPopup.isShowing()) {
dockIndicatorOverlay.hide();
dockIndicatorPopup.hide();
}
}
}
} |
package org.jsync.sync;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
import lombok.Getter;
import lombok.val;
/**
* The Sync class contains a T class instance that changes if the linked file
* changes. If that happens, the class is recompiled.
*/
public class Sync<T> {
/**
* The full name of the class, with the package. The package contains
* dots(.) and the class and package are united by a dot(.) as well.
*/
@Getter
private final String className;
/**
* An instance of file for the class given by the class name. It has .java
* at the end and is located at the source folder.
*/
private final File classFile;
/**
* The source folder of the class. This is relative to the root project.
*/
@Getter
private final String folderSourceName;
/**
* The destination folder of the class. This is relative to the root
* project.
*/
@Getter
private final String folderDestinationName;
/**
* Options from the Eclipse Java Core Compiler Package
*/
public static String options = "";
/**
* The date the file containing the class was last compiled.
*/
@Getter
private long lastCompiled;
/**
* The output from the compile of the source file.
*/
@Getter
private String compileOutput = "";
/**
* The error from the compile of the source file.
*/
@Getter
private String compileError = "";
private URLClassLoader urlClassLoader;
private final ClassLoader classLoader;
/**
* Construct a new Sync object for the specified className.
*
* @param classLoader
* The class loader this will inherit from
* @param className
* The full name of the class to be loaded
* @param folderSourceName
* The source folder name
* @param folderDestinationName
* The destination folder name
*/
public Sync(ClassLoader classLoader, String className, String folderSourceName, String folderDestinationName) {
if (!(folderDestinationName.endsWith("/") || folderDestinationName.endsWith("\\"))) {
folderDestinationName += '/';
}
if (folderSourceName.equals("")) {
folderSourceName = "./";
}
if (!(folderSourceName.endsWith("/") || folderSourceName.endsWith("\\"))) {
folderSourceName += '/';
}
if (folderDestinationName.equals("")) {
folderDestinationName = "./";
}
this.className = className;
this.classLoader = classLoader;
this.folderDestinationName = folderDestinationName;
this.folderSourceName = folderSourceName;
this.classFile = new File((className.replace('.', '/') + ".java").toString());
}
/**
* Get the class type.
*
* @return The class type or null
* @throws ClassNotFoundException
*/
public Class<?> getClassType() throws ClassNotFoundException {
return urlClassLoader.loadClass(className);
}
/**
* Get a new instance of the class or null
*
* @return A new instance or null.
*/
@SuppressWarnings("unchecked")
public T newInstance() {
try {
return (T) urlClassLoader.loadClass(className).newInstance();
} catch (Exception e) {
return null;
}
}
/**
* Checks if the source file has been modified
*
* @return The modified state
*/
public boolean isDirty() {
return classFile.lastModified() != lastCompiled || lastCompiled == 0;
}
/**
* Update all the given classes at once. They should be from the same folder
* as source and have the same destination folder and the same options.
*
* @param syncs
* The sync classes, all in the same root folder.
* @return Wether the compilation succeded and changes happened.
* @throws Exception
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean updateAll(Sync[] syncs) {
// check if update is needed
boolean areDirty = false;
for (val sync : syncs) {
sync.compileError = "";
sync.compileOutput = "";
areDirty = areDirty | sync.isDirty();
}
if (!areDirty) {
return false;
}
// check if files exist
val first = syncs[0];
URL url;
boolean result = true;
for (val sync : syncs) {
if (!sync.classFile.exists() || sync.classFile.isDirectory()) {
sync.compileError += "Cannot find file: " + sync.classFile.getPath() + '\n';
result = false;
}
}
if (result == false) {
return false;
}
for (val sync : syncs) {
sync.lastCompiled = sync.classFile.lastModified();
}
String filesFolder = first.folderSourceName;
val errorWriter = new StringWriter();
val outputWriter = new StringWriter();
val errorStream = new PrintWriter(errorWriter);
val outputStream = new PrintWriter(outputWriter);
val success = BatchCompiler.compile(filesFolder + " -d " + first.folderDestinationName + " -cp "
+ System.getProperty("java.class.path") + ";" + first.folderDestinationName + " " + Sync.options,
outputStream, errorStream, null);
// handle error for each
for (val sync : syncs) {
sync.compileError = errorWriter.toString();
sync.compileOutput = outputWriter.toString();
}
if ("".equals(errorWriter.toString()) && success) {
// check if generated classes exists
try {
File root = new File(first.folderDestinationName);
if (!root.exists() || !root.isDirectory()) {
for (val sync : syncs) {
sync.compileError += "Cannot get containing folder: " + root.getPath() + '\n';
}
return false;
}
url = root.toURI().toURL();
} catch (Exception e) {
for (val sync : syncs) {
sync.compileError += e.toString() + '\n';
}
return false;
}
val urlClassLoader = URLClassLoader.newInstance(new URL[] { url }, first.classLoader);
for (val sync : syncs) {
try {
sync.checkClass(urlClassLoader);
} catch (Exception e) {
sync.compileError += e.toString();
result = false;
}
}
return result;
}
return false;
}
/**
* Update the given class. If it depends on other classes, use updateAll.
*
* @param sync
* The sync classes, all in the same root folder.
* @return If the compilation succeeded and changes happened.
* @throws Exception
*/
public static <T> boolean update(Sync<T> sync) {
sync.compileError = "";
sync.compileOutput = "";
if (!sync.isDirty()) {
return false;
}
// check if file exist
try {
if (!sync.classFile.exists() || sync.classFile.isDirectory()) {
sync.compileError += "Cannot find file: " + sync.classFile.getPath() + '\n';
return false;
}
} catch (Exception e) {
sync.compileError += e.toString();
return false;
}
sync.lastCompiled = sync.classFile.lastModified();
val errorWriter = new StringWriter();
val outputWriter = new StringWriter();
val errorStream = new PrintWriter(errorWriter);
val outputStream = new PrintWriter(outputWriter);
val compileCommand = (sync.className.replace('.', '/') + ".java").toString() + " -d "
+ sync.folderDestinationName + " -cp " + System.getProperty("java.class.path") + ";"
+ sync.folderDestinationName + " " + Sync.options;
val success = BatchCompiler.compile(compileCommand, outputStream, errorStream, null);
sync.compileError = errorWriter.toString();
sync.compileOutput = outputWriter.toString();
if ("".equals(sync.compileError) && success) {
URL url;
try {
File root = new File(sync.folderDestinationName);
url = root.toURI().toURL();
} catch (Exception e) {
sync.compileError += e.toString();
return false;
}
val urlClassLoader = URLClassLoader.newInstance(new URL[] { url }, sync.classLoader);
try {
sync.checkClass(urlClassLoader);
} catch (Throwable e) {
sync.compileError += e.toString();
return false;
}
return true;
}
return false;
}
private void checkClass(URLClassLoader newClassLoader) throws Exception {
newClassLoader.loadClass(className);
if (urlClassLoader != null)
urlClassLoader.close();
urlClassLoader = newClassLoader;
}
} |
package org.mockito;
import org.mockito.exceptions.misusing.PotentialStubbingProblem;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.debugging.MockitoDebuggerImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.listeners.VerificationStartedEvent;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
import org.mockito.plugins.MockitoPlugins;
import org.mockito.quality.MockitoHint;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.session.MockitoSessionLogger;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Answer1;
import org.mockito.stubbing.LenientStubber;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.stubbing.Stubbing;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.verification.After;
import org.mockito.verification.Timeout;
import org.mockito.verification.VerificationAfterDelay;
import org.mockito.verification.VerificationMode;
import org.mockito.verification.VerificationWithTimeout;
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
static final MockitoCore MOCKITO_CORE = new MockitoCore();
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
*
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration and if there is no global configuration then
* it will use a default answer that returns zeros, empty collections, nulls, etc.
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
* <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 4.0.0
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
*
* //calling unstubbed method here:
* Stuff stuff = mock.getStuff();
*
* //using object returned by unstubbed call:
* stuff.doSomething();
*
* //Above doesn't yield NullPointerException this time!
* //Instead, SmartNullPointerException is thrown.
* //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
* </code></pre>
*/
public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
* ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
* then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
* <p>
* Example that shows how deep stub works:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
*
* // note that we're stubbing a chain of methods here: getBar().getName()
* when(mock.getBar().getName()).thenReturn("deep");
*
* // note that we're chaining method calls: getBar().getName()
* assertEquals("deep", mock.getBar().getName());
* </code></pre>
* </p>
*
* <p>
* <strong>WARNING: </strong>
* This feature should rarely be required for regular clean code! Leave it for legacy code.
* Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
* hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
* </p>
*
* <p>
* Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
* </p>
*
* <p>
* Please note that this answer will return existing mocks that matches the stub. This
* behavior is ok with deep stubs and allows verification to work on the last mock of the chain.
* <pre class="code"><code class="java">
* when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");
*
* mock.getBar("candy bar").getThingy().getName();
*
* assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());
* verify(mock.getBar("candy bar").getThingy()).getName();
* verify(mock.getBar(anyString()).getThingy()).getName();
* </code></pre>
* </p>
*
* <p>
* Verification only works with the last mock in the chain. You can use verification modes.
* <pre class="code"><code class="java">
* when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
* when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
*
* person.getAddress("the docks").getStreet().getName();
* person.getAddress("the docks").getStreet().getLongName();
* person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();
* person.getAddress("the docks").getStreet(Locale.CHINESE).getName();
*
* // note that we are actually referring to the very last mock in the stubbing chain.
* InOrder inOrder = inOrder(
* person.getAddress("the docks").getStreet(),
* person.getAddress("the docks").getStreet(Locale.CHINESE),
* person.getAddress("the docks").getStreet(Locale.ITALIAN)
* );
* inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
* inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
* </code></pre>
* </p>
*
* <p>
* How deep stub work internally?
* <pre class="code"><code class="java">
* //this:
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
* when(mock.getBar().getName(), "deep");
*
* //is equivalent of
* Foo foo = mock(Foo.class);
* Bar bar = mock(Bar.class);
* when(foo.getBar()).thenReturn(bar);
* when(bar.getName()).thenReturn("deep");
* </code></pre>
* </p>
*
* <p>
* This feature will not work when any return type of methods included in the chain cannot be mocked
* (for example: is a primitive or a final class). This is because of java type system.
* </p>
*/
public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
*
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* doReturn(fakeValue).when(mock).getSomething();
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*
* <p>
* <u>Note 1:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>
* syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax.
* <p>
* <u>Note 2:</u> If the mock is serialized then deserialized, then this answer will not be able to understand
* generics metadata.
*/
public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
*
* Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal
* to the class or a superclass.
*
* <p><b>Keep in mind this answer uses the return type of a method.
* If this type is assignable to the class of the mock, it will return the mock.
* Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>
*
* Consider a HttpBuilder used in a HttpRequesterWithHeaders.
*
* <pre class="code"><code class="java">
* public class HttpRequesterWithHeaders {
*
* private HttpBuilder builder;
*
* public HttpRequesterWithHeaders(HttpBuilder builder) {
* this.builder = builder;
* }
*
* public String request(String uri) {
* return builder.withUrl(uri)
* .withHeader("Content-type: application/json")
* .withHeader("Authorization: Bearer")
* .request();
* }
* }
*
* private static class HttpBuilder {
*
* private String uri;
* private List<String> headers;
*
* public HttpBuilder() {
* this.headers = new ArrayList<String>();
* }
*
* public HttpBuilder withUrl(String uri) {
* this.uri = uri;
* return this;
* }
*
* public HttpBuilder withHeader(String header) {
* this.headers.add(header);
* return this;
* }
*
* public String request() {
* return uri + headers.toString();
* }
* }
* </code></pre>
*
* The following test will succeed
*
* <pre><code>
* @Test
* public void use_full_builder_with_terminating_method() {
* HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
* HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);
* String response = "StatusCode: 200";
*
* when(builder.request()).thenReturn(response);
*
* assertThat(requester.request("URI")).isEqualTo(response);
* }
* </code></pre>
*/
public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;
/**
* Creates mock object of given class or interface.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
@CheckReturnValue
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings());
}
/**
* Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
* <p>
* Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
* <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
* <p>
* <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}
* <p>
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param name of the mock
* @return mock object
*/
@CheckReturnValue
public static <T> T mock(Class<T> classToMock, String name) {
return mock(classToMock, withSettings()
.name(name)
.defaultAnswer(RETURNS_DEFAULTS));
}
/**
* Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
* Can be used to find out if given object is a Mockito mock
* or to find out if a given mock is a spy or mock.
* <p>
* In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
* e.g. invocations, stubbing info, etc.
*
* @param toInspect - object to inspect. null input is allowed.
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
@CheckReturnValue
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* Creates mock with a specified strategy for its answers to interactions.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
* <p>
* It is the default answer so it will be used <b>only when you don't</b> stub the method call.
*
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
* </code></pre>
*
* <p>See examples in javadoc for {@link Mockito} class</p>
*
* @param classToMock class or interface to mock
* @param defaultAnswer default answer for unstubbed methods
*
* @return mock object
*/
@CheckReturnValue
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* Creates a mock with some non-standard settings.
* <p>
* The number of configuration points for a mock grows
* so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
* Hence {@link MockSettings}.
* <pre class="code"><code class="java">
* Listener mock = mock(Listener.class, withSettings()
* .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
* );
* </code></pre>
* <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
* Is the code under test so complicated that it requires non-standard mocks?
* Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
* <p>
* See also {@link Mockito#withSettings()}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param mockSettings additional mock settings
* @return mock object
*/
@CheckReturnValue
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
return MOCKITO_CORE.mock(classToMock, mockSettings);
}
/**
* Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.
* <p>
* Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //optionally, you can stub out some methods:
* when(spy.size()).thenReturn(100);
*
* //using the spy calls <b>real</b> methods
* spy.add("one");
* spy.add("two");
*
* //prints "one" - the first element of a list
* System.out.println(spy.get(0));
*
* //size() method was stubbed - 100 is printed
* System.out.println(spy.size());
*
* //optionally, you can verify
* verify(spy).add("one");
* verify(spy).add("two");
* </code></pre>
*
* <h4>Important gotcha on spying real objects!</h4>
* <ol>
* <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
* Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
* family of methods for stubbing. Example:
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
* So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
* and their effect on real instance state.
* The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
* you won't see any effects on the real instance.</li>
*
* <li>Watch out for final methods.
* Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
* Also you won't be able to verify those method as well.
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
* It may troublesome for code that rely on the spy to have these annotations.</p>
*
*
* @param object
* to spy on
* @return a spy of the real object
*/
@CheckReturnValue
public static <T> T spy(T object) {
return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
.spiedInstance(object)
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Please refer to the documentation of {@link #spy(Object)}.
* Overusing spies hints at code design smells.
* <p>
* This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.
* Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.
* This is particularly useful for spying on abstract classes because they cannot be instantiated.
* See also {@link MockSettings#useConstructor(Object...)}.
* <p>
* Examples:
* <pre class="code"><code class="java">
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
* </code></pre>
*
* @param classToSpy the class to spy
* @param <T> type of the spy
* @return a spy of the provided class
* @since 1.10.12
*/
@Incubating
@CheckReturnValue
public static <T> T spy(Class<T> classToSpy) {
return MOCKITO_CORE.mock(classToSpy, withSettings()
.useConstructor()
.defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
* <p>
* Simply put: "<b>When</b> the x method is called <b>then</b> return y".
*
* <p>
* Examples:
*
* <pre class="code"><code class="java">
* <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
*
* //you can use flexible argument matchers, e.g:
* when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
*
* //setting exception to be thrown:
* when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
*
* //you can set different behavior for consecutive method calls.
* //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //Alternative, shorter version for consecutive stubbing:
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two");
* //is the same as:
* when(mock.someMethod("some arg"))
* .thenReturn("one")
* .thenReturn("two");
*
* //shorter version for consecutive method calls throwing exceptions:
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException(), new NullPointerException();
*
* </code></pre>
*
* For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)}
* <p>
* Stubbing can be overridden: for example common stubbing can go to fixture
* setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* Once stubbed, the method will always return stubbed value regardless
* of how many times it is called.
* <p>
* Last stubbing is more important - when you stubbed the same method with
* the same arguments many times.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
*
* <p>
* See examples in javadoc for {@link Mockito} class
* @param methodCall method to be stubbed
* @return OngoingStubbing object used to stub fluently.
* <strong>Do not</strong> create a reference to this returned object.
*/
@CheckReturnValue
public static <T> OngoingStubbing<T> when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
/**
* Verifies certain behavior <b>happened once</b>.
* <p>
* Alias to <code>verify(mock, times(1))</code> E.g:
* <pre class="code"><code class="java">
* verify(mock).someMethod("some arg");
* </code></pre>
* Above is equivalent to:
* <pre class="code"><code class="java">
* verify(mock, times(1)).someMethod("some arg");
* </code></pre>
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
* Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
*
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mock to be verified
* @return mock object itself
*/
@CheckReturnValue
public static <T> T verify(T mock) {
return MOCKITO_CORE.verify(mock, times(1));
}
/**
* Verifies certain behavior happened at least once / exact number of times / never. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(5)).someMethod("was called five times");
*
* verify(mock, atLeast(2)).someMethod("was called at least two times");
*
* //you can use flexible argument matchers, e.g:
* verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>);
* </code></pre>
*
* <b>times(1) is the default</b> and can be omitted
* <p>
* Arguments passed are compared using <code>equals()</code> method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* <p>
*
* @param mock to be verified
* @param mode times(x), atLeastOnce() or never()
*
* @return mock object itself
*/
@CheckReturnValue
public static <T> T verify(T mock, VerificationMode mode) {
return MOCKITO_CORE.verify(mock, mode);
}
public static <T> void reset(T ... mocks) {
MOCKITO_CORE.reset(mocks);
}
/**
* Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
* <ul>
* <li>You are using a dependency injection framework to inject your mocks.</li>
* <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
* </ul>
*
* <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
* @param <T> The type of the mocks
* @param mocks The mocks to clear the invocations for
*/
public static <T> void clearInvocations(T ... mocks) {
MOCKITO_CORE.clearInvocations(mocks);
}
/**
* Checks if any of given mocks has any unverified interaction.
* <p>
* You can use this method after you verified your mocks - to make sure that nothing
* else was invoked on your mocks.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* Stubbed invocations (if called) are also treated as interactions.
* If you want stubbed invocations automatically verified, check out {@link Strictness#STRICT_STUBS} feature
* introduced in Mockito 2.3.0.
* If you want to ignore stubs for verification, see {@link #ignoreStubs(Object...)}.
* <p>
* A word of <b>warning</b>:
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
* Abusing it leads to overspecified, less maintainable tests.
* <p>
* This method will also detect unverified invocations that occurred before the test method,
* for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
* <p>
* Example:
*
* <pre class="code"><code class="java">
* //interactions
* mock.doSomething();
* mock.doSomethingUnexpected();
*
* //verification
* verify(mock).doSomething();
*
* //following will fail because 'doSomethingUnexpected()' is unexpected
* verifyNoMoreInteractions(mock);
*
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks beyond the previously verified interactions.<br/>
* This method has the same behavior as {@link #verifyNoMoreInteractions(Object...)}.
*
* @param mocks to be verified
* @deprecated Since 3.x.x. Please migrate your code to {@link #verifyNoInteractions(Object...)}
*/
@Deprecated
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks.
* <pre class="code"><code class="java">
* verifyNoInteractions(mockOne, mockTwo);
* </code></pre>
* This method will also detect invocations
* that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
* <p>
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
* @since 3.x.x
*/
public static void verifyNoInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoInteractions(mocks);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
@CheckReturnValue
public static Stubber doThrow(Throwable... toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
@CheckReturnValue
public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
* <code>doThrow()</code> when you want to stub the void method to throw several exception of specified class.
* <p>
* A new exception instance will be created for each method invocation.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
* </code></pre>
*
* @param toBeThrown to be thrown when the stubbed method is called
* @param toBeThrownNext next to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
// Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
@SuppressWarnings ({"unchecked", "varargs"})
@CheckReturnValue
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
}
/**
* Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
* <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
* The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class);
* doCallRealMethod().when(mock).someVoidMethod();
*
* // this will call the real implementation of Foo.someVoidMethod()
* mock.someVoidMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
* @since 1.9.5
*/
@CheckReturnValue
public static Stubber doCallRealMethod() {
return MOCKITO_CORE.stubber().doCallRealMethod();
}
/**
* Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}.
* <p>
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
* <p>
* Example:
*
* <pre class="code"><code class="java">
* doAnswer(new Answer() {
* public Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Mock mock = invocation.getMock();
* return null;
* }})
* .when(mock).someMethod();
* </code></pre>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
@CheckReturnValue
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.stubber().doAnswer(answer);
}
/**
* Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
* However, there are rare situations when doNothing() comes handy:
* <p>
* <ol>
* <li>Stubbing consecutive calls on a void method:
* <pre class="code"><code class="java">
* doNothing().
* doThrow(new RuntimeException())
* .when(mock).someVoidMethod();
*
* //does nothing the first time:
* mock.someVoidMethod();
*
* //throws RuntimeException the next time:
* mock.someVoidMethod();
* </code></pre>
* </li>
* <li>When you spy real objects and you want the void method to do nothing:
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //let's make clear() do nothing
* doNothing().when(spy).clear();
*
* spy.add("one");
*
* //clear() does nothing, so the list still contains "one"
* spy.clear();
* </code></pre>
* </li>
* </ol>
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
@CheckReturnValue
public static Stubber doNothing() {
return MOCKITO_CORE.stubber().doNothing();
}
/**
* Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
@CheckReturnValue
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned);
}
/**
* Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
* <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
* <p>
* <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
* and more readable</b> (especially when stubbing consecutive calls).
* <p>
* Here are those rare occasions when doReturn() comes handy:
* <p>
*
* <ol>
* <li>When spying real objects and calling real methods on a spy brings side effects
*
* <pre class="code"><code class="java">
* List list = new LinkedList();
* List spy = spy(list);
*
* //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
* when(spy.get(0)).thenReturn("foo", "bar", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("foo", "bar", "qix").when(spy).get(0);
* </code></pre>
* </li>
*
* <li>Overriding a previous exception-stubbing:
* <pre class="code"><code class="java">
* when(mock.foo()).thenThrow(new RuntimeException());
*
* //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
* when(mock.foo()).thenReturn("bar", "foo", "qix");
*
* //You have to use doReturn() for stubbing:
* doReturn("bar", "foo", "qix").when(mock).foo();
* </code></pre>
* </li>
* </ol>
*
* Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overridding stubbing is a potential code smell that points out too much stubbing.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
@SuppressWarnings({"unchecked", "varargs"})
@CheckReturnValue
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
}
@CheckReturnValue
public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* Please consider using {@link Strictness#STRICT_STUBS} feature which eliminates the need for <code>ignoreStubs()</code>
* and provides other benefits.
* <p>
* <code>ignoreStubs()</code> is sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
* Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
* Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions().
* <p>
* This method <b>changes the input mocks</b>! This method returns input mocks just for convenience.
* <p>
* Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
* See the second example.
* <p>
* Example:
* <pre class="code"><code class="java">
* //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
* List mock1 = mock(List.class), mock2 = mock(List.class);
*
* //stubbing mocks:
* when(mock1.get(0)).thenReturn(10);
* when(mock2.get(0)).thenReturn(20);
*
* //using mocks by calling stubbed get(0) methods:
* System.out.println(mock1.get(0)); //prints 10
* System.out.println(mock2.get(0)); //prints 20
*
* //using mocks by calling clear() methods:
* mock1.clear();
* mock2.clear();
*
* //verification:
* verify(mock1).clear();
* verify(mock2).clear();
*
* //verifyNoMoreInteractions() fails because get() methods were not accounted for.
* try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
*
* //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
* verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
*
* //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience.
* </code></pre>
* Ignoring stubs can be used with <b>verification in order</b>:
* <pre class="code"><code class="java">
* List list = mock(List.class);
* when(list.get(0)).thenReturn("foo");
*
* list.add(0);
* list.clear();
* System.out.println(list.get(0)); //we don't want to verify this
*
* InOrder inOrder = inOrder(ignoreStubs(list));
* inOrder.verify(list).add(0);
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
* Stubbed invocations are automatically verified with {@link Strictness#STRICT_STUBS} feature
* and it eliminates the need for <code>ignoreStubs()</code>. Example below uses JUnit Rules:
* <pre class="code"><code class="java">
* @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
*
* List list = mock(List.class);
* when(list.get(0)).thenReturn("foo");
*
* list.size();
* verify(list).size();
*
* list.get(0); // Automatically verified by STRICT_STUBS
* verifyNoMoreInteractions(list); // No need of ignoreStubs()
* </code></pre>
*
* @since 1.9.0
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}
/**
* Allows verifying exact number of invocations. E.g:
* <pre class="code"><code class="java">
* verify(mock, times(2)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param wantedNumberOfInvocations wanted number of invocations
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}
/**
* Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
* <p>
* Verifies that interaction did not happen. E.g:
* <pre class="code"><code class="java">
* verify(mock, never()).someMethod();
* </code></pre>
*
* <p>
* If you want to verify there were NO interactions with the mock
* check out {@link Mockito#verifyZeroInteractions(Object...)}
* or {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode never() {
return times(0);
}
/**
* Allows at-least-once verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeastOnce()).someMethod("some arg");
* </code></pre>
* Alias to <code>atLeast(1)</code>.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode atLeastOnce() {
return VerificationModeFactory.atLeastOnce();
}
/**
* Allows at-least-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atLeast(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param minNumberOfInvocations minimum number of invocations
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}
/**
* Allows at-most-once verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atMostOnce()).someMethod("some arg");
* </code></pre>
* Alias to <code>atMost(1)</code>.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode atMostOnce() {
return VerificationModeFactory.atMostOnce();
}
/**
* Allows at-most-x verification. E.g:
* <pre class="code"><code class="java">
* verify(mock, atMost(3)).someMethod("some arg");
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param maxNumberOfInvocations max number of invocations
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode atMost(int maxNumberOfInvocations) {
return VerificationModeFactory.atMost(maxNumberOfInvocations);
}
/**
* Allows non-greedy verification in order. For example
* <pre class="code"><code class="java">
* inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
* </code></pre>
* <ul>
* <li>will not fail if the method is called 3 times, unlike times( 2 )</li>
* <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li>
* </ul>
* This verification mode can only be used with in order verification.
* @param wantedNumberOfInvocations number of invocations to verify
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode calls( int wantedNumberOfInvocations ){
return VerificationModeFactory.calls( wantedNumberOfInvocations );
}
/**
* Allows checking if given method was the only one invoked. E.g:
* <pre class="code"><code class="java">
* verify(mock, only()).someMethod();
* //above is a shorthand for following 2 lines of code:
* verify(mock).someMethod();
* verifyNoMoreInteractions(mock);
* </code></pre>
*
* <p>
* See also {@link Mockito#verifyNoMoreInteractions(Object...)}
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
@CheckReturnValue
public static VerificationMode only() {
return VerificationModeFactory.only();
}
/**
* Verification will be triggered over and over until the given amount of millis, allowing testing of async code.
* Useful when interactions with the mock object did not happened yet.
* Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
* <p>
* See also {@link #after(long)} method for testing async code.
* Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(long)}.
*
* <pre class="code"><code class="java">
* //passes when someMethod() is called no later than within 100 ms
* //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes as soon as someMethod() has been called 2 times under 100 ms
* verify(mock, timeout(100).times(2)).someMethod();
*
* //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
* verify(mock, timeout(100).atLeast(2)).someMethod();
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
*/
@CheckReturnValue
public static VerificationWithTimeout timeout(long millis) {
return new Timeout(millis, VerificationModeFactory.times(1));
}
/**
* Verification will be triggered after given amount of millis, allowing testing of async code.
* Useful when interactions with the mock object did not happened yet.
* Extensive use of {@code after()} method can be a code smell - there are better ways of testing concurrent code.
* <p>
* Not yet implemented to work with InOrder verification.
* <p>
* See also {@link #timeout(long)} method for testing async code.
* Differences between {@code timeout()} and {@code after()} are explained below.
*
* <pre class="code"><code class="java">
* //passes after 100ms, if someMethod() has only been called once at that time.
* verify(mock, after(100)).someMethod();
* //above is an alias to:
* verify(mock, after(100).times(1)).someMethod();
*
* //passes if someMethod() is called <b>*exactly*</b> 2 times, as tested after 100 millis
* verify(mock, after(100).times(2)).someMethod();
*
* //passes if someMethod() has not been called, as tested after 100 millis
* verify(mock, after(100).never()).someMethod();
*
* //verifies someMethod() after a given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new After(100, yourOwnVerificationMode)).someMethod();
* </code></pre>
*
* <strong>timeout() vs. after()</strong>
* <ul>
* <li>timeout() exits immediately with success when verification passes</li>
* <li>after() awaits full duration to check if verification passes</li>
* </ul>
* Examples:
* <pre class="code"><code class="java">
* //1.
* mock.foo();
* verify(mock, after(1000)).foo();
* //waits 1000 millis and succeeds
*
* //2.
* mock.foo();
* verify(mock, timeout(1000)).foo();
* //succeeds immediately
* </code></pre>
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification
*/
@CheckReturnValue
public static VerificationAfterDelay after(long millis) {
return new After(millis, VerificationModeFactory.times(1));
}
public static void validateMockitoUsage() {
MOCKITO_CORE.validateMockitoUsage();
}
/**
* Allows mock creation with additional mock settings.
* <p>
* Don't use it too often.
* Consider writing simple tests that use simple mocks.
* Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
* If you cannot write a test in a simple way - refactor the code under test.
* <p>
* Examples of mock settings:
* <pre class="code"><code class="java">
* //Creates mock with different default answer & name
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie"));
*
* //Creates mock with different default answer, descriptive name and extra interfaces
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* .extraInterfaces(Bar.class));
* </code></pre>
* {@link MockSettings} has been introduced for two reasons.
* Firstly, to make it easy to add another mock settings when the demand comes.
* Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.
* <p>
* See javadoc for {@link MockSettings} to learn about possible mock settings.
* <p>
*
* @return mock settings instance with defaults.
*/
@CheckReturnValue
public static MockSettings withSettings() {
return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
}
/**
* Adds a description to be printed if verification fails.
* <pre class="code"><code class="java">
* verify(mock, description("This will print on failure")).someMethod("some arg");
* </code></pre>
* @param description The description to print on failure.
* @return verification mode
* @since 2.1.0
*/
@CheckReturnValue
public static VerificationMode description(String description) {
return times(1).description(description);
}
/**
* @deprecated - please use {@link MockingDetails#printInvocations()} instead.
* An instance of {@code MockingDetails} can be retrieved via {@link #mockingDetails(Object)}.
*/
@Deprecated
@CheckReturnValue
static MockitoDebugger debug() {
return new MockitoDebuggerImpl();
}
/**
* For advanced users or framework integrators. See {@link MockitoFramework} class.
*
* @since 2.1.0
*/
@Incubating
@CheckReturnValue
public static MockitoFramework framework() {
return new DefaultMockitoFramework();
}
/**
* {@code MockitoSession} is an optional, highly recommended feature
* that helps driving cleaner tests by eliminating boilerplate code and adding extra validation.
* <p>
* For more information, including use cases and sample code, see the javadoc for {@link MockitoSession}.
*
* @since 2.7.0
*/
@Incubating
@CheckReturnValue
public static MockitoSessionBuilder mockitoSession() {
return new DefaultMockitoSessionBuilder();
}
/**
* Lenient stubs bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}).
* When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as
* 'unnecessary stubbing' ({@link UnnecessaryStubbingException}) or for 'stubbing argument mismatch' {@link PotentialStubbingProblem}.
*
* <pre class="code"><code class="java">
* lenient().when(mock.foo()).thenReturn("ok");
* </code></pre>
*
* Most mocks in most tests don't need leniency and should happily prosper with {@link Strictness#STRICT_STUBS}.
* <ul>
* <li>If a specific stubbing needs to be lenient - use this method</li>
* <li>If a specific mock need to have stubbings lenient - use {@link MockSettings#lenient()}</li>
* <li>If a specific test method / test class needs to have all stubbings lenient
* - configure strictness using our JUnit support ({@link MockitoJUnit} or Mockito Session ({@link MockitoSession})</li>
*
* <h3>Elaborate example</h3>
*
* In below example, 'foo.foo()' is a stubbing that was moved to 'before()' method to avoid duplication.
* Doing so makes one of the test methods ('test3()') fail with 'unnecessary stubbing'.
* To resolve it we can configure 'foo.foo()' stubbing in 'before()' method to be lenient.
* Alternatively, we can configure entire 'foo' mock as lenient.
* <p>
* This example is simplified and not realistic.
* Pushing stubbings to 'before()' method may cause tests to be less readable.
* Some repetition in tests is OK, use your own judgement to write great tests!
* It is not desired to eliminate all possible duplication from the test code
* because it may add complexity and conceal important test information.
*
* <pre class="code"><code class="java">
* public class SomeTest {
*
* @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(STRICT_STUBS);
*
* @Mock Foo foo;
* @Mock Bar bar;
*
* @Before public void before() {
* when(foo.foo()).thenReturn("ok");
*
* // it is better to configure the stubbing to be lenient:
* // lenient().when(foo.foo()).thenReturn("ok");
*
* // or the entire mock to be lenient:
* // foo = mock(Foo.class, withSettings().lenient());
* }
*
* @Test public void test1() {
* foo.foo();
* }
*
* @Test public void test2() {
* foo.foo();
* }
*
* @Test public void test3() {
* bar.bar();
* }
* }
* </code></pre>
*
* @since 2.20.0
*/
@Incubating
public static LenientStubber lenient() {
return MOCKITO_CORE.lenient();
}
} |
package org.sqlite;
import java.sql.SQLException;
/** This class provides a thin JNI layer over the SQLite3 C API. */
final class NativeDB extends DB
{
/** SQLite connection handle. */
long pointer = 0;
private static Boolean loaded = null;
static boolean load()
{
if (loaded != null)
return loaded == Boolean.TRUE;
return loaded = new Boolean(SQLiteJDBCLoader.initialize());
// String libpath = System.getProperty("org.sqlite.lib.path");
// String libname = System.getProperty("org.sqlite.lib.name");
// if (libname == null) libname = System.mapLibraryName("sqlitejdbc");
// // look for a pre-installed library
// try {
// if (libpath == null) System.loadLibrary("sqlitejdbc");
// else System.load(new File(libpath, libname).getAbsolutePath());
// loaded = Boolean.TRUE;
// return true;
// } catch (UnsatisfiedLinkError e) { } // fall through
// // guess what a bundled library would be called
// String osname = System.getProperty("os.name").toLowerCase();
// String osarch = System.getProperty("os.arch");
// if (osname.startsWith("mac os")) {
// osname = "mac";
// osarch = "universal";
// if (osname.startsWith("windows"))
// osname = "win";
// if (osname.startsWith("sunos"))
// osname = "solaris";
// if (osarch.startsWith("i") && osarch.endsWith("86"))
// osarch = "x86";
// libname = osname + '-' + osarch + ".lib";
// // try a bundled library
// try {
// ClassLoader cl = NativeDB.class.getClassLoader();
// InputStream in = cl.getResourceAsStream(libname);
// if (in == null)
// throw new Exception("libname: "+libname+" not found");
// File tmplib = File.createTempFile("libsqlitejdbc-", ".lib");
// tmplib.deleteOnExit();
// OutputStream out = new FileOutputStream(tmplib);
// byte[] buf = new byte[1024];
// for (int len; (len = in.read(buf)) != -1;)
// out.write(buf, 0, len);
// in.close();
// out.close();
// System.load(tmplib.getAbsolutePath());
// loaded = Boolean.TRUE;
// return true;
// } catch (Exception e) { }
// loaded = Boolean.FALSE;
// return false;
}
/** linked list of all instanced UDFDatas */
private long udfdatalist = 0;
// WRAPPER FUNCTIONS ////////////////////////////////////////////
protected native synchronized void _open(String file) throws SQLException;
protected native synchronized void _close() throws SQLException;
native synchronized int shared_cache(boolean enable);
native synchronized void interrupt();
native synchronized void busy_timeout(int ms);
//native synchronized void exec(String sql) throws SQLException;
protected native synchronized long prepare(String sql) throws SQLException;
native synchronized String errmsg();
native synchronized String libversion();
native synchronized int changes();
protected native synchronized int finalize(long stmt);
protected native synchronized int step(long stmt);
protected native synchronized int reset(long stmt);
native synchronized int clear_bindings(long stmt);
native synchronized int bind_parameter_count(long stmt);
native synchronized int column_count(long stmt);
native synchronized int column_type(long stmt, int col);
native synchronized String column_decltype(long stmt, int col);
native synchronized String column_table_name(long stmt, int col);
native synchronized String column_name(long stmt, int col);
native synchronized String column_text(long stmt, int col);
native synchronized byte[] column_blob(long stmt, int col);
native synchronized double column_double(long stmt, int col);
native synchronized long column_long(long stmt, int col);
native synchronized int column_int(long stmt, int col);
native synchronized int bind_null(long stmt, int pos);
native synchronized int bind_int(long stmt, int pos, int v);
native synchronized int bind_long(long stmt, int pos, long v);
native synchronized int bind_double(long stmt, int pos, double v);
native synchronized int bind_text(long stmt, int pos, String v);
native synchronized int bind_blob(long stmt, int pos, byte[] v);
native synchronized void result_null(long context);
native synchronized void result_text(long context, String val);
native synchronized void result_blob(long context, byte[] val);
native synchronized void result_double(long context, double val);
native synchronized void result_long(long context, long val);
native synchronized void result_int(long context, int val);
native synchronized void result_error(long context, String err);
native synchronized int value_bytes(Function f, int arg);
native synchronized String value_text(Function f, int arg);
native synchronized byte[] value_blob(Function f, int arg);
native synchronized double value_double(Function f, int arg);
native synchronized long value_long(Function f, int arg);
native synchronized int value_int(Function f, int arg);
native synchronized int value_type(Function f, int arg);
native synchronized int create_function(String name, Function func);
native synchronized int destroy_function(String name);
native synchronized void free_functions();
// COMPOUND FUNCTIONS (for optimisation) /////////////////////////
/**
* Provides metadata for the columns of a statement. Returns: res[col][0] =
* true if column constrained NOT NULL res[col][1] = true if column is part
* of the primary key res[col][2] = true if column is auto-increment
*/
native synchronized boolean[][] column_metadata(long stmt);
static void throwex(String msg) throws SQLException
{
throw new SQLException(msg);
}
} |
package org.usb4java;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Utility class to load native libraries from classpath.
*
* @author Klaus Reimer (k@ailis.de)
*/
public final class Loader
{
/** Buffer size used for copying data. */
private static final int BUFFER_SIZE = 8192;
/** Constant for OS X operating system. */
private static final String OS_OSX = "osx";
/** Constant for OS X operating system. */
private static final String OS_MACOSX = "macosx";
/** Constant for Linux operating system. */
private static final String OS_LINUX = "linux";
/** Constant for Windows operating system. */
private static final String OS_WINDOWS = "windows";
/** Constant for FreeBSD operating system. */
private static final String OS_FREEBSD = "freebsd";
/** Constant for SunOS operating system. */
private static final String OS_SUNOS = "sunos";
/** Constant for i386 architecture. */
private static final String ARCH_I386 = "i386";
/** Constant for x86 architecture. */
private static final String ARCH_X86 = "x86";
/** Constant for x86_64 architecture. */
private static final String ARCH_X86_64 = "x86_64";
/** Constant for amd64 architecture. */
private static final String ARCH_AMD64 = "amd64";
/** Constant for so file extension. */
private static final String EXT_SO = "so";
/** Constant for dll file extension. */
private static final String EXT_DLL = "dll";
/** Constant for dylib file extension. */
private static final String EXT_DYLIB = "dylib";
/** The temporary directory for native libraries. */
private static File tmp;
/** If library is already loaded. */
private static boolean loaded = false;
/**
* Private constructor to prevent instantiation.
*/
private Loader()
{
// Nothing to do here
}
/**
* Returns the operating system name. This could be "linux", "windows" or
* "osx" or (for any other non-supported platform) the value of the
* "os.name" property converted to lower case and with removed space
* characters.
*
* @return The operating system name.
*/
private static String getOS()
{
final String os = System.getProperty("os.name").toLowerCase()
.replace(" ", "");
if (os.contains(OS_WINDOWS))
{
return OS_WINDOWS;
}
if (os.equals(OS_MACOSX))
{
return OS_OSX;
}
return os;
}
/**
* Returns the CPU architecture. This will be "x86" or "x86_64" (Platform
* names i386 und amd64 are converted accordingly) or (when platform is
* unsupported) the value of os.arch converted to lower-case and with
* removed space characters.
*
* @return The CPU architecture
*/
private static String getArch()
{
final String arch = System.getProperty("os.arch").toLowerCase()
.replace(" ", "");
if (arch.equals(ARCH_I386))
{
return ARCH_X86;
}
if (arch.equals(ARCH_AMD64))
{
return ARCH_X86_64;
}
return arch;
}
/**
* Returns the shared library extension name.
*
* @return The shared library extension name.
*/
private static String getExt()
{
final String os = getOS();
final String key = "usb4java.libext." + getOS();
final String ext = System.getProperty(key);
if (ext != null)
{
return ext;
}
if (os.equals(OS_LINUX) || os.equals(OS_FREEBSD) || os.equals(OS_SUNOS))
{
return EXT_SO;
}
if (os.equals(OS_WINDOWS))
{
return EXT_DLL;
}
if (os.equals(OS_OSX))
{
return EXT_DYLIB;
}
throw new LoaderException("Unable to determine the shared library "
+ "file extension for operating system '" + os
+ "'. Please specify Java parameter -D" + key
+ "=<FILE-EXTENSION>");
}
/**
* Creates the temporary directory used for unpacking the native libraries.
* This directory is marked for deletion on exit.
*
* @return The temporary directory for native libraries.
*/
private static File createTempDirectory()
{
// Return cached tmp directory when already created
if (tmp != null)
{
return tmp;
}
try
{
tmp = File.createTempFile("usb4java", null);
if (!tmp.delete())
{
throw new IOException("Unable to delete temporary file " + tmp);
}
if (!tmp.mkdirs())
{
throw new IOException("Unable to create temporary directory "
+ tmp);
}
tmp.deleteOnExit();
return tmp;
}
catch (final IOException e)
{
throw new LoaderException("Unable to create temporary directory "
+ "for usb4java natives: " + e, e);
}
}
/**
* Returns the platform name. This could be for example "linux-x86" or
* "windows-x86_64".
*
* @return The architecture name. Never null.
*/
private static String getPlatform()
{
return getOS() + "-" + getArch();
}
/**
* Returns the name of the usb4java native library. This could be
* "libusb4java.dll" for example.
*
* @return The usb4java native library name. Never null.
*/
private static String getLibName()
{
return "libusb4java." + getExt();
}
/**
* Returns the name of the libusb native library. This could be
* "libusb0.dll" for example or null if this library is not needed on the
* current platform (Because it is provided by the operating system).
*
* @return The libusb native library name or null if not needed.
*/
private static String getExtraLibName()
{
final String os = getOS();
if (os.equals(OS_WINDOWS))
{
return "libusb-1.0." + EXT_DLL;
}
return null;
}
/**
* Copies the specified input stream to the specified output file.
*
* @param input
* The input stream.
* @param output
* The output file.
* @throws IOException
* If copying failed.
*/
private static void copy(final InputStream input, final File output)
throws IOException
{
final byte[] buffer = new byte[BUFFER_SIZE];
final FileOutputStream stream = new FileOutputStream(output);
try
{
int read;
while ((read = input.read(buffer)) != -1)
{
stream.write(buffer, 0, read);
}
}
finally
{
stream.close();
}
}
/**
* Extracts a single library.
*
* @param platform
* The platform name (For example "linux-x86")
* @param lib
* The library name to extract (For example "libusb0.dll")
* @return The absolute path to the extracted library.
*/
private static String extractLibrary(final String platform,
final String lib)
{
// Extract the usb4java library
final String source = '/'
+ Loader.class.getPackage().getName().replace('.', '/') + '/'
+ platform + "/" + lib;
// Check if native library is present
final URL url = Loader.class.getResource(source);
if (url == null)
{
throw new LoaderException("Native library not found in classpath: "
+ source);
}
// If native library was found in an already extracted form then
// return this one without extracting it
if ("file".equals(url.getProtocol()))
{
try
{
return new File(url.toURI()).getAbsolutePath();
}
catch (final URISyntaxException e)
{
// Can't happen because we are not constructing the URI
// manually. But even when it happens then we fall back to
// extracting the library.
throw new LoaderException(e.toString(), e);
}
}
// Extract the library and return the path to the extracted file.
final File dest = new File(createTempDirectory(), lib);
try
{
final InputStream stream = Loader.class.getResourceAsStream(source);
if (stream == null)
{
throw new LoaderException("Unable to find " + source
+ " in the classpath");
}
try
{
copy(stream, dest);
}
finally
{
stream.close();
}
}
catch (final IOException e)
{
throw new LoaderException("Unable to extract native library "
+ source + " to " + dest + ": " + e, e);
}
// Mark usb4java library for deletion
dest.deleteOnExit();
return dest.getAbsolutePath();
}
/**
* Loads the libusb native wrapper library. Can be safely called multiple
* times. Duplicate calls are ignored. This method is automatically called
* when the {@link LibUsb} class is loaded. When you need to do it earlier
* (To catch exceptions for example) then simply call this method manually.
*
* @throws LoaderException
* When loading the native wrapper libraries failed.
*/
public static synchronized void load()
{
// Do nothing if already loaded (or still loading)
if (loaded)
{
return;
}
loaded = true;
final String platform = getPlatform();
final String lib = getLibName();
final String extraLib = getExtraLibName();
if (extraLib != null)
{
System.load(extractLibrary(platform, extraLib));
}
System.load(extractLibrary(platform, lib));
}
} |
package org.dada;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
/**
* The Application's "main" class
*/
@SuppressWarnings("serial")
public class MyVaadinUI extends UI
{
@Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
}
});
//layout.addComponent(button);
/* Create the table with a caption. */
Table table = new Table("This is my Table");
/* Define the names and data types of columns.
* The "default value" parameter is meaningless here. */
table.addContainerProperty("First Name", String.class, null);
table.addContainerProperty("Last Name", String.class, null);
table.addContainerProperty("Year", Integer.class, null);
/* Add a few items in the table. */
table.addItem(new Object[] {
"Nicolaus","Copernicus",new Integer(1473)}, new Integer(1));
table.addItem(new Object[] {
"Tycho", "Brahe", new Integer(1546)}, new Integer(2));
table.addItem(new Object[] {
"Giordano","Bruno", new Integer(1548)}, new Integer(3));
table.addItem(new Object[] {
"Galileo", "Galilei", new Integer(1564)}, new Integer(4));
table.addItem(new Object[] {
"Johannes","Kepler", new Integer(1571)}, new Integer(5));
table.addItem(new Object[] {
"Isaac", "Newton", new Integer(1643)}, new Integer(6));
layout.addComponent(table);
}
} |
package de.minecrafthaifl.nyanfighters;
import de.minecrafthaifl.nyanfighters.listeners.JoinListener;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.UUID;
public class GameListener {
static int time;
static String title;
static int id;
static int id2;
public static void lobbyWait() //Lobby-Ablauf
{
time=90;
id = Bukkit.getScheduler().scheduleSyncRepeatingTask(Nyanfighters.getInstance(), new Runnable() {
@Override
public void run() {
if(time<30)
{
if (time == 10) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch 10 Sekunden, bis das Spiel beginnt!");
} else if (time == 5) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch §45§9 Sekunden, bis das Spiel beginnt!");
title = "§45";
} else if (time == 4) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch §c4§9 Sekunden, bis das Spiel beginnt!");
title = "§c4";
} else if (time == 3) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch §63§9 Sekunden, bis das Spiel beginnt!");
title = "§63";
} else if (time == 2) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch §e2§9 Sekunden, bis das Spiel beginnt!");
title = "§e2";
} else if (time == 1) {
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch §a1§9 Sekunden, bis das Spiel beginnt!");
title = "§a1";
}else if (time == 0)
{
if (Bukkit.getOnlinePlayers().size() < 2) {
Bukkit.broadcastMessage("§6[NyanFighters] §cWarte auf weitere Spieler!");
time=91;
} else {
time = 300;
Nyanfighters.getInstance().setNoMove(true);
Bukkit.getScheduler().cancelTask(id);
gameWait();
}
}
}
else if(time%30==0)
{
Bukkit.broadcastMessage("§6[NyanFighters] §9Noch "+time+" Sekunden, bis das Spiel beginnt!");
}
time
}
}, 20L,20L);
}
public static void gameWait() //Spiel-Ablauf
{
int spawn = 0;
int i = 0;
FileConfiguration c = Nyanfighters.getInstance().getSpawnpointsConfi();
ItemStack slime = new ItemStack(Material.SLIME_BLOCK);
ItemMeta slimem = slime.getItemMeta();
slimem.setDisplayName("§r§aSprungball");
slime.setItemMeta(slimem);
while(c.isSet("SpielSpawn."+i))
{
i++;
}
i
spawn=i;
for(Player p: Bukkit.getOnlinePlayers())
{
Location teleport = YmlMethods.getSpielSpawn(i);
Location plattform = new Location(teleport.getWorld(), teleport.getX(), teleport.getY()-1, teleport.getZ(), teleport.getYaw(), teleport.getPitch());
plattform.getBlock().setType(Material.STAINED_GLASS);
Bukkit.getScheduler().scheduleSyncDelayedTask(Nyanfighters.getInstance(), new Runnable() {
@Override
public void run() {
plattform.getBlock().setType(Material.AIR);
}
},20*7);
p.teleport(teleport);
i
if(i+1==0)
{
i=spawn;
}
p.getInventory().clear();
p.getInventory().setBoots(new ItemStack(Material.DIAMOND_BOOTS));
p.getInventory().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
p.getInventory().setHelmet(new ItemStack(Material.DIAMOND_HELMET));
p.getInventory().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
p.getInventory().setItem(0,new ItemStack(Material.STONE_SWORD));
p.getInventory().setItemInOffHand(new ItemStack(Material.GOLDEN_APPLE, 16));
p.getInventory().setItem(1, new ItemStack(Material.FISHING_ROD));
p.getInventory().setItem(2, slime);
}
id = Bukkit.getScheduler().scheduleSyncRepeatingTask(Nyanfighters.getInstance(), new Runnable() {
@Override
public void run() {
if(time%20==0&&time!=300)
{
ItemStack granade = new ItemStack(Material.SNOW_BALL);
ItemMeta granadem= granade.getItemMeta();
granadem.setDisplayName("§r§2Granate");
granade.setItemMeta(granadem);
ItemStack trap = new ItemStack (Material.EGG);
ItemMeta trapm = trap.getItemMeta();
trapm.setDisplayName("§r3§fSpinnenfalle");
trap.setItemMeta(trapm);
ItemStack pusherx = new ItemStack(Material.SPLASH_POTION);
ItemMeta pusherm = pusherx.getItemMeta();
pusherm.setDisplayName("§r§4Pusher");
pusherx.setItemMeta(pusherm);
addRandomItem(trap,granade,pusherx);
Bukkit.broadcastMessage("§6[NyanFighters] §a Neue Special-Items wurden ausgeteilt!");
}
if (time == 300) {
Nyanfighters.getInstance().setNoMove(true);
Bukkit.broadcastMessage("§6[NyanFighters] §45");
} else if (time == 299) {
Bukkit.broadcastMessage("§6[NyanFighters] §c4");
} else if (time == 298) {
Bukkit.broadcastMessage("§6[NyanFighters] §63");
} else if (time == 297) {
Bukkit.broadcastMessage("§6[NyanFighters] §e2");
} else if (time == 296) {
Bukkit.broadcastMessage("§6[NyanFighters] §a1");
} else if (time == 295) {
Bukkit.broadcastMessage("§6[NyanFighters] §dGO!");
Nyanfighters.getInstance().setNoMove(false);
Nyanfighters.getInstance().setGame(true);
}else if (time == 60) {
Bukkit.broadcastMessage("§6[NyanFighters] §bNoch 60 Sekunden");
} else if (time == 30) {
Bukkit.broadcastMessage("§6[NyanFighters] §bNoch 30 Sekunden");
} else if (time == 15) {
Bukkit.broadcastMessage("§6[NyanFighters] §bNoch 15 Sekunden");
}
else if (time <= 0)
{
time = 11;
FileConfiguration statsConfi = Nyanfighters.getInstance().getStatsConfi();
ConfigurationSection section = statsConfi.getConfigurationSection("");
int kills = -1;
int deaths = -1;
String winner="";
for(String l:section.getKeys(false))
{
if(statsConfi.isSet(l+".Kills"))
{
if(statsConfi.getInt(l+".Kills")>kills)
{
kills=statsConfi.getInt(l+".Kills");
deaths=statsConfi.getInt(l+".Deaths");
winner= l;
}
else if(statsConfi.getInt(l+".Kills")==kills)
{
if(statsConfi.isSet(l+".Deaths"))
{
if(statsConfi.getInt(l+".Deaths")<deaths)
{
kills=statsConfi.getInt(l+".Kills");
deaths=statsConfi.getInt(l+".Deaths");
winner= l;
}
else if(deaths==-1)
{
kills=statsConfi.getInt(l+".Kills");
deaths=statsConfi.getInt(l+".Deaths");
winner= l;
}
}
else if(deaths==-1)
{
kills=statsConfi.getInt(l+".Kills");
deaths=0;
winner= l;
}
}
}
}
if(Bukkit.getOnlinePlayers().size()==1)
{
for(Player p:Bukkit.getOnlinePlayers())
{
winner=p.getUniqueId().toString();
}
}
if(winner.equals(""))
{
Bukkit.broadcastMessage("§6[NyanFighters] §cUnentschieden!");
}
else
{
Bukkit.broadcastMessage("§6[NyanFighters] §c"+Bukkit.getPlayer(UUID.fromString(winner)).getName()+" §9hat gewonnen!");
}
Nyanfighters.getInstance().setGame(false);
Bukkit.getScheduler().cancelTask(id);
serverRestart();
} else if (time%60 == 0) {
Bukkit.broadcastMessage("§6[NyanFighters] §bNoch " + time / 60 + " Minuten");
}
time
for(String p: JoinListener.getCP())
{
ScoreboardUtil.updateScoreboard(Bukkit.getPlayer(UUID.fromString(p)));
}
}
}, 20, 20L );
}
public static void serverRestart() //Ende Ablauf
{
for(Player p: Bukkit.getOnlinePlayers())
{
p.teleport(YmlMethods.getLobbySpawn());
p.getInventory().clear();
p.setAllowFlight(false);
}
for(Player p: Bukkit.getOnlinePlayers())
{
for(String f: JoinListener.getCP())
{
if(!p.getUniqueId().toString().equals(f))
{
Bukkit.getPlayer(UUID.fromString(f)).hidePlayer(p);
}
}
if(!JoinListener.getCP().contains(p.getUniqueId().toString()))
{
p.setFlying(false);
p.setAllowFlight(false);
}
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(Nyanfighters.getInstance(), new Runnable() {
@Override
public void run() {
if(time==10)
{
Bukkit.broadcastMessage("§6[NyanFighters] §cServer restartet in 10 Sekunden");
}
else if (time==0)
{
//Bukkit.getServer().reload();
Bukkit.broadcastMessage("§4Hier würde der Server jetzt reloaden");
}
time
}
}, 20, 20L);
}
public static void addRandomItem(ItemStack trap, ItemStack granade, ItemStack pusher)
{
for(String p:JoinListener.getCP()) {
double random = Math.random() * 3;
if (random < 1) {
Bukkit.getPlayer(UUID.fromString(p)).getInventory().addItem(trap);
} else if (random < 2) {
Bukkit.getPlayer(UUID.fromString(p)).getInventory().addItem(granade);
} else {
Bukkit.getPlayer(UUID.fromString(p)).getInventory().addItem(pusher);
Bukkit.getPlayer(UUID.fromString(p)).getInventory().addItem(new ItemStack(Material.ENDER_PEARL));
}
}
}
public static void setTime(int i)
{
time=i;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.