answer
stringlengths
17
10.2M
package io.openshift.booster; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.StaticHandler; import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE; public class HttpApplication extends AbstractVerticle { protected static final String template = "Hello from something, %s!"; @Override public void start(Future<Void> future) { // Create a router object. Router router = Router.router(vertx); router.get("/api/greeting").handler(this::greeting);
package soot.jimple.toolkits.ide.icfg; import java.util.List; import soot.Body; import soot.SootMethod; import soot.Unit; import soot.toolkits.graph.DirectedGraph; /** * A {@link JimpleBasedInterproceduralCFG} which also supports the computation * of predecessors. */ public class JimpleBasedBiDiICFG extends JimpleBasedInterproceduralCFG implements BiDiInterproceduralCFG<Unit,SootMethod> { public List<Unit> getPredsOf(Unit u) { assert u != null; Body body = unitToOwner.get(u); DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body); return unitGraph.getPredsOf(u); } }
package mb.spectrum.view; import static mb.spectrum.Utils.map; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ddf.minim.analysis.FFT; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import mb.spectrum.ConfigService; import mb.spectrum.UiUtils; import mb.spectrum.Utils; public abstract class AbstractSpectrumView extends AbstractMixedChannelView { protected static final int MIN_DB_VALUE = -100; private static final int FREQ_LINE_PER_BAR_COUNT = 5; private static final int DB_LINES_COUNT = 4; private static final double GRID_LABELS_MARGIN_RATIO = 0.1; private static final int BAND_DROP_RATE_DB = 2; private static final double LINGER_STAY_FACTOR = 0.01; private static final double LINGER_ACCELARATION_FACTOR = 1.08; // Configurable properties private static final int SAMPLING_RATE = Integer.valueOf( ConfigService.getInstance().getProperty("mb.spectrum.sampling-rate")); private static final int BUFFER_SIZE = Integer.valueOf( ConfigService.getInstance().getProperty("mb.spectrum.buffer-size")); private SimpleObjectProperty<Color> propGridColor; private List<Line> vLines, hLines; private List<Label> vLabels, hLabels; private FFT fft; // Operational properties protected List<SimpleDoubleProperty> bandValues; protected List<SimpleDoubleProperty> trailValues; protected int bandCount; private double[] bandValuesDB, trailValuesDB; private double[] trailOpValues; @Override public List<ObjectProperty<? extends Object>> getProperties() { return Arrays.asList(propGridColor); } @Override protected void initProperties() { propGridColor = new SimpleObjectProperty<>(null, "Grid Color", Color.web("#fd4a11")); bandValues = new ArrayList<>(); trailValues = new ArrayList<>(); } @Override protected List<Node> collectNodes() { vLines = new ArrayList<>(); hLines = new ArrayList<>(); vLabels = new ArrayList<>(); hLabels = new ArrayList<>(); // Get number of bands fft = new FFT(BUFFER_SIZE, SAMPLING_RATE); fft.logAverages(22, 3); bandCount = fft.avgSize(); bandValuesDB = new double[bandCount]; Arrays.fill(bandValuesDB, MIN_DB_VALUE); for (int i = 0; i < bandCount; i++) { bandValues.add(new SimpleDoubleProperty(MIN_DB_VALUE)); } trailValuesDB = new double[bandCount]; Arrays.fill(trailValuesDB, MIN_DB_VALUE); for (int i = 0; i < bandCount; i++) { trailValues.add(new SimpleDoubleProperty(MIN_DB_VALUE)); } trailOpValues = new double[bandCount]; Arrays.fill(trailOpValues, LINGER_STAY_FACTOR); for (int i = 0; i < bandCount; i++) { // Create grid lines and labels if(i % FREQ_LINE_PER_BAR_COUNT == 0) { createHzLineAndLabel(i, Math.round(fft.getAverageCenterFrequency(i) - fft.getAverageBandWidth(i) / 2)); } else if(i == bandCount - 1) { createHzLineAndLabel(i + 1, Math.round(fft.getAverageCenterFrequency(i + 1) - fft.getAverageBandWidth(i + 1) / 2)); } } // DB lines and labels (horizontal) for (int i = 0; i <= DB_LINES_COUNT; i++) { createDbGridLineAndLabel(i); } List<Node> shapes = new ArrayList<>(); shapes.addAll(vLines); shapes.addAll(vLabels); shapes.addAll(hLines); shapes.addAll(hLabels); return shapes; } @Override public void dataAvailable(float[] data) { // Perform forward FFT fft.forward(data); // Update band values for (int i = 0; i < bandCount; i++) { double bandDB = Utils.toDB(fft.getAvg(i), fft.timeSize()); bandDB = bandDB < MIN_DB_VALUE ? MIN_DB_VALUE : bandDB; if(bandDB > bandValuesDB[i]) { bandValuesDB[i] = bandDB; } } } @Override public void nextFrame() { for (int i = 0; i < bandValuesDB.length; i++) { bandValues.get(i).set(bandValuesDB[i]); // Curve drop if(bandValuesDB[i] > MIN_DB_VALUE) { bandValuesDB[i] -= BAND_DROP_RATE_DB; bandValuesDB[i] = bandValuesDB[i] < MIN_DB_VALUE ? MIN_DB_VALUE : bandValuesDB[i]; } // Trail drop trailValuesDB[i] = trailValuesDB[i] - trailOpValues[i]; trailOpValues[i] = trailOpValues[i] * LINGER_ACCELARATION_FACTOR; if(bandValuesDB[i] > trailValuesDB[i]) { trailValuesDB[i] = bandValuesDB[i]; trailOpValues[i] = LINGER_STAY_FACTOR; } if(trailValuesDB[i] < MIN_DB_VALUE) { trailValuesDB[i] = MIN_DB_VALUE; } trailValues.get(i).set(trailValuesDB[i]); } } private void createHzLineAndLabel(int barIdx, int hz) { // Create line Line line = new Line(); line.startXProperty().bind(Bindings.createDoubleBinding( () -> { double parentWidth = getRoot().widthProperty().get(); double barW = (parentWidth - parentWidth * SCENE_MARGIN_RATIO * 2) / bandCount; return parentWidth * SCENE_MARGIN_RATIO + barIdx * barW; }, getRoot().widthProperty())); line.endXProperty().bind(line.startXProperty()); line.startYProperty().bind(getRoot().heightProperty().multiply(SCENE_MARGIN_RATIO)); line.endYProperty().bind(getRoot().heightProperty().subtract( getRoot().heightProperty().multiply(SCENE_MARGIN_RATIO))); line.strokeProperty().bind(propGridColor); line.getStrokeDashArray().addAll(2d); line.setCache(true); vLines.add(line); // Create label Label label = UiUtils.createLabel(hz + "Hz", vLabels); label.layoutXProperty().bind( line.startXProperty().subtract( label.widthProperty().divide(2))); label.layoutYProperty().bind(line.endYProperty().add(label.heightProperty().multiply(GRID_LABELS_MARGIN_RATIO))); label.textFillProperty().bind(propGridColor); label.styleProperty().bind(Bindings.concat( "-fx-font-size: ", Bindings.createDoubleBinding( () -> (getRoot().widthProperty().get() * SCENE_MARGIN_RATIO) / 4, getRoot().widthProperty()))); } private void createDbGridLineAndLabel(int idx) { double dBVal = map(idx, 0, DB_LINES_COUNT, MIN_DB_VALUE, 0); // Create line Line line = new Line(); line.startXProperty().bind(getRoot().widthProperty().multiply(SCENE_MARGIN_RATIO)); line.endXProperty().bind(getRoot().widthProperty().subtract( getRoot().widthProperty().multiply(SCENE_MARGIN_RATIO))); line.startYProperty().bind( Bindings.createDoubleBinding(() -> { double parentHeigth = getRoot().heightProperty().get(); return map(dBVal, MIN_DB_VALUE, 0, parentHeigth - parentHeigth * SCENE_MARGIN_RATIO, parentHeigth * SCENE_MARGIN_RATIO); }, getRoot().heightProperty())); line.endYProperty().bind(line.startYProperty()); line.strokeProperty().bind(propGridColor); line.getStrokeDashArray().addAll(2d); line.setCache(true); hLines.add(line); // Create label Label label = UiUtils.createLabel(Math.round(dBVal) + "dB", hLabels); label.layoutXProperty().bind( line.startXProperty().subtract( label.widthProperty().add( label.widthProperty().multiply(GRID_LABELS_MARGIN_RATIO)))); label.layoutYProperty().bind(line.startYProperty().subtract(label.heightProperty().divide(2))); label.textFillProperty().bind(propGridColor); label.styleProperty().bind(Bindings.concat( "-fx-font-size: ", Bindings.createDoubleBinding( () -> (getRoot().widthProperty().get() * SCENE_MARGIN_RATIO) / 4, getRoot().widthProperty()))); } @Override public void onShow() { } @Override public void onHide() { } }
package land.face.strife.util; import com.tealcube.minecraft.bukkit.shade.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import land.face.strife.StrifePlugin; import land.face.strife.data.StrifeMob; import land.face.strife.data.champion.Champion; import land.face.strife.data.champion.LifeSkillType; import land.face.strife.data.conditions.Condition; import land.face.strife.data.conditions.Condition.CompareTarget; import land.face.strife.data.conditions.Condition.Comparison; import land.face.strife.data.conditions.Condition.ConditionUser; import land.face.strife.listeners.SwingListener; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; import me.libraryaddict.disguise.disguisetypes.MiscDisguise; import me.libraryaddict.disguise.disguisetypes.MobDisguise; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import me.libraryaddict.disguise.disguisetypes.RabbitType; import me.libraryaddict.disguise.disguisetypes.watchers.AgeableWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.DroppedItemWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.FoxWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.MushroomCowWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.RabbitWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.SheepWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.SlimeWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.SnowmanWatcher; import me.libraryaddict.disguise.disguisetypes.watchers.ZombieWatcher; import net.minecraft.server.v1_15_R1.PacketPlayOutAnimation; import org.bukkit.Bukkit; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.attribute.Attribute; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.craftbukkit.v1_15_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_15_R1.entity.CraftPlayer; import org.bukkit.entity.EntityType; import org.bukkit.entity.Fox; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.MushroomCow.Variant; import org.bukkit.entity.Player; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; public class PlayerDataUtil { private static Map<UUID, Set<Player>> NEARBY_PLAYER_CACHE = new HashMap<>(); public static void restoreHealth(LivingEntity le, double amount) { le.setHealth(Math.min(le.getHealth() + amount, le.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue())); } public static void restoreEnergy(LivingEntity le, float amount) { if (le instanceof Player) { StrifePlugin.getInstance().getEnergyManager().changeEnergy((Player) le, amount); } } public static void restoreHealthOverTime(LivingEntity le, float amount, int ticks) { if (le instanceof Player) { StrifePlugin.getInstance().getRegenTask().addHealing(le.getUniqueId(), amount, ticks); } } public static void restoreEnergyOverTime(LivingEntity le, float amount, int ticks) { if (le instanceof Player) { StrifePlugin.getInstance().getEnergyRegenTask().addEnergy(le.getUniqueId(), amount, ticks); } } public static void swingHand(LivingEntity entity, EquipmentSlot slot, long delay) { if (delay == 0) { swing(entity, slot); return; } Bukkit.getScheduler() .runTaskLater(StrifePlugin.getInstance(), () -> swing(entity, slot), delay); } private static void swing(LivingEntity entity, EquipmentSlot slot) { int swingSlot; if (slot == EquipmentSlot.HAND) { entity.swingMainHand(); swingSlot = 0; } else { entity.swingOffHand(); swingSlot = 3; } if (entity instanceof Player) { SwingListener.addFakeSwing(entity.getUniqueId()); Player targetPlayer = (Player) entity; PacketPlayOutAnimation animationPacket = new PacketPlayOutAnimation( ((CraftEntity) targetPlayer).getHandle(), swingSlot); ((CraftPlayer) targetPlayer).getHandle().playerConnection.sendPacket(animationPacket); } } public static Set<Player> getCachedNearbyPlayers(LivingEntity le) { if (NEARBY_PLAYER_CACHE.containsKey(le.getUniqueId())) { return NEARBY_PLAYER_CACHE.get(le.getUniqueId()); } Set<Player> players = new HashSet<>(); for (org.bukkit.entity.Entity entity : le.getWorld() .getNearbyEntities(le.getLocation(), 40, 40, 40, entity -> entity instanceof Player)) { players.add((Player) entity); } NEARBY_PLAYER_CACHE.put(le.getUniqueId(), players); return players; } public static void clearNearbyPlayerCache() { NEARBY_PLAYER_CACHE.clear(); } public static Disguise parseDisguise(ConfigurationSection section, String name, boolean dynamic) { if (section == null) { return null; } String disguiseType = section.getString("type", null); if (StringUtils.isBlank(disguiseType)) { return null; } DisguiseType type; try { type = DisguiseType.valueOf(disguiseType); } catch (Exception e) { Bukkit.getLogger().warning("Invalid disguise type " + disguiseType + " for " + name); return null; } if (type == DisguiseType.PLAYER) { String disguisePlayer = section.getString("disguise-player"); if (StringUtils.isBlank(disguisePlayer)) { disguisePlayer = "Pur3p0w3r"; } PlayerDisguise playerDisguise = new PlayerDisguise(name, disguisePlayer); playerDisguise.setReplaceSounds(true); playerDisguise.setName("<Inherit>"); playerDisguise.setDynamicName(dynamic); return playerDisguise; } if (type.isMob()) { String typeData = section.getString("disguise-type-data", ""); boolean babyData = section.getBoolean("baby", false); MobDisguise mobDisguise = new MobDisguise(type); if (StringUtils.isNotBlank(typeData)) { FlagWatcher watcher = mobDisguise.getWatcher(); if (watcher instanceof AgeableWatcher) { ((AgeableWatcher) watcher).setBaby(babyData); } try { switch (type) { case MUSHROOM_COW: if (typeData.toUpperCase().equals("BROWN")) { ((MushroomCowWatcher) watcher).setVariant(Variant.BROWN); } else { ((MushroomCowWatcher) watcher).setVariant(Variant.RED); } break; case FOX: Fox.Type foxType = Fox.Type.valueOf(typeData); ((FoxWatcher) watcher).setType(foxType); break; case SHEEP: DyeColor color = DyeColor.valueOf(typeData.toUpperCase()); ((SheepWatcher) watcher).setColor(color); break; case RABBIT: RabbitType rabbitType = RabbitType.valueOf(typeData); ((RabbitWatcher) watcher).setType(rabbitType); break; case ZOMBIE: ((ZombieWatcher) watcher).setBaby(babyData); break; case SLIME: ((SlimeWatcher) watcher).setSize(Integer.parseInt(typeData)); break; case SNOWMAN: ((SnowmanWatcher) watcher).setDerp(Boolean.parseBoolean(typeData)); break; } } catch (Exception e) { LogUtil.printWarning("Cannot load type " + typeData + " for " + name); } } mobDisguise.setReplaceSounds(true); return mobDisguise; } if (type.isMisc()) { MiscDisguise miscDisguise = new MiscDisguise(type); miscDisguise.setReplaceSounds(true); FlagWatcher watcher = miscDisguise.getWatcher(); try { if (type == DisguiseType.DROPPED_ITEM) { Material material = Material.valueOf(section.getString("material", "STONE")); ItemStack stack = new ItemStack(material); if (material == Material.PLAYER_HEAD) { String base64 = section.getString("base64", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTIyODRlMTMyYmZkNjU5YmM2YWRhNDk3YzRmYTMwOTRjZDkzMjMxYTZiNTA1YTEyY2U3Y2Q1MTM1YmE4ZmY5MyJ9fX0="); stack = ItemUtil.withBase64(stack, base64); } ((DroppedItemWatcher) watcher).setItemStack(stack); } } catch (Exception e) { LogUtil.printWarning("Cannot load data for " + name); } return miscDisguise; } return null; } public static boolean areConditionsMet(StrifeMob caster, StrifeMob target, Set<Condition> conditions) { for (Condition condition : conditions) { EntityType casterType = caster.getEntity().getType(); if (casterType == EntityType.PLAYER && condition.getConditionUser() == ConditionUser.MOB) { continue; } if (casterType != EntityType.PLAYER && condition.getConditionUser() == ConditionUser.PLAYER) { continue; } if (target == null) { if (condition.getCompareTarget() == CompareTarget.OTHER) { LogUtil.printDebug("-- Skipping " + condition + " - null target, OTHER compareTarget"); continue; } } if (condition.isMet(caster, target) == condition.isInverted()) { LogUtil.printDebug("-- Skipping, condition " + condition + " not met!"); return false; } } return true; } public static void updatePlayerEquipment(Player player) { StrifePlugin.getInstance().getChampionManager().updateEquipmentStats( StrifePlugin.getInstance().getChampionManager().getChampion(player)); } public static void playExpSound(Player player) { player.playSound(player.getEyeLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 0.2f, 0.8f + (float) Math.random() * 0.4f); } // TODO: Something less stupid, this shouldn't be in this Util public static boolean conditionCompare(Comparison comparison, double val1, double val2) { switch (comparison) { case GREATER_THAN: return val1 > val2; case LESS_THAN: return val1 < val2; case EQUAL: return val1 == val2; case NONE: throw new IllegalArgumentException("Compare condition is NONE! Invalid usage!"); } return false; } public static int getMaxItemDestroyLevel(Player player) { return getMaxItemDestroyLevel( StrifePlugin.getInstance().getChampionManager().getChampion(player) .getLifeSkillLevel(LifeSkillType.CRAFTING)); } private static int getMaxItemDestroyLevel(int craftLvl) { return 10 + (int) Math.floor((double) craftLvl / 3) * 5; } public static int getMaxCraftItemLevel(Player player) { return getMaxCraftItemLevel( StrifePlugin.getInstance().getChampionManager().getChampion(player) .getLifeSkillLevel(LifeSkillType.CRAFTING)); } public static int getMaxCraftItemLevel(int craftLvl) { return 5 + (int) Math.floor((double) craftLvl / 5) * 8; } public static String getName(LivingEntity livingEntity) { if (livingEntity instanceof Player) { return ((Player) livingEntity).getDisplayName(); } return livingEntity.getCustomName() == null ? livingEntity.getName() : livingEntity.getCustomName(); } public static double getEffectiveLifeSkill(Player player, LifeSkillType type, Boolean updateEquipment) { return getEffectiveLifeSkill( StrifePlugin.getInstance().getChampionManager().getChampion(player), type, updateEquipment); } public static double getEffectiveLifeSkill(Champion champion, LifeSkillType type, Boolean updateEquipment) { return champion.getEffectiveLifeSkillLevel(type, updateEquipment); } public static int getLifeSkillLevel(Player player, LifeSkillType type) { return getLifeSkillLevel(StrifePlugin.getInstance().getChampionManager() .getChampion(player), type); } public static int getLifeSkillLevel(Champion champion, LifeSkillType type) { return champion.getLifeSkillLevel(type); } public static int getTotalSkillLevel(Player player) { int amount = 0; Champion champion = StrifePlugin.getInstance().getChampionManager().getChampion(player); for (LifeSkillType type : LifeSkillType.types) { amount += champion.getLifeSkillLevel(type); } return amount; } public static float getLifeSkillExp(Player player, LifeSkillType type) { return StrifePlugin.getInstance().getChampionManager().getChampion(player) .getLifeSkillExp(type); } public static float getLifeSkillExp(Champion champion, LifeSkillType type) { return champion.getLifeSkillExp(type); } public static float getLifeSkillMaxExp(Player player, LifeSkillType type) { int level = StrifePlugin.getInstance().getChampionManager().getChampion(player) .getLifeSkillLevel(type); return StrifePlugin.getInstance().getSkillExperienceManager().getMaxExp(type, level); } public static float getLifeSkillMaxExp(Champion champion, LifeSkillType type) { int level = champion.getLifeSkillLevel(type); return StrifePlugin.getInstance().getSkillExperienceManager().getMaxExp(type, level); } public static float getSkillProgress(Champion champion, LifeSkillType type) { return champion.getSaveData().getSkillExp(type) / StrifePlugin.getInstance() .getSkillExperienceManager().getMaxExp(type, champion.getSaveData().getSkillLevel(type)); } }
package com.intellij.util.xml.stubs; import com.intellij.openapi.fileTypes.PlainTextLanguage; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet; import com.intellij.psi.stubs.*; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.xml.XmlFile; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomElementVisitor; import com.intellij.util.xml.XmlName; import com.intellij.util.xml.impl.DomFileElementImpl; import com.intellij.util.xml.impl.DomInvocationHandler; import com.intellij.util.xmlb.JDOMXIncluder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; public class XIncludeStub extends ObjectStubBase<ElementStub> { private final String myHref; private final String myXpointer; private volatile CachedValue<DomElement> myCachedValue; public XIncludeStub(ElementStub parent, @Nullable String href, @Nullable String xpointer) { super(parent); myHref = href; myXpointer = xpointer; parent.addChild(this); } @NotNull @Override public List<? extends Stub> getChildrenStubs() { return Collections.emptyList(); } @Override public ObjectStubSerializer getStubType() { return ourSerializer; } public void resolve(DomInvocationHandler parent, List<DomElement> included, XmlName xmlName) { XmlFile file = parent.getFile(); if (myCachedValue == null) { myCachedValue = CachedValuesManager.getManager(file.getProject()).createCachedValue(() -> { DomElement result = computeValue(parent); return CachedValueProvider.Result.create(result, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); }); } DomElement rootElement = myCachedValue.getValue(); if (rootElement != null) { rootElement.acceptChildren(element -> { if (element.getXmlElementName().equals(xmlName.getLocalName())) { included.add(element); } }); } } @Nullable private DomElement computeValue(DomInvocationHandler parent) { if (StringUtil.isEmpty(myHref) || StringUtil.isEmpty(myXpointer)) { return null; } Matcher matcher = JDOMXIncluder.XPOINTER_PATTERN.matcher(myXpointer); if (!matcher.matches()) { return null; } String group = matcher.group(1); matcher = JDOMXIncluder.CHILDREN_PATTERN.matcher(group); if (!matcher.matches()) { return null; } String tagName = matcher.group(1); XmlFile file = parent.getFile(); PsiFileImpl dummy = (PsiFileImpl)PsiFileFactory.getInstance(file.getProject()).createFileFromText(PlainTextLanguage.INSTANCE, myHref); dummy.setOriginalFile(file); PsiFileSystemItem fileSystemItem = new FileReferenceSet(dummy).resolve(); if (fileSystemItem instanceof XmlFile) { DomFileElementImpl<DomElement> element = parent.getManager().getFileElement((XmlFile)fileSystemItem); if (element != null) { DomElement result = element.getRootElement(); if (result != null && tagName.equals(result.getXmlElementName())) { return result; } } } return null; } @Override public String toString() { return "href=" + myHref + " xpointer=" + myXpointer; } final static ObjectStubSerializer ourSerializer = new ObjectStubSerializer<XIncludeStub, ElementStub>() { @NotNull @Override public String getExternalId() { return "XIncludeStub"; } @Override public void serialize(@NotNull XIncludeStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeUTFFast(StringUtil.notNullize(stub.myHref)); dataStream.writeUTFFast(StringUtil.notNullize(stub.myXpointer)); } @NotNull @Override public XIncludeStub deserialize(@NotNull StubInputStream dataStream, ElementStub parentStub) throws IOException { return new XIncludeStub(parentStub, dataStream.readUTFFast(), dataStream.readUTFFast()); } @Override public void indexStub(@NotNull XIncludeStub stub, @NotNull IndexSink sink) { } @Override public String toString() { return "XInclide"; } }; }
package com.hankcs.hanlp.summary; import com.hankcs.hanlp.algorithm.MaxHeap; import com.hankcs.hanlp.seg.Segment; import com.hankcs.hanlp.seg.common.Term; import java.util.*; /** * TextRank * * @author hankcs */ public class TextRankKeyword extends KeywordExtractor { /** * 0.85 */ final static float d = 0.85f; public static int max_iter = 200; final static float min_diff = 0.001f; public TextRankKeyword(Segment defaultSegment) { super(defaultSegment); } public TextRankKeyword() { } /** * * * @param document * @param size * @return */ public static List<String> getKeywordList(String document, int size) { TextRankKeyword textRankKeyword = new TextRankKeyword(); return textRankKeyword.getKeywords(document, size); } /** * * * @param content * @return * @deprecated {@link KeywordExtractor#getKeywords(java.lang.String)} */ public List<String> getKeyword(String content) { return getKeywords(content); } /** * rank * * @param content * @return */ public Map<String, Float> getTermAndRank(String content) { assert content != null; List<Term> termList = defaultSegment.seg(content); return getTermAndRank(termList); } /** * sizerank * * @param content * @param size * @return */ public Map<String, Float> getTermAndRank(String content, int size) { Map<String, Float> map = getTermAndRank(content); Map<String, Float> result = top(size, map); return result; } private Map<String, Float> top(int size, Map<String, Float> map) { Map<String, Float> result = new LinkedHashMap<String, Float>(); for (Map.Entry<String, Float> entry : new MaxHeap<Map.Entry<String, Float>>(size, new Comparator<Map.Entry<String, Float>>() { @Override public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) { return o1.getValue().compareTo(o2.getValue()); } }).addAll(map.entrySet()).toList()) { result.put(entry.getKey(), entry.getValue()); } return result; } /** * rank * * @param termList * @return */ public Map<String, Float> getTermAndRank(List<Term> termList) { List<String> wordList = new ArrayList<String>(termList.size()); for (Term t : termList) { if (shouldInclude(t)) { wordList.add(t.word); } } // System.out.println(wordList); Map<String, Set<String>> words = new TreeMap<String, Set<String>>(); Queue<String> que = new LinkedList<String>(); for (String w : wordList) { if (!words.containsKey(w)) { words.put(w, new TreeSet<String>()); } // O(n-1) if (que.size() >= 5) { que.poll(); } for (String qWord : que) { if (w.equals(qWord)) { continue; } words.get(w).add(qWord); words.get(qWord).add(w); } que.offer(w); } // System.out.println(words); Map<String, Float> score = new HashMap<String, Float>(); for (Map.Entry<String, Set<String>> entry : words.entrySet()) { score.put(entry.getKey(), sigMoid(entry.getValue().size())); } for (int i = 0; i < max_iter; ++i) { Map<String, Float> m = new HashMap<String, Float>(); float max_diff = 0; for (Map.Entry<String, Set<String>> entry : words.entrySet()) { String key = entry.getKey(); Set<String> value = entry.getValue(); m.put(key, 1 - d); for (String element : value) { int size = words.get(element).size(); if (key.equals(element) || size == 0) continue; m.put(key, m.get(key) + d / size * (score.get(element) == null ? 0 : score.get(element))); } max_diff = Math.max(max_diff, Math.abs(m.get(key) - (score.get(key) == null ? 0 : score.get(key)))); } score = m; if (max_diff <= min_diff) break; } return score; } /** * sigmoid * * @param value * @return */ public static float sigMoid(float value) { return (float) (1d / (1d + Math.exp(-value))); } @Override public List<String> getKeywords(List<Term> termList, int size) { Set<Map.Entry<String, Float>> entrySet = top(size, getTermAndRank(termList)).entrySet(); List<String> result = new ArrayList<String>(entrySet.size()); for (Map.Entry<String, Float> entry : entrySet) { result.add(entry.getKey()); } return result; } }
package org.usfirst.frc.team2506.robot; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.Ultrasonic; public class AutonomousGear { // target distance from goal static final double GEAR_RANGE_INCHES = 2.5; // robot motor speed static final double ROBOT_SPEED = 0.5; private enum AutonomousStates { MovingForward, End } private static AutonomousStates autonomousState = AutonomousStates.MovingForward; private static ADXRS450_Gyro gyro; private static SwerveDrive driveTrain; private static Ultrasonic ultrasonic; // method that copies the funcionality of a constructor public static void init(ADXRS450_Gyro gyro, SwerveDrive drive, Ultrasonic ultrasonic) { AutonomousGear.gyro = gyro; driveTrain = drive; AutonomousGear.ultrasonic = ultrasonic; } public static void run() { switch (autonomousState) { case MovingForward: // drives the robot while it is farther than GEAR_RANGE_INCHES away from the goal, then stops if (ultrasonic.getRangeInches() > GEAR_RANGE_INCHES) { driveTrain.drive(gyro, ROBOT_SPEED, 0, 0); } else { driveTrain.drive(gyro, 0, 0, 0); autonomousState = AutonomousStates.End; } break; } } }
package me.legrange.panstamp; import me.legrange.panstamp.event.AbstractRegisterListener; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import me.legrange.panstamp.definition.EndpointDefinition; import me.legrange.panstamp.definition.Unit; abstract class AbstractEndpoint<T> implements Endpoint<T> { @Override public String getName() { return epDef.getName(); } @Override public final List<String> getUnits() { List<String> res = new LinkedList<>(); for (Unit u : epDef.getUnits()) { res.add(u.getName()); } return res; } @Override public String getUnit() { return (unit != null) ? unit.getName() : ""; } @Override public void setUnit(String unit) throws NoSuchUnitException { unit = (unit != null) ? unit.trim() : ""; this.unit = unit.isEmpty() ? getUnit(unit) : null; } @Override public final boolean hasValue() { return reg.hasValue(); } @Override public synchronized void addListener(EndpointListener<T> el) { listeners.add(el); } @Override public synchronized void removeListener(EndpointListener<T> el) { listeners.remove(el); } @Override public final T getValue() throws NetworkException { return read(unit); } @Override public final void setValue(T value) throws NetworkException { write(unit, value); } @Override public final T getValue(String unit) throws NetworkException { return read(getUnit(unit)); } @Override public final void setValue(String unit, T value) throws NetworkException { write(getUnit(unit), value); } @Override public Register getRegister() { return reg; } /** * Write and transform the output value from a value in the given unit * * @param value The value to transform * @param unit The unit from which to transform it */ protected abstract void write(Unit unit, T value) throws NetworkException; /** * Read and transform the input value to a value in the given unit * * @param value The value to transform * @param unit The unit to which to transform it * @return The transformed value */ protected abstract T read(Unit unit) throws NetworkException; protected final Unit getUnit(String name) throws NoSuchUnitException { for (Unit u : epDef.getUnits()) { if (u.getName().equals(name)) { return u; } } throw new NoSuchUnitException(String.format("No unit '%s' found in endpoint '%s'", name, getName())); } protected AbstractEndpoint(Register reg, EndpointDefinition epDef) { this.reg = reg; this.epDef = epDef; this.listeners = new CopyOnWriteArrayList<>(); reg.addListener(new AbstractRegisterListener() { @Override public void valueReceived(final Register reg, final byte[] value) { for (final EndpointListener<T> l : listeners) { pool().submit(new Runnable() { @Override public void run() { try { l.valueReceived(AbstractEndpoint.this, getValue()); } catch (NetworkException ex) { Logger.getLogger(AbstractEndpoint.class.getName()).log(Level.SEVERE, null, ex); } } } ); } } }); unit = !epDef.getUnits().isEmpty() ? epDef.getUnits().get(0) : null; } void destroy() { listeners.clear(); } /** * Get the executor service used to service library threads */ private ExecutorService pool() { return reg.getPool(); } protected final Register reg; protected final EndpointDefinition epDef; private final CopyOnWriteArrayList<EndpointListener<T>> listeners; private Unit unit = null; }
package com.jeffpeng.jmod.scripting; import java.util.ArrayList; import java.util.List; import com.jeffpeng.jmod.JMODLoader; import com.jeffpeng.jmod.Lib; import com.jeffpeng.jmod.actions.*; import com.jeffpeng.jmod.descriptors.*; import com.jeffpeng.jmod.primitives.OwnedObject; import com.jeffpeng.jmod.scripting.mods.*; import com.jeffpeng.jmod.validator.Validator; public class ScriptObject extends OwnedObject { private JScript jscriptInstance; public ScriptObject(JScript jscriptinstance){ super(jscriptinstance.getMod()); jscriptInstance = jscriptinstance; } public Settings Settings = new Settings(owner); public Global Global = new Global(owner); public RotaryCraft RotaryCraft = new RotaryCraft(owner); public Chisel Chisel = new Chisel(owner); public Applecore Applecore = new Applecore(owner); public Sync Sync = new Sync(owner); public ExNihilo ExNihilo = new ExNihilo(owner); public ImmersiveEngineering ImmersiveEngineering = new ImmersiveEngineering(owner); public void loadjs(String script){ jscriptInstance.evalScript(script); } public void log(String msg){ log.info(msg); } public void addShapelessRecipe(String result, Object ingredients){ new AddShapelessRecipe(owner,result, Lib.convertArray(ingredients,String[].class) ); } public AddShapedRecipe addShapedStandardRecipe(String result, String type, String mat){ return new AddShapedRecipe(owner,result, standardShape(type,mat)); } public AddShapedRecipe addShapedRecipe(String result, Object pattern){ return new AddShapedRecipe(owner,result, Lib.convertPattern(pattern)); } public void addSmeltingRecipe(String result, String ingredient){ new AddSmeltingRecipe(owner,result,ingredient); } public AddItem addItem(String name, String refClass,int stackSize,String creativeTab){ return new AddItem(owner, name,refClass,stackSize,creativeTab); } public AddBlock addBlock(String name, String refClass, Float hardness, Float blastresistance, String tool, int harvestlevel, String material, String tab){ return new AddBlock(owner,name,refClass,hardness,blastresistance,tool,harvestlevel,material,tab); } public void testType(Object o){ throw new RuntimeException(o.getClass().getName()); } public void addMetalIngot(String name){ config.metalingots.add(name); } public void addMetalBlock(String name){ config.metalblocks.add(name); } public AddToolMaterial addToolMaterial(String name,int harvestLevel, int durability, float efficiency, float damage, int enchantability, String repairmaterial){ return new AddToolMaterial(owner,name,harvestLevel,durability,efficiency,damage,enchantability,repairmaterial); } public AddArmorMaterial addArmorMaterial(String name,int reductionbase, int helmetfactor, int chestfactor,int leggingsfactor,int bootsfactor,int enchantability,String repairmaterial){ return new AddArmorMaterial(owner,name,reductionbase,helmetfactor,chestfactor,leggingsfactor,bootsfactor,enchantability,repairmaterial); } public void removeRecipes(String target){ new RemoveRecipe(owner,target); } public void removeSmeltingRecipes(String result){ new RemoveSmeltingRecipe(owner,result); } public void hideFromNEI(String target){ if(owner.testForMod("NotEnoughItems")) new HideNEIItem(owner,target); } public TooltipDescriptor addToolTip(String[] target, String[] lines){ TooltipDescriptor newTooltip = new TooltipDescriptor(target,lines); config.tooltips.add(newTooltip); return newTooltip; } public ItemStackSubstituteDescriptor itemStackSubstitute(String source, String target){ ItemStackSubstituteDescriptor newISD = new ItemStackSubstituteDescriptor(source,target); config.itemstacksubstitutes.add(newISD); return newISD; } public AlloyDescriptor addAlloy(String result, String one, String two, int amount){ AlloyDescriptor newAD = new AlloyDescriptor(result,one,two,amount); config.alloymap.add(newAD); return newAD; } public AlloyDescriptor addAlloy(String result, String one, int amount){ AlloyDescriptor newAD = new AlloyDescriptor(result,one,amount); config.alloymap.add(newAD); return newAD; } public void addOreDict(String is, String entry){ new AddOreDictionaryEntry(owner,is,entry); } public void removeOreDict(String is, String entry){ new RemoveOreDictionaryEntry(owner,is, entry); } public void removeOreDict(String is){ new RemoveOreDictionaryEntry(owner,is, null); } public SetBlockProperties setBlockProperties(String item){ return new SetBlockProperties(owner, item); } public void dependency(String modid, String name){ config.moddependencies.put(modid, name); } public ColorDescriptor defineColor(String color, int red, int green, int blue){ ColorDescriptor newColor = new ColorDescriptor(red,green,blue); config.colors.put(color, newColor); return newColor; } public void addChestLoot(String is,int min,int max,int weight){ new AddChestLoot(owner,is,min,max,weight, null); } public void addChestLoot(String is,int min,int max,int weight,String[] targets){ new AddChestLoot(owner,is,min,max,weight, targets); } public void removeChestLoot(String is){ new RemoveChestLoot(owner,is,null); } public void removeChestLoot(String is, String[] targets){ new RemoveChestLoot(owner,is,targets); } public AddBlockDrop addBlockDrop(String block, String itemstack, Integer chance, boolean stopeventchain, boolean playeronly){ AddBlockDrop newBDD = new AddBlockDrop(owner,block, itemstack,chance, stopeventchain,playeronly); config.blockDrops.add(newBDD); return newBDD; } public FoodDataDescriptor FoodData(int hunger, float saturation,boolean wolffood,boolean alwaysEdible){ return new FoodDataDescriptor(owner,hunger,saturation,wolffood,alwaysEdible); } public ToolDataDescriptor ToolData(String toolmat){ return new ToolDataDescriptor(toolmat); } public ArmorDataDescriptor ArmorData(String mat, String type){ return new ArmorDataDescriptor(mat,type); } public void addCreativeTab(String tabId, String tabName, String itemString){ new AddCreativeTab(owner, tabId, tabName, itemString); } public AddOreGeneration addOreGeneration(){ return new AddOreGeneration(owner); } public AddStartingPlatform addStartingPlatform(int baseY, int playerY){ return new AddStartingPlatform(owner,baseY,playerY); } public AddFluid addFluid(String fluidname){ return new AddFluid(owner,fluidname); } public List<String[]> standardShape(String shape, String mat){ List<String[]> pattern = null; if(shape.equals("pickaxe")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{null,"stickWood",null}); pattern.add(new String[]{null,"stickWood",null}); } else if(shape.equals("axe")){ pattern = new ArrayList<>(); pattern.add(new String[]{null,mat,mat}); pattern.add(new String[]{null,"stickWood",mat}); pattern.add(new String[]{null,"stickWood",null}); } else if(shape.equals("shovel")){ pattern = new ArrayList<>(); pattern.add(new String[]{null,mat,null}); pattern.add(new String[]{null,"stickWood",null}); pattern.add(new String[]{null,"stickWood",null}); } else if(shape.equals("sword")){ pattern = new ArrayList<>(); pattern.add(new String[]{null,mat,null}); pattern.add(new String[]{null,mat,null}); pattern.add(new String[]{null,"stickWood",null}); } else if(shape.equals("hoe")){ pattern = new ArrayList<>(); pattern.add(new String[]{null,mat,mat}); pattern.add(new String[]{null,"stickWood",null}); pattern.add(new String[]{null,"stickWood",null}); } else if(shape.equals("helmet")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{mat,null,mat}); pattern.add(new String[]{null,null,null}); } else if(shape.equals("chest") || shape.equals("chestplate")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,null,mat}); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{mat,mat,mat}); } else if(shape.equals("leggings")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{mat,null,mat}); pattern.add(new String[]{mat,null,mat}); } else if(shape.equals("boots")){ pattern = new ArrayList<>(); pattern.add(new String[]{null,null,null}); pattern.add(new String[]{mat,null,mat}); pattern.add(new String[]{mat,null,mat}); } else if(shape.equals("block")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{mat,mat,mat}); pattern.add(new String[]{mat,mat,mat}); } if(shape.equals("smallblock")){ pattern = new ArrayList<>(); pattern.add(new String[]{mat,mat,null}); pattern.add(new String[]{mat,mat,null}); pattern.add(new String[]{null,null,null}); } return pattern; } public boolean isModLoaded(String modid){ return Validator.isValidator || JMODLoader.isModLoaded(modid); } public String getModId(){ return owner.getModId(); } public int celcius(float c){ return Math.round(c + 273.15F); } public int fahrenheit(float f){ return Math.round((f + 459.67F) * (5/9)); } }
package alluxio.master.block; import alluxio.Constants; import alluxio.MasterStorageTierAssoc; import alluxio.StorageTierAssoc; import alluxio.collections.ConcurrentHashSet; import alluxio.collections.IndexedSet; import alluxio.exception.BlockInfoException; import alluxio.exception.ExceptionMessage; import alluxio.exception.NoWorkerException; import alluxio.heartbeat.HeartbeatContext; import alluxio.heartbeat.HeartbeatExecutor; import alluxio.heartbeat.HeartbeatThread; import alluxio.master.AbstractMaster; import alluxio.master.MasterContext; import alluxio.master.block.meta.MasterBlockInfo; import alluxio.master.block.meta.MasterBlockLocation; import alluxio.master.block.meta.MasterWorkerInfo; import alluxio.master.journal.AsyncJournalWriter; import alluxio.master.journal.Journal; import alluxio.master.journal.JournalInputStream; import alluxio.master.journal.JournalOutputStream; import alluxio.master.journal.JournalProtoUtils; import alluxio.proto.journal.Block.BlockContainerIdGeneratorEntry; import alluxio.proto.journal.Block.BlockInfoEntry; import alluxio.proto.journal.Journal.JournalEntry; import alluxio.thrift.BlockMasterClientService; import alluxio.thrift.BlockMasterWorkerService; import alluxio.thrift.Command; import alluxio.thrift.CommandType; import alluxio.util.CommonUtils; import alluxio.util.io.PathUtils; import alluxio.wire.BlockInfo; import alluxio.wire.BlockLocation; import alluxio.wire.WorkerInfo; import alluxio.wire.WorkerNetAddress; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Message; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.thrift.TProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.NotThreadSafe; /** * This master manages the metadata for all the blocks and block workers in Alluxio. */ @NotThreadSafe // TODO(jiri): make thread-safe (c.f. ALLUXIO-1664) public final class BlockMaster extends AbstractMaster implements ContainerIdGenerable { private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE); /** * Concurrency and locking in the BlockMaster * * The block master uses concurrent data structures, to allow non-conflicting concurrent access. * This means each piece of metadata should be locked individually. There are two types of * metadata in the {@link BlockMaster}; {@link MasterBlockInfo} and {@link MasterWorkerInfo}. * Individual objects must be locked before modifying the object, or reading a modifiable field * of an object. This will protect the internal integrity of the metadata object. * * Lock ordering must be preserved in order to prevent deadlock. If both a worker and block * metadata must be locked at the same time, the worker metadata ({@link MasterWorkerInfo}) * must be locked before the block metadata ({@link MasterBlockInfo}). * * It should not be the case that multiple worker metadata must be locked at the same time, or * multiple block metadata must be locked at the same time. Operations involving multiple * workers or multiple blocks should be able to be performed independently. */ // Block metadata management. /** Blocks on all workers, including active and lost blocks. This state must be journaled. */ private final ConcurrentHashMap<Long, MasterBlockInfo> mBlocks = new ConcurrentHashMap<>(8192, 0.75f, 64); /** Keeps track of block which are no longer in Alluxio storage. */ private final ConcurrentHashSet<Long> mLostBlocks = new ConcurrentHashSet<>(); /** This state must be journaled. */ private final BlockContainerIdGenerator mBlockContainerIdGenerator = new BlockContainerIdGenerator(); // Worker metadata management. private final IndexedSet.FieldIndex<MasterWorkerInfo> mIdIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getId(); } }; private final IndexedSet.FieldIndex<MasterWorkerInfo> mAddressIndex = new IndexedSet.FieldIndex<MasterWorkerInfo>() { @Override public Object getFieldValue(MasterWorkerInfo o) { return o.getWorkerAddress(); } }; /** * Mapping between all possible storage level aliases and their ordinal position. This mapping * forms a total ordering on all storage level aliases in the system, and must be consistent * across masters. */ private StorageTierAssoc mGlobalStorageTierAssoc; /** All worker information. */ // This warning cannot be avoided when passing generics into varargs @SuppressWarnings("unchecked") private final IndexedSet<MasterWorkerInfo> mWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** Keeps track of workers which are no longer in communication with the master. */ // This warning cannot be avoided when passing generics into varargs @SuppressWarnings("unchecked") private final IndexedSet<MasterWorkerInfo> mLostWorkers = new IndexedSet<MasterWorkerInfo>(mIdIndex, mAddressIndex); /** * The service that detects lost worker nodes, and tries to restart the failed workers. * We store it here so that it can be accessed from tests. */ @SuppressFBWarnings("URF_UNREAD_FIELD") private Future<?> mLostWorkerDetectionService; /** The next worker id to use. This state must be journaled. */ private final AtomicLong mNextWorkerId = new AtomicLong(1); /** * @param baseDirectory the base journal directory * @return the journal directory for this master */ public static String getJournalDirectory(String baseDirectory) { return PathUtils.concatPath(baseDirectory, Constants.BLOCK_MASTER_NAME); } /** * Creates a new instance of {@link BlockMaster}. * * @param journal the journal to use for tracking master operations */ public BlockMaster(Journal journal) { super(journal, 2); } @Override public Map<String, TProcessor> getServices() { Map<String, TProcessor> services = new HashMap<String, TProcessor>(); services.put( Constants.BLOCK_MASTER_CLIENT_SERVICE_NAME, new BlockMasterClientService.Processor<BlockMasterClientServiceHandler>( new BlockMasterClientServiceHandler(this))); services.put( Constants.BLOCK_MASTER_WORKER_SERVICE_NAME, new BlockMasterWorkerService.Processor<BlockMasterWorkerServiceHandler>( new BlockMasterWorkerServiceHandler(this))); return services; } @Override public String getName() { return Constants.BLOCK_MASTER_NAME; } @Override public void processJournalCheckpoint(JournalInputStream inputStream) throws IOException { // clear state before processing checkpoint. mBlocks.clear(); super.processJournalCheckpoint(inputStream); } @Override public void processJournalEntry(JournalEntry entry) throws IOException { Message innerEntry = JournalProtoUtils.unwrap(entry); // TODO(gene): A better way to process entries besides a huge switch? if (innerEntry instanceof BlockContainerIdGeneratorEntry) { mBlockContainerIdGenerator .setNextContainerId(((BlockContainerIdGeneratorEntry) innerEntry).getNextContainerId()); } else if (innerEntry instanceof BlockInfoEntry) { BlockInfoEntry blockInfoEntry = (BlockInfoEntry) innerEntry; mBlocks.put(blockInfoEntry.getBlockId(), new MasterBlockInfo(blockInfoEntry.getBlockId(), blockInfoEntry.getLength())); } else { throw new IOException(ExceptionMessage.UNEXPECTED_JOURNAL_ENTRY.getMessage(entry)); } } @Override public void streamToJournalCheckpoint(JournalOutputStream outputStream) throws IOException { outputStream.writeEntry(mBlockContainerIdGenerator.toJournalEntry()); for (MasterBlockInfo blockInfo : mBlocks.values()) { BlockInfoEntry blockInfoEntry = BlockInfoEntry.newBuilder().setBlockId(blockInfo.getBlockId()) .setLength(blockInfo.getLength()).build(); outputStream.writeEntry(JournalEntry.newBuilder().setBlockInfo(blockInfoEntry).build()); } } @Override public void start(boolean isLeader) throws IOException { super.start(isLeader); mGlobalStorageTierAssoc = new MasterStorageTierAssoc(MasterContext.getConf()); if (isLeader) { mLostWorkerDetectionService = getExecutorService().submit(new HeartbeatThread( HeartbeatContext.MASTER_LOST_WORKER_DETECTION, new LostWorkerDetectionHeartbeatExecutor(), MasterContext.getConf().getInt(Constants.MASTER_HEARTBEAT_INTERVAL_MS))); } } /** * @return the number of workers */ public int getWorkerCount() { return mWorkers.size(); } /** * @return a list of {@link WorkerInfo} objects representing the workers in Alluxio */ public List<WorkerInfo> getWorkerInfoList() { List<WorkerInfo> workerInfoList = new ArrayList<>(mWorkers.size()); for (MasterWorkerInfo masterWorkerInfo : mWorkers) { synchronized (masterWorkerInfo) { workerInfoList.add(masterWorkerInfo.generateClientWorkerInfo()); } } return workerInfoList; } /** * @return the total capacity (in bytes) on all tiers, on all workers of Alluxio */ public long getCapacityBytes() { long ret = 0; for (MasterWorkerInfo worker : mWorkers) { synchronized (worker) { ret += worker.getCapacityBytes(); } } return ret; } /** * @return the global storage tier mapping */ public StorageTierAssoc getGlobalStorageTierAssoc() { return mGlobalStorageTierAssoc; } /** * @return the total used bytes on all tiers, on all workers of Alluxio */ public long getUsedBytes() { long ret = 0; for (MasterWorkerInfo worker : mWorkers) { synchronized (worker) { ret += worker.getUsedBytes(); } } return ret; } /** * Gets info about the lost workers. * * @return a set of worker info */ public Set<WorkerInfo> getLostWorkersInfo() { Set<WorkerInfo> ret = new HashSet<>(mLostWorkers.size()); for (MasterWorkerInfo worker : mLostWorkers) { synchronized (worker) { ret.add(worker.generateClientWorkerInfo()); } } return ret; } /** * Removes blocks from workers. * * @param blockIds a list of block ids to remove from Alluxio space * @param delete whether to delete blocks metadata in Master */ public void removeBlocks(List<Long> blockIds, boolean delete) { HashSet<Long> workerIds = new HashSet<>(); for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { continue; } workerIds.clear(); synchronized (masterBlockInfo) { // Technically, masterBlockInfo should be confirmed to still be in the data structure. A // concurrent removeBlock call can remove it. However, we are intentionally ignoring this // race, since deleting the same block again is a noop. workerIds.addAll(masterBlockInfo.getWorkers()); // Two cases here: // 1) For delete: delete the block metadata. // 2) For free: keep the block metadata. mLostBlocks will be changed in // processWorkerRemovedBlocks if (delete) { // Make sure blockId is removed from mLostBlocks when the block metadata is deleted. // Otherwise blockId in mLostBlock can be dangling index if the metadata is gone. mLostBlocks.remove(blockId); mBlocks.remove(blockId); } } // Outside of locking the block. This does not have to be synchronized with the block // metadata, since it is essentially an asynchronous signal to the worker to remove the block. for (long workerId : workerIds) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); if (workerInfo != null) { synchronized (workerInfo) { workerInfo.updateToRemovedBlock(true, blockId); } } } } } /** * @return a new block container id */ @Override public long getNewContainerId() { long counter = AsyncJournalWriter.INVALID_FLUSH_COUNTER; long containerId; synchronized (mBlockContainerIdGenerator) { containerId = mBlockContainerIdGenerator.getNewContainerId(); counter = appendJournalEntry(mBlockContainerIdGenerator.toJournalEntry()); } if (counter != AsyncJournalWriter.INVALID_FLUSH_COUNTER) { waitForJournalFlush(counter); } return containerId; } /** * Marks a block as committed on a specific worker. * * @param workerId the worker id committing the block * @param usedBytesOnTier the updated used bytes on the tier of the worker * @param tierAlias the alias of the storage tier where the worker is committing the block to * @param blockId the committing block id * @param length the length of the block */ public void commitBlock(long workerId, long usedBytesOnTier, String tierAlias, long blockId, long length) { LOG.debug("Commit block from workerId: {}, usedBytesOnTier: {}, blockId: {}, length: {}", workerId, usedBytesOnTier, blockId, length); long counter = AsyncJournalWriter.INVALID_FLUSH_COUNTER; MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); // Lock the worker metadata first. synchronized (workerInfo) { // Loop until block metadata is successfully locked. for (;;) { boolean mustInsert = false; MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { // The block metadata doesn't exist yet. masterBlockInfo = new MasterBlockInfo(blockId, length); mustInsert = true; } // Lock the block metadata. synchronized (masterBlockInfo) { if (mustInsert) { if (mBlocks.putIfAbsent(blockId, masterBlockInfo) != null) { // Another thread already inserted the metadata for this block, so start loop over. continue; } // Successfully added the new block metadata. Append a journal entry for the new // metadata. BlockInfoEntry blockInfo = BlockInfoEntry.newBuilder().setBlockId(blockId).setLength(length).build(); counter = appendJournalEntry(JournalEntry.newBuilder().setBlockInfo(blockInfo).build()); } // At this point, both the worker and the block metadata are locked. // Update the block metadata with the new worker location. masterBlockInfo.addWorker(workerId, tierAlias); // This worker has this block, so it is no longer lost. mLostBlocks.remove(blockId); // Update the worker information for this new block. workerInfo.addBlock(blockId); workerInfo.updateUsedBytes(tierAlias, usedBytesOnTier); workerInfo.updateLastUpdatedTimeMs(); } break; } } if (counter != AsyncJournalWriter.INVALID_FLUSH_COUNTER) { waitForJournalFlush(counter); } } /** * Marks a block as committed, but without a worker location. This means the block is only in ufs. * * @param blockId the id of the block to commit * @param length the length of the block */ public void commitBlockInUFS(long blockId, long length) { LOG.debug("Commit block in ufs. blockId: {}, length: {}", blockId, length); if (mBlocks.get(blockId) != null) { // Block metadata already exists, so do not need to create a new one. return; } // The block has not been committed previously, so add the metadata to commit the block. MasterBlockInfo masterBlockInfo = new MasterBlockInfo(blockId, length); long counter = AsyncJournalWriter.INVALID_FLUSH_COUNTER; synchronized (masterBlockInfo) { if (mBlocks.putIfAbsent(blockId, masterBlockInfo) == null) { // Successfully added the new block metadata. Append a journal entry for the new metadata. BlockInfoEntry blockInfo = BlockInfoEntry.newBuilder().setBlockId(blockId).setLength(length).build(); counter = appendJournalEntry(JournalEntry.newBuilder().setBlockInfo(blockInfo).build()); } } if (counter != AsyncJournalWriter.INVALID_FLUSH_COUNTER) { waitForJournalFlush(counter); } } /** * @param blockId the block id to get information for * @return the {@link BlockInfo} for the given block id * @throws BlockInfoException if the block info is not found */ public BlockInfo getBlockInfo(long blockId) throws BlockInfoException { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { throw new BlockInfoException("Block info not found for " + blockId); } synchronized (masterBlockInfo) { return generateBlockInfo(masterBlockInfo); } } /** * Retrieves information for the given list of block ids. * * @param blockIds A list of block ids to retrieve the information for * @return A list of {@link BlockInfo} objects corresponding to the input list of block ids. The * list is in the same order as the input list */ public List<BlockInfo> getBlockInfoList(List<Long> blockIds) { List<BlockInfo> ret = new ArrayList<>(blockIds.size()); for (long blockId : blockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo == null) { continue; } synchronized (masterBlockInfo) { ret.add(generateBlockInfo(masterBlockInfo)); } } return ret; } /** * @return the total bytes on each storage tier */ public Map<String, Long> getTotalBytesOnTiers() { Map<String, Long> ret = new HashMap<>(); for (MasterWorkerInfo worker : mWorkers) { synchronized (worker) { for (Map.Entry<String, Long> entry : worker.getTotalBytesOnTiers().entrySet()) { Long total = ret.get(entry.getKey()); ret.put(entry.getKey(), (total == null ? 0L : total) + entry.getValue()); } } } return ret; } /** * @return the used bytes on each storage tier */ public Map<String, Long> getUsedBytesOnTiers() { Map<String, Long> ret = new HashMap<>(); for (MasterWorkerInfo worker : mWorkers) { synchronized (worker) { for (Map.Entry<String, Long> entry : worker.getUsedBytesOnTiers().entrySet()) { Long used = ret.get(entry.getKey()); ret.put(entry.getKey(), (used == null ? 0L : used) + entry.getValue()); } } } return ret; } /** * Returns a worker id for the given worker. * * @param workerNetAddress the worker {@link WorkerNetAddress} * @return the worker id for this worker */ public long getWorkerId(WorkerNetAddress workerNetAddress) { // TODO(gpang): This NetAddress cloned in case thrift re-uses the object. Does thrift re-use it? MasterWorkerInfo existingWorker = mWorkers.getFirstByField(mAddressIndex, workerNetAddress); if (existingWorker != null) { // This worker address is already mapped to a worker id. long oldWorkerId = existingWorker.getId(); LOG.warn("The worker {} already exists as id {}.", workerNetAddress, oldWorkerId); return oldWorkerId; } MasterWorkerInfo lostWorkerInfo = mLostWorkers.getFirstByField(mAddressIndex, workerNetAddress); if (lostWorkerInfo != null) { // this is one of the lost workers synchronized (lostWorkerInfo) { final long lostWorkerId = lostWorkerInfo.getId(); LOG.warn("A lost worker {} has requested its old id {}.", workerNetAddress, lostWorkerId); // Update the timestamp of the worker before it is considered an active worker. lostWorkerInfo.updateLastUpdatedTimeMs(); mWorkers.add(lostWorkerInfo); mLostWorkers.remove(lostWorkerInfo); return lostWorkerId; } } // Generate a new worker id. long workerId = mNextWorkerId.getAndIncrement(); mWorkers.add(new MasterWorkerInfo(workerId, workerNetAddress)); LOG.info("getWorkerId(): WorkerNetAddress: {} id: {}", workerNetAddress, workerId); return workerId; } /** * Updates metadata when a worker registers with the master. * * @param workerId the worker id of the worker registering * @param storageTiers a list of storage tier aliases in order of their position in the worker's * hierarchy * @param totalBytesOnTiers a mapping from storage tier alias to total bytes * @param usedBytesOnTiers a mapping from storage tier alias to the used byes * @param currentBlocksOnTiers a mapping from storage tier alias to a list of blocks * @throws NoWorkerException if workerId cannot be found */ public void workerRegister(long workerId, List<String> storageTiers, Map<String, Long> totalBytesOnTiers, Map<String, Long> usedBytesOnTiers, Map<String, List<Long>> currentBlocksOnTiers) throws NoWorkerException { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); if (workerInfo == null) { throw new NoWorkerException("Could not find worker id: " + workerId + " to register."); } // Gather all blocks on this worker. HashSet<Long> blocks = new HashSet<>(); for (List<Long> blockIds : currentBlocksOnTiers.values()) { blocks.addAll(blockIds); } synchronized (workerInfo) { workerInfo.updateLastUpdatedTimeMs(); // Detect any lost blocks on this worker. Set<Long> removedBlocks = workerInfo.register(mGlobalStorageTierAssoc, storageTiers, totalBytesOnTiers, usedBytesOnTiers, blocks); processWorkerRemovedBlocks(workerInfo, removedBlocks); processWorkerAddedBlocks(workerInfo, currentBlocksOnTiers); } LOG.info("registerWorker(): {}", workerInfo); } /** * Updates metadata when a worker periodically heartbeats with the master. * * @param workerId the worker id * @param usedBytesOnTiers a mapping from tier alias to the used bytes * @param removedBlockIds a list of block ids removed from this worker * @param addedBlocksOnTiers a mapping from tier alias to the added blocks * @return an optional command for the worker to execute */ public Command workerHeartbeat(long workerId, Map<String, Long> usedBytesOnTiers, List<Long> removedBlockIds, Map<String, List<Long>> addedBlocksOnTiers) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, workerId); if (workerInfo == null) { LOG.warn("Could not find worker id: {} for heartbeat.", workerId); return new Command(CommandType.Register, new ArrayList<Long>()); } synchronized (workerInfo) { // Technically, workerInfo should be confirmed to still be in the data structure. Lost worker // detection can remove it. However, we are intentionally ignoring this race, since the worker // will just re-register regardless. processWorkerRemovedBlocks(workerInfo, removedBlockIds); processWorkerAddedBlocks(workerInfo, addedBlocksOnTiers); workerInfo.updateUsedBytes(usedBytesOnTiers); workerInfo.updateLastUpdatedTimeMs(); List<Long> toRemoveBlocks = workerInfo.getToRemoveBlocks(); if (toRemoveBlocks.isEmpty()) { return new Command(CommandType.Nothing, new ArrayList<Long>()); } return new Command(CommandType.Free, toRemoveBlocks); } } /** * Updates the worker and block metadata for blocks removed from a worker. * * @param workerInfo The worker metadata object * @param removedBlockIds A list of block ids removed from the worker */ @GuardedBy("workerInfo") private void processWorkerRemovedBlocks(MasterWorkerInfo workerInfo, Collection<Long> removedBlockIds) { for (long removedBlockId : removedBlockIds) { MasterBlockInfo masterBlockInfo = mBlocks.get(removedBlockId); if (masterBlockInfo == null) { LOG.warn("Worker {} informs the removed block {}, but block metadata does not exist" + " on Master!", workerInfo.getId(), removedBlockId); // TODO(pfxuan): [ALLUXIO-1804] should find a better way to handle the removed blocks. // Ideally, the delete/free I/O flow should never reach this point. Because Master may // update the block metadata only after receiving the acknowledgement from Workers. workerInfo.removeBlock(removedBlockId); // Continue to remove the remaining blocks. continue; } synchronized (masterBlockInfo) { LOG.info("Block {} is removed on worker {}.", removedBlockId, workerInfo.getId()); workerInfo.removeBlock(masterBlockInfo.getBlockId()); masterBlockInfo.removeWorker(workerInfo.getId()); if (masterBlockInfo.getNumLocations() == 0) { mLostBlocks.add(removedBlockId); } } } } /** * Updates the worker and block metadata for blocks added to a worker. * * @param workerInfo The worker metadata object * @param addedBlockIds A mapping from storage tier alias to a list of block ids added */ @GuardedBy("workerInfo") private void processWorkerAddedBlocks(MasterWorkerInfo workerInfo, Map<String, List<Long>> addedBlockIds) { for (Map.Entry<String, List<Long>> entry : addedBlockIds.entrySet()) { for (long blockId : entry.getValue()) { MasterBlockInfo masterBlockInfo = mBlocks.get(blockId); if (masterBlockInfo != null) { synchronized (masterBlockInfo) { workerInfo.addBlock(blockId); masterBlockInfo.addWorker(workerInfo.getId(), entry.getKey()); mLostBlocks.remove(blockId); } } else { LOG.warn("Failed to register workerId: {} to blockId: {}", workerInfo.getId(), blockId); } } } } /** * @return the lost blocks in Alluxio Storage */ public Set<Long> getLostBlocks() { return ImmutableSet.copyOf(mLostBlocks); } /** * Creates a {@link BlockInfo} form a given {@link MasterBlockInfo}, by populating worker * locations. * * @param masterBlockInfo the {@link MasterBlockInfo} * @return a {@link BlockInfo} from a {@link MasterBlockInfo}. Populates worker locations */ @GuardedBy("masterBlockInfo") private BlockInfo generateBlockInfo(MasterBlockInfo masterBlockInfo) { // "Join" to get all the addresses of the workers. List<BlockLocation> locations = new ArrayList<>(); List<MasterBlockLocation> blockLocations = masterBlockInfo.getBlockLocations(); // Sort the block locations by their alias ordinal in the master storage tier mapping Collections.sort(blockLocations, new Comparator<MasterBlockLocation>() { @Override public int compare(MasterBlockLocation o1, MasterBlockLocation o2) { return mGlobalStorageTierAssoc.getOrdinal(o1.getTierAlias()) - mGlobalStorageTierAssoc.getOrdinal(o2.getTierAlias()); } }); for (MasterBlockLocation masterBlockLocation : blockLocations) { MasterWorkerInfo workerInfo = mWorkers.getFirstByField(mIdIndex, masterBlockLocation.getWorkerId()); if (workerInfo != null) { // worker metadata is intentionally not locked here because: // - it would be an incorrect order (correct order is lock worker first, then block) // - only uses getters of final variables locations.add(new BlockLocation().setWorkerId(masterBlockLocation.getWorkerId()) .setWorkerAddress(workerInfo.getWorkerAddress()) .setTierAlias(masterBlockLocation.getTierAlias())); } } return new BlockInfo().setBlockId(masterBlockInfo.getBlockId()) .setLength(masterBlockInfo.getLength()).setLocations(locations); } /** * Reports the ids of the blocks lost on workers. * * @param blockIds the ids of the lost blocks */ public void reportLostBlocks(List<Long> blockIds) { mLostBlocks.addAll(blockIds); } /** * Lost worker periodic check. */ private final class LostWorkerDetectionHeartbeatExecutor implements HeartbeatExecutor { @Override public void heartbeat() { int masterWorkerTimeoutMs = MasterContext.getConf().getInt(Constants.MASTER_WORKER_TIMEOUT_MS); for (MasterWorkerInfo worker : mWorkers) { synchronized (worker) { final long lastUpdate = CommonUtils.getCurrentMs() - worker.getLastUpdatedTimeMs(); if (lastUpdate > masterWorkerTimeoutMs) { LOG.error("The worker {} timed out after {}ms without a heartbeat!", worker, lastUpdate); mLostWorkers.add(worker); mWorkers.remove(worker); processWorkerRemovedBlocks(worker, worker.getBlocks()); } } } } @Override public void close() { // Nothing to clean up } } }
package ml.duncte123.skybot.utils; import ml.duncte123.skybot.config.Config; import ml.duncte123.skybot.config.ConfigLoader; import org.slf4j.event.Level; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import java.io.File; public class ConfigUtils { private Config config; /** * This will try to load the bot config and kill the program if it fails */ public ConfigUtils() { try { AirUtils.log(Level.INFO, "Loading config.json"); this.config = ConfigLoader.getConfig(new File("config.json")); AirUtils.log(Level.INFO, "Loaded config.json"); } catch (Exception e) { if(System.getProperty("debug") != null) { AirUtils.log(Level.ERROR, "Could not load config, aborting"); System.exit(-1); } else { JsonObject jo = new JsonObject(); for(Object prop : System.getProperties().keySet()) { jo.addProperty(prop.toString(), System.getProperty(prop.toString())); } this.config = new Config(null, jo) { }; AirUtils.log(Level.DEBUG, "Using system properties for the configuration!"); System.out.println(new GsonBuilder().setPrettyPrinting().serializeNulls().create().toJson(jo)); } } } /** * This will return the config that we have * @return the config for the bot */ public Config loadConfig() { return config; } }
package com.justjournal.ctl.api; import com.justjournal.Login; import com.justjournal.model.Friend; import com.justjournal.model.User; import com.justjournal.repository.FriendsRepository; import com.justjournal.repository.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * Manage Friends * * @author Lucas Holt */ @Slf4j @RestController @RequestMapping("/api/friend") public class FriendController { private final UserRepository userRepository; private final FriendsRepository friendsDao; @Autowired public FriendController(final UserRepository userRepository, final FriendsRepository friendsDao) { this.userRepository = userRepository; this.friendsDao = friendsDao; } // TODO: refactor to return user objects? @RequestMapping(value = "{username}/friendswith/{other}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<Boolean> areWeFriends(@PathVariable("username") String username, @PathVariable("other") String otherUsername) { try { User user = userRepository.findByUsername(username); if (user == null) return new ResponseEntity<>(HttpStatus.NOT_FOUND); for (Friend friend : user.getFriends()) { if (otherUsername.equalsIgnoreCase(friend.getFriend().getUsername())) return ResponseEntity.ok(true); } return ResponseEntity.ok(false); } catch (final Exception e) { return ResponseEntity.badRequest().body(false); } } /** * @param username username * @param response http response * @return List of usernames as strings */ @Cacheable(value = "friends", key = "username") @RequestMapping(value = "{username}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Collection<User> getByUsername(@PathVariable("username") String username, HttpServletResponse response) { try { ArrayList<User> friends = new ArrayList<User>(); User user = userRepository.findByUsername(username); for (Friend friend : user.getFriends()) { friends.add(friend.getFriend()); } return friends; } catch (final Exception e) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } } @CacheEvict(value = "friends", key = "friend") @RequestMapping(value="{friend}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, String> put(@PathVariable("friend") String friend, HttpSession session, HttpServletResponse response) { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "The login timed out or is invalid."); } try { final User friendUser = userRepository.findByUsername(friend); final User owner = userRepository.findOne(Login.currentLoginId(session)); if (friendUser == null) return java.util.Collections.singletonMap("error", "Could not find friend's username"); if (owner == null) return java.util.Collections.singletonMap("error", "Could not find logged in user account."); final Friend f = new Friend(); f.setFriend(friendUser); f.setUser(owner); f.setPk(owner.getId()); if (friendsDao.save(f) != null) return java.util.Collections.singletonMap("status", "success"); return java.util.Collections.singletonMap("error", "Unable to add friend"); } catch (final Exception e) { log.error(e.getMessage()); return java.util.Collections.singletonMap("error", "Could not find friend's username"); } } @CacheEvict(value = "friends", allEntries = true) @RequestMapping(method = RequestMethod.DELETE, value="{friend}") @ResponseBody public Map<String, String> delete(@PathVariable("friend") String friend, HttpSession session, HttpServletResponse response) throws Exception { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "The login timed out or is invalid."); } try { final User friendUser = userRepository.findByUsername(friend); final User user = userRepository.findOne(Login.currentLoginId(session)); final Friend f = friendsDao.findOneByUserAndFriend(user, friendUser); if (f != null) { friendsDao.delete(f); return java.util.Collections.singletonMap("status", "success"); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return java.util.Collections.singletonMap("error", "Error deleting friend"); } } catch (final Exception e) { log.error(e.getMessage(), e); } response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return java.util.Collections.singletonMap("error", "Error deleting friend"); } }
package boa.test.datagen; import java.io.IOException; import org.junit.Test; public class TestVariableDeclarationNode extends JavaScriptBaseTest { @Test public void varaibleDeclTest1() throws IOException { nodeTest(load("test/datagen/javascript/VariableDeclarationNode.boa"), load("test/datagen/javascript/VariableDeclarationNode.js")); } @Test public void varaibleDeclTest2() throws IOException { nodeTest(load("test/datagen/javascript/VariableDeclarationNode2.boa"), load("test/datagen/javascript/VariableDeclarationNode2.js")); } @Test public void varaibleDeclTest3() throws IOException { nodeTest(load("test/datagen/javascript/VariableDeclarationNode3.boa"), load("test/datagen/javascript/VariableDeclarationNode3.js")); } @Test public void varaibleDeclTest4() throws IOException { nodeTest(load("test/datagen/javascript/VariableDeclarationNode4.boa"), load("test/datagen/javascript/VariableDeclarationNode4.js")); } @Test public void arrayLiteralTest() throws IOException { nodeTest(load("test/datagen/javascript/ArrayLiteralNode.boa"), load("test/datagen/javascript/ArrayLiteralNode.js")); } @Test public void varaibleDeclTest5() throws IOException { nodeTest(load("test/datagen/javascript/VariableDeclarationNode5.boa"), load("test/datagen/javascript/VariableDeclarationNode5.js")); } }
package io.machinecode.then.core; import io.machinecode.then.api.Deferred; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author <a href="mailto:brent.n.douglas@gmail.com">Brent Douglas</a> * @since 1.0 */ public class FutureDeferred<T,P> extends DeferredImpl<T,Throwable,P> implements Callable<T>, Runnable { protected final Future<? extends T> future; protected final long timeout; protected final TimeUnit unit; public FutureDeferred(final Future<? extends T> future) { this.future = future; this.timeout = -1; this.unit = null; } public FutureDeferred(final Future<? extends T> future, final long timeout, final TimeUnit unit) { this.future = future; this.timeout = timeout; this.unit = unit; } @Override public void run() { getFuture(future, this, timeout, unit); } @Override public T call() throws Exception { run(); return unit == null ? get() : get(timeout, unit); } public Runnable asRunnable() { return this; } public Callable<T> asCallable() { return this; } public static <T,P> void getFuture(final Future<? extends T> future, final Deferred<T,Throwable,P> def, final long timeout, final TimeUnit unit) { final T that; try { if (unit == null) { that = future.get(); } else { that = future.get(timeout, unit); } } catch (final CancellationException e) { def.cancel(true); return; } catch (final Throwable e) { def.reject(e); return; } def.resolve(that); } }
package nablarch.etl.config; import nablarch.core.repository.SystemRepository; import javax.batch.runtime.context.JobContext; import javax.batch.runtime.context.StepContext; import javax.enterprise.inject.Produces; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * ETL * <p/> * {@link JsonConfigLoader}ETL * {@link EtlConfigLoader} * "etlConfigLoader" * JVM1 * * @author Kiyohito Itoh */ public final class EtlConfigProvider { /** {@link EtlConfigLoader} */ private static final EtlConfigLoader DEFAULT_LOADER = new JsonConfigLoader(); /** ETL */ private static final Map<String, JobConfig> LOADED_ETL_CONFIG = new ConcurrentHashMap<String, JobConfig>(); private EtlConfigProvider() { } /** * ETL * * @param jobContext * @return ETL */ private static JobConfig initialize(JobContext jobContext) { JobConfig jobConfig; synchronized(LOADED_ETL_CONFIG){ jobConfig = LOADED_ETL_CONFIG.get(jobContext.getJobName()); if (jobConfig == null) { jobConfig = getLoader().load(jobContext); jobConfig.initialize(); LOADED_ETL_CONFIG.put(jobContext.getJobName(), jobConfig); } } return jobConfig; } /** * {@link EtlConfigLoader} * <p> * "etlConfigLoader" * {@link JsonConfigLoader} * @return {@link EtlConfigLoader} */ private static EtlConfigLoader getLoader() { EtlConfigLoader loader = SystemRepository.get("etlConfigLoader"); return loader != null ? loader : DEFAULT_LOADER; } /** * ETL * <p/> * * * @param jobContext * @param stepContext * @return */ @EtlConfig @Produces public static StepConfig getConfig(JobContext jobContext, StepContext stepContext) { JobConfig jobConfig = LOADED_ETL_CONFIG.get(jobContext.getJobName()); if (jobConfig == null) { jobConfig = initialize(jobContext); } return jobConfig.getStepConfig(jobContext.getJobName(), stepContext.getStepName()); } }
package net.imglib2.histogram; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import ij.IJ; import io.nii.NiftiIo; import loci.formats.FormatException; import net.imglib2.IterableInterval; import net.imglib2.RandomAccess; import net.imglib2.converter.Converter; import net.imglib2.converter.Converters; import net.imglib2.filter.MaskedIterableFilter; import net.imglib2.filter.MaskedIterableFilter.MaskedIterator; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.type.logic.BoolType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.LongType; import net.imglib2.type.numeric.real.FloatType; public class BuildHistogram { public static void main(String[] args) throws FormatException, IOException { final String outF = args[ 0 ]; final String imF = args[ 1 ]; final float histmin = Float.parseFloat( args[ 2 ]); final float histmax = Float.parseFloat( args[ 3 ]); final int numBins = Integer.parseInt( args[ 4 ]); final String maskF = args[ 5 ]; final float maskthresh = Float.parseFloat( args[ 6 ]); boolean tailBins = false; if( args.length >= 8 ) tailBins = Boolean.parseBoolean( args[ 7 ] ); System.out.println( "tailBins: " + tailBins ); Real1dBinMapper<FloatType> binMapper = new Real1dBinMapper<FloatType>( histmin, histmax, numBins, tailBins ); System.out.println( "imF : " + imF ); System.out.println( "maskF : " + maskF ); IterableInterval<FloatType> img; if( imF.endsWith( "nii" )) { img = ImageJFunctions.convertFloat( NiftiIo.readNifti( new File( imF ))); } else { img = ImageJFunctions.convertFloat( IJ.openImage( imF ) ); } IterableInterval<FloatType> maskRaw = null; if( maskF.equals( imF )) { System.out.println( "mask is same as input image"); maskRaw = img; } else { if( maskF.endsWith( "nii" )) { maskRaw = ImageJFunctions.convertFloat( NiftiIo.readNifti( new File( maskF ))); } else { maskRaw = ImageJFunctions.convertFloat( IJ.openImage( maskF ) ); } } Converter<FloatType,BoolType> maskConv = new Converter<FloatType,BoolType>() { @Override public void convert(FloatType input, BoolType output) { if( input.get() < maskthresh ) { output.set( false ); } else { output.set( true ); } } }; IterableInterval<BoolType> mask = Converters.convert( maskRaw, maskConv, new BoolType()); final Histogram1d<FloatType> hist = new Histogram1d<>( binMapper ); MaskedIterableFilter<FloatType,BoolType> mit = new MaskedIterableFilter<FloatType,BoolType>( mask.iterator() ); mit.set( img ); hist.countData( mit ); MaskedIterator<FloatType,BoolType> mi = (MaskedIterator<FloatType,BoolType>)mit.iterator(); System.out.println( "MI total : " + mi.getNumTotal() ); System.out.println( "mi valid : " + mi.getNumValid() ); System.out.println( "mi invalid : " + mi.getNumInvalid() ); System.out.println( "hist total : " + hist.totalCount() ); writeHistogram( outF, hist ); } public static <T extends RealType<T>> boolean writeHistogram( String outPath, Histogram1d<T> hist ) { T t = hist.firstDataValue().copy(); RandomAccess<LongType> hra = hist.randomAccess(); try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(outPath)); for( int i = 0; i < hist.getBinCount(); i++ ) { hist.getCenterValue( i, t ); hra.setPosition( i, 0 ); String line = Double.toString( t.getRealDouble() ) + "," + Long.toString( hra.get().get() ); writer.write( line + "\n" ); } writer.close(); } catch( Exception e ) { e.printStackTrace(); return false; } return true; } }
package com.kevinsimard.kafka.streams; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.connect.json.JsonDeserializer; import org.apache.kafka.connect.json.JsonSerializer; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KStreamBuilder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; public class Aggregator { private static final String KAFKA_HOSTS = Optional.of(System.getenv("KAFKA_HOSTS")).orElse("localhost:9092"); private static final Serde<JsonNode> JSON_SERDE = Serdes.serdeFrom(new JsonSerializer(), new JsonDeserializer()); private static List<String> processedMessages = new ArrayList<>(); public static void main(String[] args) { Properties props = new Properties(); props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 0); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "aggregator"); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_HOSTS); KafkaStreams streams = new KafkaStreams(buildStreams(), props); Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); streams.start(); } private static KStreamBuilder buildStreams() { KStreamBuilder builder = new KStreamBuilder(); KStream<String, JsonNode> salesAggregated = builder.stream(Serdes.String(), JSON_SERDE, "sales-aggregated"); salesAggregated.foreach(Aggregator::markAsProcessedInDatastore); KStream<String, JsonNode> salesRaw = builder.stream(Serdes.String(), JSON_SERDE, "sales-raw"); salesRaw.filterNot(Aggregator::isAlreadyProcessed) .groupBy(Aggregator::groupByUserId, Serdes.String(), JSON_SERDE) .aggregate(() -> null, Aggregator::aggregateValues, JSON_SERDE, "aggregated-interm") .to(Serdes.String(), JSON_SERDE, "sales-aggregated"); return builder; } @SuppressWarnings("unused") private static void markAsProcessedInCache(String key, JsonNode value) { String hash = uniqueHashForMessage(value); processedMessages.add(hash); } @SuppressWarnings("unused") private static void markAsProcessedInDatastore(String key, JsonNode value) { // TODO: Save the generated hash in datastore. // TODO: Uncomment when using datastore to prevent array from getting too big. //processedMessages.remove(uniqueHashForMessage(value)); } private static Boolean isAlreadyProcessed(String key, JsonNode value) { // TODO: Also check in datastore if not found in cache. String hash = uniqueHashForMessage(value); Boolean isProcessed = processedMessages.indexOf(hash) != -1; if (! isProcessed) markAsProcessedInCache(key, value); return isProcessed; } @SuppressWarnings("unused") private static String groupByUserId(String key, JsonNode value) { return value.get("user_id").asText(); } @SuppressWarnings("unused") private static JsonNode aggregateValues(String key, JsonNode value, JsonNode previous) { if (previous != null) { ((ObjectNode) value).put("total", previous.get("total").asDouble() + value.get("total").asDouble()); } return value; } private static String uniqueHashForMessage(JsonNode value) { // TODO: Replace the following with a hash function. return value.get("user_id").asText() + ":" + value.get("sale_id").asText(); } }
package peer; import java.util.Random; import peer.message.ACKMessage; import peer.message.BroadcastMessage; import peer.message.BundleMessage; import peer.messagecounter.ReliableBroadcastCounter; import peer.peerid.PeerID; import peer.peerid.PeerIDSet; import util.logger.Logger; import util.timer.Timer; import util.timer.TimerTask; import detection.NeighborEventsListener; import detection.message.BeaconMessage; final class ReliableBroadcast implements TimerTask, NeighborEventsListener { private final static class RebroadcastThread extends Timer { public RebroadcastThread(final long period, final TimerTask timerTask) { super(period, timerTask); } } private BundleMessage currentMessage; private final Peer peer; private final RebroadcastThread rebroadcastThread; private final static long CHECK_PERIOD = 0; private final ReliableBroadcastCounter reliableBroadcastCounter = new ReliableBroadcastCounter(); private final Object mutex = new Object(); private boolean processingMessage = false; private boolean rebroadcast = true; private long responseWaitTime; private int tryNumber; private long broadcastStartTime; private long lastBroadcastTime; private final Random r = new Random(); private final Logger logger = Logger.getLogger(ReliableBroadcast.class); public ReliableBroadcast(final Peer peer) { this.peer = peer; this.rebroadcastThread = new RebroadcastThread(CHECK_PERIOD, this); } public void start() { peer.getDetector().addNeighborListener(this); rebroadcastThread.start(); } public void stopAndWait() { synchronized (mutex) { processingMessage = false; performNotify(); } rebroadcastThread.stopAndWait(); } public boolean isProcessingMessage() { synchronized (mutex) { return processingMessage; } } protected void performNotify() { synchronized (this) { this.notifyAll(); } } private void performWait() { synchronized (this) { try { this.wait(); } catch (final InterruptedException e) { // do nothing } } } public void broadcast(final BundleMessage bundleMessage) { // block while a message is being broadcasting while (isProcessingMessage()) this.performWait(); // bundle messages containing only BeaconMessages or ACKMessages are directly broadcasted if (containsOnlyBeaconMessages(bundleMessage) || containsOnlyACKMessages(bundleMessage)) { peer.broadcast(bundleMessage); return; } // messages with empty destinations are not reliable broadcasted if (bundleMessage.getExpectedDestinations().isEmpty()) return; synchronized (mutex) { currentMessage = bundleMessage; broadcastStartTime = lastBroadcastTime = System.currentTimeMillis(); tryNumber = 1; responseWaitTime = getResponseWaitTime(currentMessage.getExpectedDestinations().size()); logger.debug("Peer " + peer.getPeerID() + " reliable broadcasting message " + bundleMessage.getMessageID() + " " + bundleMessage.getExpectedDestinations() + " responseWaitTime: " + responseWaitTime); rebroadcast = false; processingMessage = true; } reliableBroadcastCounter.addBroadcastedMessage(); peer.broadcast(bundleMessage); } public static boolean containsOnlyBeaconMessages(final BundleMessage bundleMessage) { for (final BroadcastMessage broadcastMessage : bundleMessage.getMessages()) if (!(broadcastMessage instanceof BeaconMessage)) return false; return true; } public static boolean containsOnlyACKMessages(final BundleMessage bundleMessage) { for (final BroadcastMessage broadcastMessage : bundleMessage.getMessages()) if (!(broadcastMessage instanceof ACKMessage)) return false; return true; } public void receivedACKResponse(final ACKMessage ackMessage) { // check if message is responded by the current ACK message synchronized (mutex) { if (processingMessage) if (ackMessage.getRespondedMessageID().equals(currentMessage.getMessageID())) { currentMessage.removeExpectedDestination(ackMessage.getSender()); logger.trace("Peer " + peer.getPeerID() + " added response from " + ackMessage.getSender() + " for " + currentMessage.getMessageID() + " missing responses: " + currentMessage.getExpectedDestinations()); // check if all responses have being received if (currentMessage.getExpectedDestinations().isEmpty()) { final long deliveringTime = System.currentTimeMillis() - broadcastStartTime; reliableBroadcastCounter.addDeliveredMessage(deliveringTime); logger.debug("Peer " + peer.getPeerID() + " delivered message " + currentMessage.getMessageID()); processingMessage = false; performNotify(); } } } } public long getResponseWaitTime(int destinations) { return BasicPeer.TRANSMISSION_TIME + (destinations + 1) * BasicPeer.RANDOM_DELAY; } private boolean mustRebroadcast() { synchronized (mutex) { return processingMessage && rebroadcast; } } @Override public void perform() throws InterruptedException { synchronized (mutex) { if (processingMessage && !mustRebroadcast()) { // calculate elapsed time since last broadcast long elapsedTime = System.currentTimeMillis() - lastBroadcastTime; if (elapsedTime >= responseWaitTime) { rebroadcast = true; } } } final long delayTime = r.nextInt(BasicPeer.RANDOM_DELAY); if (mustRebroadcast() && delayTime > 0) { try { Thread.sleep(delayTime); } catch (InterruptedException e) { rebroadcastThread.interrupt(); return; } } if (mustRebroadcast()) { synchronized (mutex) { if (tryNumber == 1) { logger.debug("Peer " + peer.getPeerID() + " rebroadcasted message " + currentMessage.getMessageID() + " " + currentMessage.getExpectedDestinations() + " adding " + delayTime + " ms"); reliableBroadcastCounter.addRebroadcastedMessage(); } peer.broadcast(currentMessage); responseWaitTime = getResponseWaitTime(currentMessage.getExpectedDestinations().size()); lastBroadcastTime = System.currentTimeMillis(); tryNumber++; rebroadcast = false; } } } private void removeNeighbors(final PeerIDSet disappearedNeighbors) { synchronized (mutex) { if (processingMessage) { // remove disappeared neighbors for (final PeerID dissappearedNeighbor : disappearedNeighbors.getPeerSet()) currentMessage.removeExpectedDestination(dissappearedNeighbor); if (currentMessage.getExpectedDestinations().isEmpty()) { processingMessage = false; performNotify(); } } } } @Override public void appearedNeighbors(final PeerIDSet neighbors) { } @Override public void dissapearedNeighbors(final PeerIDSet neighbors) { removeNeighbors(neighbors); } public void includeACKResponse(final ACKMessage ackMessage) { synchronized (mutex) { if (isProcessingMessage()) currentMessage.addACKMessage(ackMessage); } logger.trace("Peer " + peer.getPeerID() + " ACK message " + ackMessage + " included in current broadcasting message"); } }
package lucee.runtime.compiler; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PublicKey; import java.util.Iterator; import java.util.List; import java.util.Stack; import java.util.concurrent.ConcurrentLinkedQueue; import lucee.commons.digest.RSA; import lucee.commons.io.IOUtil; import lucee.commons.io.SystemUtil; import lucee.commons.io.res.Resource; import lucee.commons.io.res.filter.ResourceNameFilter; import lucee.commons.lang.StringUtil; import lucee.commons.lang.compiler.JavaFunction; import lucee.loader.engine.CFMLEngine; import lucee.runtime.PageSource; import lucee.runtime.PageSourceImpl; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.Constants; import lucee.runtime.exp.TemplateException; import lucee.runtime.type.util.ListUtil; import lucee.transformer.Factory; import lucee.transformer.Position; import lucee.transformer.TransformerException; import lucee.transformer.bytecode.BytecodeFactory; import lucee.transformer.bytecode.Page; import lucee.transformer.bytecode.util.ASMUtil; import lucee.transformer.bytecode.util.ClassRenamer; import lucee.transformer.cfml.tag.CFMLTransformer; import lucee.transformer.library.function.FunctionLib; import lucee.transformer.library.tag.TagLib; import lucee.transformer.util.AlreadyClassException; import lucee.transformer.util.PageSourceCode; import lucee.transformer.util.SourceCode; /** * CFML Compiler compiles CFML source templates */ public final class CFMLCompilerImpl implements CFMLCompiler { private CFMLTransformer cfmlTransformer; private ConcurrentLinkedQueue<WatchEntry> watched = new ConcurrentLinkedQueue<WatchEntry>(); /** * Constructor of the compiler * * @param config */ public CFMLCompilerImpl() { cfmlTransformer = new CFMLTransformer(); } public Result compile(ConfigImpl config, PageSource ps, TagLib[] tld, FunctionLib[] fld, Resource classRootDir, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException { return _compile(config, ps, null, null, tld, fld, classRootDir, returnValue, ignoreScopes); } public Result compile(ConfigImpl config, SourceCode sc, TagLib[] tld, FunctionLib[] fld, Resource classRootDir, String className, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException { // just to be sure PageSource ps = (sc instanceof PageSourceCode) ? ((PageSourceCode) sc).getPageSource() : null; return _compile(config, ps, sc, className, tld, fld, classRootDir, returnValue, ignoreScopes); } /* * private byte[] _compiless(ConfigImpl config,PageSource ps,SourceCode sc,String className, * TagLib[] tld, FunctionLib[] fld, Resource classRootDir,TransfomerSettings settings) throws * TemplateException { Factory factory = BytecodeFactory.getInstance(config); * * Page page=null; * * TagLib[][] _tlibs=new TagLib[][]{null,new TagLib[0]}; _tlibs[CFMLTransformer.TAG_LIB_GLOBAL]=tld; * // reset page tlds if(_tlibs[CFMLTransformer.TAG_LIB_PAGE].length>0) { * _tlibs[CFMLTransformer.TAG_LIB_PAGE]=new TagLib[0]; } * * CFMLScriptTransformer scriptTransformer = new CFMLScriptTransformer(); * scriptTransformer.transform( BytecodeFactory.getInstance(config) , page , new EvaluatorPool() , * _tlibs, fld , null , config.getCoreTagLib(ps.getDialect()).getScriptTags() , sc , settings); * * //CFMLExprTransformer extr=new CFMLExprTransformer(); //extr.transform(factory, page, ep, tld, * fld, scriptTags, cfml, settings) * * return null; } */ private Result _compile(ConfigImpl config, PageSource ps, SourceCode sc, String className, TagLib[] tld, FunctionLib[] fld, Resource classRootDir, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException { String javaName; if (className == null) { javaName = ListUtil.trim(ps.getJavaName(), "\\/", false); className = ps.getClassName(); } else { javaName = className.replace('.', '/'); } Result result = null; // byte[] barr = null; Page page = null; Factory factory = BytecodeFactory.getInstance(config); try { page = sc == null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes); page.setSplitIfNecessary(false); try { byte[] barr = page.execute(className); result = new Result(page, barr, page.getJavaFunctions()); } catch (RuntimeException re) { String msg = StringUtil.emptyIfNull(re.getMessage()); if (StringUtil.indexOfIgnoreCase(msg, "Method code too large!") != -1) { page = sc == null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes); page.setSplitIfNecessary(true); byte[] barr = page.execute(className); result = new Result(page, barr, page.getJavaFunctions()); } else throw re; } catch (ClassFormatError cfe) { String msg = StringUtil.emptyIfNull(cfe.getMessage()); if (StringUtil.indexOfIgnoreCase(msg, "Invalid method Code length") != -1) { page = ps != null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes); page.setSplitIfNecessary(true); byte[] barr = page.execute(className); result = new Result(page, barr, page.getJavaFunctions()); } else throw cfe; } // store if (classRootDir != null) { Resource classFile = classRootDir.getRealResource(page.getClassName() + ".class"); Resource classFileDirectory = classFile.getParentResource(); if (!classFileDirectory.exists()) classFileDirectory.mkdirs(); else if (classFile.exists() && !SystemUtil.isWindows()) { final String prefix = page.getClassName() + "$"; classRootDir.list(new ResourceNameFilter() { @Override public boolean accept(Resource parent, String name) { if (name.startsWith(prefix)) parent.getRealResource(name).delete(); return false; } }); } IOUtil.copy(new ByteArrayInputStream(result.barr), classFile, true); if (result.javaFunctions != null) { for (JavaFunction jf: result.javaFunctions) { IOUtil.copy(new ByteArrayInputStream(jf.byteCode), classFileDirectory.getRealResource(jf.getName() + ".class"), true); } } /// TODO; //store java functions } return result; } catch (AlreadyClassException ace) { byte[] bytes = ace.getEncrypted() ? readEncrypted(ace) : readPlain(ace); result = new Result(null, bytes, null); // TODO handle better Java Functions String displayPath = ps != null ? "[" + ps.getDisplayPath() + "] " : ""; String srcName = ASMUtil.getClassName(result.barr); int dialect = sc == null ? ps.getDialect() : sc.getDialect(); // source is cfm and target cfc if (dialect == CFMLEngine.DIALECT_CFML && endsWith(srcName, Constants.getCFMLTemplateExtensions(), dialect) && className .endsWith("_" + Constants.getCFMLComponentExtension() + (dialect == CFMLEngine.DIALECT_CFML ? Constants.CFML_CLASS_SUFFIX : Constants.LUCEE_CLASS_SUFFIX))) { throw new TemplateException("Source file [" + displayPath + "] contains the bytecode for a regular cfm template not for a component"); } // source is cfc and target cfm if (dialect == CFMLEngine.DIALECT_CFML && srcName.endsWith( "_" + Constants.getCFMLComponentExtension() + (dialect == CFMLEngine.DIALECT_CFML ? Constants.CFML_CLASS_SUFFIX : Constants.LUCEE_CLASS_SUFFIX)) && endsWith(className, Constants.getCFMLTemplateExtensions(), dialect)) throw new TemplateException("Source file [" + displayPath + "] contains a component not a regular cfm template"); // rename class name when needed if (!srcName.equals(javaName)) { byte[] barr = ClassRenamer.rename(result.barr, javaName); if (barr != null) result = new Result(result.page, barr, null); // TODO handle java functions } // store if (classRootDir != null) { Resource classFile = classRootDir.getRealResource(javaName + ".class"); Resource classFileDirectory = classFile.getParentResource(); if (!classFileDirectory.exists()) classFileDirectory.mkdirs(); result = new Result(result.page, Page.setSourceLastModified(result.barr, ps != null ? ps.getPhyscalFile().lastModified() : System.currentTimeMillis()), null);// TODO // handle // java // functions IOUtil.copy(new ByteArrayInputStream(result.barr), classFile, true); } return result; } catch (TransformerException bce) { Position pos = bce.getPosition(); int line = pos == null ? -1 : pos.line; int col = pos == null ? -1 : pos.column; if (ps != null) bce.addContext(ps, line, col, null); throw bce; } } private byte[] readPlain(AlreadyClassException ace) throws IOException { return IOUtil.toBytes(ace.getInputStream(), true); } private byte[] readEncrypted(AlreadyClassException ace) throws IOException { String str = System.getenv("PUBLIC_KEY"); if (str == null) str = System.getProperty("PUBLIC_KEY"); if (str == null) throw new RuntimeException("To decrypt encrypted bytecode, you need to set PUBLIC_KEY as system property or as an environment variable"); byte[] bytes = IOUtil.toBytes(ace.getInputStream(), true); try { PublicKey publicKey = RSA.toPublicKey(str); // first 2 bytes are just a mask to detect encrypted code, so we need to set offset 2 bytes = RSA.decrypt(bytes, publicKey, 2); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new RuntimeException(e); } return bytes; } private boolean endsWith(String name, String[] extensions, int dialect) { for (int i = 0; i < extensions.length; i++) { if (name.endsWith("_" + extensions[i] + (dialect == CFMLEngine.DIALECT_CFML ? Constants.CFML_CLASS_SUFFIX : Constants.LUCEE_CLASS_SUFFIX))) return true; } return false; } public Page transform(ConfigImpl config, PageSource source, TagLib[] tld, FunctionLib[] fld, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException { return cfmlTransformer.transform(BytecodeFactory.getInstance(config), config, source, tld, fld, returnValue, ignoreScopes); } public class Result { public final Page page; public final byte[] barr; public final List<JavaFunction> javaFunctions; public Result(Page page, byte[] barr, List<JavaFunction> javaFunctions) { this.page = page; this.barr = barr; this.javaFunctions = javaFunctions; } } public void watch(PageSource ps, long now) { watched.offer(new WatchEntry(ps, now, ps.getPhyscalFile().length(), ps.getPhyscalFile().lastModified())); } public void checkWatched() { WatchEntry we; long now = System.currentTimeMillis(); Stack<WatchEntry> tmp = new Stack<WatchEntry>(); while ((we = watched.poll()) != null) { // to young if (we.now + 1000 > now) { tmp.add(we); continue; } if (we.length != we.ps.getPhyscalFile().length() && we.ps.getPhyscalFile().length() > 0) { // TODO this is set to avoid that removed files are removed from pool, remove // this line if a UDF still wprks fine when the page is gone ((PageSourceImpl) we.ps).flush(); } } // add again entries that was to young for next round Iterator<WatchEntry> it = tmp.iterator(); while (it.hasNext()) { watched.add(we = it.next()); } } private class WatchEntry { private final PageSource ps; private final long now; private final long length; private final long lastModified; public WatchEntry(PageSource ps, long now, long length, long lastModified) { this.ps = ps; this.now = now; this.length = length; this.lastModified = lastModified; } } }
package net.bootsfaces.menu; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class ComponentListBean { private Map<String, String> allConcepts = new HashMap<>(); private Map<String, String> filteredConcepts = new HashMap<>(); private String filter = null; private String[] filteredTags = ComponentList.tags; public ComponentListBean() { allConcepts.put("Grid system", "layout/basic.jsf"); allConcepts.put("PrimeFaces", "integration/PrimeFaces.jsf"); allConcepts.put("Converters", "forms/converters.jsf"); allConcepts.put("AJAX", "forms/ajax.jsf"); allConcepts.put("Search expressions", "forms/searchExpressions.jsf"); allConcepts.put("BlockUI", "forms/blockUI.jsf"); allConcepts.put("Fontawesome 5", "layout/fontawesome5.jsf"); filteredConcepts = allConcepts; } public String[] getTags() { return filteredTags; } public String url(String component) { return ComponentList.docFiles.get(component); } public String getFilter() { return filter; } public void setFilter(String filter) { if (filter == null || filter.trim().equals("")) { filteredTags = ComponentList.tags; this.filter = filter; filteredConcepts = allConcepts; } else { filter = filter.replace("<b:", "<"); if (filter.equals(this.filter)) { return; } this.filter = filter; String smallFilter = filter.toLowerCase().trim(); List<String> result = new ArrayList<>(ComponentList.tags.length); for (String s: ComponentList.tags) { if (s.toLowerCase().contains(smallFilter)) { result.add(s); } } final String finalFilter = filter.toLowerCase(); filteredTags = result.toArray(new String[result.size()]); filteredConcepts = new HashMap<>(); allConcepts.forEach((name, url) -> { if (name.toLowerCase().contains(finalFilter) ) { filteredConcepts.put(name, url); } }); } } public String[] getFilteredTags() { return filteredTags; } public void setFilteredTags(String[] filteredTags) { this.filteredTags = filteredTags; } public void updateFilter() { } public String getDisplayName(String c) { c = c.replace("<", "").replace(">", ""); c = c.substring(0, 1).toUpperCase() + c.substring(1); return c; } public String addSlashIfNecessary(String path) { // if (path.length() <= 1) { // return path; if (path.endsWith("/")) { return path; } return path + "/"; } public Map<String, String> getFilteredConcepts() { return filteredConcepts; } }
package com.github.kokorin.jaffree; import org.junit.Assert; import org.junit.Test; public class RationalTest { @Test public void equals() { Assert.assertEquals(Rational.valueOf(1L), Rational.valueOf(1L)); Assert.assertEquals(new Rational(1L, 1L), new Rational(2L, 2L)); } @Test public void compareTo() { Assert.assertEquals(0, Rational.valueOf(1L).compareTo(Rational.valueOf(1L))); Assert.assertEquals(0, new Rational(1L, 1L).compareTo(new Rational(2L, 2L))); } @Test public void valueOf() { Assert.assertEquals(Rational.valueOf(1L), Rational.valueOf(1.)); Assert.assertEquals(new Rational(3_333_333_333_333_333L, 10_000_000_000_000_000L), Rational.valueOf(1. / 3)); Assert.assertEquals(Rational.valueOf(1L), Rational.valueOf("1")); Assert.assertEquals(Rational.valueOf(1L), Rational.valueOf("1/1")); Assert.assertEquals(new Rational(1L, 10L), Rational.valueOf("1/10")); } @Test public void simplify() { Assert.assertEquals("1/3", new Rational(10, 30).simplify().toString()); Assert.assertEquals("1/3", new Rational(3, 9).simplify().toString()); } @Test public void multiply() { Assert.assertEquals(new Rational(1, 6), new Rational(1, 2).multiply(new Rational(1, 3))); } @Test public void add() { Assert.assertEquals(new Rational(1, 2), new Rational(1, 6).add(new Rational(1, 3))); } @Test(expected = NumberFormatException.class) public void valueOfNFE_1() { Rational.valueOf("a"); } @Test(expected = NumberFormatException.class) public void valueOfNFE_2() { Rational.valueOf("1/a"); } @Test(expected = NumberFormatException.class) public void valueOfNFE_3() { Rational.valueOf("1/2/3"); } }
package br.senac.tads.pi3.duplasubstitutadetonystark.agenda; /** * * @author nicolas.falmeida1 */ public class Agenda { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("teste"); System.out.println("ekiqueme ei maumau "); } }
package com.lothrazar.samscontent; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import com.lothrazar.samscontent.block.*; import com.lothrazar.samscontent.cfg.ConfigFile; import com.lothrazar.samscontent.command.*; import com.lothrazar.samscontent.event.*; import com.lothrazar.samscontent.item.*; import com.lothrazar.samscontent.potion.*; import com.lothrazar.samscontent.proxy.*; import com.lothrazar.samscontent.stats.*; import com.lothrazar.samscontent.world.*; import com.lothrazar.util.*; import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockDoor; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; import net.minecraft.block.BlockSandStone; import net.minecraft.block.BlockStairs; import net.minecraft.block.BlockStone; import net.minecraft.block.BlockStoneSlab; import net.minecraft.block.BlockTrapDoor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.*; import net.minecraft.entity.passive.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemDoor; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemSeeds; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityNote; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.entity.living.EnderTeleportEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.UseHoeEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.PlayerTickEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = Reference.MODID, version = Reference.VERSION , canBeDeactivated = false, name = Reference.NAME, useMetadata = true ,guiFactory = "com.lothrazar.samscontent.cfg.ConfigGuiFactory") public class ModSamsContent { @Instance(value = Reference.MODID) public static ModSamsContent instance; @SidedProxy(clientSide="com.lothrazar.samscontent.proxy.ClientProxy", serverSide="com.lothrazar.samscontent.proxy.CommonProxy") public static CommonProxy proxy; public static Logger logger; public static ConfigFile cfg; public static SimpleNetworkWrapper network; public static AchievementRegistry achievements; public static CreativeTabs tabSamsContent = new CreativeTabs("tabSamsContent") { @Override public Item getTabIconItem() { return ItemRegistry.apple_chocolate; } }; private void initModInfo(ModMetadata mcinfo) { mcinfo.modId = Reference.MODID; mcinfo.name = Reference.NAME; mcinfo.version = Reference.VERSION; mcinfo.description = "Sam's content."; ArrayList<String> authorList = new ArrayList<String>(); authorList.add("Lothrazar"); mcinfo.authorList = authorList; } @EventHandler public void onPreInit(FMLPreInitializationEvent event) { logger = event.getModLog(); initModInfo(event.getModMetadata()); cfg = new ConfigFile(new Configuration(event.getSuggestedConfigurationFile())); network = NetworkRegistry.INSTANCE.newSimpleChannel( Reference.MODID ); network.registerMessage(MessageKeyPressed.class, MessageKeyPressed.class, MessageKeyPressed.ID, Side.SERVER); network.registerMessage(MessagePotion.class, MessagePotion.class, MessagePotion.ID, Side.CLIENT); PotionRegistry.registerPotionEffects(); BlockRegistry.registerBlocks(); ItemRegistry.registerItems(); achievements = new AchievementRegistry(); this.registerEventHandlers(); BlockHardnessRegistry.registerChanges(); } @EventHandler public void onInit(FMLInitializationEvent event) { //TODO: LexManos et all have not yet fixed IVillageTradeHandler // VillageTrading v = new VillageTrading(); //VillagerRegistry.instance().registerVillageTradeHandler(1, v); // VillagerRegistry.instance().registerVillageTradeHandler(2, v); achievements.registerAll(); CreativeInventoryRegistry.registerTabImprovements(); MobSpawningRegistry.registerSpawns(); ChestGen.regsiterLoot(); RecipeRegistry.registerRecipes(); StackSizeIncreaser.registerChanges(); if(ModSamsContent.cfg.moreFuel) { GameRegistry.registerFuelHandler(new FurnaceFuel()); } if(ModSamsContent.cfg.worldGenOceansNotUgly) { GameRegistry.registerWorldGenerator(new WorldGeneratorOcean(), 0); //zero is Weight of generator } proxy.registerRenderers(); } @EventHandler public void onPostInit(FMLPostInitializationEvent event) { } @EventHandler public void onServerStarting(FMLServerStartingEvent event) { if(ModSamsContent.cfg.searchtrade) event.registerServerCommand(new CommandSearchTrades()); if(ModSamsContent.cfg.searchitem) event.registerServerCommand(new CommandSearchItem()); if(ModSamsContent.cfg.searchspawner) event.registerServerCommand(new CommandSearchSpawner()); if(ModSamsContent.cfg.simplewaypoint) event.registerServerCommand(new CommandSimpleWaypoints()); if(ModSamsContent.cfg.todo) event.registerServerCommand(new CommandTodoList()); if(ModSamsContent.cfg.kit) event.registerServerCommand(new CommandKit()); if(ModSamsContent.cfg.home) event.registerServerCommand(new CommandWorldHome()); if(ModSamsContent.cfg.worldhome) event.registerServerCommand(new CommandHome()); } private void registerEventHandlers() { //TODO: version checker ArrayList<Object> handlers = new ArrayList<Object>(); handlers.add(new SaplingDespawnGrowth());//this is only one needs terrain gen buff, plus one of the regular ones handlers.add(new DebugScreenText() ); //This one can stay handlers.add(instance ); handlers.add(achievements); handlers.add(BlockRegistry.block_storelava ); handlers.add(BlockRegistry.block_storewater ); handlers.add(BlockRegistry.block_storemilk ); handlers.add(BlockRegistry.block_storeempty ); for(Object h : handlers) if(h != null) { FMLCommonHandler.instance().bus().register(h); MinecraftForge.EVENT_BUS.register(h); MinecraftForge.TERRAIN_GEN_BUS.register(h); MinecraftForge.ORE_GEN_BUS.register(h); } } @SubscribeEvent public void onEnderTeleportEvent(EnderTeleportEvent event) { PotionRegistry.onEnderTeleportEvent(event); } @SubscribeEvent public void onEntityUpdate(LivingUpdateEvent event) { PotionRegistry.onEntityUpdate(event); if(ModSamsContent.cfg.fragileTorches) // && event.entityLiving != null { boolean playerCancelled = false; if(event.entityLiving instanceof EntityPlayer) { EntityPlayer p = (EntityPlayer)event.entityLiving; if(p.isSneaking()) { playerCancelled = true;//torches are safe from breaking } } if(playerCancelled == false && event.entityLiving.worldObj.getBlockState(event.entityLiving.getPosition()).getBlock() == Blocks.torch && event.entityLiving.worldObj.rand.nextDouble() < 0.01 && event.entityLiving.worldObj.isRemote == false) { event.entityLiving.worldObj.destroyBlock(event.entityLiving.getPosition(), true); } } } @SubscribeEvent public void onLivingDropsEvent(LivingDropsEvent event) { BlockPos pos = event.entity.getPosition(); World world = event.entity.worldObj; if(ModSamsContent.cfg.removeZombieCarrotPotato && event.entity instanceof EntityZombie) { for(int i = 0; i < event.drops.size(); i++) { EntityItem item = event.drops.get(i); if(item.getEntityItem().getItem() == Items.carrot || item.getEntityItem().getItem() == Items.potato) { event.drops.remove(i); } } EntityZombie z = (EntityZombie)event.entity; if(z.isChild()) { int pct = ModSamsContent.cfg.chanceZombieChildFeather; if(event.entity.worldObj.rand.nextInt(100) <= pct) { event.drops.add(new EntityItem(world,pos.getX(),pos.getY(),pos.getZ() ,new ItemStack(Items.feather))); } } if(z.isVillager()) { int pct = ModSamsContent.cfg.chanceZombieVillagerEmerald; if(event.entity.worldObj.rand.nextInt(100) <= pct) { event.drops.add(new EntityItem(world,pos.getX(),pos.getY(),pos.getZ() ,new ItemStack(Items.emerald))); } } } //if(event.entity.worldObj.isRemote) {return;} if(ModSamsContent.cfg.petNametagDrops && SamsUtilities.isPet(event.entity) ) { if(event.entity.getCustomNameTag() != null && //'custom' is blank if no nametag event.entity.getCustomNameTag() != "" ) { //ItemStack nameTag = new ItemStack(Items.name_tag, 1); //its not just an item stack, it needs the name stuck on there ItemStack nameTag = SamsUtilities.buildEnchantedNametag(event.entity.getCustomNameTag()); if(world.isRemote == false) SamsUtilities.dropItemStackInWorld(world, event.entity.getPosition(), nameTag); } } if(ModSamsContent.cfg.petNametagChat && event.entity instanceof EntityLiving ) { if(event.entity.getCustomNameTag() != null && //'custom' is blank if no nametag event.entity.getCustomNameTag() != "" ) { //TODO: pet respawning block/spot with nametags //show message as if player, works since EntityLiving extends EntityLivingBase SamsUtilities.printChatMessage( (event.source.getDeathMessage((EntityLiving)event.entity))); } } if(SamsUtilities.isLivestock(event.entity)) { if(event.source.getSourceOfDamage() != null && event.source.getSourceOfDamage() instanceof EntityPlayer && cfg.livestockLootMultiplier > 0) { //if livestock is killed by a palyer, then multiply the loot by the scale factor for(EntityItem ei : event.drops) { //the stack size does not seem to be mutable so we just get and set the stack with a new size int newdrops = ei.getEntityItem().stackSize * cfg.livestockLootMultiplier; //do not exceed max stack size. Example: if a sword drops, do not make it a 2stack newdrops = Math.min(newdrops, ei.getEntityItem().getMaxStackSize()); ei.setEntityItemStack(new ItemStack(ei.getEntityItem().getItem(), newdrops,ei.getEntityItem().getItemDamage())); } } } } @SubscribeEvent public void onEntityInteractEvent(EntityInteractEvent event) { ItemStack held = event.entityPlayer.getCurrentEquippedItem(); if(held != null && held.getItem() == ItemRegistry.respawn_egg_empty ) { ItemRespawnEggEmpty.entitySpawnEgg(event.entityPlayer, event.target); } if(ModSamsContent.cfg.canNameVillagers && held != null && held.getItem() == Items.name_tag && held.hasDisplayName()) { if(event.entity instanceof EntityVillager) { EntityVillager v = (EntityVillager)event.entity; v.setCustomNameTag(held.getDisplayName()); SamsUtilities.decrHeldStackSize(event.entityPlayer); } } } @SubscribeEvent public void onPlayerInteract(PlayerInteractEvent event) { ItemStack held = event.entityPlayer.getCurrentEquippedItem(); Block blockClicked = event.world.getBlockState(event.pos).getBlock(); TileEntity container = event.world.getTileEntity(event.pos); if(held != null && held.getItem() == ItemRegistry.wandWater ) { ItemWandWater.cast(event); } if(held != null && held.getItem() == ItemRegistry.fire_charge_throw && event.action.RIGHT_CLICK_AIR == event.action) { ItemFireballThrowable.cast(event.world,event.entityPlayer ); } /* if(held != null && held.getItem() == ItemRegistry.wandProspect && event.action.RIGHT_CLICK_BLOCK == event.action) { ItemWandProspect.searchProspect(event.entityPlayer,held,event.pos); } */ if(held != null && held.getItem() == ItemRegistry.wandTransform && event.action.RIGHT_CLICK_BLOCK == event.action) { ItemWandTransform.transformBlock(event.entityPlayer, event.world, held, event.pos); } if(held != null && held.getItem() == ItemRegistry.frozen_snowball && event.action.RIGHT_CLICK_AIR == event.action) { ItemSnowballFrozen.cast(event.world,event.entityPlayer ); } if(held != null && held.getItem() == ItemRegistry.harvest_charge && event.action.RIGHT_CLICK_BLOCK == event.action ) { ItemMagicHarvester.replantField(event.world,event.entityPlayer,held,event.pos); } if(held != null && held.getItem() == ItemRegistry.lightning_charge ) { ItemLightning.cast(event); } if(held != null && held.getItem() == ItemRegistry.carbon_paper && event.action.RIGHT_CLICK_BLOCK == event.action) { ItemPaperCarbon.rightClickBlock(event); } if(held != null && held.getItem() == ItemRegistry.wandBuilding) { if(event.action.LEFT_CLICK_BLOCK == event.action ) { ItemWandBuilding.onPlayerLeftClick(event); } else { if(event.world.isRemote){return;} ItemWandBuilding.onPlayerRightClick(event); } } if(held != null && held.getItem() == ItemRegistry.itemChestSack && event.action.RIGHT_CLICK_BLOCK == event.action) { if(blockClicked instanceof BlockChest)// && event.entityPlayer.isSneaking() { if(container instanceof TileEntityChest) { ItemChestSackEmpty.convertChestToSack(event.entityPlayer,held,(TileEntityChest)container,event.pos); } } } if(held != null && ItemRegistry.itemChestSack != null && held.getItem() == ItemRegistry.itemChestSack && event.action.RIGHT_CLICK_BLOCK == event.action) { if(blockClicked == Blocks.chest) { if(event.world.isRemote){ return ;}//server side only! TileEntityChest chest = (TileEntityChest)event.entityPlayer.worldObj.getTileEntity(event.pos.up()); TileEntityChest teAdjacent = SamsUtilities.getChestAdj(chest); ItemChestSack.sortFromSackToChestEntity(chest,held,event); if(teAdjacent != null) { ItemChestSack.sortFromSackToChestEntity(teAdjacent,held,event); } } else { //if the up one is air, then build a chest at this spot if(event.entityPlayer.worldObj.isAirBlock(event.pos.up()))//TODO:??OFFSET? { ItemChestSack.createAndFillChest(event.entityPlayer,held, event.pos.up()); } } } if (held != null && held.getItem() != null && ItemRegistry.itemEnderBook != null && held.getItem() == ItemRegistry.itemEnderBook && event.action.RIGHT_CLICK_BLOCK == event.action) { ItemEnderBook.rightClickBlock(event.world,event.entityPlayer, held); } if(event.action == event.action.LEFT_CLICK_BLOCK && ModSamsContent.cfg.smartEnderchest && event.entityPlayer.getCurrentEquippedItem() != null && event.entityPlayer.getCurrentEquippedItem().getItem() == Item.getItemFromBlock(Blocks.ender_chest)) { event.entityPlayer.displayGUIChest(event.entityPlayer.getInventoryEnderChest()); } if(ModSamsContent.cfg.swiftDeposit && event.action == event.action.LEFT_CLICK_BLOCK && event.entityPlayer.isSneaking() && event.entityPlayer.getCurrentEquippedItem() == null) { TileEntity te = event.entity.worldObj.getTileEntity(event.pos); if(te != null && (te instanceof TileEntityChest)) { TileEntityChest chest = (TileEntityChest)te ; ChestDeposit.sortFromPlayerToChestEntity(event.world,chest,event.entityPlayer); //check for double chest TileEntityChest teAdjacent = SamsUtilities.getChestAdj(chest); if(teAdjacent != null) { ChestDeposit.sortFromPlayerToChestEntity(event.world,teAdjacent,event.entityPlayer); } } } if(ModSamsContent.cfg.betterBonemeal && event.action != event.action.LEFT_CLICK_BLOCK && SamsUtilities.isBonemeal(held) && blockClicked != null ) { BonemealExt.useBonemeal(event.world, event.entityPlayer, event.pos, blockClicked); } if(ModSamsContent.cfg.flintPumpkin && held != null && held.getItem() == Items.flint_and_steel && event.action.RIGHT_CLICK_BLOCK == event.action ) { if(blockClicked == Blocks.pumpkin) { event.world.setBlockState(event.pos, Blocks.lit_pumpkin.getDefaultState()); SamsUtilities.spawnParticle(event.world, EnumParticleTypes.FLAME, event.pos); SamsUtilities.spawnParticle(event.world, EnumParticleTypes.FLAME, event.pos.offset(event.entityPlayer.getHorizontalFacing())); SamsUtilities.playSoundAt(event.entityPlayer, "fire.ignite"); } else if(blockClicked == Blocks.lit_pumpkin)//then un-light it { event.world.setBlockState(event.pos, Blocks.pumpkin.getDefaultState()); SamsUtilities.spawnParticle(event.world, EnumParticleTypes.FLAME, event.pos); SamsUtilities.spawnParticle(event.world, EnumParticleTypes.FLAME, event.pos.offset(event.entityPlayer.getHorizontalFacing())); SamsUtilities.playSoundAt(event.entityPlayer, "random.fizz"); } } if(ModSamsContent.cfg.skullSignNames && event.action == event.action.LEFT_CLICK_BLOCK && event.entityPlayer.isSneaking() && held != null && held.getItem() == Items.skull && held.getItemDamage() == Reference.skull_player && container != null && container instanceof TileEntitySign) { TileEntitySign sign = (TileEntitySign)container; String firstLine = sign.signText[0].getUnformattedText(); if(firstLine == null) { firstLine = ""; } if(firstLine.isEmpty() || firstLine.split(" ").length == 0) { held.setTagCompound(null); } else { firstLine = firstLine.split(" ")[0]; if(held.getTagCompound() == null) held.setTagCompound(new NBTTagCompound()); held.getTagCompound().setString("SkullOwner",firstLine); } } //end of skullSignNames } @SubscribeEvent public void onHoeUse(UseHoeEvent event) { //this fires BEFORE the block turns into farmland (is cancellable) so check for grass and dirt, not farmland Block clicked = event.world.getBlockState(event.pos).getBlock(); if( (clicked == Blocks.grass || clicked == Blocks.dirt ) && event.world.isAirBlock(event.pos.up()) && ItemRegistry.beetroot_seed != null && event.current.getItem() == Items.golden_hoe && event.world.rand.nextInt(16) == 0) { if(event.world.isRemote == false) SamsUtilities.dropItemStackInWorld(event.world, event.pos, ItemRegistry.beetroot_seed); } } @SubscribeEvent public void onPlayerTick(PlayerTickEvent event) { EntityPlayer player = event.player; ItemStack held = player.getCurrentEquippedItem(); if(held != null && Item.getIdFromItem(held.getItem()) == Item.getIdFromItem(ItemRegistry.wandBuilding) ) { ItemWandBuilding.setCompoundIfNull(held); ItemWandBuilding.tickTimeout(held); } // why isnt this in potionregistry if( player.isPotionActive(PotionRegistry.ender) && //the potion gives us this safe(ish)falling player.dimension == Reference.Dimension.end && //hence the name of the class player.posY < -50 && player.worldObj.isRemote == false && player.capabilities.isCreativeMode == false ) { SamsUtilities.teleportWallSafe(player, player.worldObj, player.getPosition().up(256)); } } @SubscribeEvent public void onKeyInput(InputEvent.KeyInputEvent event) { if(ClientProxy.keyShiftUp.isPressed() ) { ModSamsContent.network.sendToServer( new MessageKeyPressed(ClientProxy.keyShiftUp.getKeyCode())); } else if(ClientProxy.keyShiftDown.isPressed() ) { ModSamsContent.network.sendToServer( new MessageKeyPressed(ClientProxy.keyShiftDown.getKeyCode())); } else if(ClientProxy.keyBarDown.isPressed() ) { ModSamsContent.network.sendToServer( new MessageKeyPressed(ClientProxy.keyBarDown.getKeyCode())); } else if(ClientProxy.keyBarUp.isPressed() ) { ModSamsContent.network.sendToServer( new MessageKeyPressed(ClientProxy.keyBarUp.getKeyCode())); } } @SubscribeEvent public void onLivingDeathEvent(LivingDeathEvent event) { if( ModSamsContent.cfg.endermenDropCarryingBlock && event.entity instanceof EntityEnderman) { EntityEnderman mob = (EntityEnderman)event.entity; IBlockState bs = mob.func_175489_ck();//mcp/forge just did not translate this if(bs != null && bs.getBlock() != null && event.entity.worldObj.isRemote == false) { SamsUtilities.dropItemStackInWorld(event.entity.worldObj, mob.getPosition(), bs.getBlock()); } } if(event.entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer)event.entity; if(ModSamsContent.cfg.dropPlayerSkullOnDeath) { ItemStack skull = SamsUtilities.buildNamedPlayerSkull(player); SamsUtilities.dropItemStackInWorld(event.entity.worldObj, player.getPosition(), skull); } if(ModSamsContent.cfg.playerDeathCoordinates) { String coordsStr = SamsUtilities.posToString(player.getPosition()); SamsUtilities.printChatMessage(player.getDisplayNameString() + " has died at " + coordsStr); } } } }
package ipt341.zarrabi.hooman.a3; import android.app.Activity; import android.media.Image; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; public class MainActivity extends Activity { //integers for each button count private int american; private int chinese; private int indian; private int italian; private int middleEast; private int portugese; //buttons private ImageButton americanButton; private ImageButton chineseButton; private ImageButton indianButton; private ImageButton italianButton; private ImageButton middleEastButton; private ImageButton portugeseButton; //listner View.OnClickListener buttonListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //initializes the buttons, listeners, and ints private void initialize() { american=0; indian=0; chinese=0; italian=0; middleEast=0; portugese=0; americanButton = (ImageButton)findViewById(R.id.AmericanButton); indianButton = (ImageButton)findViewById(R.id.IndianButton); chineseButton= (ImageButton) findViewById(R.id.ChineseButton); italianButton= (ImageButton) findViewById(R.id.ItalianButton); middleEastButton= (ImageButton) findViewById(R.id.MiddleEastButton); portugeseButton= (ImageButton) findViewById(R.id.PortugeseButton); buttonListener= new View.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.AmericanButton: american++; //TODO make toast break; case R.id.IndianButton: indian++; break; case R.id.ChineseButton: chinese++; break; case R.id.ItalianButton: italian++; break; case R.id.MiddleEastButton: middleEast++; break; case R.id.PortugeseButton: portugese++; break; } } }; } }
package com.github.wz2cool.dynamic; import com.github.wz2cool.dynamic.mybatis.MybatisQueryProvider; import com.github.wz2cool.dynamic.mybatis.ParamExpression; import com.github.wz2cool.dynamic.mybatis.db.mapper.NorthwindDao; import com.github.wz2cool.dynamic.mybatis.db.mapper.UserDao; import com.github.wz2cool.dynamic.mybatis.db.model.entity.table.Category; import com.github.wz2cool.dynamic.mybatis.db.model.entity.table.Product; import com.github.wz2cool.dynamic.mybatis.db.model.entity.table.User; import com.github.wz2cool.dynamic.mybatis.db.model.entity.view.ProductView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = TestApplication.class) public class DbFilterTest { @Value("${spring.profiles.active}") private String active; @Autowired private NorthwindDao northwindDao; @Autowired private UserDao userDao; @Test public void testDbInit() throws Exception { List<Category> categories = northwindDao.getCategories(); assertEquals(true, categories.size() > 0); List<Product> products = northwindDao.getProducts(); assertEquals(true, products.size() > 0); } @Test public void testLessThan() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.LESS_THAN, 3); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().allMatch(x -> x.getProductID() < 3)); } @Test public void testLessThanOrEqual() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.LESS_THAN_OR_EQUAL, 3); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().allMatch(x -> x.getProductID() <= 3)); } @Test public void testEqual() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.EQUAL, 2); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); ProductView productView = northwindDao.getProductViewsByDynamic(queryParams).stream().findFirst().orElse(null); assertEquals(Long.valueOf(2), productView.getProductID()); } @Test public void testEqualNull() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.EQUAL, null); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); ProductView productView = northwindDao.getProductViewsByDynamic(queryParams).stream().findFirst().orElse(null); assertEquals(null, productView); } @Test public void testNotEqual() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.NOT_EQUAL, 2); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().noneMatch(x -> x.getProductID() == 2)); } @Test public void testNotEqualNull() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.NOT_EQUAL, null); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().noneMatch(x -> x.getProductID() == null)); } @Test public void testGreaterThanOrEqual() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.GREATER_THAN_OR_EQUAL, 2); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().allMatch(x -> x.getProductID() >= 2)); } @Test public void testGreaterThan() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.GREATER_THAN, 2); ParamExpression paramExpression = MybatisQueryProvider.getWhereExpression(ProductView.class, idFilter); Map<String, Object> queryParams = new HashMap<>(); queryParams.putAll(paramExpression.getParamMap()); queryParams.put("whereExpression", paramExpression.getExpression()); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(true, productViews.stream().allMatch(x -> x.getProductID() > 2)); } @Test public void testStartWith() throws Exception { FilterDescriptor nameFilter = new FilterDescriptor(FilterCondition.AND, "categoryName", FilterOperator.START_WITH, "Be"); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( ProductView.class, "whereExpression", nameFilter); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals("Beverages", productViews.get(0).getCategoryName()); } @Test public void testEndWith() throws Exception { FilterDescriptor nameFilter = new FilterDescriptor(FilterCondition.AND, "categoryName", FilterOperator.END_WITH, "l"); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( ProductView.class, "whereExpression", nameFilter); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals("Oil", productViews.get(0).getCategoryName()); } @Test public void testIn() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.IN, new int[]{2, 4}); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( ProductView.class, "whereExpression", idFilter); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(Long.valueOf(2), productViews.get(0).getProductID()); assertEquals(Long.valueOf(4), productViews.get(1).getProductID()); } @Test public void testNotIn() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.NOT_IN, new int[]{2, 4}); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( ProductView.class, "whereExpression", idFilter); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams); assertEquals(Long.valueOf(1), productViews.get(0).getProductID()); assertEquals(Long.valueOf(3), productViews.get(1).getProductID()); } @Test public void testBetween() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.BETWEEN, new int[]{2, 4}); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( ProductView.class, "whereExpression", idFilter); List<ProductView> productViews = northwindDao.getProductViewsByDynamic(queryParams) .stream().sorted(Comparator.comparing(ProductView::getProductID)).collect(Collectors.toList()); assertEquals(Long.valueOf(2), productViews.get(0).getProductID()); assertEquals(Long.valueOf(3), productViews.get(1).getProductID()); assertEquals(Long.valueOf(4), productViews.get(2).getProductID()); } @Test public void simpleDemo() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.GREATER_THAN_OR_EQUAL, 2); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( Product.class, "whereExpression", idFilter); northwindDao.getProductByDynamic(queryParams); } @Test public void multiFilterDemo() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.GREATER_THAN_OR_EQUAL, 2); FilterDescriptor priceFilter = new FilterDescriptor(FilterCondition.AND, "price", FilterOperator.LESS_THAN, 15); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( Product.class, "whereExpression", idFilter, priceFilter); Product productView = northwindDao.getProductByDynamic(queryParams).stream().findFirst().orElse(null); assertEquals(Integer.valueOf(2), productView.getProductID()); } @Test public void testGroupFilter() throws Exception { FilterGroupDescriptor groupIdFilter = new FilterGroupDescriptor(); FilterDescriptor idFilter1 = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.GREATER_THAN, "1"); FilterDescriptor idFilter2 = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.LESS_THAN, "4"); groupIdFilter.addFilters(idFilter1, idFilter2); FilterDescriptor priceFilter = new FilterDescriptor(FilterCondition.AND, "price", FilterOperator.GREATER_THAN, 10); Map<String, Object> queryParams = MybatisQueryProvider.getWhereQueryParamMap( Product.class, "whereExpression", groupIdFilter, priceFilter); northwindDao.getProductByDynamic(queryParams); } @Test public void testSort() throws Exception { SortDescriptor priceSort = new SortDescriptor("price", SortDirection.DESC); Map<String, Object> queryParams = MybatisQueryProvider.getSortQueryParamMap( Product.class, "orderExpression", priceSort); northwindDao.getProductByDynamic(queryParams); } @Test public void testMultiSort() throws Exception { SortDescriptor priceSort = new SortDescriptor("price", SortDirection.DESC); SortDescriptor idSort = new SortDescriptor("productID", SortDirection.DESC); Map<String, Object> queryParams = MybatisQueryProvider.getSortQueryParamMap( Product.class, "orderExpression", priceSort, idSort); northwindDao.getProductByDynamic(queryParams); } @Test public void testFilterSort() throws Exception { FilterDescriptor idFilter = new FilterDescriptor(FilterCondition.AND, "productID", FilterOperator.NOT_EQUAL, 4); SortDescriptor priceSort = new SortDescriptor("price", SortDirection.ASC); Map<String, Object> filterParams = MybatisQueryProvider.getWhereQueryParamMap( Product.class, "whereExpression", idFilter); Map<String, Object> sortParams = MybatisQueryProvider.getSortQueryParamMap( Product.class, "orderExpression", priceSort); Map<String, Object> queryParams = new HashMap<>(); // map queryParams.putAll(filterParams); queryParams.putAll(sortParams); northwindDao.getProductByDynamic(queryParams); } @Test public void testAgeCustomFilter() throws Exception { CustomFilterDescriptor ageFilter = new CustomFilterDescriptor(FilterCondition.AND, "price > {0} AND price < {1}", 7, 17); Map<String, Object> filterParams = MybatisQueryProvider.getWhereQueryParamMap( Product.class, "whereExpression", ageFilter); northwindDao.getProductByDynamic(filterParams); } }
package com.applicaster.RNYouTubePlayer; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class YoutubePlayerReactPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new YoutubePlayerModule(reactContext)); return modules; } // Deprecated in RN 0.47 public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package com.pega.api2swagger; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.base.Optional; import com.pega.api2swagger.dto.SwaggerGeneratorInput; import com.pega.api2swagger.utils.FileUtils; import com.pega.api2swagger.utils.LogHelper; import com.pega.api2swagger.utils.MapUtils; import io.swagger.models.Swagger; public class SwaggerGeneratorCLI { public static LogHelper logger = new LogHelper(SwaggerGenerator.class); @Parameter(names = { "-e", "--endpoint" }, description = "Endpoint URL", required = true) private String endpoint; @Parameter(names = { "-o", "--output" }, description = "Swagger JSON will be writter to this file, file location should be absolute path", required = true) private String output; @Parameter(names = { "-m", "--method" }, description = "HTTP verb (GET/POST/PUT/DELETE) used for firing endpoint", required = true) private String method; @Parameter(names = { "-h", "--header" }, description = "Endpoint request headers should be specified as <key>=<value> pairs", required = false) private List<String> header; @Parameter(names = { "-p", "--param" }, description = "Endpoint request parameters should be specified as <key>=<value> pairs", required = false) private List<String> params; @Parameter(names = { "-pp", "--pathparam" }, description = "Endpoint request parameters should be specified as <key>=<value> pairs", required = false) private List<String> dynamicParameters; @Parameter(names = { "-a", "--authentication" }, description = "Boolean flag to specify authentication is needed", required = false) private boolean isAuthenticationNeeded; @Parameter(names = { "-username", "--username" }, description = "Username", required = false) private String username; @Parameter(names = { "-password", "--password" }, description = "Password", required = false) private String password; @Parameter(names = { "-host", "--host" }, description = "Hostname value will be populated in Swagger JSON's 'host' attribute", required = false) private String host; @Parameter(names = { "-basepath", "--basepath" }, description = "Base Path for Swagger JSON's 'basepath' attribute", required = true) private String basePath; @Parameter(names = { "-apiname", "--apiname" }, description = "Unique API name for the given endpoint", required = true) private String apiName; @Parameter(names = { "-apisummary", "--apisummary" }, description = "Endpoint Summary", required = false) private String apiSummary; @Parameter(names = { "-apidescription", "--apidescription" }, description = "Endpoint Description", required = false) private String apiDescription; @Parameter(names = { "-tag", "--apitag" }, description = "Endpoint tag", required = false) private List<String> apiTags; @Parameter(names = { "-help", "--help" }, help = true) private boolean help = false; public static void main(String args[]){ SwaggerGeneratorCLI cli = new SwaggerGeneratorCLI(); JCommander commander = null; try{ commander = new JCommander(cli, args); commander.setProgramName("API2Swagger"); } catch(ParameterException exception){ logger.error(exception.getMessage()); logger.error("For help, use --help option"); return; } if(cli.help){ commander.usage(); return; } Map<String, String> headerMap = MapUtils.convertToMap(cli.header); Map<String, String> pathParamMap = MapUtils.convertToMap(cli.dynamicParameters); Map<String, Object> paramMap = MapUtils.convertToMapObject(cli.params); SwaggerGeneratorInput userInput = new SwaggerGeneratorInput.Builder().endpoint(cli.endpoint) .method(cli.method) .pathParams(pathParamMap) .parameters(paramMap) .headers(headerMap) .swaggerJSONFilePath(cli.output) .authentication(cli.isAuthenticationNeeded) .username(cli.username) .password(cli.password) .host(cli.host) .basePath(cli.basePath) .apiName(cli.apiName) .apiDescription(cli.apiDescription) .apiSummary(cli.apiSummary) .apiTags(cli.apiTags) .build(); SwaggerGenerator main = new SwaggerGenerator(userInput); logger.info("Generating Swagger json for the input [%s]", userInput); Optional<Swagger> outputSwagger = main.buildSwaggerJson(); if(outputSwagger.isPresent()){ FileUtils.writeSwaggerToFile(userInput.swaggerJSONFilePath(), outputSwagger.get()); } logger.info("Swagger generatin is complete and output is written to "+ userInput.swaggerJSONFilePath()); } }
package org.bouncycastle.crypto.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.SecureRandom; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; /** * An implementation of all high level protocols in TLS 1.0/1.1. */ public abstract class TlsProtocol { protected static final Integer EXT_RenegotiationInfo = Integers.valueOf(ExtensionType.renegotiation_info); protected static final Integer EXT_SessionTicket = Integers.valueOf(ExtensionType.session_ticket); private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Our Connection states */ protected static final short CS_START = 0; protected static final short CS_CLIENT_HELLO = 1; protected static final short CS_SERVER_HELLO = 2; protected static final short CS_SERVER_SUPPLEMENTAL_DATA = 3; protected static final short CS_SERVER_CERTIFICATE = 4; protected static final short CS_CERTIFICATE_STATUS = 5; protected static final short CS_SERVER_KEY_EXCHANGE = 6; protected static final short CS_CERTIFICATE_REQUEST = 7; protected static final short CS_SERVER_HELLO_DONE = 8; protected static final short CS_CLIENT_SUPPLEMENTAL_DATA = 9; protected static final short CS_CLIENT_CERTIFICATE = 10; protected static final short CS_CLIENT_KEY_EXCHANGE = 11; protected static final short CS_CERTIFICATE_VERIFY = 12; protected static final short CS_CLIENT_FINISHED = 13; protected static final short CS_SERVER_SESSION_TICKET = 14; protected static final short CS_SERVER_FINISHED = 15; protected static final short CS_END = 16; /* * Queues for data from some protocols. */ private ByteQueue applicationDataQueue = new ByteQueue(); private ByteQueue alertQueue = new ByteQueue(2); private ByteQueue handshakeQueue = new ByteQueue(); /* * The Record Stream we use */ protected RecordStream recordStream; protected SecureRandom secureRandom; private TlsInputStream tlsInputStream = null; private TlsOutputStream tlsOutputStream = null; private volatile boolean closed = false; private volatile boolean failedWithError = false; private volatile boolean appDataReady = false; private volatile boolean writeExtraEmptyRecords = true; private byte[] expected_verify_data = null; protected TlsSession tlsSession = null; protected SessionParameters sessionParameters = null; protected SecurityParameters securityParameters = null; protected Certificate peerCertificate = null; protected int[] offeredCipherSuites = null; protected short[] offeredCompressionMethods = null; protected Hashtable clientExtensions = null; protected Hashtable serverExtensions = null; protected short connection_state = CS_START; protected boolean resumedSession = false; protected boolean receivedChangeCipherSpec = false; protected boolean secure_renegotiation = false; protected boolean allowCertificateStatus = false; protected boolean expectSessionTicket = false; public TlsProtocol(InputStream input, OutputStream output, SecureRandom secureRandom) { this.recordStream = new RecordStream(this, input, output); this.secureRandom = secureRandom; } protected abstract AbstractTlsContext getContext(); protected abstract TlsPeer getPeer(); protected void handleChangeCipherSpecMessage() throws IOException { } protected abstract void handleHandshakeMessage(short type, byte[] buf) throws IOException; protected void handleWarningMessage(short description) throws IOException { } protected void cleanupHandshake() { if (this.expected_verify_data != null) { Arrays.fill(this.expected_verify_data, (byte)0); this.expected_verify_data = null; } this.securityParameters.clear(); this.peerCertificate = null; this.offeredCipherSuites = null; this.offeredCompressionMethods = null; this.clientExtensions = null; this.serverExtensions = null; this.resumedSession = false; this.receivedChangeCipherSpec = false; this.secure_renegotiation = false; this.allowCertificateStatus = false; this.expectSessionTicket = false; } protected void completeHandshake() throws IOException { try { /* * We will now read data, until we have completed the handshake. */ while (this.connection_state != CS_END) { if (this.closed) { // TODO What kind of exception/alert? } safeReadRecord(); } this.recordStream.finaliseHandshake(); this.writeExtraEmptyRecords = !TlsUtils.isTLSv11(getContext()); /* * If this was an initial handshake, we are now ready to send and receive application data. */ if (!appDataReady) { this.appDataReady = true; this.tlsInputStream = new TlsInputStream(this); this.tlsOutputStream = new TlsOutputStream(this); } if (this.tlsSession != null) { if (this.sessionParameters == null) { this.sessionParameters = new SessionParameters.Builder() .setCipherSuite(this.securityParameters.cipherSuite) .setCompressionAlgorithm(this.securityParameters.compressionAlgorithm) .setMasterSecret(this.securityParameters.masterSecret) .setPeerCertificate(this.peerCertificate) // TODO Consider filtering extensions that aren't relevant to resumed sessions .setServerExtensions(this.serverExtensions) .build(); this.tlsSession = new TlsSessionImpl(this.tlsSession.getSessionID(), this.sessionParameters); } getContext().setResumableSession(this.tlsSession); } getPeer().notifyHandshakeComplete(); } finally { cleanupHandshake(); } } protected void processRecord(short protocol, byte[] buf, int offset, int len) throws IOException { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case ContentType.alert: { alertQueue.addData(buf, offset, len); processAlert(); break; } case ContentType.application_data: { if (!appDataReady) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } applicationDataQueue.addData(buf, offset, len); processApplicationData(); break; } case ContentType.change_cipher_spec: { processChangeCipherSpec(buf, offset, len); break; } case ContentType.handshake: { handshakeQueue.addData(buf, offset, len); processHandshake(); break; } case ContentType.heartbeat: { // TODO[RFC 6520] } default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ } } private void processHandshake() throws IOException { boolean read; do { read = false; /* * We need the first 4 bytes, they contain type and length of the message. */ if (handshakeQueue.size() >= 4) { byte[] beginning = new byte[4]; handshakeQueue.read(beginning, 0, 4, 0); ByteArrayInputStream bis = new ByteArrayInputStream(beginning); short type = TlsUtils.readUint8(bis); int len = TlsUtils.readUint24(bis); /* * Check if we have enough bytes in the buffer to read the full message. */ if (handshakeQueue.size() >= (len + 4)) { /* * Read the message. */ byte[] buf = handshakeQueue.removeData(len, 4); /* * RFC 2246 7.4.9. The value handshake_messages includes all handshake messages * starting at client hello up to, but not including, this finished message. * [..] Note: [Also,] Hello Request messages are omitted from handshake hashes. */ switch (type) { case HandshakeType.hello_request: break; case HandshakeType.finished: { if (this.expected_verify_data == null) { this.expected_verify_data = createVerifyData(!getContext().isServer()); } // NB: Fall through to next case label } default: recordStream.updateHandshakeData(beginning, 0, 4); recordStream.updateHandshakeData(buf, 0, len); break; } /* * Now, parse the message. */ handleHandshakeMessage(type, buf); read = true; } } } while (read); } private void processApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application data arrives in the future. */ } private void processAlert() throws IOException { while (alertQueue.size() >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = alertQueue.removeData(2, 0); short level = tmp[0]; short description = tmp[1]; getPeer().notifyAlertReceived(level, description); if (level == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ invalidateSession(); this.failedWithError = true; this.closed = true; recordStream.safeClose(); throw new IOException(TLS_ERROR_MESSAGE); } else { /* * RFC 5246 7.2.1. The other party MUST respond with a close_notify alert of its own * and close down the connection immediately, discarding any pending writes. */ // TODO Can close_notify be a fatal alert? if (description == AlertDescription.close_notify) { handleClose(false); } /* * If it is just a warning, we continue. */ handleWarningMessage(description); } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the handshake is not in the correct * state. */ private void processChangeCipherSpec(byte[] buf, int off, int len) throws IOException { for (int i = 0; i < len; ++i) { short message = TlsUtils.readUint8(buf, off + i); if (message != ChangeCipherSpec.change_cipher_spec) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (this.receivedChangeCipherSpec) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } this.receivedChangeCipherSpec = true; recordStream.receivedReadCipherSpec(); handleChangeCipherSpecMessage(); } } /** * Read data from the network. The method will return immediately, if there is still some data * left in the buffer, or block until some application data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ protected int readApplicationData(byte[] buf, int offset, int len) throws IOException { if (len < 1) { return 0; } while (applicationDataQueue.size() == 0) { /* * We need to read some data. */ if (this.closed) { if (this.failedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } /* * Connection has been closed, there is no more data to read. */ return -1; } safeReadRecord(); } len = Math.min(len, applicationDataQueue.size()); applicationDataQueue.removeData(buf, offset, len, 0); return len; } protected void safeReadRecord() throws IOException { try { if (!recordStream.readRecord()) { // TODO It would be nicer to allow graceful connection close if between records // this.failWithError(AlertLevel.warning, AlertDescription.close_notify); throw new EOFException(); } } catch (TlsFatalAlert e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, e.getAlertDescription(), "Failed to read record", e); } throw e; } catch (IOException e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to read record", e); } throw e; } catch (RuntimeException e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to read record", e); } throw e; } } protected void safeWriteRecord(short type, byte[] buf, int offset, int len) throws IOException { try { recordStream.writeRecord(type, buf, offset, len); } catch (TlsFatalAlert e) { if (!this.closed) { this.failWithError(AlertLevel.fatal, e.getAlertDescription(), "Failed to write record", e); } throw e; } catch (IOException e) { if (!closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to write record", e); } throw e; } catch (RuntimeException e) { if (!closed) { this.failWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to write record", e); } throw e; } } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ protected void writeData(byte[] buf, int offset, int len) throws IOException { if (this.closed) { if (this.failedWithError) { throw new IOException(TLS_ERROR_MESSAGE); } throw new IOException("Sorry, connection has been closed, you cannot write more data"); } while (len > 0) { /* * RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are * potentially useful as a traffic analysis countermeasure. */ if (this.writeExtraEmptyRecords) { /* * Protect against known IV attack! * * DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE. */ safeWriteRecord(ContentType.application_data, TlsUtils.EMPTY_BYTES, 0, 0); } // Fragment data according to the current fragment limit. int toWrite = Math.min(len, recordStream.getPlaintextLimit()); safeWriteRecord(ContentType.application_data, buf, offset, toWrite); offset += toWrite; len -= toWrite; } } protected void writeHandshakeMessage(byte[] buf, int off, int len) throws IOException { while (len > 0) { // Fragment data according to the current fragment limit. int toWrite = Math.min(len, recordStream.getPlaintextLimit()); safeWriteRecord(ContentType.handshake, buf, off, toWrite); off += toWrite; len -= toWrite; } } /** * @return An OutputStream which can be used to send data. */ public OutputStream getOutputStream() { return this.tlsOutputStream; } /** * @return An InputStream which can be used to read data. */ public InputStream getInputStream() { return this.tlsInputStream; } /** * Terminate this connection with an alert. Can be used for normal closure too. * * @param alertLevel * See {@link AlertLevel} for values. * @param alertDescription * See {@link AlertDescription} for values. * @throws IOException * If alert was fatal. */ protected void failWithError(short alertLevel, short alertDescription, String message, Exception cause) throws IOException { /* * Check if the connection is still open. */ if (!closed) { /* * Prepare the message */ this.closed = true; if (alertLevel == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ // TODO This isn't quite in the right place. Also, as of TLS 1.1 the above is obsolete. invalidateSession(); this.failedWithError = true; } raiseAlert(alertLevel, alertDescription, message, cause); recordStream.safeClose(); if (alertLevel != AlertLevel.fatal) { return; } } throw new IOException(TLS_ERROR_MESSAGE); } protected void invalidateSession() { if (this.sessionParameters != null) { this.sessionParameters.clear(); this.sessionParameters = null; } if (this.tlsSession != null) { this.tlsSession.invalidate(); this.tlsSession = null; } } protected void processFinishedMessage(ByteArrayInputStream buf) throws IOException { byte[] verify_data = TlsUtils.readFully(expected_verify_data.length, buf); assertEmpty(buf); /* * Compare both checksums. */ if (!Arrays.constantTimeAreEqual(expected_verify_data, verify_data)) { /* * Wrong checksum in the finished message. */ throw new TlsFatalAlert(AlertDescription.decrypt_error); } } protected void raiseAlert(short alertLevel, short alertDescription, String message, Exception cause) throws IOException { getPeer().notifyAlertRaised(alertLevel, alertDescription, message, cause); byte[] error = new byte[2]; error[0] = (byte)alertLevel; error[1] = (byte)alertDescription; safeWriteRecord(ContentType.alert, error, 0, 2); } protected void raiseWarning(short alertDescription, String message) throws IOException { raiseAlert(AlertLevel.warning, alertDescription, message, null); } protected void sendCertificateMessage(Certificate certificate) throws IOException { if (certificate == null) { certificate = Certificate.EMPTY_CHAIN; } if (certificate.getLength() == 0) { TlsContext context = getContext(); if (!context.isServer()) { ProtocolVersion serverVersion = getContext().getServerVersion(); if (serverVersion.isSSL()) { String message = serverVersion.toString() + " client didn't provide credentials"; raiseWarning(AlertDescription.no_certificate, message); return; } } } HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate); certificate.encode(message); message.writeToRecordStream(); } protected void sendChangeCipherSpecMessage() throws IOException { byte[] message = new byte[]{ 1 }; safeWriteRecord(ContentType.change_cipher_spec, message, 0, message.length); recordStream.sentWriteCipherSpec(); } protected void sendFinishedMessage() throws IOException { byte[] verify_data = createVerifyData(getContext().isServer()); HandshakeMessage message = new HandshakeMessage(HandshakeType.finished, verify_data.length); message.write(verify_data); message.writeToRecordStream(); } protected void sendSupplementalDataMessage(Vector supplementalData) throws IOException { HandshakeMessage message = new HandshakeMessage(HandshakeType.supplemental_data); writeSupplementalData(message, supplementalData); message.writeToRecordStream(); } protected byte[] createVerifyData(boolean isServer) { TlsContext context = getContext(); if (isServer) { return TlsUtils.calculateVerifyData(context, ExporterLabel.server_finished, recordStream.getCurrentHash(TlsUtils.SSL_SERVER)); } return TlsUtils.calculateVerifyData(context, ExporterLabel.client_finished, recordStream.getCurrentHash(TlsUtils.SSL_CLIENT)); } /** * Closes this connection. * * @throws IOException If something goes wrong during closing. */ public void close() throws IOException { handleClose(true); } protected void handleClose(boolean user_canceled) throws IOException { if (!closed) { if (user_canceled && !appDataReady) { raiseWarning(AlertDescription.user_canceled, "User canceled handshake"); } this.failWithError(AlertLevel.warning, AlertDescription.close_notify, "Connection closed", null); } } protected void flush() throws IOException { recordStream.flush(); } protected short processMaxFragmentLengthExtension(Hashtable clientExtensions, Hashtable serverExtensions, short alertDescription) throws IOException { short maxFragmentLength = TlsExtensionsUtils.getMaxFragmentLengthExtension(serverExtensions); if (maxFragmentLength >= 0 && !this.resumedSession) { if (maxFragmentLength != TlsExtensionsUtils.getMaxFragmentLengthExtension(clientExtensions)) { throw new TlsFatalAlert(alertDescription); } } return maxFragmentLength; } protected static boolean arrayContains(short[] a, short n) { for (int i = 0; i < a.length; ++i) { if (a[i] == n) { return true; } } return false; } protected static boolean arrayContains(int[] a, int n) { for (int i = 0; i < a.length; ++i) { if (a[i] == n) { return true; } } return false; } /** * Make sure the InputStream 'buf' now empty. Fail otherwise. * * @param buf The InputStream to check. * @throws IOException If 'buf' is not empty. */ protected static void assertEmpty(ByteArrayInputStream buf) throws IOException { if (buf.available() > 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } } protected static byte[] createRandomBlock(SecureRandom random) { random.setSeed(System.currentTimeMillis()); byte[] result = new byte[32]; random.nextBytes(result); /* * The consensus seems to be that using the time here is neither all that useful, nor * secure. Perhaps there could be an option to (re-)enable it. Instead, we seed the random * source with the current time to retain it's main benefit. */ // TlsUtils.writeGMTUnixTime(result, 0); return result; } protected static byte[] createRenegotiationInfo(byte[] renegotiated_connection) throws IOException { return TlsUtils.encodeOpaque8(renegotiated_connection); } protected static void establishMasterSecret(TlsContext context, TlsKeyExchange keyExchange) throws IOException { byte[] pre_master_secret = keyExchange.generatePremasterSecret(); try { context.getSecurityParameters().masterSecret = TlsUtils.calculateMasterSecret(context, pre_master_secret); } finally { // TODO Is there a way to ensure the data is really overwritten? /* * RFC 2246 8.1. The pre_master_secret should be deleted from memory once the * master_secret has been computed. */ if (pre_master_secret != null) { Arrays.fill(pre_master_secret, (byte)0); } } } protected static Hashtable readExtensions(ByteArrayInputStream input) throws IOException { if (input.available() < 1) { return null; } byte[] extBytes = TlsUtils.readOpaque16(input); assertEmpty(input); ByteArrayInputStream buf = new ByteArrayInputStream(extBytes); // Integer -> byte[] Hashtable extensions = new Hashtable(); while (buf.available() > 0) { Integer extension_type = Integers.valueOf(TlsUtils.readUint16(buf)); byte[] extension_data = TlsUtils.readOpaque16(buf); /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ if (null != extensions.put(extension_type, extension_data)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } return extensions; } protected static Vector readSupplementalDataMessage(ByteArrayInputStream input) throws IOException { byte[] supp_data = TlsUtils.readOpaque24(input); assertEmpty(input); ByteArrayInputStream buf = new ByteArrayInputStream(supp_data); Vector supplementalData = new Vector(); while (buf.available() > 0) { int supp_data_type = TlsUtils.readUint16(buf); byte[] data = TlsUtils.readOpaque16(buf); supplementalData.addElement(new SupplementalDataEntry(supp_data_type, data)); } return supplementalData; } protected static void writeExtensions(OutputStream output, Hashtable extensions) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); Enumeration keys = extensions.keys(); while (keys.hasMoreElements()) { Integer key = (Integer)keys.nextElement(); int extension_type = key.intValue(); byte[] extension_data = (byte[])extensions.get(key); TlsUtils.checkUint16(extension_type); TlsUtils.writeUint16(extension_type, buf); TlsUtils.writeOpaque16(extension_data, buf); } byte[] extBytes = buf.toByteArray(); TlsUtils.writeOpaque16(extBytes, output); } protected static void writeSupplementalData(OutputStream output, Vector supplementalData) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); for (int i = 0; i < supplementalData.size(); ++i) { SupplementalDataEntry entry = (SupplementalDataEntry)supplementalData.elementAt(i); int supp_data_type = entry.getDataType(); TlsUtils.checkUint16(supp_data_type); TlsUtils.writeUint16(supp_data_type, buf); TlsUtils.writeOpaque16(entry.getData(), buf); } byte[] supp_data = buf.toByteArray(); TlsUtils.writeOpaque24(supp_data, output); } protected static int getPRFAlgorithm(TlsContext context, int ciphersuite) throws IOException { boolean isTLSv12 = TlsUtils.isTLSv12(context); switch (ciphersuite) { case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha256; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha384; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha384; } return PRFAlgorithm.tls_prf_legacy; } default: { if (isTLSv12) { return PRFAlgorithm.tls_prf_sha256; } return PRFAlgorithm.tls_prf_legacy; } } } class HandshakeMessage extends ByteArrayOutputStream { HandshakeMessage(short handshakeType) throws IOException { this(handshakeType, 60); } HandshakeMessage(short handshakeType, int length) throws IOException { super(length + 4); TlsUtils.writeUint8(handshakeType, this); // Reserve space for length count += 3; } void writeToRecordStream() throws IOException { // Patch actual length back in int length = count - 4; TlsUtils.checkUint24(length); TlsUtils.writeUint24(length, buf, 1); writeHandshakeMessage(buf, 0, count); buf = null; } } }
package net.imagej.ops.geom.geom3d.mesh; public interface Facet { // NB: Marker Interface }
package net.serverpeon.twitcharchiver.ui; import com.google.common.base.Predicate; import net.serverpeon.twitcharchiver.downloader.VideoStore; import net.serverpeon.twitcharchiver.downloader.VideoStoreDownloader; import net.serverpeon.twitcharchiver.twitch.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.*; import java.awt.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; public class GUI extends JFrame { private final static Logger logger = LogManager.getLogger(GUI.class); private final ExecutorService executors = Executors.newSingleThreadExecutor(); private final OAuthPanel oauth; private final ChannelPanel channel; private final DataPanel vp = new DataPanel(); private final DownloadPanel download; private final AtomicReference<VideoStore> vs = new AtomicReference<>(); private String selectedChannel = null; private OAuthToken userOAuthToken = null; public GUI() { super("Twitch Archiver - by @KiskaeEU"); this.oauth = new OAuthPanel(new Predicate<String>() { @Override public boolean apply(String s) { final OAuthToken oauthToken; if (s.startsWith("oauth:")) oauthToken = new OAuthToken(s.substring(6)); else oauthToken = new OAuthToken(s); setSelectedChannel(null, null); if (s.isEmpty()) return false; executors.execute(new Runnable() { @Override public void run() { try { final String userName = TwitchApi.getTwitchUsernameWithOAuth(oauthToken); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setSelectedChannel(userName, oauthToken); } }); } catch (InvalidOAuthTokenException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog( GUI.this, "The OAuth token you gave was invalid.", "Invalid token", JOptionPane.ERROR_MESSAGE ); } }); } } }); return false; } }); this.channel = new ChannelPanel(new Runnable() { @Override public void run() { if (!channel.isStorageDirectorySet()) { JOptionPane.showMessageDialog(GUI.this, "Please set the download directory before querying Twitch", "Please set download directory", JOptionPane.ERROR_MESSAGE ); return; } oauth.setEnabled(false); channel.setEnabled(false); channel.enableProgressBar(true); download.setEnabled(false); final VideoStore vs = new VideoStore(channel.getStorageDirectory(), selectedChannel, userOAuthToken); GUI.this.vs.set(vs); vp.setTableModel(vs.getTableView(), new Predicate<Boolean>() { @Override public boolean apply(Boolean aBoolean) { vs.setSelectedForAll(aBoolean); return false; } }); final int limit = channel.getLimit(); executors.execute(new Runnable() { @Override public void run() { final Runnable r = new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { oauth.setEnabled(true); channel.setEnabled(true); channel.enableProgressBar(false); download.setEnabled(true); } }); } }; try { vs.loadData(limit, r); } catch (SubscriberOnlyException ex) { r.run(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(GUI.this, "These videos are limited to subscribers, this should only show" + " up if you're messing with code.", "I cannae see them, captain", JOptionPane.ERROR_MESSAGE); } }); } catch (UnrecognizedVodFormatException ex) { r.run(); logger.error("Exception during VoD retrieval.", ex); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(GUI.this, "Something failed while retrieving information from twitch, " + "please contact @KiskaeEU on twitter.", "Error 37: Twitch", JOptionPane.ERROR_MESSAGE); } }); } } }); } }); this.download = new DownloadPanel(new Runnable() { @Override public void run() { final VideoStore vs = getVideoStore(); int ret = JOptionPane.showConfirmDialog(GUI.this, "Please make sure you have enough disk space to store the videos. \n" + "Do you have enough space?", "Check your disk space!", JOptionPane.YES_NO_OPTION ); if (ret == JOptionPane.YES_OPTION && vs != null) { oauth.setEnabled(false); channel.setEnabled(false); download.setEnabled(false); vp.setEnabled(false); download.setProcessing(true); executors.execute(new VideoStoreDownloader(vs, new Runnable() { @Override public void run() { oauth.setEnabled(true); channel.setEnabled(true); download.setEnabled(true); vp.setEnabled(true); download.setProcessing(false); JOptionPane.showMessageDialog(GUI.this, "All downloads have finished", "DONE", JOptionPane.INFORMATION_MESSAGE ); } }, download.getNumberOfProcesses())); } } }); } public void init() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (final UnsupportedLookAndFeelException ignored) { /* Will just default to the cross-platform L&F */ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.warn("Exception setting Swing L&F", e); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initWindow(); } }); } private void setSelectedChannel(final String channelName, OAuthToken oauthToken) { this.selectedChannel = channelName; this.userOAuthToken = oauthToken; this.channel.setChannelName(channelName); this.download.setEnabled(false); } private void initWindow() { this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.add(vp, BorderLayout.CENTER); this.add(createControlPanel(), BorderLayout.LINE_END); this.download.setEnabled(false); SwingUtilities.updateComponentTreeUI(this); this.pack(); this.setVisible(true); } public VideoStore getVideoStore() { return this.vs.get(); } private JComponent createControlPanel() { final JPanel ret = new JPanel(); ret.setLayout(new BoxLayout(ret, BoxLayout.PAGE_AXIS)); ret.add(this.oauth); ret.add(Box.createVerticalGlue()); ret.add(this.channel); ret.add(Box.createVerticalGlue()); ret.add(this.download); return ret; } }
package com.birdbraintechnologies.birdblocks.bluetooth; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.content.Context; import android.util.Log; import java.util.Arrays; import java.util.UUID; import java.util.concurrent.CountDownLatch; public class UARTConnection extends BluetoothGattCallback { private static final String TAG = UARTConnection.class.getName(); private int connectionState; private CountDownLatch startLatch = new CountDownLatch(1); private CountDownLatch doneLatch = new CountDownLatch(1); private UUID uartUUID, txUUID, rxUUID; private BluetoothGatt btGatt; private BluetoothGattCharacteristic tx; private BluetoothGattCharacteristic rx; public UARTConnection(Context context, BluetoothDevice device, UARTSettings settings) { this.uartUUID = settings.getUARTServiceUUID(); this.txUUID = settings.getTxCharacteristicUUID(); this.rxUUID = settings.getRxCharacteristicUUID(); establishUARTConnection(context, device); } synchronized public boolean writeBytes(byte[] bytes) { startLatch = new CountDownLatch(1); doneLatch = new CountDownLatch(1); // Serialize callback tx.setValue(bytes); startLatch.countDown(); boolean res = btGatt.writeCharacteristic(tx); try { doneLatch.await(); } catch (InterruptedException e) { Log.e(TAG, "Error: " + e); } return res; } private boolean establishUARTConnection(Context context, BluetoothDevice device) { this.btGatt = device.connectGatt(context, false, this); startLatch.countDown(); try { doneLatch.await(); } catch (InterruptedException e) { // TODO: Handle error return false; } Log.d(TAG, "Successfully established connection to " + device); return true; } @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { connectionState = newState; if (status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothGatt.STATE_CONNECTED) { gatt.discoverServices(); } } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { tx = gatt.getService(uartUUID).getCharacteristic(txUUID); rx = gatt.getService(uartUUID).getCharacteristic(rxUUID); doneLatch.countDown(); } } @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { // For serializing write operations try { startLatch.await(); } catch (InterruptedException e) { Log.e(TAG, "Error: " + e); } if (status == BluetoothGatt.GATT_SUCCESS) { Log.d(TAG, "Successfully wrote " + Arrays.toString(characteristic.getValue()) + " to TX"); } else { Log.d(TAG, "Error writing " + Arrays.toString(characteristic.getValue()) + " to TX"); } // TODO: Inidcate write success/failure to main thread // For serializing write operations doneLatch.countDown(); } public boolean isConnected() { return this.connectionState == BluetoothGatt.STATE_CONNECTED; } public void disconnect() { btGatt.disconnect(); btGatt.close(); } }
package com.redhat.victims.database; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.commons.io.FileUtils; import com.redhat.victims.VictimsConfig; import com.redhat.victims.VictimsException; import com.redhat.victims.VictimsRecord; import com.redhat.victims.VictimsService; import com.redhat.victims.VictimsService.RecordStream; import com.redhat.victims.fingerprint.Algorithms; public class VictimsSqlDB implements VictimsDBInterface { protected static final String UPDATE_FILE_NAME = "lastUpdate"; protected File lastUpdate; protected String cache; protected Connection connection; protected HashMap<Integer, Integer> cachedCount; // database credentials protected String user = "victims"; protected String password = "victims"; // Prepared statements used PreparedStatement insertRecord; PreparedStatement insertFileHash; PreparedStatement insertMeta; PreparedStatement insertCVE; PreparedStatement fetchRecordId; PreparedStatement fetchCVES; PreparedStatement deleteRecordHash; PreparedStatement deleteRecordId; PreparedStatement deleteFileHashes; PreparedStatement deleteMeta; PreparedStatement deleteCVES; PreparedStatement countMatchedFileHash; PreparedStatement countFileHashes; PreparedStatement[] cascadeDeleteOnId; protected void initDB() throws SQLException { Statement stmt = this.connection.createStatement(); stmt.execute(Query.CREATE_TABLE_RECORDS); stmt.execute(Query.CREATE_TABLE_FILEHASHES); stmt.execute(Query.CREATE_TABLE_META); stmt.execute(Query.CREATE_TABLE_CVES); } protected void prepareStatements() throws SQLException { insertRecord = connection.prepareStatement(Query.INSERT_RECORD); insertFileHash = connection.prepareStatement(Query.INSERT_FILEHASH); insertMeta = connection.prepareStatement(Query.INSERT_META); insertCVE = connection.prepareStatement(Query.INSERT_CVES); fetchRecordId = connection.prepareStatement(Query.GET_RECORD_ID); fetchCVES = connection.prepareStatement(Query.FIND_CVES); deleteRecordHash = connection .prepareStatement(Query.DELETE_RECORD_HASH); deleteRecordId = connection.prepareStatement(Query.DELETE_RECORD_ID); deleteFileHashes = connection.prepareStatement(Query.DELETE_FILEHASHES); deleteMeta = connection.prepareStatement(Query.DELETE_METAS); deleteCVES = connection.prepareStatement(Query.DELETE_CVES); cascadeDeleteOnId = new PreparedStatement[] { deleteFileHashes, deleteMeta, deleteCVES, deleteRecordId }; countMatchedFileHash = connection .prepareStatement(Query.FILEHASH_MATCHES_PER_RECORD); countFileHashes = connection .prepareStatement(Query.FILEHASH_COUNT_PER_RECORD); } protected void connect(String dbUrl, boolean init) throws SQLException { this.connection = DriverManager.getConnection(dbUrl, user, password); if (init) { initDB(); } prepareStatements(); this.connection.setAutoCommit(false); } public VictimsSqlDB(String driver) throws IOException, ClassNotFoundException { this.cache = VictimsConfig.cache().toString(); this.lastUpdate = FileUtils.getFile(this.cache, UPDATE_FILE_NAME); Class.forName(driver); } public VictimsSqlDB(String driver, String dbUrl, boolean init) throws IOException, ClassNotFoundException, SQLException { this(driver); connect(dbUrl, init); } protected int getRecordId(String hash) throws SQLException { fetchRecordId.setString(1, hash); ResultSet rs = fetchRecordId.executeQuery(); while (rs.next()) { return rs.getInt("id"); } return -1; } protected int addRecord(String hash) throws SQLException { insertRecord.setString(1, hash); insertRecord.execute(); ResultSet rs = insertRecord.getGeneratedKeys(); while (rs.next()) { System.out.println(hash + " : " + rs.getInt(1)); return rs.getInt(1); } return -1; } protected void removeRecord(String hash) throws SQLException { int id = getRecordId(hash); if (id > 0) { for (PreparedStatement ps : cascadeDeleteOnId) { ps.setInt(1, id); ps.execute(); } } } protected void remove(RecordStream rs) throws SQLException, IOException { while (rs.hasNext()) { VictimsRecord vr = rs.getNext(); deleteRecordHash.setString(1, vr.hash); } deleteRecordHash.executeBatch(); } protected void update(RecordStream rs) throws SQLException, IOException { while (rs.hasNext()) { VictimsRecord vr = rs.getNext(); String hash = vr.hash.trim(); removeRecord(hash); // add the new/updated hash int id = addRecord(hash); // insert file hahes for (String filehash : vr.getHashes(Algorithms.SHA512).keySet()) { insertFileHash.setInt(1, id); insertFileHash.setString(2, filehash.trim()); insertFileHash.addBatch(); } // insert metadata key-value pairs HashMap<String, String> md = vr.getFlattenedMetaData(); for (String key : md.keySet()) { insertMeta.setInt(1, id); insertMeta.setString(2, key); insertMeta.setString(3, md.get(key)); insertMeta.addBatch(); } // insert cves for (String cve : vr.cves) { insertCVE.setInt(1, id); insertCVE.setString(2, cve.trim()); insertCVE.addBatch(); } } insertFileHash.executeBatch(); insertMeta.executeBatch(); insertCVE.executeBatch(); } protected void setLastUpdate(Date date) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat(VictimsRecord.DATE_FORMAT); String stamp = sdf.format(date); FileUtils.write(lastUpdate, stamp); } public Date lastUpdated() throws VictimsException { Throwable throwable = null; try { SimpleDateFormat sdf = new SimpleDateFormat( VictimsRecord.DATE_FORMAT); Date since; since = sdf.parse("1970-01-01T00:00:00"); if (VictimsConfig.forcedUpdate()) { return since; } // get last updated if available try { if (lastUpdate.exists()) { String temp; temp = FileUtils.readFileToString(lastUpdate).trim(); since = sdf.parse(temp); } } catch (IOException e) { throwable = e; } return since; } catch (ParseException e) { throwable = e; } throw new VictimsException("Failed to retreive last updated data", throwable); } public void synchronize() throws VictimsException { Throwable throwable = null; try { Savepoint savepoint = this.connection.setSavepoint(); try { VictimsService service = new VictimsService(); Date since = lastUpdated(); remove(service.removed(since)); update(service.updates(since)); setLastUpdate(new Date()); this.connection.releaseSavepoint(savepoint); this.connection.commit(); // reset cache cachedCount = null; } catch (IOException e) { throwable = e; } catch (SQLException e) { throwable = e; } this.connection.rollback(savepoint); this.connection.commit(); } catch (SQLException e) { throwable = e; } throw new VictimsException("Failed to sync database", throwable); } protected ArrayList<String> getVulnerabilities(int recordId) throws SQLException { ArrayList<String> cves = new ArrayList<String>(); fetchCVES.setInt(1, recordId); ResultSet matches = fetchCVES.executeQuery(); while (matches.next()) { cves.add(matches.getString(1)); } return cves; } public ArrayList<String> getVulnerabilities(String sha512) throws VictimsException { try { ArrayList<String> cves = new ArrayList<String>(); fetchRecordId.setString(1, sha512); ResultSet rs = fetchRecordId.executeQuery(); while (rs.next()) { cves.addAll(getVulnerabilities(rs.getInt(1))); } return cves; } catch (SQLException e) { throw new VictimsException( "Could not determine vulnerabilities for hash: " + sha512, e); } } public ArrayList<String> getEmbeddedVulnerabilities(VictimsRecord vr) throws SQLException { ArrayList<String> cves = new ArrayList<String>(); HashMap<Integer, Integer> hashCount = new HashMap<Integer, Integer>(); /* * FIXME: The current h2 jdbc implementation does not do this correctly. * This is done by hand now instead. * * countMatchedFileHash.setObject(1, * vr.getHashes(Algorithms.SHA512).keySet().toArray()); * System.out.println(countMatchedFileHash.toString().replace(",", * "\n")); rs = countMatchedFileHash.executeQuery(); */ // Temporary statement construction String sql = Query.FILEHASH_MATCHES_PER_RECORD.replace("?", "%s"); String contents = "'"; for (String content : vr.getHashes(Algorithms.SHA512).keySet()) { contents += content + "', '"; } // chop of the last 3 charectors ", '" contents = contents.substring(0, contents.length() - 3); sql = String.format(sql, contents); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { hashCount.put(rs.getInt(1), rs.getInt(2)); } if (hashCount.size() > 0) { if (cachedCount == null) { // populate cache if not available cachedCount = new HashMap<Integer, Integer>(); rs = countFileHashes.executeQuery(); while (rs.next()) { cachedCount.put(rs.getInt("record"), rs.getInt(2)); } } for (Integer id : hashCount.keySet()) { // Match every record that has all its filehashes in // the provided VictimsRecord if (hashCount.get(id).equals(cachedCount.get(id))) { cves.addAll(getVulnerabilities(id)); } } } return cves; } public ArrayList<String> getVulnerabilities(VictimsRecord vr) throws VictimsException { try { ArrayList<String> cves = new ArrayList<String>(); // Match jar sha512 cves.addAll(getVulnerabilities(vr.hash.trim())); // Match any embedded filehashes cves.addAll(getEmbeddedVulnerabilities(vr)); return cves; } catch (SQLException e) { throw new VictimsException( "Could not determine vulnerabilities for VictimsRecord with hash: " + vr.hash, e); } } public static class Query { protected final static String CREATE_TABLE_RECORDS = "CREATE TABLE records ( " + "id BIGINT AUTO_INCREMENT, " + "hash VARCHAR(128)" + ")"; protected final static String CREATE_TABLE_FILEHASHES = "CREATE TABLE filehashes (" + "record BIGINT, " + "filehash VARCHAR(128), " + "FOREIGN KEY(record) REFERENCES records(id) " + "ON DELETE CASCADE" + ")"; protected final static String CREATE_TABLE_META = "CREATE TABLE meta (" + "record BIGINT, " + "key VARCHAR(255), " + "value VARCHAR(255), " + "FOREIGN KEY(record) REFERENCES records(id) " + "ON DELETE CASCADE" + ")"; protected final static String CREATE_TABLE_CVES = "CREATE TABLE cves (" + "record BIGINT, " + "cve VARCHAR(32), " + "FOREIGN KEY(record) REFERENCES records(id) " + "ON DELETE CASCADE" + ")"; protected static final String INSERT_FILEHASH = "INSERT INTO filehashes (record, filehash) VALUES (?, ?)"; protected final static String INSERT_META = "INSERT INTO meta (record, key, value) VALUES (?, ?, ?)"; protected final static String INSERT_CVES = "INSERT INTO cves (record, cve) VALUES (?, ?)"; protected final static String INSERT_RECORD = "INSERT INTO records (hash) VALUES (?)"; protected final static String GET_RECORD_ID = "SELECT id FROM records WHERE hash = ?"; protected final static String FIND_CVES = "SELECT cve FROM cves WHERE record = ?"; protected final static String DELETE_RECORD_HASH = "DELETE FROM records WHERE hash = ?"; protected final static String DELETE_RECORD_ID = "DELETE FROM records WHERE id = ?"; protected final static String DELETE_FILEHASHES = "DELETE FROM filehashes WHERE record = ?"; protected final static String DELETE_METAS = "DELETE FROM meta WHERE record = ?"; protected final static String DELETE_CVES = "DELETE FROM cves WHERE record = ?"; protected final static String FILEHASH_MATCHES_PER_RECORD = "SELECT record, count(filehash) FROM filehashes " + "WHERE filehash IN (?) " + "GROUP BY record"; protected final static String FILEHASH_COUNT_PER_RECORD = "SELECT record, count(*) FROM filehashes GROUP BY record"; } }
package net.orfjackal.nestedjunit; import org.junit.*; import org.junit.internal.runners.statements.*; import org.junit.runner.*; import org.junit.runner.notification.RunNotifier; import org.junit.runners.*; import org.junit.runners.model.*; import java.lang.reflect.Method; import java.util.*; /** * Allows organizing JUnit 4 tests into member classes. This makes it possible * to write tests in a more Behaviour-Driven Development (BDD) style: * <pre><code> * &#64;RunWith(NestedJUnit.class) * public class WerewolfTest extends Assert { * public class Given_the_moon_is_full { * &#64;Before public void When_you_walk_in_the_woods() { * ... * } * &#64;Test public void Then_you_can_hear_werewolves_howling() { * ... * } * &#64;Test public void Then_you_wish_you_had_a_silver_bullet() { * ... * } * } * public class Given_the_moon_is_not_full { * &#64;Before public void When_you_walk_in_the_woods() { * ... * } * &#64;Test public void Then_you_do_not_hear_any_werewolves() { * ... * } * &#64;Test public void Then_you_are_not_afraid() { * ... * } * } * } * </code></pre> * * @author Esko Luontola */ public class NestedJUnit extends Runner { private final BlockJUnit4ClassRunner level1; private final NestedParentRunner level2; private final Description description; public NestedJUnit(Class<?> testClass) throws InitializationError { level1 = new BlockJUnit4ClassRunner(testClass) { @Override protected void validateInstanceMethods(List<Throwable> errors) { // disable; don't fail if has no test methods } }; level2 = new NestedParentRunner(level1.getTestClass(), testClass); description = level1.getDescription(); for (Description child : level2.getDescription().getChildren()) { description.addChild(child); } } @Override public void run(RunNotifier notifier) { level1.run(notifier); level2.run(notifier); } @Override public Description getDescription() { return description; } private class NestedParentRunner extends ParentRunner<Runner> { private final List<Runner> children = new ArrayList<Runner>(); private final TestClass parent; public NestedParentRunner(TestClass parent, Class<?> testClass) throws InitializationError { super(testClass); this.parent = parent; addToChildrenAllNestedClassesWithTests(testClass); } private void addToChildrenAllNestedClassesWithTests(Class<?> testClass) throws InitializationError { for (Class<?> child : testClass.getDeclaredClasses()) { if (containsTests(child)) { children.add(new NestedRunner(parent, child)); } } } private boolean containsTests(Class<?> clazz) { for (Method method : clazz.getMethods()) { if (method.getAnnotation(Test.class) != null) { return true; } } return false; } @Override protected List<Runner> getChildren() { return children; } @Override protected Description describeChild(Runner child) { return child.getDescription(); } @Override protected void runChild(Runner child, RunNotifier notifier) { child.run(notifier); } } private class NestedRunner extends BlockJUnit4ClassRunner { private final TestClass parentClass; private Object parent; public NestedRunner(TestClass parentClass, Class<?> testClass) throws InitializationError { super(testClass); this.parentClass = parentClass; } @Override protected void validateNoNonStaticInnerClass(List<Throwable> errors) { // disable default validation; our inner classes are non-static } @Override protected void validateZeroArgConstructor(List<Throwable> errors) { // disable default validation; our inner classes take the outer class as parameter } @Override protected Object createTest() throws Exception { parent = parentClass.getJavaClass().newInstance(); return getTestClass().getOnlyConstructor().newInstance(parent); } @Override protected Statement methodBlock(FrameworkMethod method) { Statement statement = super.methodBlock(method); statement = withParentBefores(statement); statement = withParentAfters(statement); return statement; } private Statement withParentBefores(Statement statement) { List<FrameworkMethod> befores = parentClass.getAnnotatedMethods(Before.class); return befores.isEmpty() ? statement : new RunBefores(statement, befores, parent); } private Statement withParentAfters(Statement statement) { List<FrameworkMethod> afters = parentClass.getAnnotatedMethods(After.class); return afters.isEmpty() ? statement : new RunAfters(statement, afters, parent); } } }
package netdiscoveryIPv6; import java.net.DatagramPacket; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketAddress; import java.util.Enumeration; import plugincore.PluginEngine; import com.google.gson.Gson; import shared.MsgEvent; import shared.MsgEventType; public class DiscoveryEngineIPv6 implements Runnable { //private MulticastSocket socket; private Gson gson; public DiscoveryEngineIPv6() { gson = new Gson(); } public void shutdown() { //socket.close(); } public void run() { try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); new Thread(new DiscoveryEngineWorkerIPv6(networkInterface)).start(); } PluginEngine.DiscoveryActiveIPv6 = true; } catch (Exception ex) { System.out.println("DiscoveryEngineIPv6 : Run Error " + ex.toString()); } } public static DiscoveryEngineIPv6 getInstance() { return DiscoveryThreadHolder.INSTANCE; } private static class DiscoveryThreadHolder { private static final DiscoveryEngineIPv6 INSTANCE = new DiscoveryEngineIPv6(); } class DiscoveryEngineWorkerIPv6 implements Runnable { private NetworkInterface networkInterface; private MulticastSocket socket; public DiscoveryEngineWorkerIPv6(NetworkInterface networkInterface) { this.networkInterface = networkInterface; } public void shutdown() { socket.close(); } public void run() { try { if (!networkInterface.getDisplayName().startsWith("docker") && !networkInterface.getDisplayName().startsWith("veth") && !networkInterface.isLoopback() && networkInterface.isUp() && networkInterface.supportsMulticast() && !networkInterface.isPointToPoint() && !networkInterface.isVirtual()) { System.out.println("Trying interface: " + networkInterface.getDisplayName()); boolean isIPv6Bound = false; for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { if(interfaceAddress.getAddress() instanceof Inet6Address) { if(!interfaceAddress.getAddress().isLinkLocalAddress()) { isIPv6Bound = true; SocketAddress sa = new InetSocketAddress(interfaceAddress.getAddress().getHostAddress(),32005); socket = new MulticastSocket(null); socket.bind(sa); } } } if(isIPv6Bound) { SocketAddress saj = new InetSocketAddress(Inet6Address.getByName("ff05::1:c"),32005); socket.joinGroup(saj, networkInterface); while (PluginEngine.isActive) { //System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!"); //Receive a packet byte[] recvBuf = new byte[15000]; DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); socket.receive(packet); //Packet received System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress()); System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData())); //See if the packet holds the right command (message) String message = new String(packet.getData()).trim(); if (message.equals("DISCOVER_FUIFSERVER_REQUEST")) { //String response = "region=region0,agent=agent0,recaddr=" + packet.getAddress().getHostAddress(); //MsgEventType //MsgEventType msgType, String msgRegion, String msgAgent, String msgPlugin, String msgBody MsgEvent me = new MsgEvent(MsgEventType.DISCOVER,PluginEngine.region,PluginEngine.agent,PluginEngine.plugin,"Broadcast discovery response."); me.setParam("clientip", packet.getAddress().getHostAddress()); // convert java object to JSON format, // and returned as JSON formatted string String json = gson.toJson(me); //byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes(); byte[] sendData = json.getBytes(); //Send a response DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort()); socket.send(sendPacket); // process peer PluginEngine.processPeer(packet.getAddress().getHostAddress(), "dummy-value"); // process peer //System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress()); } } } } } catch(Exception ex) { System.out.println("DiscoveryEngineIPv6 : DiscoveryEngineWorkerIPv6 : Run Error " + ex.toString()); } } } }
package com.sjl.dsl4xml.example; import static com.sjl.dsl4xml.DocumentReader.*; import java.io.*; import java.text.*; import java.util.*; import org.junit.*; import com.sjl.dsl4xml.*; import com.sjl.dsl4xml.support.convert.*; public class TwitterFeedTest { // This creates a new reader capable of parsing twitter responses. // Only call this once, then re-use the returned DocumentReader object (it is thread safe!) private static DocumentReader<Tweets> newReader() { DocumentReader<Tweets> _tweetsReader = mappingOf(Tweets.class).to( tag("entry", Tweet.class).with( tag("published"), tag("title"), tag("content", Content.class). withPCDataMappedTo("value"). with(attributes("type")), tag("author", Author.class).with( tag("name"), tag("uri") ) ) ); _tweetsReader.registerConverters(new ThreadSafeDateConverter("yyyy-MM-dd'T'HH:mm:ss")); return _tweetsReader; } @Test public void marshallsTwitterResponseToTweetObjects() throws Exception { Tweets _tweets = marshallTestDocumentToTweets(); Assert.assertEquals(15, _tweets.size()); Tweet _first = _tweets.get(0); Assert.assertEquals( "Note de lecture : Succeeding with Use Cases par Richard Denney" + " http://t.co/5lcCXWsO #bookReview #useCases #UML", _first.getTitle() ); DateFormat _df = new SimpleDateFormat("yyyyMMddHHmmss"); Assert.assertEquals(_df.parse("20120409101024"), _first.getPublished()); Assert.assertEquals("html", _first.getContent().getType()); Assert.assertEquals( "Note de lecture : Succeeding with Use Cases par Richard Denney <a href=" + "\"http: "search.twitter.com/search?q=%23bookReview\" title=\"#bookReview\"" + " class=\" \"> "q=%23useCases\" title=\"#useCases\" class=\" \">#useCases</a> <em><a " + "href=\"http://search.twitter.com/search?q=%23UML\" title=\"#UML\" class=\" \"" + ">#UML</a></em>", _first.getContent().getValue() ); Assert.assertEquals( "addinquy (Christophe Addinquy)", _first.getAuthor().getName() ); Assert.assertEquals( "http://twitter.com/addinquy", _first.getAuthor().getUri() ); } private Tweets marshallTestDocumentToTweets() { DocumentReader<Tweets> _m = newReader(); return _m.read(getTestInput(), "utf-8"); } private InputStream getTestInput() { return getClass().getResourceAsStream("example4.xml"); } // model classes public static class Tweets implements Iterable<Tweet> { private List<Tweet> tweets; public Tweets() { tweets = new ArrayList<Tweet>(); } public void addTweet(Tweet aTweet) { tweets.add(aTweet); } public Iterator<Tweet> iterator() { return tweets.iterator(); } public int size() { return tweets.size(); } public Tweet get(int anIndex) { return tweets.get(anIndex); } } public static class Tweet { public String title; public Date published; public Content content; private Language language; private Author author; public String getTitle() { return title; } public void setTitle(String aTitle) { title = aTitle; } public Date getPublished() { return published; } public void setPublished(Date aDate) { published = aDate; } public Content getContent() { return content; } public void setContent(Content aContent) { content = aContent; } public Language getLanguage() { return language; } public void setLanguage(Language aLanguage) { language = aLanguage; } public Author getAuthor() { return author; } public void setAuthor(Author aAuthor) { author = aAuthor; } } public static class Language { public String code; public Language() {} public String getCode() { return code; } public void setCode(String aCode) { code = aCode; } } public static class Content { public String type; public String value; public String getType() { return type; } public void setType(String aType) { type = aType; } public String getValue() { return value; } public void setValue(String aValue) { value = aValue; } } public static class Author { private String name; private String uri; public Author() {} public String getName() { return name; } public void setName(String aName) { name = aName; } public String getUri() { return uri; } public void setUri(String aUri) { uri = aUri; } } }
package org.hisp.dhis.android.dashboard.ui.fragments; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.squareup.otto.Subscribe; import org.hisp.dhis.android.dashboard.R; import org.hisp.dhis.android.dashboard.api.persistence.preferences.SettingsManager; import org.hisp.dhis.android.dashboard.ui.activities.LauncherActivity; import org.hisp.dhis.android.dashboard.ui.events.UiEvent; import org.hisp.dhis.android.dashboard.ui.views.FontEditText; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public final class SettingsFragment extends BaseFragment { @Bind(R.id.toolbar) Toolbar mToolbar; FontEditText widthEditText; FontEditText heightEditText; public static final String MINIMUM_WIDTH = "480"; public static final String MINIMUM_HEIGHT = "320"; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_settings, container, false); widthEditText = (FontEditText) view.findViewById(R.id.update_width_edit); heightEditText =(FontEditText) view.findViewById(R.id.update_height_edit); widthEditText.addTextChangedListener(new CustomTextWatcher(SettingsManager.CHART_WIDTH, SettingsManager.DEFAULT_WIDTH, widthEditText)); heightEditText.addTextChangedListener(new CustomTextWatcher(SettingsManager.CHART_HEIGHT, SettingsManager.DEFAULT_HEIGHT, heightEditText)); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { ButterKnife.bind(this, view); mToolbar.setNavigationIcon(R.mipmap.ic_menu); mToolbar.setTitle(R.string.settings); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleNavigationDrawer(); } }); String width = SettingsManager.getInstance(getContext()).getPreference((SettingsManager.CHART_WIDTH), SettingsManager.DEFAULT_WIDTH); String height = SettingsManager.getInstance(getContext()).getPreference((SettingsManager.CHART_HEIGHT), SettingsManager.DEFAULT_HEIGHT); widthEditText.setText(width); heightEditText.setText(height); } @OnClick(R.id.delete_and_log_out_button) @SuppressWarnings("unused") public void onClick() { if (isDhisServiceBound()) { getDhisService().logOutUser(); } } @Subscribe @SuppressWarnings("unused") public void onLogOut(UiEvent event) { if (isAdded() && getActivity() != null) { startActivity(new Intent(getActivity(), LauncherActivity.class)); getActivity().finish(); } } private class CustomTextWatcher implements TextWatcher{ final String preference; final int minimumValue; final EditText mEditText; public CustomTextWatcher(String preference, String minimumValue, EditText editText){ this.preference = preference; this.minimumValue = Integer.parseInt(minimumValue); this.mEditText = editText; } @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.toString().length()>0) { if (Integer.parseInt(s.toString())>= minimumValue) { mEditText.setError(null); SettingsManager.getInstance(getContext()).setPreference(preference, s.toString()); }else{ mEditText.setError(getContext().getString(R.string.invalid_value)+" "+minimumValue); } } } } }
package com.rultor.agents.daemons; import com.amazonaws.services.s3.model.ObjectMetadata; import com.google.common.base.Joiner; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import com.jcabi.s3.Bucket; import com.jcabi.ssh.SSH; import com.jcabi.ssh.Shell; import com.jcabi.xml.XML; import com.rultor.Time; import com.rultor.agents.AbstractAgent; import com.rultor.agents.shells.TalkShells; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.util.Date; import java.util.logging.Level; import javax.ws.rs.core.MediaType; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.NullInputStream; import org.apache.commons.lang3.CharEncoding; import org.xembly.Directive; import org.xembly.Directives; /** * Marks the daemon as done. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @Immutable @ToString @EqualsAndHashCode(callSuper = false, of = "bucket") public final class ArchivesDaemon extends AbstractAgent { /** * S3 bucket. */ private final transient Bucket bucket; /** * Ctor. * @param bkt Bucket */ public ArchivesDaemon(final Bucket bkt) { super( "/talk/daemon[started and code and ended]", "/talk/shell" ); this.bucket = bkt; } @Override public Iterable<Directive> process(final XML xml) throws IOException { final Shell shell = new TalkShells(xml).get(); final File file = File.createTempFile("rultor", ".log"); final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); new Shell.Safe(shell).exec( Joiner.on("; ").join( String.format("dir=%s", SSH.escape(dir)), "if [ -r \"${dir}/stdout\" ]", "then cat \"${dir}/stdout\" | col -b 2>&1", "else echo 'stdout not found, internal error'", "fi" ), new NullInputStream(0L), new FileOutputStream(file), Logger.stream(Level.WARNING, this) ); new Shell.Empty(new Shell.Safe(shell)).exec( String.format("sudo rm -rf %1$s || rm -rf %s", SSH.escape(dir)) ); final String hash = xml.xpath("/talk/daemon/@id").get(0); final URI uri = this.upload(file, hash); final String title = this.title(xml, file); Logger.info(this, "daemon archived into %s: %s", uri, title); FileUtils.deleteQuietly(file); return new Directives().xpath("/talk/daemon").remove() .xpath("/talk").addIf("archive") .add("log").attr("id", hash) .attr("title", title) .set(uri.toString()); } /** * Upload file to S3. * @param file The file * @param hash Hash * @return S3 URI * @throws IOException If fails */ private URI upload(final File file, final String hash) throws IOException { final ObjectMetadata meta = new ObjectMetadata(); meta.setContentType(MediaType.TEXT_PLAIN); meta.setContentEncoding(CharEncoding.UTF_8); meta.setContentLength(file.length()); final String key = String.format("%tY/%1$tm/%s.txt", new Date(), hash); this.bucket.ocket(key).write(new FileInputStream(file), meta); return URI.create(String.format("s3://%s/%s", this.bucket.name(), key)); } /** * Make a title. * @param xml XML * @param file File with stdout * @return Title * @throws IOException If fails */ private String title(final XML xml, final File file) throws IOException { final int code = Integer.parseInt( xml.xpath("/talk/daemon/code/text()").get(0) ); final String status; if (code == 0) { status = "SUCCESS"; } else { status = "FAILURE"; } return Logger.format( "%s: %d (%s) in %[ms]s, %d lines", xml.xpath("/talk/daemon/title/text()").get(0), code, status, new Time(xml.xpath("/talk/daemon/ended/text()").get(0)).msec() - new Time(xml.xpath("/talk/daemon/started/text()").get(0)).msec(), FileUtils.readLines(file).size() ); } }
package nl.rostykerei.cci.ch02.q02; import nl.rostykerei.cci.datastructure.LinkedListNode; /** * Question 2.2 - Return Kth to Last. * * @author Rosty Kerei; */ public class KthToLast { /** * Returns k-th node to the last one. * * @param list input list * @param k index to the last * @return k-th node to the last one */ public static <T> LinkedListNode<T> kthToLast(LinkedListNode<T> list, int k) { LinkedListNode<T> left = list; LinkedListNode<T> right = list; int i = 0; while (right != null) { if (i > k) { left = left.getNext(); } right = right.getNext(); i++; } return i > k ? left : null; } }
package guru.nidi.ramlproxy; import org.junit.Assume; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AbstractProcessTest { private static final Pattern VERSION = Pattern.compile("<version>(.+?)</version>"); private static String version() throws IOException { String pom = ""; try (final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("pom.xml")))) { while (in.ready()) { pom += in.readLine(); } } final Matcher matcher = VERSION.matcher(pom); matcher.find(); matcher.find(); return matcher.group(1); } private final Process[] proc = new Process[1]; private final BlockingQueue<String> output = new ArrayBlockingQueue<>(1000); protected void startProxyProcess(String... parameters) throws IOException, InterruptedException { final String jar = "target/raml-tester-proxy-" + version() + ".jar"; if (!new File(jar).exists()) { Assume.assumeTrue("jar not found", false); return; } final ArrayList<String> params = new ArrayList<>(Arrays.asList("java", "-jar", jar)); params.addAll(Arrays.asList(parameters)); proc[0] = new ProcessBuilder(params).start(); final Thread reader = new Thread(new Runnable() { @Override public void run() { final BufferedReader in = new BufferedReader(new InputStreamReader(proc[0].getInputStream())); for (; ; ) { try { String line; if (in.ready() && (line = in.readLine()) != null) { output.add(line); } else { Thread.sleep(100); } } catch (Exception e) { } } } }); reader.setDaemon(true); reader.start(); String line; do { line = output.poll(15, TimeUnit.SECONDS); System.out.println("******** " + line + " ********"); } while (line != null && !line.endsWith("Proxy started")); } protected void stopProxyProcess() { if (proc[0] != null) { proc[0].destroy(); } } protected String readLine() throws InterruptedException { return output.poll(1, TimeUnit.SECONDS); } }
package com.thales.window; import com.thales.ga.ManifestOptimiser; import com.thales.model.Manifest; import com.thales.model.Priority; import com.thales.model.Vessel; import com.thales.utils.FXExecutor; import com.thales.window.Manifest.FitnessView; import com.thales.window.Manifest.GenerationView; import com.thales.window.Manifest.ManifestView; import com.thales.window.deckView.DeckView; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import org.jenetics.stat.DoubleMomentStatistics; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; public class VesselOptimizationView extends HBox { // TODO final DeckView deckView = new DeckView(); final TabPane boaties = new TabPane(); final ColorMenubar menuBar; final GenerationView generationView = new GenerationView(); final FitnessView fitnessView = new FitnessView(); final ManifestView manifestView = new ManifestView(); private final ManifestOptimiser optimiser; Hashtable<Vessel, DeckView> boatiesTable = new Hashtable<>(); //TODO Vessel v = Vessel.VESSEL2; public VesselOptimizationView(ManifestOptimiser optimiser) { this.optimiser = optimiser; VBox leftBox = new VBox(); menuBar = new ColorMenubar(deckView); leftBox.getChildren().addAll(generationView, fitnessView, manifestView); // TODO Vessel v = Vessel.VESSEL2; // TODO get from manifest // DeckView deckView = new DeckView(); // boatiesTable.put(v, deckView); // Tab tab = new Tab(); // tab.setText(v.getId()); // tab.setContent(new ColorMenubar(deckView)); // tab.setClosable(false); // InputStream icon = this.getClass().getResourceAsStream("/icon.png"); // Image image = new Image(icon); // tab.setGraphic(new ImageView(image)); // boaties.getTabs().addAll(tab); createTab(v); createTab(Vessel.VESSEL7) this.getChildren().addAll(leftBox, boaties); } private void createTab(Vessel v) { DeckView deckView = new DeckView(); boatiesTable.put(v, deckView); Tab tab = new Tab(); tab.setText(v.getId()); tab.setContent(new ColorMenubar(deckView)); tab.setClosable(false); InputStream icon = this.getClass().getResourceAsStream("/icon.png"); Image image = new Image(icon); tab.setGraphic(new ImageView(image)); boaties.getTabs().addAll(tab); } public void go() { optimiser.optimise((g, s, m) -> { FXExecutor.INSTANCE.execute(() -> { if (g % 5 == 0) { DoubleMomentStatistics fitness = (DoubleMomentStatistics) s.getFitness(); fitnessView.addDataToQueue(fitness.getMin(), fitness.getMean()); generationView.setPriority( m.getItems().stream().filter((item) -> item.getPriority().equals(Priority.HIGH)).count()); manifestView.update(m); generationView.setBoxCount(m.getItems().size()); // deckView.updateDeck(m); boatiesTable.get(v).updateDeck(m); } generationView.setGeneration(g); }); }); } }
package net.spy.memcached; import net.spy.memcached.compat.SpyThread; import net.spy.memcached.compat.log.Logger; import net.spy.memcached.compat.log.LoggerFactory; import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.metrics.MetricCollector; import net.spy.memcached.metrics.MetricType; import net.spy.memcached.ops.GetOperation; import net.spy.memcached.ops.KeyedOperation; import net.spy.memcached.ops.NoopOperation; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationException; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.TapOperation; import net.spy.memcached.ops.VBucketAware; import net.spy.memcached.protocol.binary.BinaryOperationFactory; import net.spy.memcached.protocol.binary.MultiGetOperationImpl; import net.spy.memcached.protocol.binary.TapAckOperationImpl; import net.spy.memcached.util.StringUtils; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * Main class for handling connections to a memcached cluster. */ public class MemcachedConnection extends SpyThread { /** * The number of empty selects we'll allow before assuming we may have * missed one and should check the current selectors. This generally * indicates a bug, but we'll check it nonetheless. */ private static final int DOUBLE_CHECK_EMPTY = 256; /** * The number of empty selects we'll allow before blowing up. It's too * easy to write a bug that causes it to loop uncontrollably. This helps * find those bugs and often works around them. */ private static final int EXCESSIVE_EMPTY = 0x1000000; /** * The default wakeup delay if not overridden by a system property. */ private static final int DEFAULT_WAKEUP_DELAY = 1000; /** * If an operation gets cloned more than this ceiling, cancel it for * safety reasons. */ private static final int MAX_CLONE_COUNT = 100; private static final String RECON_QUEUE_METRIC = "[MEM] Reconnecting Nodes (ReconnectQueue)"; private static final String SHUTD_QUEUE_METRIC = "[MEM] Shutting Down Nodes (NodesToShutdown)"; private static final String OVERALL_REQUEST_METRIC = "[MEM] Request Rate: All"; private static final String OVERALL_AVG_BYTES_WRITE_METRIC = "[MEM] Average Bytes written to OS per write"; private static final String OVERALL_AVG_BYTES_READ_METRIC = "[MEM] Average Bytes read from OS per read"; private static final String OVERALL_AVG_TIME_ON_WIRE_METRIC = "[MEM] Average Time on wire for operations (µs)"; private static final String OVERALL_RESPONSE_METRIC = "[MEM] Response Rate: All (Failure + Success + Retry)"; private static final String OVERALL_RESPONSE_RETRY_METRIC = "[MEM] Response Rate: Retry"; private static final String OVERALL_RESPONSE_FAIL_METRIC = "[MEM] Response Rate: Failure"; private static final String OVERALL_RESPONSE_SUCC_METRIC = "[MEM] Response Rate: Success"; /** * If the connection is alread shut down or shutting down. */ protected volatile boolean shutDown = false; /** * If true, optimization will collapse multiple sequential get ops. */ private final boolean shouldOptimize; /** * Holds the current {@link Selector} to use. */ protected Selector selector = null; /** * The {@link NodeLocator} to use for this connection. */ protected final NodeLocator locator; /** * The configured {@link FailureMode}. */ protected final FailureMode failureMode; /** * Maximum amount of time to wait between reconnect attempts. */ private final long maxDelay; /** * Contains the current number of empty select() calls, which could indicate * bugs. */ private int emptySelects = 0; /** * The buffer size that will be used when reading from the server. */ private final int bufSize; /** * The connection factory to create {@link MemcachedNode}s from. */ private final ConnectionFactory connectionFactory; /** * AddedQueue is used to track the QueueAttachments for which operations * have recently been queued. */ protected final ConcurrentLinkedQueue<MemcachedNode> addedQueue; /** * reconnectQueue contains the attachments that need to be reconnected. * The key is the time at which they are eligible for reconnect. */ private final SortedMap<Long, MemcachedNode> reconnectQueue; /** * True if not shutting down or shut down. */ protected volatile boolean running = true; /** * Holds all connection observers that get notified on connection status * changes. */ private final Collection<ConnectionObserver> connObservers = new ConcurrentLinkedQueue<ConnectionObserver>(); /** * The {@link OperationFactory} to clone or create operations. */ private final OperationFactory opFact; /** * The threshold for timeout exceptions. */ private final int timeoutExceptionThreshold; /** * Holds operations that need to be retried. */ private final List<Operation> retryOps; /** * Holds all nodes that are scheduled for shutdown. */ protected final ConcurrentLinkedQueue<MemcachedNode> nodesToShutdown; /** * If set to true, a proper check after finish connecting is done to see * if the node is not responding but really alive. */ private final boolean verifyAliveOnConnect; /** * The {@link ExecutorService} to use for callbacks. */ private final ExecutorService listenerExecutorService; /** * The {@link MetricCollector} to accumulate metrics (or dummy). */ protected final MetricCollector metrics; /** * The current type of metrics to collect. */ protected final MetricType metricType; /** * The selector wakeup delay, defaults to 1000ms. */ private final int wakeupDelay; /** * Construct a {@link MemcachedConnection}. * * @param bufSize the size of the buffer used for reading from the server. * @param f the factory that will provide an operation queue. * @param a the addresses of the servers to connect to. * @param obs the initial observers to add. * @param fm the failure mode to use. * @param opfactory the operation factory. * @throws IOException if a connection attempt fails early */ public MemcachedConnection(final int bufSize, final ConnectionFactory f, final List<InetSocketAddress> a, final Collection<ConnectionObserver> obs, final FailureMode fm, final OperationFactory opfactory) throws IOException { connObservers.addAll(obs); reconnectQueue = new TreeMap<Long, MemcachedNode>(); addedQueue = new ConcurrentLinkedQueue<MemcachedNode>(); failureMode = fm; shouldOptimize = f.shouldOptimize(); maxDelay = TimeUnit.SECONDS.toMillis(f.getMaxReconnectDelay()); opFact = opfactory; timeoutExceptionThreshold = f.getTimeoutExceptionThreshold(); selector = Selector.open(); retryOps = Collections.synchronizedList(new ArrayList<Operation>()); nodesToShutdown = new ConcurrentLinkedQueue<MemcachedNode>(); listenerExecutorService = f.getListenerExecutorService(); this.bufSize = bufSize; this.connectionFactory = f; String verifyAlive = System.getProperty("net.spy.verifyAliveOnConnect"); if(verifyAlive != null && verifyAlive.equals("true")) { verifyAliveOnConnect = true; } else { verifyAliveOnConnect = false; } wakeupDelay = Integer.parseInt( System.getProperty("net.spy.wakeupDelay", Integer.toString(DEFAULT_WAKEUP_DELAY))); List<MemcachedNode> connections = createConnections(a); locator = f.createLocator(connections); metrics = f.getMetricCollector(); metricType = f.enableMetrics(); registerMetrics(); setName("Memcached IO over " + this); setDaemon(f.isDaemon()); start(); } /** * Register Metrics for collection. * * Note that these Metrics may or may not take effect, depending on the * {@link MetricCollector} implementation. This can be controlled from * the {@link DefaultConnectionFactory}. */ protected void registerMetrics() { if (metricType.equals(MetricType.DEBUG) || metricType.equals(MetricType.PERFORMANCE)) { metrics.addHistogram(OVERALL_AVG_BYTES_READ_METRIC); metrics.addHistogram(OVERALL_AVG_BYTES_WRITE_METRIC); metrics.addHistogram(OVERALL_AVG_TIME_ON_WIRE_METRIC); metrics.addMeter(OVERALL_RESPONSE_METRIC); metrics.addMeter(OVERALL_REQUEST_METRIC); if (metricType.equals(MetricType.DEBUG)) { metrics.addCounter(RECON_QUEUE_METRIC); metrics.addCounter(SHUTD_QUEUE_METRIC); metrics.addMeter(OVERALL_RESPONSE_RETRY_METRIC); metrics.addMeter(OVERALL_RESPONSE_SUCC_METRIC); metrics.addMeter(OVERALL_RESPONSE_FAIL_METRIC); } } } /** * Create connections for the given list of addresses. * * @param addrs the list of addresses to connect to. * @return addrs list of {@link MemcachedNode}s. * @throws IOException if connecting was not successful. */ protected List<MemcachedNode> createConnections( final Collection<InetSocketAddress> addrs) throws IOException { List<MemcachedNode> connections = new ArrayList<MemcachedNode>(addrs.size()); for (SocketAddress sa : addrs) { SocketChannel ch = SocketChannel.open(); ch.configureBlocking(false); MemcachedNode qa = connectionFactory.createMemcachedNode(sa, ch, bufSize); qa.setConnection(this); int ops = 0; ch.socket().setTcpNoDelay(!connectionFactory.useNagleAlgorithm()); try { if (ch.connect(sa)) { getLogger().info("Connected to %s immediately", qa); connected(qa); } else { getLogger().info("Added %s to connect queue", qa); ops = SelectionKey.OP_CONNECT; } selector.wakeup(); qa.setSk(ch.register(selector, ops, qa)); assert ch.isConnected() || qa.getSk().interestOps() == SelectionKey.OP_CONNECT : "Not connected, and not wanting to connect"; } catch (SocketException e) { getLogger().warn("Socket error on initial connect", e); queueReconnect(qa); } connections.add(qa); } return connections; } /** * Make sure that the current selectors make sense. * * @return true if they do. */ private boolean selectorsMakeSense() { for (MemcachedNode qa : locator.getAll()) { if (qa.getSk() != null && qa.getSk().isValid()) { if (qa.getChannel().isConnected()) { int sops = qa.getSk().interestOps(); int expected = 0; if (qa.hasReadOp()) { expected |= SelectionKey.OP_READ; } if (qa.hasWriteOp()) { expected |= SelectionKey.OP_WRITE; } if (qa.getBytesRemainingToWrite() > 0) { expected |= SelectionKey.OP_WRITE; } assert sops == expected : "Invalid ops: " + qa + ", expected " + expected + ", got " + sops; } else { int sops = qa.getSk().interestOps(); assert sops == SelectionKey.OP_CONNECT : "Not connected, and not watching for connect: " + sops; } } } getLogger().debug("Checked the selectors."); return true; } /** * Handle all IO that flows through the connection. * * This method is called in an endless loop, listens on NIO selectors and * dispatches the underlying read/write calls if needed. */ public void handleIO() throws IOException { if (shutDown) { getLogger().debug("No IO while shut down."); return; } handleInputQueue(); getLogger().debug("Done dealing with queue."); long delay = wakeupDelay; if (!reconnectQueue.isEmpty()) { long now = System.currentTimeMillis(); long then = reconnectQueue.firstKey(); delay = Math.max(then - now, 1); } getLogger().debug("Selecting with delay of %sms", delay); assert selectorsMakeSense() : "Selectors don't make sense."; int selected = selector.select(delay); if (shutDown) { return; } else if (selected == 0 && addedQueue.isEmpty()) { handleWokenUpSelector(); } else if (selector.selectedKeys().isEmpty()) { handleEmptySelects(); } else { getLogger().debug("Selected %d, selected %d keys", selected, selector.selectedKeys().size()); emptySelects = 0; Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while(iterator.hasNext()) { SelectionKey sk = iterator.next(); handleIO(sk); iterator.remove(); } } handleOperationalTasks(); } /** * Helper method which gets called if the selector is woken up because of the * timeout setting, if has been interrupted or if happens during regular * write operation phases. * * <p>This method can be overriden by child implementations to handle custom * behavior on a manually woken selector, like sending pings through the * channels to make sure they are alive.</p> * * <p>Note that there is no guarantee that this method is at all or in the * regular interval called, so all overriding implementations need to take * that into account. Also, it needs to take into account that it may be * called very often under heavy workloads, so it should not perform extensive * tasks in the same thread.</p> */ protected void handleWokenUpSelector() { } /** * Helper method for {@link #handleIO()} to encapsulate everything that * needs to be checked on a regular basis that has nothing to do directly * with reading and writing data. * * @throws IOException if an error happens during shutdown queue handling. */ private void handleOperationalTasks() throws IOException { checkPotentiallyTimedOutConnection(); if (!shutDown && !reconnectQueue.isEmpty()) { attemptReconnects(); } if (!retryOps.isEmpty()) { ArrayList<Operation> operations = new ArrayList<Operation>(retryOps); retryOps.clear(); redistributeOperations(operations); } handleShutdownQueue(); } /** * Helper method for {@link #handleIO()} to handle empty select calls. */ private void handleEmptySelects() { getLogger().debug("No selectors ready, interrupted: " + Thread.interrupted()); if (++emptySelects > DOUBLE_CHECK_EMPTY) { for (SelectionKey sk : selector.keys()) { getLogger().debug("%s has %s, interested in %s", sk, sk.readyOps(), sk.interestOps()); if (sk.readyOps() != 0) { getLogger().debug("%s has a ready op, handling IO", sk); handleIO(sk); } else { lostConnection((MemcachedNode) sk.attachment()); } } assert emptySelects < EXCESSIVE_EMPTY : "Too many empty selects"; } } /** * Check if nodes need to be shut down and do so if needed. * * @throws IOException if the channel could not be closed properly. */ private void handleShutdownQueue() throws IOException { for (MemcachedNode qa : nodesToShutdown) { if (!addedQueue.contains(qa)) { nodesToShutdown.remove(qa); metrics.decrementCounter(SHUTD_QUEUE_METRIC); Collection<Operation> notCompletedOperations = qa.destroyInputQueue(); if (qa.getChannel() != null) { qa.getChannel().close(); qa.setSk(null); if (qa.getBytesRemainingToWrite() > 0) { getLogger().warn("Shut down with %d bytes remaining to write", qa.getBytesRemainingToWrite()); } getLogger().debug("Shut down channel %s", qa.getChannel()); } redistributeOperations(notCompletedOperations); } } } /** * Check if one or more nodes exceeded the timeout Threshold. */ private void checkPotentiallyTimedOutConnection() { boolean stillCheckingTimeouts = true; while (stillCheckingTimeouts) { try { for (SelectionKey sk : selector.keys()) { MemcachedNode mn = (MemcachedNode) sk.attachment(); if (mn.getContinuousTimeout() > timeoutExceptionThreshold) { getLogger().warn("%s exceeded continuous timeout threshold", sk); lostConnection(mn); } } stillCheckingTimeouts = false; } catch(ConcurrentModificationException e) { getLogger().warn("Retrying selector keys after " + "ConcurrentModificationException caught", e); continue; } } } /** * Handle any requests that have been made against the client. */ private void handleInputQueue() { if (!addedQueue.isEmpty()) { getLogger().debug("Handling queue"); Collection<MemcachedNode> toAdd = new HashSet<MemcachedNode>(); Collection<MemcachedNode> todo = new HashSet<MemcachedNode>(); MemcachedNode qaNode; while ((qaNode = addedQueue.poll()) != null) { todo.add(qaNode); } for (MemcachedNode node : todo) { boolean readyForIO = false; if (node.isActive()) { if (node.getCurrentWriteOp() != null) { readyForIO = true; getLogger().debug("Handling queued write %s", node); } } else { toAdd.add(node); } node.copyInputQueue(); if (readyForIO) { try { if (node.getWbuf().hasRemaining()) { handleWrites(node); } } catch (IOException e) { getLogger().warn("Exception handling write", e); lostConnection(node); } } node.fixupOps(); } addedQueue.addAll(toAdd); } } /** * Add a connection observer. * * @return whether the observer was successfully added. */ public boolean addObserver(final ConnectionObserver obs) { return connObservers.add(obs); } /** * Remove a connection observer. * * @return true if the observer existed and now doesn't. */ public boolean removeObserver(final ConnectionObserver obs) { return connObservers.remove(obs); } /** * Indicate a successful connect to the given node. * * @param node the node which was successfully connected. */ private void connected(final MemcachedNode node) { assert node.getChannel().isConnected() : "Not connected."; int rt = node.getReconnectCount(); node.connected(); for (ConnectionObserver observer : connObservers) { observer.connectionEstablished(node.getSocketAddress(), rt); } } /** * Indicate a lost connection to the given node. * * @param node the node where the connection was lost. */ private void lostConnection(final MemcachedNode node) { queueReconnect(node); for (ConnectionObserver observer : connObservers) { observer.connectionLost(node.getSocketAddress()); } } /** * Makes sure that the given node belongs to the current cluster. * * Before trying to connect to a node, make sure it actually belongs to the * currently connected cluster. */ boolean belongsToCluster(final MemcachedNode node) { for (MemcachedNode n : locator.getAll()) { if (n.getSocketAddress().equals(node.getSocketAddress())) { return true; } } return false; } /** * Handle IO for a specific selector. * * Any IOException will cause a reconnect. Note that this code makes sure * that the corresponding node is not only able to connect, but also able to * respond in a correct fashion (if verifyAliveOnConnect is set to true * through a property). This is handled by issuing a dummy * version/noop call and making sure it returns in a correct and timely * fashion. * * @param sk the selector to handle IO against. */ private void handleIO(final SelectionKey sk) { MemcachedNode node = (MemcachedNode) sk.attachment(); try { getLogger().debug("Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)", sk, sk.isReadable(), sk.isWritable(), sk.isConnectable(), sk.attachment()); if (sk.isConnectable() && belongsToCluster(node)) { getLogger().debug("Connection state changed for %s", sk); final SocketChannel channel = node.getChannel(); if (channel.finishConnect()) { finishConnect(sk, node); } else { assert !channel.isConnected() : "connected"; } } else { handleReadsAndWrites(sk, node); } } catch (ClosedChannelException e) { if (!shutDown) { getLogger().info("Closed channel and not shutting down. Queueing" + " reconnect on %s", node, e); lostConnection(node); } } catch (ConnectException e) { getLogger().info("Reconnecting due to failure to connect to %s", node, e); queueReconnect(node); } catch (OperationException e) { node.setupForAuth(); getLogger().info("Reconnection due to exception handling a memcached " + "operation on %s. This may be due to an authentication failure.", node, e); lostConnection(node); } catch (Exception e) { node.setupForAuth(); getLogger().info("Reconnecting due to exception on %s", node, e); lostConnection(node); } node.fixupOps(); } /** * A helper method for {@link #handleIO(java.nio.channels.SelectionKey)} to * handle reads and writes if appropriate. * * @param sk the selection key to use. * @param node th enode to read write from. * @throws IOException if an error occurs during read/write. */ private void handleReadsAndWrites(final SelectionKey sk, final MemcachedNode node) throws IOException { if (sk.isValid() && sk.isReadable()) { handleReads(node); } if (sk.isValid() && sk.isWritable()) { handleWrites(node); } } /** * Finish the connect phase and potentially verify its liveness. * * @param sk the selection key for the node. * @param node the actual node. * @throws IOException if something goes wrong during reading/writing. */ private void finishConnect(final SelectionKey sk, final MemcachedNode node) throws IOException { if (verifyAliveOnConnect) { final CountDownLatch latch = new CountDownLatch(1); final OperationFuture<Boolean> rv = new OperationFuture<Boolean>("noop", latch, 2500, listenerExecutorService); NoopOperation testOp = opFact.noop(new OperationCallback() { public void receivedStatus(OperationStatus status) { rv.set(status.isSuccess(), status); } @Override public void complete() { latch.countDown(); } }); testOp.setHandlingNode(node); testOp.initialize(); checkState(); insertOperation(node, testOp); node.copyInputQueue(); boolean done = false; if (sk.isValid()) { long timeout = TimeUnit.MILLISECONDS.toNanos( connectionFactory.getOperationTimeout()); long stop = System.nanoTime() + timeout; while (stop > System.nanoTime()) { handleWrites(node); handleReads(node); if(done = (latch.getCount() == 0)) { break; } } } if (!done || testOp.isCancelled() || testOp.hasErrored() || testOp.isTimedOut()) { throw new ConnectException("Could not send noop upon connect! " + "This may indicate a running, but not responding memcached " + "instance."); } } connected(node); addedQueue.offer(node); if (node.getWbuf().hasRemaining()) { handleWrites(node); } } /** * Handle pending writes for the given node. * * @param node the node to handle writes for. * @throws IOException can be raised during writing failures. */ private void handleWrites(final MemcachedNode node) throws IOException { node.fillWriteBuffer(shouldOptimize); boolean canWriteMore = node.getBytesRemainingToWrite() > 0; while (canWriteMore) { int wrote = node.writeSome(); metrics.updateHistogram(OVERALL_AVG_BYTES_WRITE_METRIC, wrote); node.fillWriteBuffer(shouldOptimize); canWriteMore = wrote > 0 && node.getBytesRemainingToWrite() > 0; } } /** * Handle pending reads for the given node. * * @param node the node to handle reads for. * @throws IOException can be raised during reading failures. */ private void handleReads(final MemcachedNode node) throws IOException { Operation currentOp = node.getCurrentReadOp(); if (currentOp instanceof TapAckOperationImpl) { node.removeCurrentReadOp(); return; } ByteBuffer rbuf = node.getRbuf(); final SocketChannel channel = node.getChannel(); int read = channel.read(rbuf); metrics.updateHistogram(OVERALL_AVG_BYTES_READ_METRIC, read); if (read < 0) { currentOp = handleReadsWhenChannelEndOfStream(currentOp, node, rbuf); } while (read > 0) { getLogger().debug("Read %d bytes", read); rbuf.flip(); while (rbuf.remaining() > 0) { if (currentOp == null) { throw new IllegalStateException("No read operation."); } long timeOnWire = System.nanoTime() - currentOp.getWriteCompleteTimestamp(); metrics.updateHistogram(OVERALL_AVG_TIME_ON_WIRE_METRIC, (int)(timeOnWire / 1000)); metrics.markMeter(OVERALL_RESPONSE_METRIC); synchronized(currentOp) { readBufferAndLogMetrics(currentOp, rbuf, node); } currentOp = node.getCurrentReadOp(); } rbuf.clear(); read = channel.read(rbuf); node.completedRead(); } } /** * Read from the buffer and add metrics information. * * @param currentOp the current operation to read. * @param rbuf the read buffer to read from. * @param node the node to read from. * @throws IOException if reading was not successful. */ private void readBufferAndLogMetrics(final Operation currentOp, final ByteBuffer rbuf, final MemcachedNode node) throws IOException { currentOp.readFromBuffer(rbuf); if (currentOp.getState() == OperationState.COMPLETE) { getLogger().debug("Completed read op: %s and giving the next %d " + "bytes", currentOp, rbuf.remaining()); Operation op = node.removeCurrentReadOp(); assert op == currentOp : "Expected to pop " + currentOp + " got " + op; if (op.hasErrored()) { metrics.markMeter(OVERALL_RESPONSE_FAIL_METRIC); } else { metrics.markMeter(OVERALL_RESPONSE_SUCC_METRIC); } } else if (currentOp.getState() == OperationState.RETRY) { handleRetryInformation(currentOp.getErrorMsg()); getLogger().debug("Reschedule read op due to NOT_MY_VBUCKET error: " + "%s ", currentOp); ((VBucketAware) currentOp).addNotMyVbucketNode( currentOp.getHandlingNode()); Operation op = node.removeCurrentReadOp(); assert op == currentOp : "Expected to pop " + currentOp + " got " + op; retryOps.add(currentOp); metrics.markMeter(OVERALL_RESPONSE_RETRY_METRIC); } } /** * Deal with an operation where the channel reached the end of a stream. * * @param currentOp the current operation to read. * @param node the node for that operation. * @param rbuf the read buffer. * * @return the next operation on the node to read. * @throws IOException if disconnect while reading. */ private Operation handleReadsWhenChannelEndOfStream(final Operation currentOp, final MemcachedNode node, final ByteBuffer rbuf) throws IOException { if (currentOp instanceof TapOperation) { currentOp.getCallback().complete(); ((TapOperation) currentOp).streamClosed(OperationState.COMPLETE); getLogger().debug("Completed read op: %s and giving the next %d bytes", currentOp, rbuf.remaining()); Operation op = node.removeCurrentReadOp(); assert op == currentOp : "Expected to pop " + currentOp + " got " + op; return node.getCurrentReadOp(); } else { throw new IOException("Disconnected unexpected, will reconnect."); } } /** * Convert the {@link ByteBuffer} into a string for easier debugging. * * @param b the buffer to debug. * @param size the size of the buffer. * @return the stringified {@link ByteBuffer}. */ static String dbgBuffer(ByteBuffer b, int size) { StringBuilder sb = new StringBuilder(); byte[] bytes = b.array(); for (int i = 0; i < size; i++) { char ch = (char) bytes[i]; if (Character.isWhitespace(ch) || Character.isLetterOrDigit(ch)) { sb.append(ch); } else { sb.append("\\x"); sb.append(Integer.toHexString(bytes[i] & 0xff)); } } return sb.toString(); } /** * Optionally handle retry (NOT_MY_VBUKET) responses. * * This method can be overridden in subclasses to handle the content * of the retry message appropriately. * * @param retryMessage the body of the retry message. */ protected void handleRetryInformation(final byte[] retryMessage) { getLogger().debug("Got RETRY message: " + new String(retryMessage) + ", but not handled."); } /** * Enqueue the given {@link MemcachedNode} for reconnect. * * @param node the node to reconnect. */ protected void queueReconnect(final MemcachedNode node) { if (shutDown) { return; } getLogger().warn("Closing, and reopening %s, attempt %d.", node, node.getReconnectCount()); if (node.getSk() != null) { node.getSk().cancel(); assert !node.getSk().isValid() : "Cancelled selection key is valid"; } node.reconnecting(); try { if (node.getChannel() != null && node.getChannel().socket() != null) { node.getChannel().socket().close(); } else { getLogger().info("The channel or socket was null for %s", node); } } catch (IOException e) { getLogger().warn("IOException trying to close a socket", e); } node.setChannel(null); long delay = (long) Math.min(maxDelay, Math.pow(2, node.getReconnectCount()) * 1000); long reconnectTime = System.currentTimeMillis() + delay; while (reconnectQueue.containsKey(reconnectTime)) { reconnectTime++; } reconnectQueue.put(reconnectTime, node); metrics.incrementCounter(RECON_QUEUE_METRIC); node.setupResend(); if (failureMode == FailureMode.Redistribute) { redistributeOperations(node.destroyInputQueue()); } else if (failureMode == FailureMode.Cancel) { cancelOperations(node.destroyInputQueue()); } } /** * Cancel the given collection of operations. * * @param ops the list of operations to cancel. */ private void cancelOperations(final Collection<Operation> ops) { for (Operation op : ops) { op.cancel(); } } /** * Redistribute the given list of operations to (potentially) other nodes. * * Note that operations can only be redistributed if they have not been * cancelled already, timed out already or do not have definite targets * (a key). * * @param ops the operations to redistribute. */ public void redistributeOperations(final Collection<Operation> ops) { for (Operation op : ops) { redistributeOperation(op); } } /** * Redistribute the given operation to (potentially) other nodes. * * Note that operations can only be redistributed if they have not been * cancelled already, timed out already or do not have definite targets * (a key). * * @param op the operation to redistribute. */ public void redistributeOperation(Operation op) { if (op.isCancelled() || op.isTimedOut()) { return; } if (op.getCloneCount() >= MAX_CLONE_COUNT) { getLogger().warn("Cancelling operation " + op + "because it has been " + "retried (cloned) more than " + MAX_CLONE_COUNT + "times."); op.cancel(); return; } // The operation gets redistributed but has never been actually written, // it we just straight re-add it without cloning. if (op.getState() == OperationState.WRITE_QUEUED && op.getHandlingNode() != null) { addOperation(op.getHandlingNode(), op); return; } if (op instanceof MultiGetOperationImpl) { for (String key : ((MultiGetOperationImpl) op).getRetryKeys()) { addOperation(key, opFact.get(key, (GetOperation.Callback) op.getCallback())); } } else if (op instanceof KeyedOperation) { KeyedOperation ko = (KeyedOperation) op; int added = 0; for (Operation newop : opFact.clone(ko)) { if (newop instanceof KeyedOperation) { KeyedOperation newKeyedOp = (KeyedOperation) newop; for (String k : newKeyedOp.getKeys()) { addOperation(k, newop); op.addClone(newop); newop.setCloneCount(op.getCloneCount()+1); } } else { newop.cancel(); getLogger().warn("Could not redistribute cloned non-keyed " + "operation", newop); } added++; } assert added > 0 : "Didn't add any new operations when redistributing"; } else { op.cancel(); } } /** * Attempt to reconnect {@link MemcachedNode}s in the reconnect queue. * * If the {@link MemcachedNode} does not belong to the cluster list anymore, * the reconnect attempt is cancelled. If it does, the code tries to * reconnect immediately and if this is not possible it waits until the * connection information arrives. * * Note that if a socket error arises during reconnect, the node is scheduled * for re-reconnect immediately. */ private void attemptReconnects() { final long now = System.currentTimeMillis(); final Map<MemcachedNode, Boolean> seen = new IdentityHashMap<MemcachedNode, Boolean>(); final List<MemcachedNode> rereQueue = new ArrayList<MemcachedNode>(); SocketChannel ch = null; Iterator<MemcachedNode> i = reconnectQueue.headMap(now).values().iterator(); while(i.hasNext()) { final MemcachedNode node = i.next(); i.remove(); metrics.decrementCounter(RECON_QUEUE_METRIC); try { if (!belongsToCluster(node)) { getLogger().debug("Node does not belong to cluster anymore, " + "skipping reconnect: %s", node); continue; } if (!seen.containsKey(node)) { seen.put(node, Boolean.TRUE); getLogger().info("Reconnecting %s", node); ch = SocketChannel.open(); ch.configureBlocking(false); ch.socket().setTcpNoDelay(!connectionFactory.useNagleAlgorithm()); int ops = 0; if (ch.connect(node.getSocketAddress())) { connected(node); addedQueue.offer(node); getLogger().info("Immediately reconnected to %s", node); assert ch.isConnected(); } else { ops = SelectionKey.OP_CONNECT; } node.registerChannel(ch, ch.register(selector, ops, node)); assert node.getChannel() == ch : "Channel was lost."; } else { getLogger().debug("Skipping duplicate reconnect request for %s", node); } } catch (SocketException e) { getLogger().warn("Error on reconnect", e); rereQueue.add(node); } catch (Exception e) { getLogger().error("Exception on reconnect, lost node %s", node, e); } finally { potentiallyCloseLeakingChannel(ch, node); } } for (MemcachedNode n : rereQueue) { queueReconnect(n); } } /** * Make sure channel connections are not leaked and properly close under * faulty reconnect cirumstances. * * @param ch the channel to potentially close. * @param node the node to which the channel should be bound to. */ private void potentiallyCloseLeakingChannel(final SocketChannel ch, final MemcachedNode node) { if (ch != null && !ch.isConnected() && !ch.isConnectionPending()) { try { ch.close(); } catch (IOException e) { getLogger().error("Exception closing channel: %s", node, e); } } } /** * Returns the {@link NodeLocator} in use for this connection. * * @return the current {@link NodeLocator}. */ public NodeLocator getLocator() { return locator; } /** * Enqueue the given {@link Operation} with the used key. * * @param key the key to use. * @param o the {@link Operation} to enqueue. */ public void enqueueOperation(final String key, final Operation o) { checkState(); StringUtils.validateKey(key, opFact instanceof BinaryOperationFactory); addOperation(key, o); } /** * Add an operation to a connection identified by the given key. * * If the {@link MemcachedNode} is active or the {@link FailureMode} is set * to retry, the primary node will be used for that key. If the primary * node is not available and the {@link FailureMode} cancel is used, the * operation will be cancelled without further retry. * * For any other {@link FailureMode} mechanisms (Redistribute), another * possible node is used (only if its active as well). If no other active * node could be identified, the original primary node is used and retried. * * @param key the key the operation is operating upon. * @param o the operation to add. */ protected void addOperation(final String key, final Operation o) { MemcachedNode placeIn = null; MemcachedNode primary = locator.getPrimary(key); if (primary.isActive() || failureMode == FailureMode.Retry) { placeIn = primary; } else if (failureMode == FailureMode.Cancel) { o.cancel(); } else { Iterator<MemcachedNode> i = locator.getSequence(key); while (placeIn == null && i.hasNext()) { MemcachedNode n = i.next(); if (n.isActive()) { placeIn = n; } } if (placeIn == null) { placeIn = primary; this.getLogger().warn("Could not redistribute to another node, " + "retrying primary node for %s.", key); } } assert o.isCancelled() || placeIn != null : "No node found for key " + key; if (placeIn != null) { addOperation(placeIn, o); } else { assert o.isCancelled() : "No node found for " + key + " (and not " + "immediately cancelled)"; } } /** * Insert an operation on the given node to the beginning of the queue. * * @param node the node where to insert the {@link Operation}. * @param o the operation to insert. */ public void insertOperation(final MemcachedNode node, final Operation o) { o.setHandlingNode(node); o.initialize(); node.insertOp(o); addedQueue.offer(node); metrics.markMeter(OVERALL_REQUEST_METRIC); Selector s = selector.wakeup(); assert s == selector : "Wakeup returned the wrong selector."; getLogger().debug("Added %s to %s", o, node); } /** * Enqueue an operation on the given node. * * @param node the node where to enqueue the {@link Operation}. * @param o the operation to add. */ protected void addOperation(final MemcachedNode node, final Operation o) { if (!node.isAuthenticated()) { retryOperation(o); return; } o.setHandlingNode(node); o.initialize(); node.addOp(o); addedQueue.offer(node); metrics.markMeter(OVERALL_REQUEST_METRIC); Selector s = selector.wakeup(); assert s == selector : "Wakeup returned the wrong selector."; getLogger().debug("Added %s to %s", o, node); } /** * Enqueue the given list of operations on each handling node. * * @param ops the operations for each node. */ public void addOperations(final Map<MemcachedNode, Operation> ops) { for (Map.Entry<MemcachedNode, Operation> me : ops.entrySet()) { addOperation(me.getKey(), me.getValue()); } } /** * Broadcast an operation to all nodes. * * @return a {@link CountDownLatch} that will be counted down when the * operations are complete. */ public CountDownLatch broadcastOperation(final BroadcastOpFactory of) { return broadcastOperation(of, locator.getAll()); } /** * Broadcast an operation to a collection of nodes. * * @return a {@link CountDownLatch} that will be counted down when the * operations are complete. */ public CountDownLatch broadcastOperation(final BroadcastOpFactory of, final Collection<MemcachedNode> nodes) { final CountDownLatch latch = new CountDownLatch(nodes.size()); for (MemcachedNode node : nodes) { getLogger().debug("broadcast Operation: node = " + node); Operation op = of.newOp(node, latch); op.initialize(); node.addOp(op); op.setHandlingNode(node); addedQueue.offer(node); metrics.markMeter(OVERALL_REQUEST_METRIC); } Selector s = selector.wakeup(); assert s == selector : "Wakeup returned the wrong selector."; return latch; } /** * Shut down all connections and do not accept further incoming ops. */ public void shutdown() throws IOException { shutDown = true; try { Selector s = selector.wakeup(); assert s == selector : "Wakeup returned the wrong selector."; for (MemcachedNode node : locator.getAll()) { if (node.getChannel() != null) { node.getChannel().close(); node.setSk(null); if (node.getBytesRemainingToWrite() > 0) { getLogger().warn("Shut down with %d bytes remaining to write", node.getBytesRemainingToWrite()); } getLogger().debug("Shut down channel %s", node.getChannel()); } } selector.close(); getLogger().debug("Shut down selector %s", selector); } finally { running = false; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{MemcachedConnection to"); for (MemcachedNode qa : locator.getAll()) { sb.append(" ").append(qa.getSocketAddress()); } sb.append("}"); return sb.toString(); } /** * Construct a String containing information about all nodes and their state. * * @return a stringified representation of the connection status. */ public String connectionsStatus() { StringBuilder connStatus = new StringBuilder(); connStatus.append("Connection Status {"); for (MemcachedNode node : locator.getAll()) { connStatus .append(" ") .append(node.getSocketAddress()) .append(" active: ") .append(node.isActive()) .append(", authed: ") .append(node.isAuthenticated()) .append(MessageFormat.format(", last read: {0} ms ago", node.lastReadDelta())); } connStatus.append(" }"); return connStatus.toString(); } /** * Increase the timeout counter for the given handling node. * * @param op the operation to grab the node from. */ public static void opTimedOut(final Operation op) { MemcachedConnection.setTimeout(op, true); } /** * Reset the timeout counter for the given handling node. * * @param op the operation to grab the node from. */ public static void opSucceeded(final Operation op) { MemcachedConnection.setTimeout(op, false); } /** * Set the continuous timeout on an operation. * * Ignore operations which have no handling nodes set yet (which may happen before nodes are properly * authenticated). * * @param op the operation to use. * @param isTimeout is timed out or not. */ private static void setTimeout(final Operation op, final boolean isTimeout) { Logger logger = LoggerFactory.getLogger(MemcachedConnection.class); try { if (op == null || op.isTimedOutUnsent()) { return; } MemcachedNode node = op.getHandlingNode(); if (node != null) { node.setContinuousTimeout(isTimeout); } } catch (Exception e) { logger.error(e.getMessage()); } } protected void checkState() { if (shutDown) { throw new IllegalStateException("Shutting down"); } assert isAlive() : "IO Thread is not running."; } /** * Handle IO as long as the application is running. */ @Override public void run() { while (running) { try { handleIO(); } catch (IOException e) { logRunException(e); } catch (CancelledKeyException e) { logRunException(e); } catch (ClosedSelectorException e) { logRunException(e); } catch (IllegalStateException e) { logRunException(e); } catch (ConcurrentModificationException e) { logRunException(e); } } getLogger().info("Shut down memcached client"); } /** * Log a exception to different levels depending on the state. * * Exceptions get logged at debug level when happening during shutdown, but * at warning level when operating normally. * * @param e the exception to log. */ private void logRunException(final Exception e) { if (shutDown) { getLogger().debug("Exception occurred during shutdown", e); } else { getLogger().warn("Problem handling memcached IO", e); } } /** * Returns whether the connection is shut down or not. * * @return true if the connection is shut down, false otherwise. */ public boolean isShutDown() { return shutDown; } /** * Add a operation to the retry queue. * * @param op the operation to retry. */ public void retryOperation(Operation op) { retryOps.add(op); } }
package mho.haskellesque.math; import mho.haskellesque.iterables.ExhaustiveProvider; import mho.haskellesque.iterables.IterableUtils; import mho.haskellesque.ordering.Ordering; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static mho.haskellesque.iterables.IterableUtils.*; import static mho.haskellesque.math.Combinatorics.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class CombinatoricsTest { private static final @NotNull ExhaustiveProvider P = ExhaustiveProvider.INSTANCE; @Test public void testFactorial_int() { aeq(factorial(0), 1); aeq(factorial(1), 1); aeq(factorial(2), 2); aeq(factorial(3), 6); aeq(factorial(4), 24); aeq(factorial(5), 120); aeq(factorial(6), 720); aeq(factorial(10), 3628800); aeq(factorial(100), "9332621544394415268169923885626670049071596826438162146859296389521759999322991" + "5608941463976156518286253697920827223758251185210916864000000000000000000000000"); try { factorial(-1); fail(); } catch (ArithmeticException ignored) {} } @Test public void testFactorial_BigInteger() { aeq(factorial(BigInteger.ZERO), 1); aeq(factorial(BigInteger.ONE), 1); aeq(factorial(BigInteger.valueOf(2)), 2); aeq(factorial(BigInteger.valueOf(3)), 6); aeq(factorial(BigInteger.valueOf(4)), 24); aeq(factorial(BigInteger.valueOf(5)), 120); aeq(factorial(BigInteger.valueOf(6)), 720); aeq(factorial(BigInteger.TEN), 3628800); aeq(factorial(BigInteger.valueOf(100)), "9332621544394415268169923885626670049071596826438162146859296389521759999322991" + "5608941463976156518286253697920827223758251185210916864000000000000000000000000"); try { factorial(BigInteger.valueOf(-1)); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSubfactorial_int() { aeq(subfactorial(0), 1); aeq(subfactorial(1), 0); aeq(subfactorial(2), 1); aeq(subfactorial(3), 2); aeq(subfactorial(4), 9); aeq(subfactorial(5), 44); aeq(subfactorial(6), 265); aeq(subfactorial(10), 1334961); aeq(subfactorial(100), "3433279598416380476519597752677614203236578380537578498354340028268518079332763" + "2432791396429850988990237345920155783984828001486412574060553756854137069878601"); try { subfactorial(-1); fail(); } catch (ArithmeticException ignored) {} } @Test public void testSubfactorial_BigInteger() { aeq(subfactorial(BigInteger.ZERO), 1); aeq(subfactorial(BigInteger.ONE), 0); aeq(subfactorial(BigInteger.valueOf(2)), 1); aeq(subfactorial(BigInteger.valueOf(3)), 2); aeq(subfactorial(BigInteger.valueOf(4)), 9); aeq(subfactorial(BigInteger.valueOf(5)), 44); aeq(subfactorial(BigInteger.valueOf(6)), 265); aeq(subfactorial(BigInteger.TEN), 1334961); aeq(subfactorial(BigInteger.valueOf(100)), "3433279598416380476519597752677614203236578380537578498354340028268518079332763" + "2432791396429850988990237345920155783984828001486412574060553756854137069878601"); try { subfactorial(BigInteger.valueOf(-1)); fail(); } catch (ArithmeticException ignored) {} } @Test public void testPairsAscending() { aeq(pairsAscending(Arrays.asList(1, 2, 3), fromString("abc")), "[(1, a), (1, b), (1, c), (2, a), (2, b), (2, c), (3, a), (3, b), (3, c)]"); aeq(pairsAscending(Arrays.asList(1, null, 3), fromString("abc")), "[(1, a), (1, b), (1, c), (null, a), (null, b), (null, c), (3, a), (3, b), (3, c)]"); aeq(take(20, pairsAscending(P.naturalBigIntegers(), fromString("abc"))), "[(0, a), (0, b), (0, c), (1, a), (1, b), (1, c), (2, a), (2, b), (2, c), (3, a)," + " (3, b), (3, c), (4, a), (4, b), (4, c), (5, a), (5, b), (5, c), (6, a), (6, b)]"); aeq(pairsAscending(new ArrayList<Integer>(), fromString("abc")), "[]"); aeq(pairsAscending(new ArrayList<Integer>(), new ArrayList<Character>()), "[]"); } @Test public void testTriplesAscending() { aeq(triplesAscending(Arrays.asList(1, 2, 3), fromString("abc"), P.booleans()), "[(1, a, false), (1, a, true), (1, b, false), (1, b, true), (1, c, false), (1, c, true)," + " (2, a, false), (2, a, true), (2, b, false), (2, b, true), (2, c, false), (2, c, true)," + " (3, a, false), (3, a, true), (3, b, false), (3, b, true), (3, c, false), (3, c, true)]"); aeq(triplesAscending(Arrays.asList(1, null, 3), fromString("abc"), P.booleans()), "[(1, a, false), (1, a, true), (1, b, false), (1, b, true), (1, c, false), (1, c, true)," + " (null, a, false), (null, a, true), (null, b, false), (null, b, true), (null, c, false)," + " (null, c, true), (3, a, false), (3, a, true), (3, b, false), (3, b, true), (3, c, false)," + " (3, c, true)]"); aeq(take(20, triplesAscending(P.naturalBigIntegers(), fromString("abc"), P.booleans())), "[(0, a, false), (0, a, true), (0, b, false), (0, b, true), (0, c, false), (0, c, true)," + " (1, a, false), (1, a, true), (1, b, false), (1, b, true), (1, c, false), (1, c, true)," + " (2, a, false), (2, a, true), (2, b, false), (2, b, true), (2, c, false), (2, c, true)," + " (3, a, false), (3, a, true)]"); aeq(triplesAscending(new ArrayList<Integer>(), fromString("abc"), P.booleans()), "[]"); aeq(triplesAscending(new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>()), "[]"); } @Test public void testQuadruplesAscending() { aeq(quadruplesAscending(Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings()), "[(1, a, false, EQ), (1, a, false, LT), (1, a, false, GT), (1, a, true, EQ), (1, a, true, LT)," + " (1, a, true, GT), (1, b, false, EQ), (1, b, false, LT), (1, b, false, GT), (1, b, true, EQ)," + " (1, b, true, LT), (1, b, true, GT), (1, c, false, EQ), (1, c, false, LT), (1, c, false, GT)," + " (1, c, true, EQ), (1, c, true, LT), (1, c, true, GT), (2, a, false, EQ), (2, a, false, LT)," + " (2, a, false, GT), (2, a, true, EQ), (2, a, true, LT), (2, a, true, GT), (2, b, false, EQ)," + " (2, b, false, LT), (2, b, false, GT), (2, b, true, EQ), (2, b, true, LT), (2, b, true, GT)," + " (2, c, false, EQ), (2, c, false, LT), (2, c, false, GT), (2, c, true, EQ), (2, c, true, LT)," + " (2, c, true, GT), (3, a, false, EQ), (3, a, false, LT), (3, a, false, GT), (3, a, true, EQ)," + " (3, a, true, LT), (3, a, true, GT), (3, b, false, EQ), (3, b, false, LT), (3, b, false, GT)," + " (3, b, true, EQ), (3, b, true, LT), (3, b, true, GT), (3, c, false, EQ), (3, c, false, LT)," + " (3, c, false, GT), (3, c, true, EQ), (3, c, true, LT), (3, c, true, GT)]"); aeq(quadruplesAscending(Arrays.asList(1, null, 3), fromString("abc"), P.booleans(), P.orderings()), "[(1, a, false, EQ), (1, a, false, LT), (1, a, false, GT), (1, a, true, EQ), (1, a, true, LT)," + " (1, a, true, GT), (1, b, false, EQ), (1, b, false, LT), (1, b, false, GT), (1, b, true, EQ)," + " (1, b, true, LT), (1, b, true, GT), (1, c, false, EQ), (1, c, false, LT), (1, c, false, GT)," + " (1, c, true, EQ), (1, c, true, LT), (1, c, true, GT), (null, a, false, EQ), (null, a, false, LT)," + " (null, a, false, GT), (null, a, true, EQ), (null, a, true, LT), (null, a, true, GT)," + " (null, b, false, EQ), (null, b, false, LT), (null, b, false, GT), (null, b, true, EQ)," + " (null, b, true, LT), (null, b, true, GT), (null, c, false, EQ), (null, c, false, LT)," + " (null, c, false, GT), (null, c, true, EQ), (null, c, true, LT), (null, c, true, GT)," + " (3, a, false, EQ), (3, a, false, LT), (3, a, false, GT), (3, a, true, EQ), (3, a, true, LT)," + " (3, a, true, GT), (3, b, false, EQ), (3, b, false, LT), (3, b, false, GT), (3, b, true, EQ)," + " (3, b, true, LT), (3, b, true, GT), (3, c, false, EQ), (3, c, false, LT), (3, c, false, GT)," + " (3, c, true, EQ), (3, c, true, LT), (3, c, true, GT)]"); aeq(take(20, quadruplesAscending(P.naturalBigIntegers(), fromString("abc"), P.booleans(), P.orderings())), "[(0, a, false, EQ), (0, a, false, LT), (0, a, false, GT), (0, a, true, EQ), (0, a, true, LT)," + " (0, a, true, GT), (0, b, false, EQ), (0, b, false, LT), (0, b, false, GT), (0, b, true, EQ)," + " (0, b, true, LT), (0, b, true, GT), (0, c, false, EQ), (0, c, false, LT), (0, c, false, GT)," + " (0, c, true, EQ), (0, c, true, LT), (0, c, true, GT), (1, a, false, EQ), (1, a, false, LT)]"); aeq(quadruplesAscending(new ArrayList<Integer>(), fromString("abc"), P.booleans(), P.orderings()), "[]"); aeq(quadruplesAscending( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>() ), "[]"); } @Test public void testQuintuplesAscending() { aeq(quintuplesAscending( (Iterable<Integer>) Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[(1, a, false, EQ, yes), (1, a, false, EQ, no), (1, a, false, LT, yes), (1, a, false, LT, no)," + " (1, a, false, GT, yes), (1, a, false, GT, no), (1, a, true, EQ, yes), (1, a, true, EQ, no)," + " (1, a, true, LT, yes), (1, a, true, LT, no), (1, a, true, GT, yes), (1, a, true, GT, no)," + " (1, b, false, EQ, yes), (1, b, false, EQ, no), (1, b, false, LT, yes), (1, b, false, LT, no)," + " (1, b, false, GT, yes), (1, b, false, GT, no), (1, b, true, EQ, yes), (1, b, true, EQ, no)," + " (1, b, true, LT, yes), (1, b, true, LT, no), (1, b, true, GT, yes), (1, b, true, GT, no)," + " (1, c, false, EQ, yes), (1, c, false, EQ, no), (1, c, false, LT, yes), (1, c, false, LT, no)," + " (1, c, false, GT, yes), (1, c, false, GT, no), (1, c, true, EQ, yes), (1, c, true, EQ, no)," + " (1, c, true, LT, yes), (1, c, true, LT, no), (1, c, true, GT, yes), (1, c, true, GT, no)," + " (2, a, false, EQ, yes), (2, a, false, EQ, no), (2, a, false, LT, yes), (2, a, false, LT, no)," + " (2, a, false, GT, yes), (2, a, false, GT, no), (2, a, true, EQ, yes), (2, a, true, EQ, no)," + " (2, a, true, LT, yes), (2, a, true, LT, no), (2, a, true, GT, yes), (2, a, true, GT, no)," + " (2, b, false, EQ, yes), (2, b, false, EQ, no), (2, b, false, LT, yes), (2, b, false, LT, no)," + " (2, b, false, GT, yes), (2, b, false, GT, no), (2, b, true, EQ, yes), (2, b, true, EQ, no)," + " (2, b, true, LT, yes), (2, b, true, LT, no), (2, b, true, GT, yes), (2, b, true, GT, no)," + " (2, c, false, EQ, yes), (2, c, false, EQ, no), (2, c, false, LT, yes), (2, c, false, LT, no)," + " (2, c, false, GT, yes), (2, c, false, GT, no), (2, c, true, EQ, yes), (2, c, true, EQ, no)," + " (2, c, true, LT, yes), (2, c, true, LT, no), (2, c, true, GT, yes), (2, c, true, GT, no)," + " (3, a, false, EQ, yes), (3, a, false, EQ, no), (3, a, false, LT, yes), (3, a, false, LT, no)," + " (3, a, false, GT, yes), (3, a, false, GT, no), (3, a, true, EQ, yes), (3, a, true, EQ, no)," + " (3, a, true, LT, yes), (3, a, true, LT, no), (3, a, true, GT, yes), (3, a, true, GT, no)," + " (3, b, false, EQ, yes), (3, b, false, EQ, no), (3, b, false, LT, yes), (3, b, false, LT, no)," + " (3, b, false, GT, yes), (3, b, false, GT, no), (3, b, true, EQ, yes), (3, b, true, EQ, no)," + " (3, b, true, LT, yes), (3, b, true, LT, no), (3, b, true, GT, yes), (3, b, true, GT, no)," + " (3, c, false, EQ, yes), (3, c, false, EQ, no), (3, c, false, LT, yes), (3, c, false, LT, no)," + " (3, c, false, GT, yes), (3, c, false, GT, no), (3, c, true, EQ, yes), (3, c, true, EQ, no)," + " (3, c, true, LT, yes), (3, c, true, LT, no), (3, c, true, GT, yes), (3, c, true, GT, no)]"); aeq(quintuplesAscending( (Iterable<Integer>) Arrays.asList(1, null, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[(1, a, false, EQ, yes), (1, a, false, EQ, no), (1, a, false, LT, yes), (1, a, false, LT, no)," + " (1, a, false, GT, yes), (1, a, false, GT, no), (1, a, true, EQ, yes), (1, a, true, EQ, no)," + " (1, a, true, LT, yes), (1, a, true, LT, no), (1, a, true, GT, yes), (1, a, true, GT, no)," + " (1, b, false, EQ, yes), (1, b, false, EQ, no), (1, b, false, LT, yes), (1, b, false, LT, no)," + " (1, b, false, GT, yes), (1, b, false, GT, no), (1, b, true, EQ, yes), (1, b, true, EQ, no)," + " (1, b, true, LT, yes), (1, b, true, LT, no), (1, b, true, GT, yes), (1, b, true, GT, no)," + " (1, c, false, EQ, yes), (1, c, false, EQ, no), (1, c, false, LT, yes), (1, c, false, LT, no)," + " (1, c, false, GT, yes), (1, c, false, GT, no), (1, c, true, EQ, yes), (1, c, true, EQ, no)," + " (1, c, true, LT, yes), (1, c, true, LT, no), (1, c, true, GT, yes), (1, c, true, GT, no)," + " (null, a, false, EQ, yes), (null, a, false, EQ, no), (null, a, false, LT, yes)," + " (null, a, false, LT, no), (null, a, false, GT, yes), (null, a, false, GT, no)," + " (null, a, true, EQ, yes), (null, a, true, EQ, no), (null, a, true, LT, yes)," + " (null, a, true, LT, no), (null, a, true, GT, yes), (null, a, true, GT, no)," + " (null, b, false, EQ, yes), (null, b, false, EQ, no), (null, b, false, LT, yes)," + " (null, b, false, LT, no), (null, b, false, GT, yes), (null, b, false, GT, no)," + " (null, b, true, EQ, yes), (null, b, true, EQ, no), (null, b, true, LT, yes)," + " (null, b, true, LT, no), (null, b, true, GT, yes), (null, b, true, GT, no)," + " (null, c, false, EQ, yes), (null, c, false, EQ, no), (null, c, false, LT, yes)," + " (null, c, false, LT, no), (null, c, false, GT, yes), (null, c, false, GT, no)," + " (null, c, true, EQ, yes), (null, c, true, EQ, no), (null, c, true, LT, yes)," + " (null, c, true, LT, no), (null, c, true, GT, yes), (null, c, true, GT, no)," + " (3, a, false, EQ, yes), (3, a, false, EQ, no), (3, a, false, LT, yes), (3, a, false, LT, no)," + " (3, a, false, GT, yes), (3, a, false, GT, no), (3, a, true, EQ, yes), (3, a, true, EQ, no)," + " (3, a, true, LT, yes), (3, a, true, LT, no), (3, a, true, GT, yes), (3, a, true, GT, no)," + " (3, b, false, EQ, yes), (3, b, false, EQ, no), (3, b, false, LT, yes), (3, b, false, LT, no)," + " (3, b, false, GT, yes), (3, b, false, GT, no), (3, b, true, EQ, yes), (3, b, true, EQ, no)," + " (3, b, true, LT, yes), (3, b, true, LT, no), (3, b, true, GT, yes), (3, b, true, GT, no)," + " (3, c, false, EQ, yes), (3, c, false, EQ, no), (3, c, false, LT, yes), (3, c, false, LT, no)," + " (3, c, false, GT, yes), (3, c, false, GT, no), (3, c, true, EQ, yes), (3, c, true, EQ, no)," + " (3, c, true, LT, yes), (3, c, true, LT, no), (3, c, true, GT, yes), (3, c, true, GT, no)]"); aeq(take(20, quintuplesAscending( P.naturalBigIntegers(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") )), "[(0, a, false, EQ, yes), (0, a, false, EQ, no), (0, a, false, LT, yes), (0, a, false, LT, no)," + " (0, a, false, GT, yes), (0, a, false, GT, no), (0, a, true, EQ, yes), (0, a, true, EQ, no)," + " (0, a, true, LT, yes), (0, a, true, LT, no), (0, a, true, GT, yes), (0, a, true, GT, no)," + " (0, b, false, EQ, yes), (0, b, false, EQ, no), (0, b, false, LT, yes), (0, b, false, LT, no)," + " (0, b, false, GT, yes), (0, b, false, GT, no), (0, b, true, EQ, yes), (0, b, true, EQ, no)]"); aeq(quintuplesAscending( new ArrayList<Integer>(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[]"); aeq(quintuplesAscending( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>() ), "[]"); } @Test public void testSextuplesAscending() { aeq(sextuplesAscending( (Iterable<Integer>) Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[(1, a, false, EQ, yes, Infinity), (1, a, false, EQ, yes, NaN), (1, a, false, EQ, no, Infinity)," + " (1, a, false, EQ, no, NaN), (1, a, false, LT, yes, Infinity), (1, a, false, LT, yes, NaN)," + " (1, a, false, LT, no, Infinity), (1, a, false, LT, no, NaN), (1, a, false, GT, yes, Infinity)," + " (1, a, false, GT, yes, NaN), (1, a, false, GT, no, Infinity), (1, a, false, GT, no, NaN)," + " (1, a, true, EQ, yes, Infinity), (1, a, true, EQ, yes, NaN), (1, a, true, EQ, no, Infinity)," + " (1, a, true, EQ, no, NaN), (1, a, true, LT, yes, Infinity), (1, a, true, LT, yes, NaN)," + " (1, a, true, LT, no, Infinity), (1, a, true, LT, no, NaN), (1, a, true, GT, yes, Infinity)," + " (1, a, true, GT, yes, NaN), (1, a, true, GT, no, Infinity), (1, a, true, GT, no, NaN)," + " (1, b, false, EQ, yes, Infinity), (1, b, false, EQ, yes, NaN), (1, b, false, EQ, no, Infinity)," + " (1, b, false, EQ, no, NaN), (1, b, false, LT, yes, Infinity), (1, b, false, LT, yes, NaN)," + " (1, b, false, LT, no, Infinity), (1, b, false, LT, no, NaN), (1, b, false, GT, yes, Infinity)," + " (1, b, false, GT, yes, NaN), (1, b, false, GT, no, Infinity), (1, b, false, GT, no, NaN)," + " (1, b, true, EQ, yes, Infinity), (1, b, true, EQ, yes, NaN), (1, b, true, EQ, no, Infinity)," + " (1, b, true, EQ, no, NaN), (1, b, true, LT, yes, Infinity), (1, b, true, LT, yes, NaN)," + " (1, b, true, LT, no, Infinity), (1, b, true, LT, no, NaN), (1, b, true, GT, yes, Infinity)," + " (1, b, true, GT, yes, NaN), (1, b, true, GT, no, Infinity), (1, b, true, GT, no, NaN)," + " (1, c, false, EQ, yes, Infinity), (1, c, false, EQ, yes, NaN), (1, c, false, EQ, no, Infinity)," + " (1, c, false, EQ, no, NaN), (1, c, false, LT, yes, Infinity), (1, c, false, LT, yes, NaN)," + " (1, c, false, LT, no, Infinity), (1, c, false, LT, no, NaN), (1, c, false, GT, yes, Infinity)," + " (1, c, false, GT, yes, NaN), (1, c, false, GT, no, Infinity), (1, c, false, GT, no, NaN)," + " (1, c, true, EQ, yes, Infinity), (1, c, true, EQ, yes, NaN), (1, c, true, EQ, no, Infinity)," + " (1, c, true, EQ, no, NaN), (1, c, true, LT, yes, Infinity), (1, c, true, LT, yes, NaN)," + " (1, c, true, LT, no, Infinity), (1, c, true, LT, no, NaN), (1, c, true, GT, yes, Infinity)," + " (1, c, true, GT, yes, NaN), (1, c, true, GT, no, Infinity), (1, c, true, GT, no, NaN)," + " (2, a, false, EQ, yes, Infinity), (2, a, false, EQ, yes, NaN), (2, a, false, EQ, no, Infinity)," + " (2, a, false, EQ, no, NaN), (2, a, false, LT, yes, Infinity), (2, a, false, LT, yes, NaN)," + " (2, a, false, LT, no, Infinity), (2, a, false, LT, no, NaN), (2, a, false, GT, yes, Infinity)," + " (2, a, false, GT, yes, NaN), (2, a, false, GT, no, Infinity), (2, a, false, GT, no, NaN)," + " (2, a, true, EQ, yes, Infinity), (2, a, true, EQ, yes, NaN), (2, a, true, EQ, no, Infinity)," + " (2, a, true, EQ, no, NaN), (2, a, true, LT, yes, Infinity), (2, a, true, LT, yes, NaN)," + " (2, a, true, LT, no, Infinity), (2, a, true, LT, no, NaN), (2, a, true, GT, yes, Infinity)," + " (2, a, true, GT, yes, NaN), (2, a, true, GT, no, Infinity), (2, a, true, GT, no, NaN)," + " (2, b, false, EQ, yes, Infinity), (2, b, false, EQ, yes, NaN), (2, b, false, EQ, no, Infinity)," + " (2, b, false, EQ, no, NaN), (2, b, false, LT, yes, Infinity), (2, b, false, LT, yes, NaN)," + " (2, b, false, LT, no, Infinity), (2, b, false, LT, no, NaN), (2, b, false, GT, yes, Infinity)," + " (2, b, false, GT, yes, NaN), (2, b, false, GT, no, Infinity), (2, b, false, GT, no, NaN)," + " (2, b, true, EQ, yes, Infinity), (2, b, true, EQ, yes, NaN), (2, b, true, EQ, no, Infinity)," + " (2, b, true, EQ, no, NaN), (2, b, true, LT, yes, Infinity), (2, b, true, LT, yes, NaN)," + " (2, b, true, LT, no, Infinity), (2, b, true, LT, no, NaN), (2, b, true, GT, yes, Infinity)," + " (2, b, true, GT, yes, NaN), (2, b, true, GT, no, Infinity), (2, b, true, GT, no, NaN)," + " (2, c, false, EQ, yes, Infinity), (2, c, false, EQ, yes, NaN), (2, c, false, EQ, no, Infinity)," + " (2, c, false, EQ, no, NaN), (2, c, false, LT, yes, Infinity), (2, c, false, LT, yes, NaN)," + " (2, c, false, LT, no, Infinity), (2, c, false, LT, no, NaN), (2, c, false, GT, yes, Infinity)," + " (2, c, false, GT, yes, NaN), (2, c, false, GT, no, Infinity), (2, c, false, GT, no, NaN)," + " (2, c, true, EQ, yes, Infinity), (2, c, true, EQ, yes, NaN), (2, c, true, EQ, no, Infinity)," + " (2, c, true, EQ, no, NaN), (2, c, true, LT, yes, Infinity), (2, c, true, LT, yes, NaN)," + " (2, c, true, LT, no, Infinity), (2, c, true, LT, no, NaN), (2, c, true, GT, yes, Infinity)," + " (2, c, true, GT, yes, NaN), (2, c, true, GT, no, Infinity), (2, c, true, GT, no, NaN)," + " (3, a, false, EQ, yes, Infinity), (3, a, false, EQ, yes, NaN), (3, a, false, EQ, no, Infinity)," + " (3, a, false, EQ, no, NaN), (3, a, false, LT, yes, Infinity), (3, a, false, LT, yes, NaN)," + " (3, a, false, LT, no, Infinity), (3, a, false, LT, no, NaN), (3, a, false, GT, yes, Infinity)," + " (3, a, false, GT, yes, NaN), (3, a, false, GT, no, Infinity), (3, a, false, GT, no, NaN)," + " (3, a, true, EQ, yes, Infinity), (3, a, true, EQ, yes, NaN), (3, a, true, EQ, no, Infinity)," + " (3, a, true, EQ, no, NaN), (3, a, true, LT, yes, Infinity), (3, a, true, LT, yes, NaN)," + " (3, a, true, LT, no, Infinity), (3, a, true, LT, no, NaN), (3, a, true, GT, yes, Infinity)," + " (3, a, true, GT, yes, NaN), (3, a, true, GT, no, Infinity), (3, a, true, GT, no, NaN)," + " (3, b, false, EQ, yes, Infinity), (3, b, false, EQ, yes, NaN), (3, b, false, EQ, no, Infinity)," + " (3, b, false, EQ, no, NaN), (3, b, false, LT, yes, Infinity), (3, b, false, LT, yes, NaN)," + " (3, b, false, LT, no, Infinity), (3, b, false, LT, no, NaN), (3, b, false, GT, yes, Infinity)," + " (3, b, false, GT, yes, NaN), (3, b, false, GT, no, Infinity), (3, b, false, GT, no, NaN)," + " (3, b, true, EQ, yes, Infinity), (3, b, true, EQ, yes, NaN), (3, b, true, EQ, no, Infinity)," + " (3, b, true, EQ, no, NaN), (3, b, true, LT, yes, Infinity), (3, b, true, LT, yes, NaN)," + " (3, b, true, LT, no, Infinity), (3, b, true, LT, no, NaN), (3, b, true, GT, yes, Infinity)," + " (3, b, true, GT, yes, NaN), (3, b, true, GT, no, Infinity), (3, b, true, GT, no, NaN)," + " (3, c, false, EQ, yes, Infinity), (3, c, false, EQ, yes, NaN), (3, c, false, EQ, no, Infinity)," + " (3, c, false, EQ, no, NaN), (3, c, false, LT, yes, Infinity), (3, c, false, LT, yes, NaN)," + " (3, c, false, LT, no, Infinity), (3, c, false, LT, no, NaN), (3, c, false, GT, yes, Infinity)," + " (3, c, false, GT, yes, NaN), (3, c, false, GT, no, Infinity), (3, c, false, GT, no, NaN)," + " (3, c, true, EQ, yes, Infinity), (3, c, true, EQ, yes, NaN), (3, c, true, EQ, no, Infinity)," + " (3, c, true, EQ, no, NaN), (3, c, true, LT, yes, Infinity), (3, c, true, LT, yes, NaN)," + " (3, c, true, LT, no, Infinity), (3, c, true, LT, no, NaN), (3, c, true, GT, yes, Infinity)," + " (3, c, true, GT, yes, NaN), (3, c, true, GT, no, Infinity), (3, c, true, GT, no, NaN)]"); aeq(sextuplesAscending( (Iterable<Integer>) Arrays.asList(1, null, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[(1, a, false, EQ, yes, Infinity), (1, a, false, EQ, yes, NaN), (1, a, false, EQ, no, Infinity)," + " (1, a, false, EQ, no, NaN), (1, a, false, LT, yes, Infinity), (1, a, false, LT, yes, NaN)," + " (1, a, false, LT, no, Infinity), (1, a, false, LT, no, NaN), (1, a, false, GT, yes, Infinity)," + " (1, a, false, GT, yes, NaN), (1, a, false, GT, no, Infinity), (1, a, false, GT, no, NaN)," + " (1, a, true, EQ, yes, Infinity), (1, a, true, EQ, yes, NaN), (1, a, true, EQ, no, Infinity)," + " (1, a, true, EQ, no, NaN), (1, a, true, LT, yes, Infinity), (1, a, true, LT, yes, NaN)," + " (1, a, true, LT, no, Infinity), (1, a, true, LT, no, NaN), (1, a, true, GT, yes, Infinity)," + " (1, a, true, GT, yes, NaN), (1, a, true, GT, no, Infinity), (1, a, true, GT, no, NaN)," + " (1, b, false, EQ, yes, Infinity), (1, b, false, EQ, yes, NaN), (1, b, false, EQ, no, Infinity)," + " (1, b, false, EQ, no, NaN), (1, b, false, LT, yes, Infinity), (1, b, false, LT, yes, NaN)," + " (1, b, false, LT, no, Infinity), (1, b, false, LT, no, NaN), (1, b, false, GT, yes, Infinity)," + " (1, b, false, GT, yes, NaN), (1, b, false, GT, no, Infinity), (1, b, false, GT, no, NaN)," + " (1, b, true, EQ, yes, Infinity), (1, b, true, EQ, yes, NaN), (1, b, true, EQ, no, Infinity)," + " (1, b, true, EQ, no, NaN), (1, b, true, LT, yes, Infinity), (1, b, true, LT, yes, NaN)," + " (1, b, true, LT, no, Infinity), (1, b, true, LT, no, NaN), (1, b, true, GT, yes, Infinity)," + " (1, b, true, GT, yes, NaN), (1, b, true, GT, no, Infinity), (1, b, true, GT, no, NaN)," + " (1, c, false, EQ, yes, Infinity), (1, c, false, EQ, yes, NaN), (1, c, false, EQ, no, Infinity)," + " (1, c, false, EQ, no, NaN), (1, c, false, LT, yes, Infinity), (1, c, false, LT, yes, NaN)," + " (1, c, false, LT, no, Infinity), (1, c, false, LT, no, NaN), (1, c, false, GT, yes, Infinity)," + " (1, c, false, GT, yes, NaN), (1, c, false, GT, no, Infinity), (1, c, false, GT, no, NaN)," + " (1, c, true, EQ, yes, Infinity), (1, c, true, EQ, yes, NaN), (1, c, true, EQ, no, Infinity)," + " (1, c, true, EQ, no, NaN), (1, c, true, LT, yes, Infinity), (1, c, true, LT, yes, NaN)," + " (1, c, true, LT, no, Infinity), (1, c, true, LT, no, NaN), (1, c, true, GT, yes, Infinity)," + " (1, c, true, GT, yes, NaN), (1, c, true, GT, no, Infinity), (1, c, true, GT, no, NaN)," + " (null, a, false, EQ, yes, Infinity), (null, a, false, EQ, yes, NaN)," + " (null, a, false, EQ, no, Infinity), (null, a, false, EQ, no, NaN)," + " (null, a, false, LT, yes, Infinity), (null, a, false, LT, yes, NaN)," + " (null, a, false, LT, no, Infinity), (null, a, false, LT, no, NaN)," + " (null, a, false, GT, yes, Infinity), (null, a, false, GT, yes, NaN)," + " (null, a, false, GT, no, Infinity), (null, a, false, GT, no, NaN)," + " (null, a, true, EQ, yes, Infinity), (null, a, true, EQ, yes, NaN)," + " (null, a, true, EQ, no, Infinity), (null, a, true, EQ, no, NaN)," + " (null, a, true, LT, yes, Infinity), (null, a, true, LT, yes, NaN)," + " (null, a, true, LT, no, Infinity), (null, a, true, LT, no, NaN)," + " (null, a, true, GT, yes, Infinity), (null, a, true, GT, yes, NaN)," + " (null, a, true, GT, no, Infinity), (null, a, true, GT, no, NaN)," + " (null, b, false, EQ, yes, Infinity), (null, b, false, EQ, yes, NaN)," + " (null, b, false, EQ, no, Infinity), (null, b, false, EQ, no, NaN)," + " (null, b, false, LT, yes, Infinity), (null, b, false, LT, yes, NaN)," + " (null, b, false, LT, no, Infinity), (null, b, false, LT, no, NaN)," + " (null, b, false, GT, yes, Infinity), (null, b, false, GT, yes, NaN)," + " (null, b, false, GT, no, Infinity), (null, b, false, GT, no, NaN)," + " (null, b, true, EQ, yes, Infinity), (null, b, true, EQ, yes, NaN)," + " (null, b, true, EQ, no, Infinity), (null, b, true, EQ, no, NaN)," + " (null, b, true, LT, yes, Infinity), (null, b, true, LT, yes, NaN)," + " (null, b, true, LT, no, Infinity), (null, b, true, LT, no, NaN)," + " (null, b, true, GT, yes, Infinity), (null, b, true, GT, yes, NaN)," + " (null, b, true, GT, no, Infinity), (null, b, true, GT, no, NaN)," + " (null, c, false, EQ, yes, Infinity), (null, c, false, EQ, yes, NaN)," + " (null, c, false, EQ, no, Infinity), (null, c, false, EQ, no, NaN)," + " (null, c, false, LT, yes, Infinity), (null, c, false, LT, yes, NaN)," + " (null, c, false, LT, no, Infinity), (null, c, false, LT, no, NaN)," + " (null, c, false, GT, yes, Infinity), (null, c, false, GT, yes, NaN)," + " (null, c, false, GT, no, Infinity), (null, c, false, GT, no, NaN)," + " (null, c, true, EQ, yes, Infinity), (null, c, true, EQ, yes, NaN)," + " (null, c, true, EQ, no, Infinity), (null, c, true, EQ, no, NaN)," + " (null, c, true, LT, yes, Infinity), (null, c, true, LT, yes, NaN)," + " (null, c, true, LT, no, Infinity), (null, c, true, LT, no, NaN)," + " (null, c, true, GT, yes, Infinity), (null, c, true, GT, yes, NaN)," + " (null, c, true, GT, no, Infinity), (null, c, true, GT, no, NaN)," + " (3, a, false, EQ, yes, Infinity), (3, a, false, EQ, yes, NaN), (3, a, false, EQ, no, Infinity)," + " (3, a, false, EQ, no, NaN), (3, a, false, LT, yes, Infinity), (3, a, false, LT, yes, NaN)," + " (3, a, false, LT, no, Infinity), (3, a, false, LT, no, NaN), (3, a, false, GT, yes, Infinity)," + " (3, a, false, GT, yes, NaN), (3, a, false, GT, no, Infinity), (3, a, false, GT, no, NaN)," + " (3, a, true, EQ, yes, Infinity), (3, a, true, EQ, yes, NaN), (3, a, true, EQ, no, Infinity)," + " (3, a, true, EQ, no, NaN), (3, a, true, LT, yes, Infinity), (3, a, true, LT, yes, NaN)," + " (3, a, true, LT, no, Infinity), (3, a, true, LT, no, NaN), (3, a, true, GT, yes, Infinity)," + " (3, a, true, GT, yes, NaN), (3, a, true, GT, no, Infinity), (3, a, true, GT, no, NaN)," + " (3, b, false, EQ, yes, Infinity), (3, b, false, EQ, yes, NaN), (3, b, false, EQ, no, Infinity)," + " (3, b, false, EQ, no, NaN), (3, b, false, LT, yes, Infinity), (3, b, false, LT, yes, NaN)," + " (3, b, false, LT, no, Infinity), (3, b, false, LT, no, NaN), (3, b, false, GT, yes, Infinity)," + " (3, b, false, GT, yes, NaN), (3, b, false, GT, no, Infinity), (3, b, false, GT, no, NaN)," + " (3, b, true, EQ, yes, Infinity), (3, b, true, EQ, yes, NaN), (3, b, true, EQ, no, Infinity)," + " (3, b, true, EQ, no, NaN), (3, b, true, LT, yes, Infinity), (3, b, true, LT, yes, NaN)," + " (3, b, true, LT, no, Infinity), (3, b, true, LT, no, NaN), (3, b, true, GT, yes, Infinity)," + " (3, b, true, GT, yes, NaN), (3, b, true, GT, no, Infinity), (3, b, true, GT, no, NaN)," + " (3, c, false, EQ, yes, Infinity), (3, c, false, EQ, yes, NaN), (3, c, false, EQ, no, Infinity)," + " (3, c, false, EQ, no, NaN), (3, c, false, LT, yes, Infinity), (3, c, false, LT, yes, NaN)," + " (3, c, false, LT, no, Infinity), (3, c, false, LT, no, NaN), (3, c, false, GT, yes, Infinity)," + " (3, c, false, GT, yes, NaN), (3, c, false, GT, no, Infinity), (3, c, false, GT, no, NaN)," + " (3, c, true, EQ, yes, Infinity), (3, c, true, EQ, yes, NaN), (3, c, true, EQ, no, Infinity)," + " (3, c, true, EQ, no, NaN), (3, c, true, LT, yes, Infinity), (3, c, true, LT, yes, NaN)," + " (3, c, true, LT, no, Infinity), (3, c, true, LT, no, NaN), (3, c, true, GT, yes, Infinity)," + " (3, c, true, GT, yes, NaN), (3, c, true, GT, no, Infinity), (3, c, true, GT, no, NaN)]"); aeq(take(20, sextuplesAscending( P.naturalBigIntegers(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), (Iterable<Float>) Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) )), "[(0, a, false, EQ, yes, Infinity), (0, a, false, EQ, yes, NaN), (0, a, false, EQ, no, Infinity)," + " (0, a, false, EQ, no, NaN), (0, a, false, LT, yes, Infinity), (0, a, false, LT, yes, NaN)," + " (0, a, false, LT, no, Infinity), (0, a, false, LT, no, NaN), (0, a, false, GT, yes, Infinity)," + " (0, a, false, GT, yes, NaN), (0, a, false, GT, no, Infinity), (0, a, false, GT, no, NaN)," + " (0, a, true, EQ, yes, Infinity), (0, a, true, EQ, yes, NaN), (0, a, true, EQ, no, Infinity)," + " (0, a, true, EQ, no, NaN), (0, a, true, LT, yes, Infinity), (0, a, true, LT, yes, NaN)," + " (0, a, true, LT, no, Infinity), (0, a, true, LT, no, NaN)]"); aeq(sextuplesAscending( new ArrayList<Integer>(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[]"); aeq(sextuplesAscending( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>(), new ArrayList<Float>() ), "[]"); } @Test public void testSeptuplesAscending() { List<Integer> x = Arrays.asList(1, 0); List<Integer> y = Arrays.asList(0, 1); aeq(septuplesAscending( (Iterable<Integer>) Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), (Iterable<List<Integer>>) Arrays.asList(x, y) ), "[(1, a, false, EQ, yes, Infinity, [1, 0]), (1, a, false, EQ, yes, Infinity, [0, 1])," + " (1, a, false, EQ, yes, NaN, [1, 0]), (1, a, false, EQ, yes, NaN, [0, 1])," + " (1, a, false, EQ, no, Infinity, [1, 0]), (1, a, false, EQ, no, Infinity, [0, 1])," + " (1, a, false, EQ, no, NaN, [1, 0]), (1, a, false, EQ, no, NaN, [0, 1])," + " (1, a, false, LT, yes, Infinity, [1, 0]), (1, a, false, LT, yes, Infinity, [0, 1])," + " (1, a, false, LT, yes, NaN, [1, 0]), (1, a, false, LT, yes, NaN, [0, 1])," + " (1, a, false, LT, no, Infinity, [1, 0]), (1, a, false, LT, no, Infinity, [0, 1])," + " (1, a, false, LT, no, NaN, [1, 0]), (1, a, false, LT, no, NaN, [0, 1])," + " (1, a, false, GT, yes, Infinity, [1, 0]), (1, a, false, GT, yes, Infinity, [0, 1])," + " (1, a, false, GT, yes, NaN, [1, 0]), (1, a, false, GT, yes, NaN, [0, 1])," + " (1, a, false, GT, no, Infinity, [1, 0]), (1, a, false, GT, no, Infinity, [0, 1])," + " (1, a, false, GT, no, NaN, [1, 0]), (1, a, false, GT, no, NaN, [0, 1])," + " (1, a, true, EQ, yes, Infinity, [1, 0]), (1, a, true, EQ, yes, Infinity, [0, 1])," + " (1, a, true, EQ, yes, NaN, [1, 0]), (1, a, true, EQ, yes, NaN, [0, 1])," + " (1, a, true, EQ, no, Infinity, [1, 0]), (1, a, true, EQ, no, Infinity, [0, 1])," + " (1, a, true, EQ, no, NaN, [1, 0]), (1, a, true, EQ, no, NaN, [0, 1])," + " (1, a, true, LT, yes, Infinity, [1, 0]), (1, a, true, LT, yes, Infinity, [0, 1])," + " (1, a, true, LT, yes, NaN, [1, 0]), (1, a, true, LT, yes, NaN, [0, 1])," + " (1, a, true, LT, no, Infinity, [1, 0]), (1, a, true, LT, no, Infinity, [0, 1])," + " (1, a, true, LT, no, NaN, [1, 0]), (1, a, true, LT, no, NaN, [0, 1])," + " (1, a, true, GT, yes, Infinity, [1, 0]), (1, a, true, GT, yes, Infinity, [0, 1])," + " (1, a, true, GT, yes, NaN, [1, 0]), (1, a, true, GT, yes, NaN, [0, 1])," + " (1, a, true, GT, no, Infinity, [1, 0]), (1, a, true, GT, no, Infinity, [0, 1])," + " (1, a, true, GT, no, NaN, [1, 0]), (1, a, true, GT, no, NaN, [0, 1])," + " (1, b, false, EQ, yes, Infinity, [1, 0]), (1, b, false, EQ, yes, Infinity, [0, 1])," + " (1, b, false, EQ, yes, NaN, [1, 0]), (1, b, false, EQ, yes, NaN, [0, 1])," + " (1, b, false, EQ, no, Infinity, [1, 0]), (1, b, false, EQ, no, Infinity, [0, 1])," + " (1, b, false, EQ, no, NaN, [1, 0]), (1, b, false, EQ, no, NaN, [0, 1])," + " (1, b, false, LT, yes, Infinity, [1, 0]), (1, b, false, LT, yes, Infinity, [0, 1])," + " (1, b, false, LT, yes, NaN, [1, 0]), (1, b, false, LT, yes, NaN, [0, 1])," + " (1, b, false, LT, no, Infinity, [1, 0]), (1, b, false, LT, no, Infinity, [0, 1])," + " (1, b, false, LT, no, NaN, [1, 0]), (1, b, false, LT, no, NaN, [0, 1])," + " (1, b, false, GT, yes, Infinity, [1, 0]), (1, b, false, GT, yes, Infinity, [0, 1])," + " (1, b, false, GT, yes, NaN, [1, 0]), (1, b, false, GT, yes, NaN, [0, 1])," + " (1, b, false, GT, no, Infinity, [1, 0]), (1, b, false, GT, no, Infinity, [0, 1])," + " (1, b, false, GT, no, NaN, [1, 0]), (1, b, false, GT, no, NaN, [0, 1])," + " (1, b, true, EQ, yes, Infinity, [1, 0]), (1, b, true, EQ, yes, Infinity, [0, 1])," + " (1, b, true, EQ, yes, NaN, [1, 0]), (1, b, true, EQ, yes, NaN, [0, 1])," + " (1, b, true, EQ, no, Infinity, [1, 0]), (1, b, true, EQ, no, Infinity, [0, 1])," + " (1, b, true, EQ, no, NaN, [1, 0]), (1, b, true, EQ, no, NaN, [0, 1])," + " (1, b, true, LT, yes, Infinity, [1, 0]), (1, b, true, LT, yes, Infinity, [0, 1])," + " (1, b, true, LT, yes, NaN, [1, 0]), (1, b, true, LT, yes, NaN, [0, 1])," + " (1, b, true, LT, no, Infinity, [1, 0]), (1, b, true, LT, no, Infinity, [0, 1])," + " (1, b, true, LT, no, NaN, [1, 0]), (1, b, true, LT, no, NaN, [0, 1])," + " (1, b, true, GT, yes, Infinity, [1, 0]), (1, b, true, GT, yes, Infinity, [0, 1])," + " (1, b, true, GT, yes, NaN, [1, 0]), (1, b, true, GT, yes, NaN, [0, 1])," + " (1, b, true, GT, no, Infinity, [1, 0]), (1, b, true, GT, no, Infinity, [0, 1])," + " (1, b, true, GT, no, NaN, [1, 0]), (1, b, true, GT, no, NaN, [0, 1])," + " (1, c, false, EQ, yes, Infinity, [1, 0]), (1, c, false, EQ, yes, Infinity, [0, 1])," + " (1, c, false, EQ, yes, NaN, [1, 0]), (1, c, false, EQ, yes, NaN, [0, 1])," + " (1, c, false, EQ, no, Infinity, [1, 0]), (1, c, false, EQ, no, Infinity, [0, 1])," + " (1, c, false, EQ, no, NaN, [1, 0]), (1, c, false, EQ, no, NaN, [0, 1])," + " (1, c, false, LT, yes, Infinity, [1, 0]), (1, c, false, LT, yes, Infinity, [0, 1])," + " (1, c, false, LT, yes, NaN, [1, 0]), (1, c, false, LT, yes, NaN, [0, 1])," + " (1, c, false, LT, no, Infinity, [1, 0]), (1, c, false, LT, no, Infinity, [0, 1])," + " (1, c, false, LT, no, NaN, [1, 0]), (1, c, false, LT, no, NaN, [0, 1])," + " (1, c, false, GT, yes, Infinity, [1, 0]), (1, c, false, GT, yes, Infinity, [0, 1])," + " (1, c, false, GT, yes, NaN, [1, 0]), (1, c, false, GT, yes, NaN, [0, 1])," + " (1, c, false, GT, no, Infinity, [1, 0]), (1, c, false, GT, no, Infinity, [0, 1])," + " (1, c, false, GT, no, NaN, [1, 0]), (1, c, false, GT, no, NaN, [0, 1])," + " (1, c, true, EQ, yes, Infinity, [1, 0]), (1, c, true, EQ, yes, Infinity, [0, 1])," + " (1, c, true, EQ, yes, NaN, [1, 0]), (1, c, true, EQ, yes, NaN, [0, 1])," + " (1, c, true, EQ, no, Infinity, [1, 0]), (1, c, true, EQ, no, Infinity, [0, 1])," + " (1, c, true, EQ, no, NaN, [1, 0]), (1, c, true, EQ, no, NaN, [0, 1])," + " (1, c, true, LT, yes, Infinity, [1, 0]), (1, c, true, LT, yes, Infinity, [0, 1])," + " (1, c, true, LT, yes, NaN, [1, 0]), (1, c, true, LT, yes, NaN, [0, 1])," + " (1, c, true, LT, no, Infinity, [1, 0]), (1, c, true, LT, no, Infinity, [0, 1])," + " (1, c, true, LT, no, NaN, [1, 0]), (1, c, true, LT, no, NaN, [0, 1])," + " (1, c, true, GT, yes, Infinity, [1, 0]), (1, c, true, GT, yes, Infinity, [0, 1])," + " (1, c, true, GT, yes, NaN, [1, 0]), (1, c, true, GT, yes, NaN, [0, 1])," + " (1, c, true, GT, no, Infinity, [1, 0]), (1, c, true, GT, no, Infinity, [0, 1])," + " (1, c, true, GT, no, NaN, [1, 0]), (1, c, true, GT, no, NaN, [0, 1])," + " (2, a, false, EQ, yes, Infinity, [1, 0]), (2, a, false, EQ, yes, Infinity, [0, 1])," + " (2, a, false, EQ, yes, NaN, [1, 0]), (2, a, false, EQ, yes, NaN, [0, 1])," + " (2, a, false, EQ, no, Infinity, [1, 0]), (2, a, false, EQ, no, Infinity, [0, 1])," + " (2, a, false, EQ, no, NaN, [1, 0]), (2, a, false, EQ, no, NaN, [0, 1])," + " (2, a, false, LT, yes, Infinity, [1, 0]), (2, a, false, LT, yes, Infinity, [0, 1])," + " (2, a, false, LT, yes, NaN, [1, 0]), (2, a, false, LT, yes, NaN, [0, 1])," + " (2, a, false, LT, no, Infinity, [1, 0]), (2, a, false, LT, no, Infinity, [0, 1])," + " (2, a, false, LT, no, NaN, [1, 0]), (2, a, false, LT, no, NaN, [0, 1])," + " (2, a, false, GT, yes, Infinity, [1, 0]), (2, a, false, GT, yes, Infinity, [0, 1])," + " (2, a, false, GT, yes, NaN, [1, 0]), (2, a, false, GT, yes, NaN, [0, 1])," + " (2, a, false, GT, no, Infinity, [1, 0]), (2, a, false, GT, no, Infinity, [0, 1])," + " (2, a, false, GT, no, NaN, [1, 0]), (2, a, false, GT, no, NaN, [0, 1])," + " (2, a, true, EQ, yes, Infinity, [1, 0]), (2, a, true, EQ, yes, Infinity, [0, 1])," + " (2, a, true, EQ, yes, NaN, [1, 0]), (2, a, true, EQ, yes, NaN, [0, 1])," + " (2, a, true, EQ, no, Infinity, [1, 0]), (2, a, true, EQ, no, Infinity, [0, 1])," + " (2, a, true, EQ, no, NaN, [1, 0]), (2, a, true, EQ, no, NaN, [0, 1])," + " (2, a, true, LT, yes, Infinity, [1, 0]), (2, a, true, LT, yes, Infinity, [0, 1])," + " (2, a, true, LT, yes, NaN, [1, 0]), (2, a, true, LT, yes, NaN, [0, 1])," + " (2, a, true, LT, no, Infinity, [1, 0]), (2, a, true, LT, no, Infinity, [0, 1])," + " (2, a, true, LT, no, NaN, [1, 0]), (2, a, true, LT, no, NaN, [0, 1])," + " (2, a, true, GT, yes, Infinity, [1, 0]), (2, a, true, GT, yes, Infinity, [0, 1])," + " (2, a, true, GT, yes, NaN, [1, 0]), (2, a, true, GT, yes, NaN, [0, 1])," + " (2, a, true, GT, no, Infinity, [1, 0]), (2, a, true, GT, no, Infinity, [0, 1])," + " (2, a, true, GT, no, NaN, [1, 0]), (2, a, true, GT, no, NaN, [0, 1])," + " (2, b, false, EQ, yes, Infinity, [1, 0]), (2, b, false, EQ, yes, Infinity, [0, 1])," + " (2, b, false, EQ, yes, NaN, [1, 0]), (2, b, false, EQ, yes, NaN, [0, 1])," + " (2, b, false, EQ, no, Infinity, [1, 0]), (2, b, false, EQ, no, Infinity, [0, 1])," + " (2, b, false, EQ, no, NaN, [1, 0]), (2, b, false, EQ, no, NaN, [0, 1])," + " (2, b, false, LT, yes, Infinity, [1, 0]), (2, b, false, LT, yes, Infinity, [0, 1])," + " (2, b, false, LT, yes, NaN, [1, 0]), (2, b, false, LT, yes, NaN, [0, 1])," + " (2, b, false, LT, no, Infinity, [1, 0]), (2, b, false, LT, no, Infinity, [0, 1])," + " (2, b, false, LT, no, NaN, [1, 0]), (2, b, false, LT, no, NaN, [0, 1])," + " (2, b, false, GT, yes, Infinity, [1, 0]), (2, b, false, GT, yes, Infinity, [0, 1])," + " (2, b, false, GT, yes, NaN, [1, 0]), (2, b, false, GT, yes, NaN, [0, 1])," + " (2, b, false, GT, no, Infinity, [1, 0]), (2, b, false, GT, no, Infinity, [0, 1])," + " (2, b, false, GT, no, NaN, [1, 0]), (2, b, false, GT, no, NaN, [0, 1])," + " (2, b, true, EQ, yes, Infinity, [1, 0]), (2, b, true, EQ, yes, Infinity, [0, 1])," + " (2, b, true, EQ, yes, NaN, [1, 0]), (2, b, true, EQ, yes, NaN, [0, 1])," + " (2, b, true, EQ, no, Infinity, [1, 0]), (2, b, true, EQ, no, Infinity, [0, 1])," + " (2, b, true, EQ, no, NaN, [1, 0]), (2, b, true, EQ, no, NaN, [0, 1])," + " (2, b, true, LT, yes, Infinity, [1, 0]), (2, b, true, LT, yes, Infinity, [0, 1])," + " (2, b, true, LT, yes, NaN, [1, 0]), (2, b, true, LT, yes, NaN, [0, 1])," + " (2, b, true, LT, no, Infinity, [1, 0]), (2, b, true, LT, no, Infinity, [0, 1])," + " (2, b, true, LT, no, NaN, [1, 0]), (2, b, true, LT, no, NaN, [0, 1])," + " (2, b, true, GT, yes, Infinity, [1, 0]), (2, b, true, GT, yes, Infinity, [0, 1])," + " (2, b, true, GT, yes, NaN, [1, 0]), (2, b, true, GT, yes, NaN, [0, 1])," + " (2, b, true, GT, no, Infinity, [1, 0]), (2, b, true, GT, no, Infinity, [0, 1])," + " (2, b, true, GT, no, NaN, [1, 0]), (2, b, true, GT, no, NaN, [0, 1])," + " (2, c, false, EQ, yes, Infinity, [1, 0]), (2, c, false, EQ, yes, Infinity, [0, 1])," + " (2, c, false, EQ, yes, NaN, [1, 0]), (2, c, false, EQ, yes, NaN, [0, 1])," + " (2, c, false, EQ, no, Infinity, [1, 0]), (2, c, false, EQ, no, Infinity, [0, 1])," + " (2, c, false, EQ, no, NaN, [1, 0]), (2, c, false, EQ, no, NaN, [0, 1])," + " (2, c, false, LT, yes, Infinity, [1, 0]), (2, c, false, LT, yes, Infinity, [0, 1])," + " (2, c, false, LT, yes, NaN, [1, 0]), (2, c, false, LT, yes, NaN, [0, 1])," + " (2, c, false, LT, no, Infinity, [1, 0]), (2, c, false, LT, no, Infinity, [0, 1])," + " (2, c, false, LT, no, NaN, [1, 0]), (2, c, false, LT, no, NaN, [0, 1])," + " (2, c, false, GT, yes, Infinity, [1, 0]), (2, c, false, GT, yes, Infinity, [0, 1])," + " (2, c, false, GT, yes, NaN, [1, 0]), (2, c, false, GT, yes, NaN, [0, 1])," + " (2, c, false, GT, no, Infinity, [1, 0]), (2, c, false, GT, no, Infinity, [0, 1])," + " (2, c, false, GT, no, NaN, [1, 0]), (2, c, false, GT, no, NaN, [0, 1])," + " (2, c, true, EQ, yes, Infinity, [1, 0]), (2, c, true, EQ, yes, Infinity, [0, 1])," + " (2, c, true, EQ, yes, NaN, [1, 0]), (2, c, true, EQ, yes, NaN, [0, 1])," + " (2, c, true, EQ, no, Infinity, [1, 0]), (2, c, true, EQ, no, Infinity, [0, 1])," + " (2, c, true, EQ, no, NaN, [1, 0]), (2, c, true, EQ, no, NaN, [0, 1])," + " (2, c, true, LT, yes, Infinity, [1, 0]), (2, c, true, LT, yes, Infinity, [0, 1])," + " (2, c, true, LT, yes, NaN, [1, 0]), (2, c, true, LT, yes, NaN, [0, 1])," + " (2, c, true, LT, no, Infinity, [1, 0]), (2, c, true, LT, no, Infinity, [0, 1])," + " (2, c, true, LT, no, NaN, [1, 0]), (2, c, true, LT, no, NaN, [0, 1])," + " (2, c, true, GT, yes, Infinity, [1, 0]), (2, c, true, GT, yes, Infinity, [0, 1])," + " (2, c, true, GT, yes, NaN, [1, 0]), (2, c, true, GT, yes, NaN, [0, 1])," + " (2, c, true, GT, no, Infinity, [1, 0]), (2, c, true, GT, no, Infinity, [0, 1])," + " (2, c, true, GT, no, NaN, [1, 0]), (2, c, true, GT, no, NaN, [0, 1])," + " (3, a, false, EQ, yes, Infinity, [1, 0]), (3, a, false, EQ, yes, Infinity, [0, 1])," + " (3, a, false, EQ, yes, NaN, [1, 0]), (3, a, false, EQ, yes, NaN, [0, 1])," + " (3, a, false, EQ, no, Infinity, [1, 0]), (3, a, false, EQ, no, Infinity, [0, 1])," + " (3, a, false, EQ, no, NaN, [1, 0]), (3, a, false, EQ, no, NaN, [0, 1])," + " (3, a, false, LT, yes, Infinity, [1, 0]), (3, a, false, LT, yes, Infinity, [0, 1])," + " (3, a, false, LT, yes, NaN, [1, 0]), (3, a, false, LT, yes, NaN, [0, 1])," + " (3, a, false, LT, no, Infinity, [1, 0]), (3, a, false, LT, no, Infinity, [0, 1])," + " (3, a, false, LT, no, NaN, [1, 0]), (3, a, false, LT, no, NaN, [0, 1])," + " (3, a, false, GT, yes, Infinity, [1, 0]), (3, a, false, GT, yes, Infinity, [0, 1])," + " (3, a, false, GT, yes, NaN, [1, 0]), (3, a, false, GT, yes, NaN, [0, 1])," + " (3, a, false, GT, no, Infinity, [1, 0]), (3, a, false, GT, no, Infinity, [0, 1])," + " (3, a, false, GT, no, NaN, [1, 0]), (3, a, false, GT, no, NaN, [0, 1])," + " (3, a, true, EQ, yes, Infinity, [1, 0]), (3, a, true, EQ, yes, Infinity, [0, 1])," + " (3, a, true, EQ, yes, NaN, [1, 0]), (3, a, true, EQ, yes, NaN, [0, 1])," + " (3, a, true, EQ, no, Infinity, [1, 0]), (3, a, true, EQ, no, Infinity, [0, 1])," + " (3, a, true, EQ, no, NaN, [1, 0]), (3, a, true, EQ, no, NaN, [0, 1])," + " (3, a, true, LT, yes, Infinity, [1, 0]), (3, a, true, LT, yes, Infinity, [0, 1])," + " (3, a, true, LT, yes, NaN, [1, 0]), (3, a, true, LT, yes, NaN, [0, 1])," + " (3, a, true, LT, no, Infinity, [1, 0]), (3, a, true, LT, no, Infinity, [0, 1])," + " (3, a, true, LT, no, NaN, [1, 0]), (3, a, true, LT, no, NaN, [0, 1])," + " (3, a, true, GT, yes, Infinity, [1, 0]), (3, a, true, GT, yes, Infinity, [0, 1])," + " (3, a, true, GT, yes, NaN, [1, 0]), (3, a, true, GT, yes, NaN, [0, 1])," + " (3, a, true, GT, no, Infinity, [1, 0]), (3, a, true, GT, no, Infinity, [0, 1])," + " (3, a, true, GT, no, NaN, [1, 0]), (3, a, true, GT, no, NaN, [0, 1])," + " (3, b, false, EQ, yes, Infinity, [1, 0]), (3, b, false, EQ, yes, Infinity, [0, 1])," + " (3, b, false, EQ, yes, NaN, [1, 0]), (3, b, false, EQ, yes, NaN, [0, 1])," + " (3, b, false, EQ, no, Infinity, [1, 0]), (3, b, false, EQ, no, Infinity, [0, 1])," + " (3, b, false, EQ, no, NaN, [1, 0]), (3, b, false, EQ, no, NaN, [0, 1])," + " (3, b, false, LT, yes, Infinity, [1, 0]), (3, b, false, LT, yes, Infinity, [0, 1])," + " (3, b, false, LT, yes, NaN, [1, 0]), (3, b, false, LT, yes, NaN, [0, 1])," + " (3, b, false, LT, no, Infinity, [1, 0]), (3, b, false, LT, no, Infinity, [0, 1])," + " (3, b, false, LT, no, NaN, [1, 0]), (3, b, false, LT, no, NaN, [0, 1])," + " (3, b, false, GT, yes, Infinity, [1, 0]), (3, b, false, GT, yes, Infinity, [0, 1])," + " (3, b, false, GT, yes, NaN, [1, 0]), (3, b, false, GT, yes, NaN, [0, 1])," + " (3, b, false, GT, no, Infinity, [1, 0]), (3, b, false, GT, no, Infinity, [0, 1])," + " (3, b, false, GT, no, NaN, [1, 0]), (3, b, false, GT, no, NaN, [0, 1])," + " (3, b, true, EQ, yes, Infinity, [1, 0]), (3, b, true, EQ, yes, Infinity, [0, 1])," + " (3, b, true, EQ, yes, NaN, [1, 0]), (3, b, true, EQ, yes, NaN, [0, 1])," + " (3, b, true, EQ, no, Infinity, [1, 0]), (3, b, true, EQ, no, Infinity, [0, 1])," + " (3, b, true, EQ, no, NaN, [1, 0]), (3, b, true, EQ, no, NaN, [0, 1])," + " (3, b, true, LT, yes, Infinity, [1, 0]), (3, b, true, LT, yes, Infinity, [0, 1])," + " (3, b, true, LT, yes, NaN, [1, 0]), (3, b, true, LT, yes, NaN, [0, 1])," + " (3, b, true, LT, no, Infinity, [1, 0]), (3, b, true, LT, no, Infinity, [0, 1])," + " (3, b, true, LT, no, NaN, [1, 0]), (3, b, true, LT, no, NaN, [0, 1])," + " (3, b, true, GT, yes, Infinity, [1, 0]), (3, b, true, GT, yes, Infinity, [0, 1])," + " (3, b, true, GT, yes, NaN, [1, 0]), (3, b, true, GT, yes, NaN, [0, 1])," + " (3, b, true, GT, no, Infinity, [1, 0]), (3, b, true, GT, no, Infinity, [0, 1])," + " (3, b, true, GT, no, NaN, [1, 0]), (3, b, true, GT, no, NaN, [0, 1])," + " (3, c, false, EQ, yes, Infinity, [1, 0]), (3, c, false, EQ, yes, Infinity, [0, 1])," + " (3, c, false, EQ, yes, NaN, [1, 0]), (3, c, false, EQ, yes, NaN, [0, 1])," + " (3, c, false, EQ, no, Infinity, [1, 0]), (3, c, false, EQ, no, Infinity, [0, 1])," + " (3, c, false, EQ, no, NaN, [1, 0]), (3, c, false, EQ, no, NaN, [0, 1])," + " (3, c, false, LT, yes, Infinity, [1, 0]), (3, c, false, LT, yes, Infinity, [0, 1])," + " (3, c, false, LT, yes, NaN, [1, 0]), (3, c, false, LT, yes, NaN, [0, 1])," + " (3, c, false, LT, no, Infinity, [1, 0]), (3, c, false, LT, no, Infinity, [0, 1])," + " (3, c, false, LT, no, NaN, [1, 0]), (3, c, false, LT, no, NaN, [0, 1])," + " (3, c, false, GT, yes, Infinity, [1, 0]), (3, c, false, GT, yes, Infinity, [0, 1])," + " (3, c, false, GT, yes, NaN, [1, 0]), (3, c, false, GT, yes, NaN, [0, 1])," + " (3, c, false, GT, no, Infinity, [1, 0]), (3, c, false, GT, no, Infinity, [0, 1])," + " (3, c, false, GT, no, NaN, [1, 0]), (3, c, false, GT, no, NaN, [0, 1])," + " (3, c, true, EQ, yes, Infinity, [1, 0]), (3, c, true, EQ, yes, Infinity, [0, 1])," + " (3, c, true, EQ, yes, NaN, [1, 0]), (3, c, true, EQ, yes, NaN, [0, 1])," + " (3, c, true, EQ, no, Infinity, [1, 0]), (3, c, true, EQ, no, Infinity, [0, 1])," + " (3, c, true, EQ, no, NaN, [1, 0]), (3, c, true, EQ, no, NaN, [0, 1])," + " (3, c, true, LT, yes, Infinity, [1, 0]), (3, c, true, LT, yes, Infinity, [0, 1])," + " (3, c, true, LT, yes, NaN, [1, 0]), (3, c, true, LT, yes, NaN, [0, 1])," + " (3, c, true, LT, no, Infinity, [1, 0]), (3, c, true, LT, no, Infinity, [0, 1])," + " (3, c, true, LT, no, NaN, [1, 0]), (3, c, true, LT, no, NaN, [0, 1])," + " (3, c, true, GT, yes, Infinity, [1, 0]), (3, c, true, GT, yes, Infinity, [0, 1])," + " (3, c, true, GT, yes, NaN, [1, 0]), (3, c, true, GT, yes, NaN, [0, 1])," + " (3, c, true, GT, no, Infinity, [1, 0]), (3, c, true, GT, no, Infinity, [0, 1])," + " (3, c, true, GT, no, NaN, [1, 0]), (3, c, true, GT, no, NaN, [0, 1])]"); aeq(septuplesAscending( (Iterable<Integer>) Arrays.asList(1, null, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), (Iterable<List<Integer>>) Arrays.asList(x, y) ), "[(1, a, false, EQ, yes, Infinity, [1, 0]), (1, a, false, EQ, yes, Infinity, [0, 1])," + " (1, a, false, EQ, yes, NaN, [1, 0]), (1, a, false, EQ, yes, NaN, [0, 1])," + " (1, a, false, EQ, no, Infinity, [1, 0]), (1, a, false, EQ, no, Infinity, [0, 1])," + " (1, a, false, EQ, no, NaN, [1, 0]), (1, a, false, EQ, no, NaN, [0, 1])," + " (1, a, false, LT, yes, Infinity, [1, 0]), (1, a, false, LT, yes, Infinity, [0, 1])," + " (1, a, false, LT, yes, NaN, [1, 0]), (1, a, false, LT, yes, NaN, [0, 1])," + " (1, a, false, LT, no, Infinity, [1, 0]), (1, a, false, LT, no, Infinity, [0, 1])," + " (1, a, false, LT, no, NaN, [1, 0]), (1, a, false, LT, no, NaN, [0, 1])," + " (1, a, false, GT, yes, Infinity, [1, 0]), (1, a, false, GT, yes, Infinity, [0, 1])," + " (1, a, false, GT, yes, NaN, [1, 0]), (1, a, false, GT, yes, NaN, [0, 1])," + " (1, a, false, GT, no, Infinity, [1, 0]), (1, a, false, GT, no, Infinity, [0, 1])," + " (1, a, false, GT, no, NaN, [1, 0]), (1, a, false, GT, no, NaN, [0, 1])," + " (1, a, true, EQ, yes, Infinity, [1, 0]), (1, a, true, EQ, yes, Infinity, [0, 1])," + " (1, a, true, EQ, yes, NaN, [1, 0]), (1, a, true, EQ, yes, NaN, [0, 1])," + " (1, a, true, EQ, no, Infinity, [1, 0]), (1, a, true, EQ, no, Infinity, [0, 1])," + " (1, a, true, EQ, no, NaN, [1, 0]), (1, a, true, EQ, no, NaN, [0, 1])," + " (1, a, true, LT, yes, Infinity, [1, 0]), (1, a, true, LT, yes, Infinity, [0, 1])," + " (1, a, true, LT, yes, NaN, [1, 0]), (1, a, true, LT, yes, NaN, [0, 1])," + " (1, a, true, LT, no, Infinity, [1, 0]), (1, a, true, LT, no, Infinity, [0, 1])," + " (1, a, true, LT, no, NaN, [1, 0]), (1, a, true, LT, no, NaN, [0, 1])," + " (1, a, true, GT, yes, Infinity, [1, 0]), (1, a, true, GT, yes, Infinity, [0, 1])," + " (1, a, true, GT, yes, NaN, [1, 0]), (1, a, true, GT, yes, NaN, [0, 1])," + " (1, a, true, GT, no, Infinity, [1, 0]), (1, a, true, GT, no, Infinity, [0, 1])," + " (1, a, true, GT, no, NaN, [1, 0]), (1, a, true, GT, no, NaN, [0, 1])," + " (1, b, false, EQ, yes, Infinity, [1, 0]), (1, b, false, EQ, yes, Infinity, [0, 1])," + " (1, b, false, EQ, yes, NaN, [1, 0]), (1, b, false, EQ, yes, NaN, [0, 1])," + " (1, b, false, EQ, no, Infinity, [1, 0]), (1, b, false, EQ, no, Infinity, [0, 1])," + " (1, b, false, EQ, no, NaN, [1, 0]), (1, b, false, EQ, no, NaN, [0, 1])," + " (1, b, false, LT, yes, Infinity, [1, 0]), (1, b, false, LT, yes, Infinity, [0, 1])," + " (1, b, false, LT, yes, NaN, [1, 0]), (1, b, false, LT, yes, NaN, [0, 1])," + " (1, b, false, LT, no, Infinity, [1, 0]), (1, b, false, LT, no, Infinity, [0, 1])," + " (1, b, false, LT, no, NaN, [1, 0]), (1, b, false, LT, no, NaN, [0, 1])," + " (1, b, false, GT, yes, Infinity, [1, 0]), (1, b, false, GT, yes, Infinity, [0, 1])," + " (1, b, false, GT, yes, NaN, [1, 0]), (1, b, false, GT, yes, NaN, [0, 1])," + " (1, b, false, GT, no, Infinity, [1, 0]), (1, b, false, GT, no, Infinity, [0, 1])," + " (1, b, false, GT, no, NaN, [1, 0]), (1, b, false, GT, no, NaN, [0, 1])," + " (1, b, true, EQ, yes, Infinity, [1, 0]), (1, b, true, EQ, yes, Infinity, [0, 1])," + " (1, b, true, EQ, yes, NaN, [1, 0]), (1, b, true, EQ, yes, NaN, [0, 1])," + " (1, b, true, EQ, no, Infinity, [1, 0]), (1, b, true, EQ, no, Infinity, [0, 1])," + " (1, b, true, EQ, no, NaN, [1, 0]), (1, b, true, EQ, no, NaN, [0, 1])," + " (1, b, true, LT, yes, Infinity, [1, 0]), (1, b, true, LT, yes, Infinity, [0, 1])," + " (1, b, true, LT, yes, NaN, [1, 0]), (1, b, true, LT, yes, NaN, [0, 1])," + " (1, b, true, LT, no, Infinity, [1, 0]), (1, b, true, LT, no, Infinity, [0, 1])," + " (1, b, true, LT, no, NaN, [1, 0]), (1, b, true, LT, no, NaN, [0, 1])," + " (1, b, true, GT, yes, Infinity, [1, 0]), (1, b, true, GT, yes, Infinity, [0, 1])," + " (1, b, true, GT, yes, NaN, [1, 0]), (1, b, true, GT, yes, NaN, [0, 1])," + " (1, b, true, GT, no, Infinity, [1, 0]), (1, b, true, GT, no, Infinity, [0, 1])," + " (1, b, true, GT, no, NaN, [1, 0]), (1, b, true, GT, no, NaN, [0, 1])," + " (1, c, false, EQ, yes, Infinity, [1, 0]), (1, c, false, EQ, yes, Infinity, [0, 1])," + " (1, c, false, EQ, yes, NaN, [1, 0]), (1, c, false, EQ, yes, NaN, [0, 1])," + " (1, c, false, EQ, no, Infinity, [1, 0]), (1, c, false, EQ, no, Infinity, [0, 1])," + " (1, c, false, EQ, no, NaN, [1, 0]), (1, c, false, EQ, no, NaN, [0, 1])," + " (1, c, false, LT, yes, Infinity, [1, 0]), (1, c, false, LT, yes, Infinity, [0, 1])," + " (1, c, false, LT, yes, NaN, [1, 0]), (1, c, false, LT, yes, NaN, [0, 1])," + " (1, c, false, LT, no, Infinity, [1, 0]), (1, c, false, LT, no, Infinity, [0, 1])," + " (1, c, false, LT, no, NaN, [1, 0]), (1, c, false, LT, no, NaN, [0, 1])," + " (1, c, false, GT, yes, Infinity, [1, 0]), (1, c, false, GT, yes, Infinity, [0, 1])," + " (1, c, false, GT, yes, NaN, [1, 0]), (1, c, false, GT, yes, NaN, [0, 1])," + " (1, c, false, GT, no, Infinity, [1, 0]), (1, c, false, GT, no, Infinity, [0, 1])," + " (1, c, false, GT, no, NaN, [1, 0]), (1, c, false, GT, no, NaN, [0, 1])," + " (1, c, true, EQ, yes, Infinity, [1, 0]), (1, c, true, EQ, yes, Infinity, [0, 1])," + " (1, c, true, EQ, yes, NaN, [1, 0]), (1, c, true, EQ, yes, NaN, [0, 1])," + " (1, c, true, EQ, no, Infinity, [1, 0]), (1, c, true, EQ, no, Infinity, [0, 1])," + " (1, c, true, EQ, no, NaN, [1, 0]), (1, c, true, EQ, no, NaN, [0, 1])," + " (1, c, true, LT, yes, Infinity, [1, 0]), (1, c, true, LT, yes, Infinity, [0, 1])," + " (1, c, true, LT, yes, NaN, [1, 0]), (1, c, true, LT, yes, NaN, [0, 1])," + " (1, c, true, LT, no, Infinity, [1, 0]), (1, c, true, LT, no, Infinity, [0, 1])," + " (1, c, true, LT, no, NaN, [1, 0]), (1, c, true, LT, no, NaN, [0, 1])," + " (1, c, true, GT, yes, Infinity, [1, 0]), (1, c, true, GT, yes, Infinity, [0, 1])," + " (1, c, true, GT, yes, NaN, [1, 0]), (1, c, true, GT, yes, NaN, [0, 1])," + " (1, c, true, GT, no, Infinity, [1, 0]), (1, c, true, GT, no, Infinity, [0, 1])," + " (1, c, true, GT, no, NaN, [1, 0]), (1, c, true, GT, no, NaN, [0, 1])," + " (null, a, false, EQ, yes, Infinity, [1, 0]), (null, a, false, EQ, yes, Infinity, [0, 1])," + " (null, a, false, EQ, yes, NaN, [1, 0]), (null, a, false, EQ, yes, NaN, [0, 1])," + " (null, a, false, EQ, no, Infinity, [1, 0]), (null, a, false, EQ, no, Infinity, [0, 1])," + " (null, a, false, EQ, no, NaN, [1, 0]), (null, a, false, EQ, no, NaN, [0, 1])," + " (null, a, false, LT, yes, Infinity, [1, 0]), (null, a, false, LT, yes, Infinity, [0, 1])," + " (null, a, false, LT, yes, NaN, [1, 0]), (null, a, false, LT, yes, NaN, [0, 1])," + " (null, a, false, LT, no, Infinity, [1, 0]), (null, a, false, LT, no, Infinity, [0, 1])," + " (null, a, false, LT, no, NaN, [1, 0]), (null, a, false, LT, no, NaN, [0, 1])," + " (null, a, false, GT, yes, Infinity, [1, 0]), (null, a, false, GT, yes, Infinity, [0, 1])," + " (null, a, false, GT, yes, NaN, [1, 0]), (null, a, false, GT, yes, NaN, [0, 1])," + " (null, a, false, GT, no, Infinity, [1, 0]), (null, a, false, GT, no, Infinity, [0, 1])," + " (null, a, false, GT, no, NaN, [1, 0]), (null, a, false, GT, no, NaN, [0, 1])," + " (null, a, true, EQ, yes, Infinity, [1, 0]), (null, a, true, EQ, yes, Infinity, [0, 1])," + " (null, a, true, EQ, yes, NaN, [1, 0]), (null, a, true, EQ, yes, NaN, [0, 1])," + " (null, a, true, EQ, no, Infinity, [1, 0]), (null, a, true, EQ, no, Infinity, [0, 1])," + " (null, a, true, EQ, no, NaN, [1, 0]), (null, a, true, EQ, no, NaN, [0, 1])," + " (null, a, true, LT, yes, Infinity, [1, 0]), (null, a, true, LT, yes, Infinity, [0, 1])," + " (null, a, true, LT, yes, NaN, [1, 0]), (null, a, true, LT, yes, NaN, [0, 1])," + " (null, a, true, LT, no, Infinity, [1, 0]), (null, a, true, LT, no, Infinity, [0, 1])," + " (null, a, true, LT, no, NaN, [1, 0]), (null, a, true, LT, no, NaN, [0, 1])," + " (null, a, true, GT, yes, Infinity, [1, 0]), (null, a, true, GT, yes, Infinity, [0, 1])," + " (null, a, true, GT, yes, NaN, [1, 0]), (null, a, true, GT, yes, NaN, [0, 1])," + " (null, a, true, GT, no, Infinity, [1, 0]), (null, a, true, GT, no, Infinity, [0, 1])," + " (null, a, true, GT, no, NaN, [1, 0]), (null, a, true, GT, no, NaN, [0, 1])," + " (null, b, false, EQ, yes, Infinity, [1, 0]), (null, b, false, EQ, yes, Infinity, [0, 1])," + " (null, b, false, EQ, yes, NaN, [1, 0]), (null, b, false, EQ, yes, NaN, [0, 1])," + " (null, b, false, EQ, no, Infinity, [1, 0]), (null, b, false, EQ, no, Infinity, [0, 1])," + " (null, b, false, EQ, no, NaN, [1, 0]), (null, b, false, EQ, no, NaN, [0, 1])," + " (null, b, false, LT, yes, Infinity, [1, 0]), (null, b, false, LT, yes, Infinity, [0, 1])," + " (null, b, false, LT, yes, NaN, [1, 0]), (null, b, false, LT, yes, NaN, [0, 1])," + " (null, b, false, LT, no, Infinity, [1, 0]), (null, b, false, LT, no, Infinity, [0, 1])," + " (null, b, false, LT, no, NaN, [1, 0]), (null, b, false, LT, no, NaN, [0, 1])," + " (null, b, false, GT, yes, Infinity, [1, 0]), (null, b, false, GT, yes, Infinity, [0, 1])," + " (null, b, false, GT, yes, NaN, [1, 0]), (null, b, false, GT, yes, NaN, [0, 1])," + " (null, b, false, GT, no, Infinity, [1, 0]), (null, b, false, GT, no, Infinity, [0, 1])," + " (null, b, false, GT, no, NaN, [1, 0]), (null, b, false, GT, no, NaN, [0, 1])," + " (null, b, true, EQ, yes, Infinity, [1, 0]), (null, b, true, EQ, yes, Infinity, [0, 1])," + " (null, b, true, EQ, yes, NaN, [1, 0]), (null, b, true, EQ, yes, NaN, [0, 1])," + " (null, b, true, EQ, no, Infinity, [1, 0]), (null, b, true, EQ, no, Infinity, [0, 1])," + " (null, b, true, EQ, no, NaN, [1, 0]), (null, b, true, EQ, no, NaN, [0, 1])," + " (null, b, true, LT, yes, Infinity, [1, 0]), (null, b, true, LT, yes, Infinity, [0, 1])," + " (null, b, true, LT, yes, NaN, [1, 0]), (null, b, true, LT, yes, NaN, [0, 1])," + " (null, b, true, LT, no, Infinity, [1, 0]), (null, b, true, LT, no, Infinity, [0, 1])," + " (null, b, true, LT, no, NaN, [1, 0]), (null, b, true, LT, no, NaN, [0, 1])," + " (null, b, true, GT, yes, Infinity, [1, 0]), (null, b, true, GT, yes, Infinity, [0, 1])," + " (null, b, true, GT, yes, NaN, [1, 0]), (null, b, true, GT, yes, NaN, [0, 1])," + " (null, b, true, GT, no, Infinity, [1, 0]), (null, b, true, GT, no, Infinity, [0, 1])," + " (null, b, true, GT, no, NaN, [1, 0]), (null, b, true, GT, no, NaN, [0, 1])," + " (null, c, false, EQ, yes, Infinity, [1, 0]), (null, c, false, EQ, yes, Infinity, [0, 1])," + " (null, c, false, EQ, yes, NaN, [1, 0]), (null, c, false, EQ, yes, NaN, [0, 1])," + " (null, c, false, EQ, no, Infinity, [1, 0]), (null, c, false, EQ, no, Infinity, [0, 1])," + " (null, c, false, EQ, no, NaN, [1, 0]), (null, c, false, EQ, no, NaN, [0, 1])," + " (null, c, false, LT, yes, Infinity, [1, 0]), (null, c, false, LT, yes, Infinity, [0, 1])," + " (null, c, false, LT, yes, NaN, [1, 0]), (null, c, false, LT, yes, NaN, [0, 1])," + " (null, c, false, LT, no, Infinity, [1, 0]), (null, c, false, LT, no, Infinity, [0, 1])," + " (null, c, false, LT, no, NaN, [1, 0]), (null, c, false, LT, no, NaN, [0, 1])," + " (null, c, false, GT, yes, Infinity, [1, 0]), (null, c, false, GT, yes, Infinity, [0, 1])," + " (null, c, false, GT, yes, NaN, [1, 0]), (null, c, false, GT, yes, NaN, [0, 1])," + " (null, c, false, GT, no, Infinity, [1, 0]), (null, c, false, GT, no, Infinity, [0, 1])," + " (null, c, false, GT, no, NaN, [1, 0]), (null, c, false, GT, no, NaN, [0, 1])," + " (null, c, true, EQ, yes, Infinity, [1, 0]), (null, c, true, EQ, yes, Infinity, [0, 1])," + " (null, c, true, EQ, yes, NaN, [1, 0]), (null, c, true, EQ, yes, NaN, [0, 1])," + " (null, c, true, EQ, no, Infinity, [1, 0]), (null, c, true, EQ, no, Infinity, [0, 1])," + " (null, c, true, EQ, no, NaN, [1, 0]), (null, c, true, EQ, no, NaN, [0, 1])," + " (null, c, true, LT, yes, Infinity, [1, 0]), (null, c, true, LT, yes, Infinity, [0, 1])," + " (null, c, true, LT, yes, NaN, [1, 0]), (null, c, true, LT, yes, NaN, [0, 1])," + " (null, c, true, LT, no, Infinity, [1, 0]), (null, c, true, LT, no, Infinity, [0, 1])," + " (null, c, true, LT, no, NaN, [1, 0]), (null, c, true, LT, no, NaN, [0, 1])," + " (null, c, true, GT, yes, Infinity, [1, 0]), (null, c, true, GT, yes, Infinity, [0, 1])," + " (null, c, true, GT, yes, NaN, [1, 0]), (null, c, true, GT, yes, NaN, [0, 1])," + " (null, c, true, GT, no, Infinity, [1, 0]), (null, c, true, GT, no, Infinity, [0, 1])," + " (null, c, true, GT, no, NaN, [1, 0]), (null, c, true, GT, no, NaN, [0, 1])," + " (3, a, false, EQ, yes, Infinity, [1, 0]), (3, a, false, EQ, yes, Infinity, [0, 1])," + " (3, a, false, EQ, yes, NaN, [1, 0]), (3, a, false, EQ, yes, NaN, [0, 1])," + " (3, a, false, EQ, no, Infinity, [1, 0]), (3, a, false, EQ, no, Infinity, [0, 1])," + " (3, a, false, EQ, no, NaN, [1, 0]), (3, a, false, EQ, no, NaN, [0, 1])," + " (3, a, false, LT, yes, Infinity, [1, 0]), (3, a, false, LT, yes, Infinity, [0, 1])," + " (3, a, false, LT, yes, NaN, [1, 0]), (3, a, false, LT, yes, NaN, [0, 1])," + " (3, a, false, LT, no, Infinity, [1, 0]), (3, a, false, LT, no, Infinity, [0, 1])," + " (3, a, false, LT, no, NaN, [1, 0]), (3, a, false, LT, no, NaN, [0, 1])," + " (3, a, false, GT, yes, Infinity, [1, 0]), (3, a, false, GT, yes, Infinity, [0, 1])," + " (3, a, false, GT, yes, NaN, [1, 0]), (3, a, false, GT, yes, NaN, [0, 1])," + " (3, a, false, GT, no, Infinity, [1, 0]), (3, a, false, GT, no, Infinity, [0, 1])," + " (3, a, false, GT, no, NaN, [1, 0]), (3, a, false, GT, no, NaN, [0, 1])," + " (3, a, true, EQ, yes, Infinity, [1, 0]), (3, a, true, EQ, yes, Infinity, [0, 1])," + " (3, a, true, EQ, yes, NaN, [1, 0]), (3, a, true, EQ, yes, NaN, [0, 1])," + " (3, a, true, EQ, no, Infinity, [1, 0]), (3, a, true, EQ, no, Infinity, [0, 1])," + " (3, a, true, EQ, no, NaN, [1, 0]), (3, a, true, EQ, no, NaN, [0, 1])," + " (3, a, true, LT, yes, Infinity, [1, 0]), (3, a, true, LT, yes, Infinity, [0, 1])," + " (3, a, true, LT, yes, NaN, [1, 0]), (3, a, true, LT, yes, NaN, [0, 1])," + " (3, a, true, LT, no, Infinity, [1, 0]), (3, a, true, LT, no, Infinity, [0, 1])," + " (3, a, true, LT, no, NaN, [1, 0]), (3, a, true, LT, no, NaN, [0, 1])," + " (3, a, true, GT, yes, Infinity, [1, 0]), (3, a, true, GT, yes, Infinity, [0, 1])," + " (3, a, true, GT, yes, NaN, [1, 0]), (3, a, true, GT, yes, NaN, [0, 1])," + " (3, a, true, GT, no, Infinity, [1, 0]), (3, a, true, GT, no, Infinity, [0, 1])," + " (3, a, true, GT, no, NaN, [1, 0]), (3, a, true, GT, no, NaN, [0, 1])," + " (3, b, false, EQ, yes, Infinity, [1, 0]), (3, b, false, EQ, yes, Infinity, [0, 1])," + " (3, b, false, EQ, yes, NaN, [1, 0]), (3, b, false, EQ, yes, NaN, [0, 1])," + " (3, b, false, EQ, no, Infinity, [1, 0]), (3, b, false, EQ, no, Infinity, [0, 1])," + " (3, b, false, EQ, no, NaN, [1, 0]), (3, b, false, EQ, no, NaN, [0, 1])," + " (3, b, false, LT, yes, Infinity, [1, 0]), (3, b, false, LT, yes, Infinity, [0, 1])," + " (3, b, false, LT, yes, NaN, [1, 0]), (3, b, false, LT, yes, NaN, [0, 1])," + " (3, b, false, LT, no, Infinity, [1, 0]), (3, b, false, LT, no, Infinity, [0, 1])," + " (3, b, false, LT, no, NaN, [1, 0]), (3, b, false, LT, no, NaN, [0, 1])," + " (3, b, false, GT, yes, Infinity, [1, 0]), (3, b, false, GT, yes, Infinity, [0, 1])," + " (3, b, false, GT, yes, NaN, [1, 0]), (3, b, false, GT, yes, NaN, [0, 1])," + " (3, b, false, GT, no, Infinity, [1, 0]), (3, b, false, GT, no, Infinity, [0, 1])," + " (3, b, false, GT, no, NaN, [1, 0]), (3, b, false, GT, no, NaN, [0, 1])," + " (3, b, true, EQ, yes, Infinity, [1, 0]), (3, b, true, EQ, yes, Infinity, [0, 1])," + " (3, b, true, EQ, yes, NaN, [1, 0]), (3, b, true, EQ, yes, NaN, [0, 1])," + " (3, b, true, EQ, no, Infinity, [1, 0]), (3, b, true, EQ, no, Infinity, [0, 1])," + " (3, b, true, EQ, no, NaN, [1, 0]), (3, b, true, EQ, no, NaN, [0, 1])," + " (3, b, true, LT, yes, Infinity, [1, 0]), (3, b, true, LT, yes, Infinity, [0, 1])," + " (3, b, true, LT, yes, NaN, [1, 0]), (3, b, true, LT, yes, NaN, [0, 1])," + " (3, b, true, LT, no, Infinity, [1, 0]), (3, b, true, LT, no, Infinity, [0, 1])," + " (3, b, true, LT, no, NaN, [1, 0]), (3, b, true, LT, no, NaN, [0, 1])," + " (3, b, true, GT, yes, Infinity, [1, 0]), (3, b, true, GT, yes, Infinity, [0, 1])," + " (3, b, true, GT, yes, NaN, [1, 0]), (3, b, true, GT, yes, NaN, [0, 1])," + " (3, b, true, GT, no, Infinity, [1, 0]), (3, b, true, GT, no, Infinity, [0, 1])," + " (3, b, true, GT, no, NaN, [1, 0]), (3, b, true, GT, no, NaN, [0, 1])," + " (3, c, false, EQ, yes, Infinity, [1, 0]), (3, c, false, EQ, yes, Infinity, [0, 1])," + " (3, c, false, EQ, yes, NaN, [1, 0]), (3, c, false, EQ, yes, NaN, [0, 1])," + " (3, c, false, EQ, no, Infinity, [1, 0]), (3, c, false, EQ, no, Infinity, [0, 1])," + " (3, c, false, EQ, no, NaN, [1, 0]), (3, c, false, EQ, no, NaN, [0, 1])," + " (3, c, false, LT, yes, Infinity, [1, 0]), (3, c, false, LT, yes, Infinity, [0, 1])," + " (3, c, false, LT, yes, NaN, [1, 0]), (3, c, false, LT, yes, NaN, [0, 1])," + " (3, c, false, LT, no, Infinity, [1, 0]), (3, c, false, LT, no, Infinity, [0, 1])," + " (3, c, false, LT, no, NaN, [1, 0]), (3, c, false, LT, no, NaN, [0, 1])," + " (3, c, false, GT, yes, Infinity, [1, 0]), (3, c, false, GT, yes, Infinity, [0, 1])," + " (3, c, false, GT, yes, NaN, [1, 0]), (3, c, false, GT, yes, NaN, [0, 1])," + " (3, c, false, GT, no, Infinity, [1, 0]), (3, c, false, GT, no, Infinity, [0, 1])," + " (3, c, false, GT, no, NaN, [1, 0]), (3, c, false, GT, no, NaN, [0, 1])," + " (3, c, true, EQ, yes, Infinity, [1, 0]), (3, c, true, EQ, yes, Infinity, [0, 1])," + " (3, c, true, EQ, yes, NaN, [1, 0]), (3, c, true, EQ, yes, NaN, [0, 1])," + " (3, c, true, EQ, no, Infinity, [1, 0]), (3, c, true, EQ, no, Infinity, [0, 1])," + " (3, c, true, EQ, no, NaN, [1, 0]), (3, c, true, EQ, no, NaN, [0, 1])," + " (3, c, true, LT, yes, Infinity, [1, 0]), (3, c, true, LT, yes, Infinity, [0, 1])," + " (3, c, true, LT, yes, NaN, [1, 0]), (3, c, true, LT, yes, NaN, [0, 1])," + " (3, c, true, LT, no, Infinity, [1, 0]), (3, c, true, LT, no, Infinity, [0, 1])," + " (3, c, true, LT, no, NaN, [1, 0]), (3, c, true, LT, no, NaN, [0, 1])," + " (3, c, true, GT, yes, Infinity, [1, 0]), (3, c, true, GT, yes, Infinity, [0, 1])," + " (3, c, true, GT, yes, NaN, [1, 0]), (3, c, true, GT, yes, NaN, [0, 1])," + " (3, c, true, GT, no, Infinity, [1, 0]), (3, c, true, GT, no, Infinity, [0, 1])," + " (3, c, true, GT, no, NaN, [1, 0]), (3, c, true, GT, no, NaN, [0, 1])]"); aeq(take(20, septuplesAscending( P.naturalBigIntegers(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), (Iterable<Float>) Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), (Iterable<List<Integer>>) Arrays.asList(x, y) )), "[(0, a, false, EQ, yes, Infinity, [1, 0]), (0, a, false, EQ, yes, Infinity, [0, 1])," + " (0, a, false, EQ, yes, NaN, [1, 0]), (0, a, false, EQ, yes, NaN, [0, 1])," + " (0, a, false, EQ, no, Infinity, [1, 0]), (0, a, false, EQ, no, Infinity, [0, 1])," + " (0, a, false, EQ, no, NaN, [1, 0]), (0, a, false, EQ, no, NaN, [0, 1])," + " (0, a, false, LT, yes, Infinity, [1, 0]), (0, a, false, LT, yes, Infinity, [0, 1])," + " (0, a, false, LT, yes, NaN, [1, 0]), (0, a, false, LT, yes, NaN, [0, 1])," + " (0, a, false, LT, no, Infinity, [1, 0]), (0, a, false, LT, no, Infinity, [0, 1])," + " (0, a, false, LT, no, NaN, [1, 0]), (0, a, false, LT, no, NaN, [0, 1])," + " (0, a, false, GT, yes, Infinity, [1, 0]), (0, a, false, GT, yes, Infinity, [0, 1])," + " (0, a, false, GT, yes, NaN, [1, 0]), (0, a, false, GT, yes, NaN, [0, 1])]"); aeq(septuplesAscending( new ArrayList<Integer>(), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), (Iterable<List<Integer>>) Arrays.asList(x, y) ), "[]"); aeq(septuplesAscending( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>(), new ArrayList<Float>(), new ArrayList<List<Integer>>() ), "[]"); } @Test public void testListsAscending_int_Iterable() { aeq(listsAscending(0, Arrays.asList(1, 2, 3)), "[[]]"); aeq(listsAscending(1, Arrays.asList(1, 2, 3)), "[[1], [2], [3]]"); aeq(listsAscending(2, Arrays.asList(1, 2, 3)), "[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]"); aeq(listsAscending(3, Arrays.asList(1, 2, 3)), "[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2]," + " [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1]," + " [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3]," + " [3, 3, 1], [3, 3, 2], [3, 3, 3]]"); aeq(listsAscending(0, Arrays.asList(1, null, 3)), "[[]]"); aeq(listsAscending(1, Arrays.asList(1, null, 3)), "[[1], [null], [3]]"); aeq(listsAscending(2, Arrays.asList(1, null, 3)), "[[1, 1], [1, null], [1, 3], [null, 1], [null, null], [null, 3], [3, 1], [3, null], [3, 3]]"); aeq(listsAscending(3, Arrays.asList(1, null, 3)), "[[1, 1, 1], [1, 1, null], [1, 1, 3], [1, null, 1], [1, null, null], [1, null, 3], [1, 3, 1]," + " [1, 3, null], [1, 3, 3], [null, 1, 1], [null, 1, null], [null, 1, 3], [null, null, 1]," + " [null, null, null], [null, null, 3], [null, 3, 1], [null, 3, null], [null, 3, 3], [3, 1, 1]," + " [3, 1, null], [3, 1, 3], [3, null, 1], [3, null, null], [3, null, 3], [3, 3, 1], [3, 3, null]," + " [3, 3, 3]]"); aeq(listsAscending(0, new ArrayList<Integer>()), "[[]]"); aeq(listsAscending(1, new ArrayList<Integer>()), "[]"); aeq(listsAscending(2, new ArrayList<Integer>()), "[]"); aeq(listsAscending(3, new ArrayList<Integer>()), "[]"); try { listsAscending(-1, Arrays.asList(1, 2, 3)); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testListsAscending_BigInteger_Iterable() { aeq(listsAscending(BigInteger.ZERO, Arrays.asList(1, 2, 3)), "[[]]"); aeq(listsAscending(BigInteger.ONE, Arrays.asList(1, 2, 3)), "[[1], [2], [3]]"); aeq(listsAscending(BigInteger.valueOf(2), Arrays.asList(1, 2, 3)), "[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]"); aeq(listsAscending(BigInteger.valueOf(3), Arrays.asList(1, 2, 3)), "[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2]," + " [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1]," + " [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3]," + " [3, 3, 1], [3, 3, 2], [3, 3, 3]]"); aeq(listsAscending(0, Arrays.asList(1, null, 3)), "[[]]"); aeq(listsAscending(1, Arrays.asList(1, null, 3)), "[[1], [null], [3]]"); aeq(listsAscending(2, Arrays.asList(1, null, 3)), "[[1, 1], [1, null], [1, 3], [null, 1], [null, null], [null, 3], [3, 1], [3, null], [3, 3]]"); aeq(listsAscending(3, Arrays.asList(1, null, 3)), "[[1, 1, 1], [1, 1, null], [1, 1, 3], [1, null, 1], [1, null, null], [1, null, 3], [1, 3, 1]," + " [1, 3, null], [1, 3, 3], [null, 1, 1], [null, 1, null], [null, 1, 3], [null, null, 1]," + " [null, null, null], [null, null, 3], [null, 3, 1], [null, 3, null], [null, 3, 3], [3, 1, 1]," + " [3, 1, null], [3, 1, 3], [3, null, 1], [3, null, null], [3, null, 3], [3, 3, 1], [3, 3, null]," + " [3, 3, 3]]"); aeq(listsAscending(BigInteger.ZERO, new ArrayList<Integer>()), "[[]]"); aeq(listsAscending(BigInteger.ONE, new ArrayList<Integer>()), "[]"); aeq(listsAscending(BigInteger.valueOf(2), new ArrayList<Integer>()), "[]"); aeq(listsAscending(BigInteger.valueOf(3), new ArrayList<Integer>()), "[]"); try { listsAscending(BigInteger.valueOf(-1), Arrays.asList(1, 2, 3)); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testListsAscending_int_String() { aeq(stringsAscending(0, "abc"), "[]"); aeq(length(stringsAscending(0, "abc")), 1); aeq(stringsAscending(1, "abc"), "[a, b, c]"); aeq(stringsAscending(2, "abc"), "[aa, ab, ac, ba, bb, bc, ca, cb, cc]"); aeq(stringsAscending(3, "abc"), "[aaa, aab, aac, aba, abb, abc, aca, acb, acc, baa, bab, bac, bba," + " bbb, bbc, bca, bcb, bcc, caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc]"); aeq(stringsAscending(0, "a"), "[]"); aeq(stringsAscending(1, "a"), "[a]"); aeq(stringsAscending(2, "a"), "[aa]"); aeq(stringsAscending(3, "a"), "[aaa]"); aeq(stringsAscending(0, ""), "[]"); aeq(length(stringsAscending(0, "")), 1); aeq(stringsAscending(1, ""), "[]"); aeq(length(stringsAscending(1, "")), 0); aeq(stringsAscending(2, ""), "[]"); aeq(length(stringsAscending(2, "")), 0); aeq(stringsAscending(3, ""), "[]"); aeq(length(stringsAscending(3, "")), 0); try { stringsAscending(-1, ""); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testListsAscending_BigInteger_String() { aeq(stringsAscending(BigInteger.ZERO, "abc"), "[]"); aeq(length(stringsAscending(BigInteger.ZERO, "abc")), 1); aeq(length(stringsAscending(0, "abc")), 1); aeq(stringsAscending(BigInteger.ONE, "abc"), "[a, b, c]"); aeq(stringsAscending(BigInteger.valueOf(2), "abc"), "[aa, ab, ac, ba, bb, bc, ca, cb, cc]"); aeq(stringsAscending(BigInteger.valueOf(3), "abc"), "[aaa, aab, aac, aba, abb, abc, aca, acb, acc, baa, bab, bac, bba," + " bbb, bbc, bca, bcb, bcc, caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc]"); aeq(stringsAscending(BigInteger.ZERO, "a"), "[]"); aeq(stringsAscending(BigInteger.ONE, "a"), "[a]"); aeq(stringsAscending(BigInteger.valueOf(2), "a"), "[aa]"); aeq(stringsAscending(BigInteger.valueOf(3), "a"), "[aaa]"); aeq(stringsAscending(BigInteger.ZERO, ""), "[]"); aeq(length(stringsAscending(BigInteger.ZERO, "")), 1); aeq(stringsAscending(BigInteger.ONE, ""), "[]"); aeq(length(stringsAscending(BigInteger.ONE, "")), 0); aeq(stringsAscending(BigInteger.valueOf(2), ""), "[]"); aeq(length(stringsAscending(BigInteger.valueOf(2), "")), 0); aeq(stringsAscending(BigInteger.valueOf(3), ""), "[]"); aeq(length(stringsAscending(BigInteger.valueOf(3), "")), 0); try { stringsAscending(BigInteger.valueOf(-1), ""); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testListsShortlex() { aeq(take(20, listsShortlex(Arrays.asList(1, 2, 3))), "[[], [1], [2], [3], [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2]," + " [3, 3], [1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1]]"); aeq(listsShortlex(new ArrayList<Integer>()), "[[]]"); } @Test public void testStringsShortlex() { aeq(take(20, stringsShortlex("abc")), "[, a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc, aaa, aab, aac, aba, abb, abc, aca]"); aeq(stringsShortlex(""), "[]"); aeq(length(stringsShortlex("")), 1); } @Test public void testPairsLogarithmicOrder_Iterable() { aeq(pairsLogarithmicOrder(Arrays.asList(1, 2, 3, 4)), "[(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (2, 2), (4, 1), (1, 4)," + " (3, 2), (2, 3), (4, 2), (3, 3), (2, 4), (4, 3), (3, 4), (4, 4)]"); aeq(pairsLogarithmicOrder(Arrays.asList(1, 2, null, 4)), "[(1, 1), (1, 2), (2, 1), (1, null), (null, 1), (2, 2), (4, 1), (1, 4)," + " (null, 2), (2, null), (4, 2), (null, null), (2, 4), (4, null), (null, 4), (4, 4)]"); aeq(pairsLogarithmicOrder(new ArrayList<Integer>()), "[]"); aeq(take(20, pairsLogarithmicOrder(P.naturalBigIntegers())), "[(0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (1, 1), (3, 0), (0, 3), (4, 0), (2, 1)," + " (5, 0), (1, 2), (6, 0), (3, 1), (7, 0), (0, 4), (8, 0), (4, 1), (9, 0), (2, 2)]"); aeq(take(20, pairsLogarithmicOrder((Iterable<BigInteger>) cons(null, P.naturalBigIntegers()))), "[(null, null), (null, 0), (0, null), (null, 1), (1, null), (0, 0), (2, null), (null, 2), (3, null)," + " (1, 0), (4, null), (0, 1), (5, null), (2, 0), (6, null), (null, 3), (7, null), (3, 0), (8, null)," + " (1, 1)]"); } @Test public void testPairsLogarithmicOrder_Iterable_Iterable() { aeq(pairsLogarithmicOrder(Arrays.asList(1, 2, 3, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (1, c), (3, a), (2, b), (4, a), (1, d)," + " (3, b), (2, c), (4, b), (3, c), (2, d), (4, c), (3, d), (4, d)]"); aeq(pairsLogarithmicOrder(Arrays.asList(1, 2, null, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (1, c), (null, a), (2, b), (4, a), (1, d)," + " (null, b), (2, c), (4, b), (null, c), (2, d), (4, c), (null, d), (4, d)]"); aeq(pairsLogarithmicOrder(new ArrayList<Integer>(), fromString("abcd")), "[]"); aeq(pairsLogarithmicOrder(new ArrayList<Integer>(), new ArrayList<Character>()), "[]"); aeq(take(20, pairsLogarithmicOrder(P.naturalBigIntegers(), fromString("abcd"))), "[(0, a), (0, b), (1, a), (0, c), (2, a), (1, b), (3, a), (0, d), (4, a), (2, b)," + " (5, a), (1, c), (6, a), (3, b), (7, a), (8, a), (4, b), (9, a), (2, c), (10, a)]"); aeq(take(20, pairsLogarithmicOrder(fromString("abcd"), P.naturalBigIntegers())), "[(a, 0), (a, 1), (b, 0), (a, 2), (c, 0), (b, 1), (d, 0), (a, 3), (c, 1), (b, 2)," + " (d, 1), (a, 4), (c, 2), (b, 3), (d, 2), (a, 5), (c, 3), (b, 4), (d, 3), (a, 6)]"); aeq(take(20, pairsLogarithmicOrder(P.positiveBigIntegers(), P.negativeBigIntegers())), "[(1, -1), (1, -2), (2, -1), (1, -3), (3, -1), (2, -2), (4, -1), (1, -4), (5, -1), (3, -2)," + " (6, -1), (2, -3), (7, -1), (4, -2), (8, -1), (1, -5), (9, -1), (5, -2), (10, -1), (3, -3)]"); } @Test public void testPairsSquareRootOrder_Iterable() { aeq(pairsSquareRootOrder(Arrays.asList(1, 2, 3, 4)), "[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2), (4, 1), (4, 2)," + " (1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4), (4, 3), (4, 4)]"); aeq(pairsSquareRootOrder(Arrays.asList(1, 2, null, 4)), "[(1, 1), (1, 2), (2, 1), (2, 2), (null, 1), (null, 2), (4, 1), (4, 2)," + " (1, null), (1, 4), (2, null), (2, 4), (null, null), (null, 4), (4, null), (4, 4)]"); aeq(pairsSquareRootOrder(new ArrayList<Integer>()), "[]"); aeq(take(20, pairsSquareRootOrder(P.naturalBigIntegers())), "[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1), (0, 2), (0, 3)," + " (1, 2), (1, 3), (2, 2), (2, 3), (3, 2), (3, 3), (4, 0), (4, 1), (5, 0), (5, 1)]"); aeq(take(20, pairsSquareRootOrder((Iterable<BigInteger>) cons(null, P.naturalBigIntegers()))), "[(null, null), (null, 0), (0, null), (0, 0), (1, null), (1, 0), (2, null), (2, 0), (null, 1)," + " (null, 2), (0, 1), (0, 2), (1, 1), (1, 2), (2, 1), (2, 2), (3, null), (3, 0), (4, null), (4, 0)]"); } @Test public void testPairsSquareRootOrder_Iterable_Iterable() { aeq(pairsSquareRootOrder(Arrays.asList(1, 2, 3, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (2, b), (3, a), (3, b), (4, a), (4, b)," + " (1, c), (1, d), (2, c), (2, d), (3, c), (3, d), (4, c), (4, d)]"); aeq(pairsSquareRootOrder(Arrays.asList(1, 2, null, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (2, b), (null, a), (null, b), (4, a), (4, b)," + " (1, c), (1, d), (2, c), (2, d), (null, c), (null, d), (4, c), (4, d)]"); aeq(pairsSquareRootOrder(new ArrayList<Integer>(), fromString("abcd")), "[]"); aeq(pairsSquareRootOrder(new ArrayList<Integer>(), new ArrayList<Character>()), "[]"); aeq(take(20, pairsSquareRootOrder(P.naturalBigIntegers(), fromString("abcd"))), "[(0, a), (0, b), (1, a), (1, b), (2, a), (2, b), (3, a), (3, b), (0, c), (0, d)," + " (1, c), (1, d), (2, c), (2, d), (3, c), (3, d), (4, a), (4, b), (5, a), (5, b)]"); aeq(take(20, pairsSquareRootOrder(fromString("abcd"), P.naturalBigIntegers())), "[(a, 0), (a, 1), (b, 0), (b, 1), (c, 0), (c, 1), (d, 0), (d, 1), (a, 2), (a, 3)," + " (b, 2), (b, 3), (c, 2), (c, 3), (d, 2), (d, 3), (a, 4), (a, 5), (b, 4), (b, 5)]"); aeq(take(20, pairsSquareRootOrder(P.positiveBigIntegers(), P.negativeBigIntegers())), "[(1, -1), (1, -2), (2, -1), (2, -2), (3, -1), (3, -2), (4, -1), (4, -2), (1, -3), (1, -4)," + " (2, -3), (2, -4), (3, -3), (3, -4), (4, -3), (4, -4), (5, -1), (5, -2), (6, -1), (6, -2)]"); } @Test public void testPairs() { aeq(pairs(Arrays.asList(1, 2, 3, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (2, b), (1, c), (1, d), (2, c), (2, d)," + " (3, a), (3, b), (4, a), (4, b), (3, c), (3, d), (4, c), (4, d)]"); aeq(pairs(Arrays.asList(1, 2, null, 4), fromString("abcd")), "[(1, a), (1, b), (2, a), (2, b), (1, c), (1, d), (2, c), (2, d)," + " (null, a), (null, b), (4, a), (4, b), (null, c), (null, d), (4, c), (4, d)]"); aeq(pairs(new ArrayList<Integer>(), fromString("abcd")), "[]"); aeq(pairs(new ArrayList<Integer>(), new ArrayList<Character>()), "[]"); aeq(take(20, pairs(P.naturalBigIntegers(), fromString("abcd"))), "[(0, a), (0, b), (1, a), (1, b), (0, c), (0, d), (1, c), (1, d), (2, a), (2, b)," + " (3, a), (3, b), (2, c), (2, d), (3, c), (3, d), (4, a), (4, b), (5, a), (5, b)]"); aeq(take(20, pairs(fromString("abcd"), P.naturalBigIntegers())), "[(a, 0), (a, 1), (b, 0), (b, 1), (a, 2), (a, 3), (b, 2), (b, 3), (c, 0), (c, 1)," + " (d, 0), (d, 1), (c, 2), (c, 3), (d, 2), (d, 3), (a, 4), (a, 5), (b, 4), (b, 5)]"); aeq(take(20, pairs(P.positiveBigIntegers(), P.negativeBigIntegers())), "[(1, -1), (1, -2), (2, -1), (2, -2), (1, -3), (1, -4), (2, -3), (2, -4), (3, -1), (3, -2)," + " (4, -1), (4, -2), (3, -3), (3, -4), (4, -3), (4, -4), (1, -5), (1, -6), (2, -5), (2, -6)]"); } @Test public void testTriples() { aeq(triples(Arrays.asList(1, 2, 3), fromString("abc"), P.booleans()), "[(1, a, false), (1, a, true), (1, b, false), (1, b, true), (2, a, false), (2, a, true)," + " (2, b, false), (2, b, true), (1, c, false), (1, c, true), (2, c, false), (2, c, true)," + " (3, a, false), (3, a, true), (3, b, false), (3, b, true), (3, c, false), (3, c, true)]"); aeq(triples(Arrays.asList(1, 2, null, 4), fromString("abcd"), P.booleans()), "[(1, a, false), (1, a, true), (1, b, false), (1, b, true), (2, a, false), (2, a, true)," + " (2, b, false), (2, b, true), (1, c, false), (1, c, true), (1, d, false), (1, d, true)," + " (2, c, false), (2, c, true), (2, d, false), (2, d, true), (null, a, false), (null, a, true)," + " (null, b, false), (null, b, true), (4, a, false), (4, a, true), (4, b, false), (4, b, true)," + " (null, c, false), (null, c, true), (null, d, false), (null, d, true), (4, c, false)," + " (4, c, true), (4, d, false), (4, d, true)]"); aeq(triples(new ArrayList<Integer>(), fromString("abcd"), P.booleans()), "[]"); aeq(triples(new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>()), "[]"); aeq(take(20, triples(P.naturalBigIntegers(), fromString("abcd"), P.booleans())), "[(0, a, false), (0, a, true), (0, b, false), (0, b, true), (1, a, false), (1, a, true)," + " (1, b, false), (1, b, true), (0, c, false), (0, c, true), (0, d, false), (0, d, true)," + " (1, c, false), (1, c, true), (1, d, false), (1, d, true), (2, a, false), (2, a, true)," + " (2, b, false), (2, b, true)]"); aeq(take(20, triples(fromString("abcd"), P.booleans(), P.naturalBigIntegers())), "[(a, false, 0), (a, false, 1), (a, true, 0), (a, true, 1), (b, false, 0), (b, false, 1)," + " (b, true, 0), (b, true, 1), (a, false, 2), (a, false, 3), (a, true, 2), (a, true, 3)," + " (b, false, 2), (b, false, 3), (b, true, 2), (b, true, 3), (c, false, 0), (c, false, 1)," + " (c, true, 0), (c, true, 1)]"); aeq(take(20, triples(P.positiveBigIntegers(), P.negativeBigIntegers(), P.characters())), "[(1, -1, a), (1, -1, b), (1, -2, a), (1, -2, b), (2, -1, a), (2, -1, b), (2, -2, a), (2, -2, b)," + " (1, -1, c), (1, -1, d), (1, -2, c), (1, -2, d), (2, -1, c), (2, -1, d), (2, -2, c), (2, -2, d)," + " (1, -3, a), (1, -3, b), (1, -4, a), (1, -4, b)]"); } @Test public void testQuadruples() { aeq(quadruples(Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings()), "[(1, a, false, EQ), (1, a, false, LT), (1, a, true, EQ), (1, a, true, LT), (1, b, false, EQ)," + " (1, b, false, LT), (1, b, true, EQ), (1, b, true, LT), (2, a, false, EQ), (2, a, false, LT)," + " (2, a, true, EQ), (2, a, true, LT), (2, b, false, EQ), (2, b, false, LT), (2, b, true, EQ)," + " (2, b, true, LT), (1, a, false, GT), (1, a, true, GT), (1, b, false, GT), (1, b, true, GT)," + " (2, a, false, GT), (2, a, true, GT), (2, b, false, GT), (2, b, true, GT), (1, c, false, EQ)," + " (1, c, false, LT), (1, c, true, EQ), (1, c, true, LT), (2, c, false, EQ), (2, c, false, LT)," + " (2, c, true, EQ), (2, c, true, LT), (1, c, false, GT), (1, c, true, GT), (2, c, false, GT)," + " (2, c, true, GT), (3, a, false, EQ), (3, a, false, LT), (3, a, true, EQ), (3, a, true, LT)," + " (3, b, false, EQ), (3, b, false, LT), (3, b, true, EQ), (3, b, true, LT), (3, a, false, GT)," + " (3, a, true, GT), (3, b, false, GT), (3, b, true, GT), (3, c, false, EQ), (3, c, false, LT)," + " (3, c, true, EQ), (3, c, true, LT), (3, c, false, GT), (3, c, true, GT)]"); aeq(quadruples(Arrays.asList(1, 2, null, 4), fromString("abcd"), P.booleans(), P.orderings()), "[(1, a, false, EQ), (1, a, false, LT), (1, a, true, EQ), (1, a, true, LT), (1, b, false, EQ)," + " (1, b, false, LT), (1, b, true, EQ), (1, b, true, LT), (2, a, false, EQ), (2, a, false, LT)," + " (2, a, true, EQ), (2, a, true, LT), (2, b, false, EQ), (2, b, false, LT), (2, b, true, EQ)," + " (2, b, true, LT), (1, a, false, GT), (1, a, true, GT), (1, b, false, GT), (1, b, true, GT)," + " (2, a, false, GT), (2, a, true, GT), (2, b, false, GT), (2, b, true, GT), (1, c, false, EQ)," + " (1, c, false, LT), (1, c, true, EQ), (1, c, true, LT), (1, d, false, EQ), (1, d, false, LT)," + " (1, d, true, EQ), (1, d, true, LT), (2, c, false, EQ), (2, c, false, LT), (2, c, true, EQ)," + " (2, c, true, LT), (2, d, false, EQ), (2, d, false, LT), (2, d, true, EQ), (2, d, true, LT)," + " (1, c, false, GT), (1, c, true, GT), (1, d, false, GT), (1, d, true, GT), (2, c, false, GT)," + " (2, c, true, GT), (2, d, false, GT), (2, d, true, GT), (null, a, false, EQ), (null, a, false, LT)," + " (null, a, true, EQ), (null, a, true, LT), (null, b, false, EQ), (null, b, false, LT)," + " (null, b, true, EQ), (null, b, true, LT), (4, a, false, EQ), (4, a, false, LT), (4, a, true, EQ)," + " (4, a, true, LT), (4, b, false, EQ), (4, b, false, LT), (4, b, true, EQ), (4, b, true, LT)," + " (null, a, false, GT), (null, a, true, GT), (null, b, false, GT), (null, b, true, GT)," + " (4, a, false, GT), (4, a, true, GT), (4, b, false, GT), (4, b, true, GT), (null, c, false, EQ)," + " (null, c, false, LT), (null, c, true, EQ), (null, c, true, LT), (null, d, false, EQ)," + " (null, d, false, LT), (null, d, true, EQ), (null, d, true, LT), (4, c, false, EQ)," + " (4, c, false, LT), (4, c, true, EQ), (4, c, true, LT), (4, d, false, EQ), (4, d, false, LT)," + " (4, d, true, EQ), (4, d, true, LT), (null, c, false, GT), (null, c, true, GT)," + " (null, d, false, GT), (null, d, true, GT), (4, c, false, GT), (4, c, true, GT), (4, d, false, GT)," + " (4, d, true, GT)]"); aeq(quadruples(new ArrayList<Integer>(), fromString("abcd"), P.booleans(), P.orderings()), "[]"); aeq(quadruples( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>() ), "[]"); aeq(take(20, quadruples(P.naturalBigIntegers(), fromString("abcd"), P.booleans(), P.orderings())), "[(0, a, false, EQ), (0, a, false, LT), (0, a, true, EQ), (0, a, true, LT), (0, b, false, EQ)," + " (0, b, false, LT), (0, b, true, EQ), (0, b, true, LT), (1, a, false, EQ), (1, a, false, LT)," + " (1, a, true, EQ), (1, a, true, LT), (1, b, false, EQ), (1, b, false, LT), (1, b, true, EQ)," + " (1, b, true, LT), (0, a, false, GT), (0, a, true, GT), (0, b, false, GT), (0, b, true, GT)]"); aeq(take(20, quadruples(fromString("abcd"), P.booleans(), P.naturalBigIntegers(), P.orderings())), "[(a, false, 0, EQ), (a, false, 0, LT), (a, false, 1, EQ), (a, false, 1, LT), (a, true, 0, EQ)," + " (a, true, 0, LT), (a, true, 1, EQ), (a, true, 1, LT), (b, false, 0, EQ), (b, false, 0, LT)," + " (b, false, 1, EQ), (b, false, 1, LT), (b, true, 0, EQ), (b, true, 0, LT), (b, true, 1, EQ)," + " (b, true, 1, LT), (a, false, 0, GT), (a, false, 1, GT), (a, true, 0, GT), (a, true, 1, GT)]"); aeq(take(20, quadruples(P.positiveBigIntegers(), P.negativeBigIntegers(), P.characters(), P.strings())), "[(1, -1, a, ), (1, -1, a, a), (1, -1, b, ), (1, -1, b, a), (1, -2, a, ), (1, -2, a, a)," + " (1, -2, b, ), (1, -2, b, a), (2, -1, a, ), (2, -1, a, a), (2, -1, b, ), (2, -1, b, a)," + " (2, -2, a, ), (2, -2, a, a), (2, -2, b, ), (2, -2, b, a), (1, -1, a, aa), (1, -1, a, b)," + " (1, -1, b, aa), (1, -1, b, b)]"); } @Test public void testQuintuples() { aeq(quintuples( Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[(1, a, false, EQ, yes), (1, a, false, EQ, no), (1, a, false, LT, yes), (1, a, false, LT, no)," + " (1, a, true, EQ, yes), (1, a, true, EQ, no), (1, a, true, LT, yes), (1, a, true, LT, no)," + " (1, b, false, EQ, yes), (1, b, false, EQ, no), (1, b, false, LT, yes), (1, b, false, LT, no)," + " (1, b, true, EQ, yes), (1, b, true, EQ, no), (1, b, true, LT, yes), (1, b, true, LT, no)," + " (2, a, false, EQ, yes), (2, a, false, EQ, no), (2, a, false, LT, yes), (2, a, false, LT, no)," + " (2, a, true, EQ, yes), (2, a, true, EQ, no), (2, a, true, LT, yes), (2, a, true, LT, no)," + " (2, b, false, EQ, yes), (2, b, false, EQ, no), (2, b, false, LT, yes), (2, b, false, LT, no)," + " (2, b, true, EQ, yes), (2, b, true, EQ, no), (2, b, true, LT, yes), (2, b, true, LT, no)," + " (1, a, false, GT, yes), (1, a, false, GT, no), (1, a, true, GT, yes), (1, a, true, GT, no)," + " (1, b, false, GT, yes), (1, b, false, GT, no), (1, b, true, GT, yes), (1, b, true, GT, no)," + " (2, a, false, GT, yes), (2, a, false, GT, no), (2, a, true, GT, yes), (2, a, true, GT, no)," + " (2, b, false, GT, yes), (2, b, false, GT, no), (2, b, true, GT, yes), (2, b, true, GT, no)," + " (1, c, false, EQ, yes), (1, c, false, EQ, no), (1, c, false, LT, yes), (1, c, false, LT, no)," + " (1, c, true, EQ, yes), (1, c, true, EQ, no), (1, c, true, LT, yes), (1, c, true, LT, no)," + " (2, c, false, EQ, yes), (2, c, false, EQ, no), (2, c, false, LT, yes), (2, c, false, LT, no)," + " (2, c, true, EQ, yes), (2, c, true, EQ, no), (2, c, true, LT, yes), (2, c, true, LT, no)," + " (1, c, false, GT, yes), (1, c, false, GT, no), (1, c, true, GT, yes), (1, c, true, GT, no)," + " (2, c, false, GT, yes), (2, c, false, GT, no), (2, c, true, GT, yes), (2, c, true, GT, no)," + " (3, a, false, EQ, yes), (3, a, false, EQ, no), (3, a, false, LT, yes), (3, a, false, LT, no)," + " (3, a, true, EQ, yes), (3, a, true, EQ, no), (3, a, true, LT, yes), (3, a, true, LT, no)," + " (3, b, false, EQ, yes), (3, b, false, EQ, no), (3, b, false, LT, yes), (3, b, false, LT, no)," + " (3, b, true, EQ, yes), (3, b, true, EQ, no), (3, b, true, LT, yes), (3, b, true, LT, no)," + " (3, a, false, GT, yes), (3, a, false, GT, no), (3, a, true, GT, yes), (3, a, true, GT, no)," + " (3, b, false, GT, yes), (3, b, false, GT, no), (3, b, true, GT, yes), (3, b, true, GT, no)," + " (3, c, false, EQ, yes), (3, c, false, EQ, no), (3, c, false, LT, yes), (3, c, false, LT, no)," + " (3, c, true, EQ, yes), (3, c, true, EQ, no), (3, c, true, LT, yes), (3, c, true, LT, no)," + " (3, c, false, GT, yes), (3, c, false, GT, no), (3, c, true, GT, yes), (3, c, true, GT, no)]"); aeq(quintuples( Arrays.asList(1, 2, null, 4), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[(1, a, false, EQ, yes), (1, a, false, EQ, no), (1, a, false, LT, yes), (1, a, false, LT, no)," + " (1, a, true, EQ, yes), (1, a, true, EQ, no), (1, a, true, LT, yes), (1, a, true, LT, no)," + " (1, b, false, EQ, yes), (1, b, false, EQ, no), (1, b, false, LT, yes), (1, b, false, LT, no)," + " (1, b, true, EQ, yes), (1, b, true, EQ, no), (1, b, true, LT, yes), (1, b, true, LT, no)," + " (2, a, false, EQ, yes), (2, a, false, EQ, no), (2, a, false, LT, yes), (2, a, false, LT, no)," + " (2, a, true, EQ, yes), (2, a, true, EQ, no), (2, a, true, LT, yes), (2, a, true, LT, no)," + " (2, b, false, EQ, yes), (2, b, false, EQ, no), (2, b, false, LT, yes), (2, b, false, LT, no)," + " (2, b, true, EQ, yes), (2, b, true, EQ, no), (2, b, true, LT, yes), (2, b, true, LT, no)," + " (1, a, false, GT, yes), (1, a, false, GT, no), (1, a, true, GT, yes), (1, a, true, GT, no)," + " (1, b, false, GT, yes), (1, b, false, GT, no), (1, b, true, GT, yes), (1, b, true, GT, no)," + " (2, a, false, GT, yes), (2, a, false, GT, no), (2, a, true, GT, yes), (2, a, true, GT, no)," + " (2, b, false, GT, yes), (2, b, false, GT, no), (2, b, true, GT, yes), (2, b, true, GT, no)," + " (1, c, false, EQ, yes), (1, c, false, EQ, no), (1, c, false, LT, yes), (1, c, false, LT, no)," + " (1, c, true, EQ, yes), (1, c, true, EQ, no), (1, c, true, LT, yes), (1, c, true, LT, no)," + " (1, d, false, EQ, yes), (1, d, false, EQ, no), (1, d, false, LT, yes), (1, d, false, LT, no)," + " (1, d, true, EQ, yes), (1, d, true, EQ, no), (1, d, true, LT, yes), (1, d, true, LT, no)," + " (2, c, false, EQ, yes), (2, c, false, EQ, no), (2, c, false, LT, yes), (2, c, false, LT, no)," + " (2, c, true, EQ, yes), (2, c, true, EQ, no), (2, c, true, LT, yes), (2, c, true, LT, no)," + " (2, d, false, EQ, yes), (2, d, false, EQ, no), (2, d, false, LT, yes), (2, d, false, LT, no)," + " (2, d, true, EQ, yes), (2, d, true, EQ, no), (2, d, true, LT, yes), (2, d, true, LT, no)," + " (1, c, false, GT, yes), (1, c, false, GT, no), (1, c, true, GT, yes), (1, c, true, GT, no)," + " (1, d, false, GT, yes), (1, d, false, GT, no), (1, d, true, GT, yes), (1, d, true, GT, no)," + " (2, c, false, GT, yes), (2, c, false, GT, no), (2, c, true, GT, yes), (2, c, true, GT, no)," + " (2, d, false, GT, yes), (2, d, false, GT, no), (2, d, true, GT, yes), (2, d, true, GT, no)," + " (null, a, false, EQ, yes), (null, a, false, EQ, no), (null, a, false, LT, yes)," + " (null, a, false, LT, no), (null, a, true, EQ, yes), (null, a, true, EQ, no)," + " (null, a, true, LT, yes), (null, a, true, LT, no), (null, b, false, EQ, yes)," + " (null, b, false, EQ, no), (null, b, false, LT, yes), (null, b, false, LT, no)," + " (null, b, true, EQ, yes), (null, b, true, EQ, no), (null, b, true, LT, yes)," + " (null, b, true, LT, no), (4, a, false, EQ, yes), (4, a, false, EQ, no), (4, a, false, LT, yes)," + " (4, a, false, LT, no), (4, a, true, EQ, yes), (4, a, true, EQ, no), (4, a, true, LT, yes)," + " (4, a, true, LT, no), (4, b, false, EQ, yes), (4, b, false, EQ, no), (4, b, false, LT, yes)," + " (4, b, false, LT, no), (4, b, true, EQ, yes), (4, b, true, EQ, no), (4, b, true, LT, yes)," + " (4, b, true, LT, no), (null, a, false, GT, yes), (null, a, false, GT, no)," + " (null, a, true, GT, yes), (null, a, true, GT, no), (null, b, false, GT, yes)," + " (null, b, false, GT, no), (null, b, true, GT, yes), (null, b, true, GT, no)," + " (4, a, false, GT, yes), (4, a, false, GT, no), (4, a, true, GT, yes), (4, a, true, GT, no)," + " (4, b, false, GT, yes), (4, b, false, GT, no), (4, b, true, GT, yes), (4, b, true, GT, no)," + " (null, c, false, EQ, yes), (null, c, false, EQ, no), (null, c, false, LT, yes)," + " (null, c, false, LT, no), (null, c, true, EQ, yes), (null, c, true, EQ, no)," + " (null, c, true, LT, yes), (null, c, true, LT, no), (null, d, false, EQ, yes)," + " (null, d, false, EQ, no), (null, d, false, LT, yes), (null, d, false, LT, no)," + " (null, d, true, EQ, yes), (null, d, true, EQ, no), (null, d, true, LT, yes)," + " (null, d, true, LT, no), (4, c, false, EQ, yes), (4, c, false, EQ, no), (4, c, false, LT, yes)," + " (4, c, false, LT, no), (4, c, true, EQ, yes), (4, c, true, EQ, no), (4, c, true, LT, yes)," + " (4, c, true, LT, no), (4, d, false, EQ, yes), (4, d, false, EQ, no), (4, d, false, LT, yes)," + " (4, d, false, LT, no), (4, d, true, EQ, yes), (4, d, true, EQ, no), (4, d, true, LT, yes)," + " (4, d, true, LT, no), (null, c, false, GT, yes), (null, c, false, GT, no)," + " (null, c, true, GT, yes), (null, c, true, GT, no), (null, d, false, GT, yes)," + " (null, d, false, GT, no), (null, d, true, GT, yes), (null, d, true, GT, no)," + " (4, c, false, GT, yes), (4, c, false, GT, no), (4, c, true, GT, yes), (4, c, true, GT, no)," + " (4, d, false, GT, yes), (4, d, false, GT, no), (4, d, true, GT, yes), (4, d, true, GT, no)]"); aeq(quintuples( new ArrayList<Integer>(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") ), "[]"); aeq(quintuples( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>() ), "[]"); aeq(take(20, quintuples( P.naturalBigIntegers(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no") )), "[(0, a, false, EQ, yes), (0, a, false, EQ, no), (0, a, false, LT, yes), (0, a, false, LT, no)," + " (0, a, true, EQ, yes), (0, a, true, EQ, no), (0, a, true, LT, yes), (0, a, true, LT, no)," + " (0, b, false, EQ, yes), (0, b, false, EQ, no), (0, b, false, LT, yes), (0, b, false, LT, no)," + " (0, b, true, EQ, yes), (0, b, true, EQ, no), (0, b, true, LT, yes), (0, b, true, LT, no)," + " (1, a, false, EQ, yes), (1, a, false, EQ, no), (1, a, false, LT, yes), (1, a, false, LT, no)]"); aeq(take(20, quintuples( fromString("abcd"), P.booleans(), P.naturalBigIntegers(), P.orderings(), Arrays.asList("yes", "no") )), "[(a, false, 0, EQ, yes), (a, false, 0, EQ, no), (a, false, 0, LT, yes), (a, false, 0, LT, no)," + " (a, false, 1, EQ, yes), (a, false, 1, EQ, no), (a, false, 1, LT, yes), (a, false, 1, LT, no)," + " (a, true, 0, EQ, yes), (a, true, 0, EQ, no), (a, true, 0, LT, yes), (a, true, 0, LT, no)," + " (a, true, 1, EQ, yes), (a, true, 1, EQ, no), (a, true, 1, LT, yes), (a, true, 1, LT, no)," + " (b, false, 0, EQ, yes), (b, false, 0, EQ, no), (b, false, 0, LT, yes), (b, false, 0, LT, no)]"); aeq(take(20, quintuples( P.positiveBigIntegers(), P.negativeBigIntegers(), P.characters(), P.strings(), P.floats() )), "[(1, -1, a, , NaN), (1, -1, a, , Infinity), (1, -1, a, a, NaN), (1, -1, a, a, Infinity)," + " (1, -1, b, , NaN), (1, -1, b, , Infinity), (1, -1, b, a, NaN), (1, -1, b, a, Infinity)," + " (1, -2, a, , NaN), (1, -2, a, , Infinity), (1, -2, a, a, NaN), (1, -2, a, a, Infinity)," + " (1, -2, b, , NaN), (1, -2, b, , Infinity), (1, -2, b, a, NaN), (1, -2, b, a, Infinity)," + " (2, -1, a, , NaN), (2, -1, a, , Infinity), (2, -1, a, a, NaN), (2, -1, a, a, Infinity)]"); } @Test public void testSextuples() { aeq(sextuples( Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[(1, a, false, EQ, yes, Infinity), (1, a, false, EQ, yes, NaN), (1, a, false, EQ, no, Infinity)," + " (1, a, false, EQ, no, NaN), (1, a, false, LT, yes, Infinity), (1, a, false, LT, yes, NaN)," + " (1, a, false, LT, no, Infinity), (1, a, false, LT, no, NaN), (1, a, true, EQ, yes, Infinity)," + " (1, a, true, EQ, yes, NaN), (1, a, true, EQ, no, Infinity), (1, a, true, EQ, no, NaN)," + " (1, a, true, LT, yes, Infinity), (1, a, true, LT, yes, NaN), (1, a, true, LT, no, Infinity)," + " (1, a, true, LT, no, NaN), (1, b, false, EQ, yes, Infinity), (1, b, false, EQ, yes, NaN)," + " (1, b, false, EQ, no, Infinity), (1, b, false, EQ, no, NaN), (1, b, false, LT, yes, Infinity)," + " (1, b, false, LT, yes, NaN), (1, b, false, LT, no, Infinity), (1, b, false, LT, no, NaN)," + " (1, b, true, EQ, yes, Infinity), (1, b, true, EQ, yes, NaN), (1, b, true, EQ, no, Infinity)," + " (1, b, true, EQ, no, NaN), (1, b, true, LT, yes, Infinity), (1, b, true, LT, yes, NaN)," + " (1, b, true, LT, no, Infinity), (1, b, true, LT, no, NaN), (2, a, false, EQ, yes, Infinity)," + " (2, a, false, EQ, yes, NaN), (2, a, false, EQ, no, Infinity), (2, a, false, EQ, no, NaN)," + " (2, a, false, LT, yes, Infinity), (2, a, false, LT, yes, NaN), (2, a, false, LT, no, Infinity)," + " (2, a, false, LT, no, NaN), (2, a, true, EQ, yes, Infinity), (2, a, true, EQ, yes, NaN)," + " (2, a, true, EQ, no, Infinity), (2, a, true, EQ, no, NaN), (2, a, true, LT, yes, Infinity)," + " (2, a, true, LT, yes, NaN), (2, a, true, LT, no, Infinity), (2, a, true, LT, no, NaN)," + " (2, b, false, EQ, yes, Infinity), (2, b, false, EQ, yes, NaN), (2, b, false, EQ, no, Infinity)," + " (2, b, false, EQ, no, NaN), (2, b, false, LT, yes, Infinity), (2, b, false, LT, yes, NaN)," + " (2, b, false, LT, no, Infinity), (2, b, false, LT, no, NaN), (2, b, true, EQ, yes, Infinity)," + " (2, b, true, EQ, yes, NaN), (2, b, true, EQ, no, Infinity), (2, b, true, EQ, no, NaN)," + " (2, b, true, LT, yes, Infinity), (2, b, true, LT, yes, NaN), (2, b, true, LT, no, Infinity)," + " (2, b, true, LT, no, NaN), (1, a, false, GT, yes, Infinity), (1, a, false, GT, yes, NaN)," + " (1, a, false, GT, no, Infinity), (1, a, false, GT, no, NaN), (1, a, true, GT, yes, Infinity)," + " (1, a, true, GT, yes, NaN), (1, a, true, GT, no, Infinity), (1, a, true, GT, no, NaN)," + " (1, b, false, GT, yes, Infinity), (1, b, false, GT, yes, NaN), (1, b, false, GT, no, Infinity)," + " (1, b, false, GT, no, NaN), (1, b, true, GT, yes, Infinity), (1, b, true, GT, yes, NaN)," + " (1, b, true, GT, no, Infinity), (1, b, true, GT, no, NaN), (2, a, false, GT, yes, Infinity)," + " (2, a, false, GT, yes, NaN), (2, a, false, GT, no, Infinity), (2, a, false, GT, no, NaN)," + " (2, a, true, GT, yes, Infinity), (2, a, true, GT, yes, NaN), (2, a, true, GT, no, Infinity)," + " (2, a, true, GT, no, NaN), (2, b, false, GT, yes, Infinity), (2, b, false, GT, yes, NaN)," + " (2, b, false, GT, no, Infinity), (2, b, false, GT, no, NaN), (2, b, true, GT, yes, Infinity)," + " (2, b, true, GT, yes, NaN), (2, b, true, GT, no, Infinity), (2, b, true, GT, no, NaN)," + " (1, c, false, EQ, yes, Infinity), (1, c, false, EQ, yes, NaN), (1, c, false, EQ, no, Infinity)," + " (1, c, false, EQ, no, NaN), (1, c, false, LT, yes, Infinity), (1, c, false, LT, yes, NaN)," + " (1, c, false, LT, no, Infinity), (1, c, false, LT, no, NaN), (1, c, true, EQ, yes, Infinity)," + " (1, c, true, EQ, yes, NaN), (1, c, true, EQ, no, Infinity), (1, c, true, EQ, no, NaN)," + " (1, c, true, LT, yes, Infinity), (1, c, true, LT, yes, NaN), (1, c, true, LT, no, Infinity)," + " (1, c, true, LT, no, NaN), (2, c, false, EQ, yes, Infinity), (2, c, false, EQ, yes, NaN)," + " (2, c, false, EQ, no, Infinity), (2, c, false, EQ, no, NaN), (2, c, false, LT, yes, Infinity)," + " (2, c, false, LT, yes, NaN), (2, c, false, LT, no, Infinity), (2, c, false, LT, no, NaN)," + " (2, c, true, EQ, yes, Infinity), (2, c, true, EQ, yes, NaN), (2, c, true, EQ, no, Infinity)," + " (2, c, true, EQ, no, NaN), (2, c, true, LT, yes, Infinity), (2, c, true, LT, yes, NaN)," + " (2, c, true, LT, no, Infinity), (2, c, true, LT, no, NaN), (1, c, false, GT, yes, Infinity)," + " (1, c, false, GT, yes, NaN), (1, c, false, GT, no, Infinity), (1, c, false, GT, no, NaN)," + " (1, c, true, GT, yes, Infinity), (1, c, true, GT, yes, NaN), (1, c, true, GT, no, Infinity)," + " (1, c, true, GT, no, NaN), (2, c, false, GT, yes, Infinity), (2, c, false, GT, yes, NaN)," + " (2, c, false, GT, no, Infinity), (2, c, false, GT, no, NaN), (2, c, true, GT, yes, Infinity)," + " (2, c, true, GT, yes, NaN), (2, c, true, GT, no, Infinity), (2, c, true, GT, no, NaN)," + " (3, a, false, EQ, yes, Infinity), (3, a, false, EQ, yes, NaN), (3, a, false, EQ, no, Infinity)," + " (3, a, false, EQ, no, NaN), (3, a, false, LT, yes, Infinity), (3, a, false, LT, yes, NaN)," + " (3, a, false, LT, no, Infinity), (3, a, false, LT, no, NaN), (3, a, true, EQ, yes, Infinity)," + " (3, a, true, EQ, yes, NaN), (3, a, true, EQ, no, Infinity), (3, a, true, EQ, no, NaN)," + " (3, a, true, LT, yes, Infinity), (3, a, true, LT, yes, NaN), (3, a, true, LT, no, Infinity)," + " (3, a, true, LT, no, NaN), (3, b, false, EQ, yes, Infinity), (3, b, false, EQ, yes, NaN)," + " (3, b, false, EQ, no, Infinity), (3, b, false, EQ, no, NaN), (3, b, false, LT, yes, Infinity)," + " (3, b, false, LT, yes, NaN), (3, b, false, LT, no, Infinity), (3, b, false, LT, no, NaN)," + " (3, b, true, EQ, yes, Infinity), (3, b, true, EQ, yes, NaN), (3, b, true, EQ, no, Infinity)," + " (3, b, true, EQ, no, NaN), (3, b, true, LT, yes, Infinity), (3, b, true, LT, yes, NaN)," + " (3, b, true, LT, no, Infinity), (3, b, true, LT, no, NaN), (3, a, false, GT, yes, Infinity)," + " (3, a, false, GT, yes, NaN), (3, a, false, GT, no, Infinity), (3, a, false, GT, no, NaN)," + " (3, a, true, GT, yes, Infinity), (3, a, true, GT, yes, NaN), (3, a, true, GT, no, Infinity)," + " (3, a, true, GT, no, NaN), (3, b, false, GT, yes, Infinity), (3, b, false, GT, yes, NaN)," + " (3, b, false, GT, no, Infinity), (3, b, false, GT, no, NaN), (3, b, true, GT, yes, Infinity)," + " (3, b, true, GT, yes, NaN), (3, b, true, GT, no, Infinity), (3, b, true, GT, no, NaN)," + " (3, c, false, EQ, yes, Infinity), (3, c, false, EQ, yes, NaN), (3, c, false, EQ, no, Infinity)," + " (3, c, false, EQ, no, NaN), (3, c, false, LT, yes, Infinity), (3, c, false, LT, yes, NaN)," + " (3, c, false, LT, no, Infinity), (3, c, false, LT, no, NaN), (3, c, true, EQ, yes, Infinity)," + " (3, c, true, EQ, yes, NaN), (3, c, true, EQ, no, Infinity), (3, c, true, EQ, no, NaN)," + " (3, c, true, LT, yes, Infinity), (3, c, true, LT, yes, NaN), (3, c, true, LT, no, Infinity)," + " (3, c, true, LT, no, NaN), (3, c, false, GT, yes, Infinity), (3, c, false, GT, yes, NaN)," + " (3, c, false, GT, no, Infinity), (3, c, false, GT, no, NaN), (3, c, true, GT, yes, Infinity)," + " (3, c, true, GT, yes, NaN), (3, c, true, GT, no, Infinity), (3, c, true, GT, no, NaN)]"); aeq(sextuples( Arrays.asList(1, 2, null, 4), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[(1, a, false, EQ, yes, Infinity), (1, a, false, EQ, yes, NaN), (1, a, false, EQ, no, Infinity)," + " (1, a, false, EQ, no, NaN), (1, a, false, LT, yes, Infinity), (1, a, false, LT, yes, NaN)," + " (1, a, false, LT, no, Infinity), (1, a, false, LT, no, NaN), (1, a, true, EQ, yes, Infinity)," + " (1, a, true, EQ, yes, NaN), (1, a, true, EQ, no, Infinity), (1, a, true, EQ, no, NaN)," + " (1, a, true, LT, yes, Infinity), (1, a, true, LT, yes, NaN), (1, a, true, LT, no, Infinity)," + " (1, a, true, LT, no, NaN), (1, b, false, EQ, yes, Infinity), (1, b, false, EQ, yes, NaN)," + " (1, b, false, EQ, no, Infinity), (1, b, false, EQ, no, NaN), (1, b, false, LT, yes, Infinity)," + " (1, b, false, LT, yes, NaN), (1, b, false, LT, no, Infinity), (1, b, false, LT, no, NaN)," + " (1, b, true, EQ, yes, Infinity), (1, b, true, EQ, yes, NaN), (1, b, true, EQ, no, Infinity)," + " (1, b, true, EQ, no, NaN), (1, b, true, LT, yes, Infinity), (1, b, true, LT, yes, NaN)," + " (1, b, true, LT, no, Infinity), (1, b, true, LT, no, NaN), (2, a, false, EQ, yes, Infinity)," + " (2, a, false, EQ, yes, NaN), (2, a, false, EQ, no, Infinity), (2, a, false, EQ, no, NaN)," + " (2, a, false, LT, yes, Infinity), (2, a, false, LT, yes, NaN), (2, a, false, LT, no, Infinity)," + " (2, a, false, LT, no, NaN), (2, a, true, EQ, yes, Infinity), (2, a, true, EQ, yes, NaN)," + " (2, a, true, EQ, no, Infinity), (2, a, true, EQ, no, NaN), (2, a, true, LT, yes, Infinity)," + " (2, a, true, LT, yes, NaN), (2, a, true, LT, no, Infinity), (2, a, true, LT, no, NaN)," + " (2, b, false, EQ, yes, Infinity), (2, b, false, EQ, yes, NaN), (2, b, false, EQ, no, Infinity)," + " (2, b, false, EQ, no, NaN), (2, b, false, LT, yes, Infinity), (2, b, false, LT, yes, NaN)," + " (2, b, false, LT, no, Infinity), (2, b, false, LT, no, NaN), (2, b, true, EQ, yes, Infinity)," + " (2, b, true, EQ, yes, NaN), (2, b, true, EQ, no, Infinity), (2, b, true, EQ, no, NaN)," + " (2, b, true, LT, yes, Infinity), (2, b, true, LT, yes, NaN), (2, b, true, LT, no, Infinity)," + " (2, b, true, LT, no, NaN), (1, a, false, GT, yes, Infinity), (1, a, false, GT, yes, NaN)," + " (1, a, false, GT, no, Infinity), (1, a, false, GT, no, NaN), (1, a, true, GT, yes, Infinity)," + " (1, a, true, GT, yes, NaN), (1, a, true, GT, no, Infinity), (1, a, true, GT, no, NaN)," + " (1, b, false, GT, yes, Infinity), (1, b, false, GT, yes, NaN), (1, b, false, GT, no, Infinity)," + " (1, b, false, GT, no, NaN), (1, b, true, GT, yes, Infinity), (1, b, true, GT, yes, NaN)," + " (1, b, true, GT, no, Infinity), (1, b, true, GT, no, NaN), (2, a, false, GT, yes, Infinity)," + " (2, a, false, GT, yes, NaN), (2, a, false, GT, no, Infinity), (2, a, false, GT, no, NaN)," + " (2, a, true, GT, yes, Infinity), (2, a, true, GT, yes, NaN), (2, a, true, GT, no, Infinity)," + " (2, a, true, GT, no, NaN), (2, b, false, GT, yes, Infinity), (2, b, false, GT, yes, NaN)," + " (2, b, false, GT, no, Infinity), (2, b, false, GT, no, NaN), (2, b, true, GT, yes, Infinity)," + " (2, b, true, GT, yes, NaN), (2, b, true, GT, no, Infinity), (2, b, true, GT, no, NaN)," + " (1, c, false, EQ, yes, Infinity), (1, c, false, EQ, yes, NaN), (1, c, false, EQ, no, Infinity)," + " (1, c, false, EQ, no, NaN), (1, c, false, LT, yes, Infinity), (1, c, false, LT, yes, NaN)," + " (1, c, false, LT, no, Infinity), (1, c, false, LT, no, NaN), (1, c, true, EQ, yes, Infinity)," + " (1, c, true, EQ, yes, NaN), (1, c, true, EQ, no, Infinity), (1, c, true, EQ, no, NaN)," + " (1, c, true, LT, yes, Infinity), (1, c, true, LT, yes, NaN), (1, c, true, LT, no, Infinity)," + " (1, c, true, LT, no, NaN), (1, d, false, EQ, yes, Infinity), (1, d, false, EQ, yes, NaN)," + " (1, d, false, EQ, no, Infinity), (1, d, false, EQ, no, NaN), (1, d, false, LT, yes, Infinity)," + " (1, d, false, LT, yes, NaN), (1, d, false, LT, no, Infinity), (1, d, false, LT, no, NaN)," + " (1, d, true, EQ, yes, Infinity), (1, d, true, EQ, yes, NaN), (1, d, true, EQ, no, Infinity)," + " (1, d, true, EQ, no, NaN), (1, d, true, LT, yes, Infinity), (1, d, true, LT, yes, NaN)," + " (1, d, true, LT, no, Infinity), (1, d, true, LT, no, NaN), (2, c, false, EQ, yes, Infinity)," + " (2, c, false, EQ, yes, NaN), (2, c, false, EQ, no, Infinity), (2, c, false, EQ, no, NaN)," + " (2, c, false, LT, yes, Infinity), (2, c, false, LT, yes, NaN), (2, c, false, LT, no, Infinity)," + " (2, c, false, LT, no, NaN), (2, c, true, EQ, yes, Infinity), (2, c, true, EQ, yes, NaN)," + " (2, c, true, EQ, no, Infinity), (2, c, true, EQ, no, NaN), (2, c, true, LT, yes, Infinity)," + " (2, c, true, LT, yes, NaN), (2, c, true, LT, no, Infinity), (2, c, true, LT, no, NaN)," + " (2, d, false, EQ, yes, Infinity), (2, d, false, EQ, yes, NaN), (2, d, false, EQ, no, Infinity)," + " (2, d, false, EQ, no, NaN), (2, d, false, LT, yes, Infinity), (2, d, false, LT, yes, NaN)," + " (2, d, false, LT, no, Infinity), (2, d, false, LT, no, NaN), (2, d, true, EQ, yes, Infinity)," + " (2, d, true, EQ, yes, NaN), (2, d, true, EQ, no, Infinity), (2, d, true, EQ, no, NaN)," + " (2, d, true, LT, yes, Infinity), (2, d, true, LT, yes, NaN), (2, d, true, LT, no, Infinity)," + " (2, d, true, LT, no, NaN), (1, c, false, GT, yes, Infinity), (1, c, false, GT, yes, NaN)," + " (1, c, false, GT, no, Infinity), (1, c, false, GT, no, NaN), (1, c, true, GT, yes, Infinity)," + " (1, c, true, GT, yes, NaN), (1, c, true, GT, no, Infinity), (1, c, true, GT, no, NaN)," + " (1, d, false, GT, yes, Infinity), (1, d, false, GT, yes, NaN), (1, d, false, GT, no, Infinity)," + " (1, d, false, GT, no, NaN), (1, d, true, GT, yes, Infinity), (1, d, true, GT, yes, NaN)," + " (1, d, true, GT, no, Infinity), (1, d, true, GT, no, NaN), (2, c, false, GT, yes, Infinity)," + " (2, c, false, GT, yes, NaN), (2, c, false, GT, no, Infinity), (2, c, false, GT, no, NaN)," + " (2, c, true, GT, yes, Infinity), (2, c, true, GT, yes, NaN), (2, c, true, GT, no, Infinity)," + " (2, c, true, GT, no, NaN), (2, d, false, GT, yes, Infinity), (2, d, false, GT, yes, NaN)," + " (2, d, false, GT, no, Infinity), (2, d, false, GT, no, NaN), (2, d, true, GT, yes, Infinity)," + " (2, d, true, GT, yes, NaN), (2, d, true, GT, no, Infinity), (2, d, true, GT, no, NaN)," + " (null, a, false, EQ, yes, Infinity), (null, a, false, EQ, yes, NaN)," + " (null, a, false, EQ, no, Infinity), (null, a, false, EQ, no, NaN)," + " (null, a, false, LT, yes, Infinity), (null, a, false, LT, yes, NaN)," + " (null, a, false, LT, no, Infinity), (null, a, false, LT, no, NaN)," + " (null, a, true, EQ, yes, Infinity), (null, a, true, EQ, yes, NaN)," + " (null, a, true, EQ, no, Infinity), (null, a, true, EQ, no, NaN)," + " (null, a, true, LT, yes, Infinity), (null, a, true, LT, yes, NaN)," + " (null, a, true, LT, no, Infinity), (null, a, true, LT, no, NaN)," + " (null, b, false, EQ, yes, Infinity), (null, b, false, EQ, yes, NaN)," + " (null, b, false, EQ, no, Infinity), (null, b, false, EQ, no, NaN)," + " (null, b, false, LT, yes, Infinity), (null, b, false, LT, yes, NaN)," + " (null, b, false, LT, no, Infinity), (null, b, false, LT, no, NaN)," + " (null, b, true, EQ, yes, Infinity), (null, b, true, EQ, yes, NaN)," + " (null, b, true, EQ, no, Infinity), (null, b, true, EQ, no, NaN)," + " (null, b, true, LT, yes, Infinity), (null, b, true, LT, yes, NaN)," + " (null, b, true, LT, no, Infinity), (null, b, true, LT, no, NaN), (4, a, false, EQ, yes, Infinity)," + " (4, a, false, EQ, yes, NaN), (4, a, false, EQ, no, Infinity), (4, a, false, EQ, no, NaN)," + " (4, a, false, LT, yes, Infinity), (4, a, false, LT, yes, NaN), (4, a, false, LT, no, Infinity)," + " (4, a, false, LT, no, NaN), (4, a, true, EQ, yes, Infinity), (4, a, true, EQ, yes, NaN)," + " (4, a, true, EQ, no, Infinity), (4, a, true, EQ, no, NaN), (4, a, true, LT, yes, Infinity)," + " (4, a, true, LT, yes, NaN), (4, a, true, LT, no, Infinity), (4, a, true, LT, no, NaN)," + " (4, b, false, EQ, yes, Infinity), (4, b, false, EQ, yes, NaN), (4, b, false, EQ, no, Infinity)," + " (4, b, false, EQ, no, NaN), (4, b, false, LT, yes, Infinity), (4, b, false, LT, yes, NaN)," + " (4, b, false, LT, no, Infinity), (4, b, false, LT, no, NaN), (4, b, true, EQ, yes, Infinity)," + " (4, b, true, EQ, yes, NaN), (4, b, true, EQ, no, Infinity), (4, b, true, EQ, no, NaN)," + " (4, b, true, LT, yes, Infinity), (4, b, true, LT, yes, NaN), (4, b, true, LT, no, Infinity)," + " (4, b, true, LT, no, NaN), (null, a, false, GT, yes, Infinity), (null, a, false, GT, yes, NaN)," + " (null, a, false, GT, no, Infinity), (null, a, false, GT, no, NaN)," + " (null, a, true, GT, yes, Infinity), (null, a, true, GT, yes, NaN)," + " (null, a, true, GT, no, Infinity), (null, a, true, GT, no, NaN)," + " (null, b, false, GT, yes, Infinity), (null, b, false, GT, yes, NaN)," + " (null, b, false, GT, no, Infinity), (null, b, false, GT, no, NaN)," + " (null, b, true, GT, yes, Infinity), (null, b, true, GT, yes, NaN)," + " (null, b, true, GT, no, Infinity), (null, b, true, GT, no, NaN), (4, a, false, GT, yes, Infinity)," + " (4, a, false, GT, yes, NaN), (4, a, false, GT, no, Infinity), (4, a, false, GT, no, NaN)," + " (4, a, true, GT, yes, Infinity), (4, a, true, GT, yes, NaN), (4, a, true, GT, no, Infinity)," + " (4, a, true, GT, no, NaN), (4, b, false, GT, yes, Infinity), (4, b, false, GT, yes, NaN)," + " (4, b, false, GT, no, Infinity), (4, b, false, GT, no, NaN), (4, b, true, GT, yes, Infinity)," + " (4, b, true, GT, yes, NaN), (4, b, true, GT, no, Infinity), (4, b, true, GT, no, NaN)," + " (null, c, false, EQ, yes, Infinity), (null, c, false, EQ, yes, NaN)," + " (null, c, false, EQ, no, Infinity), (null, c, false, EQ, no, NaN)," + " (null, c, false, LT, yes, Infinity), (null, c, false, LT, yes, NaN)," + " (null, c, false, LT, no, Infinity), (null, c, false, LT, no, NaN)," + " (null, c, true, EQ, yes, Infinity), (null, c, true, EQ, yes, NaN)," + " (null, c, true, EQ, no, Infinity), (null, c, true, EQ, no, NaN)," + " (null, c, true, LT, yes, Infinity), (null, c, true, LT, yes, NaN)," + " (null, c, true, LT, no, Infinity), (null, c, true, LT, no, NaN)," + " (null, d, false, EQ, yes, Infinity), (null, d, false, EQ, yes, NaN)," + " (null, d, false, EQ, no, Infinity), (null, d, false, EQ, no, NaN)," + " (null, d, false, LT, yes, Infinity), (null, d, false, LT, yes, NaN)," + " (null, d, false, LT, no, Infinity), (null, d, false, LT, no, NaN)," + " (null, d, true, EQ, yes, Infinity), (null, d, true, EQ, yes, NaN)," + " (null, d, true, EQ, no, Infinity), (null, d, true, EQ, no, NaN)," + " (null, d, true, LT, yes, Infinity), (null, d, true, LT, yes, NaN)," + " (null, d, true, LT, no, Infinity), (null, d, true, LT, no, NaN), (4, c, false, EQ, yes, Infinity)," + " (4, c, false, EQ, yes, NaN), (4, c, false, EQ, no, Infinity), (4, c, false, EQ, no, NaN)," + " (4, c, false, LT, yes, Infinity), (4, c, false, LT, yes, NaN), (4, c, false, LT, no, Infinity)," + " (4, c, false, LT, no, NaN), (4, c, true, EQ, yes, Infinity), (4, c, true, EQ, yes, NaN)," + " (4, c, true, EQ, no, Infinity), (4, c, true, EQ, no, NaN), (4, c, true, LT, yes, Infinity)," + " (4, c, true, LT, yes, NaN), (4, c, true, LT, no, Infinity), (4, c, true, LT, no, NaN)," + " (4, d, false, EQ, yes, Infinity), (4, d, false, EQ, yes, NaN), (4, d, false, EQ, no, Infinity)," + " (4, d, false, EQ, no, NaN), (4, d, false, LT, yes, Infinity), (4, d, false, LT, yes, NaN)," + " (4, d, false, LT, no, Infinity), (4, d, false, LT, no, NaN), (4, d, true, EQ, yes, Infinity)," + " (4, d, true, EQ, yes, NaN), (4, d, true, EQ, no, Infinity), (4, d, true, EQ, no, NaN)," + " (4, d, true, LT, yes, Infinity), (4, d, true, LT, yes, NaN), (4, d, true, LT, no, Infinity)," + " (4, d, true, LT, no, NaN), (null, c, false, GT, yes, Infinity), (null, c, false, GT, yes, NaN)," + " (null, c, false, GT, no, Infinity), (null, c, false, GT, no, NaN)," + " (null, c, true, GT, yes, Infinity), (null, c, true, GT, yes, NaN)," + " (null, c, true, GT, no, Infinity), (null, c, true, GT, no, NaN)," + " (null, d, false, GT, yes, Infinity), (null, d, false, GT, yes, NaN)," + " (null, d, false, GT, no, Infinity), (null, d, false, GT, no, NaN)," + " (null, d, true, GT, yes, Infinity), (null, d, true, GT, yes, NaN)," + " (null, d, true, GT, no, Infinity), (null, d, true, GT, no, NaN), (4, c, false, GT, yes, Infinity)," + " (4, c, false, GT, yes, NaN), (4, c, false, GT, no, Infinity), (4, c, false, GT, no, NaN)," + " (4, c, true, GT, yes, Infinity), (4, c, true, GT, yes, NaN), (4, c, true, GT, no, Infinity)," + " (4, c, true, GT, no, NaN), (4, d, false, GT, yes, Infinity), (4, d, false, GT, yes, NaN)," + " (4, d, false, GT, no, Infinity), (4, d, false, GT, no, NaN), (4, d, true, GT, yes, Infinity)," + " (4, d, true, GT, yes, NaN), (4, d, true, GT, no, Infinity), (4, d, true, GT, no, NaN)]"); aeq(sextuples( new ArrayList<Integer>(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) ), "[]"); aeq(sextuples( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>(), new ArrayList<Float>() ), "[]"); aeq(take(20, sextuples( P.naturalBigIntegers(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), (List<Float>) Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) )), "[(0, a, false, EQ, yes, Infinity), (0, a, false, EQ, yes, NaN), (0, a, false, EQ, no, Infinity)," + " (0, a, false, EQ, no, NaN), (0, a, false, LT, yes, Infinity), (0, a, false, LT, yes, NaN)," + " (0, a, false, LT, no, Infinity), (0, a, false, LT, no, NaN), (0, a, true, EQ, yes, Infinity)," + " (0, a, true, EQ, yes, NaN), (0, a, true, EQ, no, Infinity), (0, a, true, EQ, no, NaN)," + " (0, a, true, LT, yes, Infinity), (0, a, true, LT, yes, NaN), (0, a, true, LT, no, Infinity)," + " (0, a, true, LT, no, NaN), (0, b, false, EQ, yes, Infinity), (0, b, false, EQ, yes, NaN)," + " (0, b, false, EQ, no, Infinity), (0, b, false, EQ, no, NaN)]"); aeq(take(20, sextuples( fromString("abcd"), P.booleans(), P.naturalBigIntegers(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN) )), "[(a, false, 0, EQ, yes, Infinity), (a, false, 0, EQ, yes, NaN), (a, false, 0, EQ, no, Infinity)," + " (a, false, 0, EQ, no, NaN), (a, false, 0, LT, yes, Infinity), (a, false, 0, LT, yes, NaN)," + " (a, false, 0, LT, no, Infinity), (a, false, 0, LT, no, NaN), (a, false, 1, EQ, yes, Infinity)," + " (a, false, 1, EQ, yes, NaN), (a, false, 1, EQ, no, Infinity), (a, false, 1, EQ, no, NaN)," + " (a, false, 1, LT, yes, Infinity), (a, false, 1, LT, yes, NaN), (a, false, 1, LT, no, Infinity)," + " (a, false, 1, LT, no, NaN), (a, true, 0, EQ, yes, Infinity), (a, true, 0, EQ, yes, NaN)," + " (a, true, 0, EQ, no, Infinity), (a, true, 0, EQ, no, NaN)]"); aeq(take(20, sextuples( P.positiveBigIntegers(), P.negativeBigIntegers(), P.characters(), P.strings(), P.floats(), P.lists(P.integers()) )), "[(1, -1, a, , NaN, []), (1, -1, a, , NaN, [0]), (1, -1, a, , Infinity, [])," + " (1, -1, a, , Infinity, [0]), (1, -1, a, a, NaN, []), (1, -1, a, a, NaN, [0])," + " (1, -1, a, a, Infinity, []), (1, -1, a, a, Infinity, [0]), (1, -1, b, , NaN, [])," + " (1, -1, b, , NaN, [0]), (1, -1, b, , Infinity, []), (1, -1, b, , Infinity, [0])," + " (1, -1, b, a, NaN, []), (1, -1, b, a, NaN, [0]), (1, -1, b, a, Infinity, [])," + " (1, -1, b, a, Infinity, [0]), (1, -2, a, , NaN, []), (1, -2, a, , NaN, [0])," + " (1, -2, a, , Infinity, []), (1, -2, a, , Infinity, [0])]"); } @Test public void testSeptuples() { List<Integer> x = Arrays.asList(1, 0); List<Integer> y = Arrays.asList(0, 1); aeq(septuples( Arrays.asList(1, 2, 3), fromString("abc"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), Arrays.asList(x, y) ), "[(1, a, false, EQ, yes, Infinity, [1, 0]), (1, a, false, EQ, yes, Infinity, [0, 1])," + " (1, a, false, EQ, yes, NaN, [1, 0]), (1, a, false, EQ, yes, NaN, [0, 1])," + " (1, a, false, EQ, no, Infinity, [1, 0]), (1, a, false, EQ, no, Infinity, [0, 1])," + " (1, a, false, EQ, no, NaN, [1, 0]), (1, a, false, EQ, no, NaN, [0, 1])," + " (1, a, false, LT, yes, Infinity, [1, 0]), (1, a, false, LT, yes, Infinity, [0, 1])," + " (1, a, false, LT, yes, NaN, [1, 0]), (1, a, false, LT, yes, NaN, [0, 1])," + " (1, a, false, LT, no, Infinity, [1, 0]), (1, a, false, LT, no, Infinity, [0, 1])," + " (1, a, false, LT, no, NaN, [1, 0]), (1, a, false, LT, no, NaN, [0, 1])," + " (1, a, true, EQ, yes, Infinity, [1, 0]), (1, a, true, EQ, yes, Infinity, [0, 1])," + " (1, a, true, EQ, yes, NaN, [1, 0]), (1, a, true, EQ, yes, NaN, [0, 1])," + " (1, a, true, EQ, no, Infinity, [1, 0]), (1, a, true, EQ, no, Infinity, [0, 1])," + " (1, a, true, EQ, no, NaN, [1, 0]), (1, a, true, EQ, no, NaN, [0, 1])," + " (1, a, true, LT, yes, Infinity, [1, 0]), (1, a, true, LT, yes, Infinity, [0, 1])," + " (1, a, true, LT, yes, NaN, [1, 0]), (1, a, true, LT, yes, NaN, [0, 1])," + " (1, a, true, LT, no, Infinity, [1, 0]), (1, a, true, LT, no, Infinity, [0, 1])," + " (1, a, true, LT, no, NaN, [1, 0]), (1, a, true, LT, no, NaN, [0, 1])," + " (1, b, false, EQ, yes, Infinity, [1, 0]), (1, b, false, EQ, yes, Infinity, [0, 1])," + " (1, b, false, EQ, yes, NaN, [1, 0]), (1, b, false, EQ, yes, NaN, [0, 1])," + " (1, b, false, EQ, no, Infinity, [1, 0]), (1, b, false, EQ, no, Infinity, [0, 1])," + " (1, b, false, EQ, no, NaN, [1, 0]), (1, b, false, EQ, no, NaN, [0, 1])," + " (1, b, false, LT, yes, Infinity, [1, 0]), (1, b, false, LT, yes, Infinity, [0, 1])," + " (1, b, false, LT, yes, NaN, [1, 0]), (1, b, false, LT, yes, NaN, [0, 1])," + " (1, b, false, LT, no, Infinity, [1, 0]), (1, b, false, LT, no, Infinity, [0, 1])," + " (1, b, false, LT, no, NaN, [1, 0]), (1, b, false, LT, no, NaN, [0, 1])," + " (1, b, true, EQ, yes, Infinity, [1, 0]), (1, b, true, EQ, yes, Infinity, [0, 1])," + " (1, b, true, EQ, yes, NaN, [1, 0]), (1, b, true, EQ, yes, NaN, [0, 1])," + " (1, b, true, EQ, no, Infinity, [1, 0]), (1, b, true, EQ, no, Infinity, [0, 1])," + " (1, b, true, EQ, no, NaN, [1, 0]), (1, b, true, EQ, no, NaN, [0, 1])," + " (1, b, true, LT, yes, Infinity, [1, 0]), (1, b, true, LT, yes, Infinity, [0, 1])," + " (1, b, true, LT, yes, NaN, [1, 0]), (1, b, true, LT, yes, NaN, [0, 1])," + " (1, b, true, LT, no, Infinity, [1, 0]), (1, b, true, LT, no, Infinity, [0, 1])," + " (1, b, true, LT, no, NaN, [1, 0]), (1, b, true, LT, no, NaN, [0, 1])," + " (2, a, false, EQ, yes, Infinity, [1, 0]), (2, a, false, EQ, yes, Infinity, [0, 1])," + " (2, a, false, EQ, yes, NaN, [1, 0]), (2, a, false, EQ, yes, NaN, [0, 1])," + " (2, a, false, EQ, no, Infinity, [1, 0]), (2, a, false, EQ, no, Infinity, [0, 1])," + " (2, a, false, EQ, no, NaN, [1, 0]), (2, a, false, EQ, no, NaN, [0, 1])," + " (2, a, false, LT, yes, Infinity, [1, 0]), (2, a, false, LT, yes, Infinity, [0, 1])," + " (2, a, false, LT, yes, NaN, [1, 0]), (2, a, false, LT, yes, NaN, [0, 1])," + " (2, a, false, LT, no, Infinity, [1, 0]), (2, a, false, LT, no, Infinity, [0, 1])," + " (2, a, false, LT, no, NaN, [1, 0]), (2, a, false, LT, no, NaN, [0, 1])," + " (2, a, true, EQ, yes, Infinity, [1, 0]), (2, a, true, EQ, yes, Infinity, [0, 1])," + " (2, a, true, EQ, yes, NaN, [1, 0]), (2, a, true, EQ, yes, NaN, [0, 1])," + " (2, a, true, EQ, no, Infinity, [1, 0]), (2, a, true, EQ, no, Infinity, [0, 1])," + " (2, a, true, EQ, no, NaN, [1, 0]), (2, a, true, EQ, no, NaN, [0, 1])," + " (2, a, true, LT, yes, Infinity, [1, 0]), (2, a, true, LT, yes, Infinity, [0, 1])," + " (2, a, true, LT, yes, NaN, [1, 0]), (2, a, true, LT, yes, NaN, [0, 1])," + " (2, a, true, LT, no, Infinity, [1, 0]), (2, a, true, LT, no, Infinity, [0, 1])," + " (2, a, true, LT, no, NaN, [1, 0]), (2, a, true, LT, no, NaN, [0, 1])," + " (2, b, false, EQ, yes, Infinity, [1, 0]), (2, b, false, EQ, yes, Infinity, [0, 1])," + " (2, b, false, EQ, yes, NaN, [1, 0]), (2, b, false, EQ, yes, NaN, [0, 1])," + " (2, b, false, EQ, no, Infinity, [1, 0]), (2, b, false, EQ, no, Infinity, [0, 1])," + " (2, b, false, EQ, no, NaN, [1, 0]), (2, b, false, EQ, no, NaN, [0, 1])," + " (2, b, false, LT, yes, Infinity, [1, 0]), (2, b, false, LT, yes, Infinity, [0, 1])," + " (2, b, false, LT, yes, NaN, [1, 0]), (2, b, false, LT, yes, NaN, [0, 1])," + " (2, b, false, LT, no, Infinity, [1, 0]), (2, b, false, LT, no, Infinity, [0, 1])," + " (2, b, false, LT, no, NaN, [1, 0]), (2, b, false, LT, no, NaN, [0, 1])," + " (2, b, true, EQ, yes, Infinity, [1, 0]), (2, b, true, EQ, yes, Infinity, [0, 1])," + " (2, b, true, EQ, yes, NaN, [1, 0]), (2, b, true, EQ, yes, NaN, [0, 1])," + " (2, b, true, EQ, no, Infinity, [1, 0]), (2, b, true, EQ, no, Infinity, [0, 1])," + " (2, b, true, EQ, no, NaN, [1, 0]), (2, b, true, EQ, no, NaN, [0, 1])," + " (2, b, true, LT, yes, Infinity, [1, 0]), (2, b, true, LT, yes, Infinity, [0, 1])," + " (2, b, true, LT, yes, NaN, [1, 0]), (2, b, true, LT, yes, NaN, [0, 1])," + " (2, b, true, LT, no, Infinity, [1, 0]), (2, b, true, LT, no, Infinity, [0, 1])," + " (2, b, true, LT, no, NaN, [1, 0]), (2, b, true, LT, no, NaN, [0, 1])," + " (1, a, false, GT, yes, Infinity, [1, 0]), (1, a, false, GT, yes, Infinity, [0, 1])," + " (1, a, false, GT, yes, NaN, [1, 0]), (1, a, false, GT, yes, NaN, [0, 1])," + " (1, a, false, GT, no, Infinity, [1, 0]), (1, a, false, GT, no, Infinity, [0, 1])," + " (1, a, false, GT, no, NaN, [1, 0]), (1, a, false, GT, no, NaN, [0, 1])," + " (1, a, true, GT, yes, Infinity, [1, 0]), (1, a, true, GT, yes, Infinity, [0, 1])," + " (1, a, true, GT, yes, NaN, [1, 0]), (1, a, true, GT, yes, NaN, [0, 1])," + " (1, a, true, GT, no, Infinity, [1, 0]), (1, a, true, GT, no, Infinity, [0, 1])," + " (1, a, true, GT, no, NaN, [1, 0]), (1, a, true, GT, no, NaN, [0, 1])," + " (1, b, false, GT, yes, Infinity, [1, 0]), (1, b, false, GT, yes, Infinity, [0, 1])," + " (1, b, false, GT, yes, NaN, [1, 0]), (1, b, false, GT, yes, NaN, [0, 1])," + " (1, b, false, GT, no, Infinity, [1, 0]), (1, b, false, GT, no, Infinity, [0, 1])," + " (1, b, false, GT, no, NaN, [1, 0]), (1, b, false, GT, no, NaN, [0, 1])," + " (1, b, true, GT, yes, Infinity, [1, 0]), (1, b, true, GT, yes, Infinity, [0, 1])," + " (1, b, true, GT, yes, NaN, [1, 0]), (1, b, true, GT, yes, NaN, [0, 1])," + " (1, b, true, GT, no, Infinity, [1, 0]), (1, b, true, GT, no, Infinity, [0, 1])," + " (1, b, true, GT, no, NaN, [1, 0]), (1, b, true, GT, no, NaN, [0, 1])," + " (2, a, false, GT, yes, Infinity, [1, 0]), (2, a, false, GT, yes, Infinity, [0, 1])," + " (2, a, false, GT, yes, NaN, [1, 0]), (2, a, false, GT, yes, NaN, [0, 1])," + " (2, a, false, GT, no, Infinity, [1, 0]), (2, a, false, GT, no, Infinity, [0, 1])," + " (2, a, false, GT, no, NaN, [1, 0]), (2, a, false, GT, no, NaN, [0, 1])," + " (2, a, true, GT, yes, Infinity, [1, 0]), (2, a, true, GT, yes, Infinity, [0, 1])," + " (2, a, true, GT, yes, NaN, [1, 0]), (2, a, true, GT, yes, NaN, [0, 1])," + " (2, a, true, GT, no, Infinity, [1, 0]), (2, a, true, GT, no, Infinity, [0, 1])," + " (2, a, true, GT, no, NaN, [1, 0]), (2, a, true, GT, no, NaN, [0, 1])," + " (2, b, false, GT, yes, Infinity, [1, 0]), (2, b, false, GT, yes, Infinity, [0, 1])," + " (2, b, false, GT, yes, NaN, [1, 0]), (2, b, false, GT, yes, NaN, [0, 1])," + " (2, b, false, GT, no, Infinity, [1, 0]), (2, b, false, GT, no, Infinity, [0, 1])," + " (2, b, false, GT, no, NaN, [1, 0]), (2, b, false, GT, no, NaN, [0, 1])," + " (2, b, true, GT, yes, Infinity, [1, 0]), (2, b, true, GT, yes, Infinity, [0, 1])," + " (2, b, true, GT, yes, NaN, [1, 0]), (2, b, true, GT, yes, NaN, [0, 1])," + " (2, b, true, GT, no, Infinity, [1, 0]), (2, b, true, GT, no, Infinity, [0, 1])," + " (2, b, true, GT, no, NaN, [1, 0]), (2, b, true, GT, no, NaN, [0, 1])," + " (1, c, false, EQ, yes, Infinity, [1, 0]), (1, c, false, EQ, yes, Infinity, [0, 1])," + " (1, c, false, EQ, yes, NaN, [1, 0]), (1, c, false, EQ, yes, NaN, [0, 1])," + " (1, c, false, EQ, no, Infinity, [1, 0]), (1, c, false, EQ, no, Infinity, [0, 1])," + " (1, c, false, EQ, no, NaN, [1, 0]), (1, c, false, EQ, no, NaN, [0, 1])," + " (1, c, false, LT, yes, Infinity, [1, 0]), (1, c, false, LT, yes, Infinity, [0, 1])," + " (1, c, false, LT, yes, NaN, [1, 0]), (1, c, false, LT, yes, NaN, [0, 1])," + " (1, c, false, LT, no, Infinity, [1, 0]), (1, c, false, LT, no, Infinity, [0, 1])," + " (1, c, false, LT, no, NaN, [1, 0]), (1, c, false, LT, no, NaN, [0, 1])," + " (1, c, true, EQ, yes, Infinity, [1, 0]), (1, c, true, EQ, yes, Infinity, [0, 1])," + " (1, c, true, EQ, yes, NaN, [1, 0]), (1, c, true, EQ, yes, NaN, [0, 1])," + " (1, c, true, EQ, no, Infinity, [1, 0]), (1, c, true, EQ, no, Infinity, [0, 1])," + " (1, c, true, EQ, no, NaN, [1, 0]), (1, c, true, EQ, no, NaN, [0, 1])," + " (1, c, true, LT, yes, Infinity, [1, 0]), (1, c, true, LT, yes, Infinity, [0, 1])," + " (1, c, true, LT, yes, NaN, [1, 0]), (1, c, true, LT, yes, NaN, [0, 1])," + " (1, c, true, LT, no, Infinity, [1, 0]), (1, c, true, LT, no, Infinity, [0, 1])," + " (1, c, true, LT, no, NaN, [1, 0]), (1, c, true, LT, no, NaN, [0, 1])," + " (2, c, false, EQ, yes, Infinity, [1, 0]), (2, c, false, EQ, yes, Infinity, [0, 1])," + " (2, c, false, EQ, yes, NaN, [1, 0]), (2, c, false, EQ, yes, NaN, [0, 1])," + " (2, c, false, EQ, no, Infinity, [1, 0]), (2, c, false, EQ, no, Infinity, [0, 1])," + " (2, c, false, EQ, no, NaN, [1, 0]), (2, c, false, EQ, no, NaN, [0, 1])," + " (2, c, false, LT, yes, Infinity, [1, 0]), (2, c, false, LT, yes, Infinity, [0, 1])," + " (2, c, false, LT, yes, NaN, [1, 0]), (2, c, false, LT, yes, NaN, [0, 1])," + " (2, c, false, LT, no, Infinity, [1, 0]), (2, c, false, LT, no, Infinity, [0, 1])," + " (2, c, false, LT, no, NaN, [1, 0]), (2, c, false, LT, no, NaN, [0, 1])," + " (2, c, true, EQ, yes, Infinity, [1, 0]), (2, c, true, EQ, yes, Infinity, [0, 1])," + " (2, c, true, EQ, yes, NaN, [1, 0]), (2, c, true, EQ, yes, NaN, [0, 1])," + " (2, c, true, EQ, no, Infinity, [1, 0]), (2, c, true, EQ, no, Infinity, [0, 1])," + " (2, c, true, EQ, no, NaN, [1, 0]), (2, c, true, EQ, no, NaN, [0, 1])," + " (2, c, true, LT, yes, Infinity, [1, 0]), (2, c, true, LT, yes, Infinity, [0, 1])," + " (2, c, true, LT, yes, NaN, [1, 0]), (2, c, true, LT, yes, NaN, [0, 1])," + " (2, c, true, LT, no, Infinity, [1, 0]), (2, c, true, LT, no, Infinity, [0, 1])," + " (2, c, true, LT, no, NaN, [1, 0]), (2, c, true, LT, no, NaN, [0, 1])," + " (1, c, false, GT, yes, Infinity, [1, 0]), (1, c, false, GT, yes, Infinity, [0, 1])," + " (1, c, false, GT, yes, NaN, [1, 0]), (1, c, false, GT, yes, NaN, [0, 1])," + " (1, c, false, GT, no, Infinity, [1, 0]), (1, c, false, GT, no, Infinity, [0, 1])," + " (1, c, false, GT, no, NaN, [1, 0]), (1, c, false, GT, no, NaN, [0, 1])," + " (1, c, true, GT, yes, Infinity, [1, 0]), (1, c, true, GT, yes, Infinity, [0, 1])," + " (1, c, true, GT, yes, NaN, [1, 0]), (1, c, true, GT, yes, NaN, [0, 1])," + " (1, c, true, GT, no, Infinity, [1, 0]), (1, c, true, GT, no, Infinity, [0, 1])," + " (1, c, true, GT, no, NaN, [1, 0]), (1, c, true, GT, no, NaN, [0, 1])," + " (2, c, false, GT, yes, Infinity, [1, 0]), (2, c, false, GT, yes, Infinity, [0, 1])," + " (2, c, false, GT, yes, NaN, [1, 0]), (2, c, false, GT, yes, NaN, [0, 1])," + " (2, c, false, GT, no, Infinity, [1, 0]), (2, c, false, GT, no, Infinity, [0, 1])," + " (2, c, false, GT, no, NaN, [1, 0]), (2, c, false, GT, no, NaN, [0, 1])," + " (2, c, true, GT, yes, Infinity, [1, 0]), (2, c, true, GT, yes, Infinity, [0, 1])," + " (2, c, true, GT, yes, NaN, [1, 0]), (2, c, true, GT, yes, NaN, [0, 1])," + " (2, c, true, GT, no, Infinity, [1, 0]), (2, c, true, GT, no, Infinity, [0, 1])," + " (2, c, true, GT, no, NaN, [1, 0]), (2, c, true, GT, no, NaN, [0, 1])," + " (3, a, false, EQ, yes, Infinity, [1, 0]), (3, a, false, EQ, yes, Infinity, [0, 1])," + " (3, a, false, EQ, yes, NaN, [1, 0]), (3, a, false, EQ, yes, NaN, [0, 1])," + " (3, a, false, EQ, no, Infinity, [1, 0]), (3, a, false, EQ, no, Infinity, [0, 1])," + " (3, a, false, EQ, no, NaN, [1, 0]), (3, a, false, EQ, no, NaN, [0, 1])," + " (3, a, false, LT, yes, Infinity, [1, 0]), (3, a, false, LT, yes, Infinity, [0, 1])," + " (3, a, false, LT, yes, NaN, [1, 0]), (3, a, false, LT, yes, NaN, [0, 1])," + " (3, a, false, LT, no, Infinity, [1, 0]), (3, a, false, LT, no, Infinity, [0, 1])," + " (3, a, false, LT, no, NaN, [1, 0]), (3, a, false, LT, no, NaN, [0, 1])," + " (3, a, true, EQ, yes, Infinity, [1, 0]), (3, a, true, EQ, yes, Infinity, [0, 1])," + " (3, a, true, EQ, yes, NaN, [1, 0]), (3, a, true, EQ, yes, NaN, [0, 1])," + " (3, a, true, EQ, no, Infinity, [1, 0]), (3, a, true, EQ, no, Infinity, [0, 1])," + " (3, a, true, EQ, no, NaN, [1, 0]), (3, a, true, EQ, no, NaN, [0, 1])," + " (3, a, true, LT, yes, Infinity, [1, 0]), (3, a, true, LT, yes, Infinity, [0, 1])," + " (3, a, true, LT, yes, NaN, [1, 0]), (3, a, true, LT, yes, NaN, [0, 1])," + " (3, a, true, LT, no, Infinity, [1, 0]), (3, a, true, LT, no, Infinity, [0, 1])," + " (3, a, true, LT, no, NaN, [1, 0]), (3, a, true, LT, no, NaN, [0, 1])," + " (3, b, false, EQ, yes, Infinity, [1, 0]), (3, b, false, EQ, yes, Infinity, [0, 1])," + " (3, b, false, EQ, yes, NaN, [1, 0]), (3, b, false, EQ, yes, NaN, [0, 1])," + " (3, b, false, EQ, no, Infinity, [1, 0]), (3, b, false, EQ, no, Infinity, [0, 1])," + " (3, b, false, EQ, no, NaN, [1, 0]), (3, b, false, EQ, no, NaN, [0, 1])," + " (3, b, false, LT, yes, Infinity, [1, 0]), (3, b, false, LT, yes, Infinity, [0, 1])," + " (3, b, false, LT, yes, NaN, [1, 0]), (3, b, false, LT, yes, NaN, [0, 1])," + " (3, b, false, LT, no, Infinity, [1, 0]), (3, b, false, LT, no, Infinity, [0, 1])," + " (3, b, false, LT, no, NaN, [1, 0]), (3, b, false, LT, no, NaN, [0, 1])," + " (3, b, true, EQ, yes, Infinity, [1, 0]), (3, b, true, EQ, yes, Infinity, [0, 1])," + " (3, b, true, EQ, yes, NaN, [1, 0]), (3, b, true, EQ, yes, NaN, [0, 1])," + " (3, b, true, EQ, no, Infinity, [1, 0]), (3, b, true, EQ, no, Infinity, [0, 1])," + " (3, b, true, EQ, no, NaN, [1, 0]), (3, b, true, EQ, no, NaN, [0, 1])," + " (3, b, true, LT, yes, Infinity, [1, 0]), (3, b, true, LT, yes, Infinity, [0, 1])," + " (3, b, true, LT, yes, NaN, [1, 0]), (3, b, true, LT, yes, NaN, [0, 1])," + " (3, b, true, LT, no, Infinity, [1, 0]), (3, b, true, LT, no, Infinity, [0, 1])," + " (3, b, true, LT, no, NaN, [1, 0]), (3, b, true, LT, no, NaN, [0, 1])," + " (3, a, false, GT, yes, Infinity, [1, 0]), (3, a, false, GT, yes, Infinity, [0, 1])," + " (3, a, false, GT, yes, NaN, [1, 0]), (3, a, false, GT, yes, NaN, [0, 1])," + " (3, a, false, GT, no, Infinity, [1, 0]), (3, a, false, GT, no, Infinity, [0, 1])," + " (3, a, false, GT, no, NaN, [1, 0]), (3, a, false, GT, no, NaN, [0, 1])," + " (3, a, true, GT, yes, Infinity, [1, 0]), (3, a, true, GT, yes, Infinity, [0, 1])," + " (3, a, true, GT, yes, NaN, [1, 0]), (3, a, true, GT, yes, NaN, [0, 1])," + " (3, a, true, GT, no, Infinity, [1, 0]), (3, a, true, GT, no, Infinity, [0, 1])," + " (3, a, true, GT, no, NaN, [1, 0]), (3, a, true, GT, no, NaN, [0, 1])," + " (3, b, false, GT, yes, Infinity, [1, 0]), (3, b, false, GT, yes, Infinity, [0, 1])," + " (3, b, false, GT, yes, NaN, [1, 0]), (3, b, false, GT, yes, NaN, [0, 1])," + " (3, b, false, GT, no, Infinity, [1, 0]), (3, b, false, GT, no, Infinity, [0, 1])," + " (3, b, false, GT, no, NaN, [1, 0]), (3, b, false, GT, no, NaN, [0, 1])," + " (3, b, true, GT, yes, Infinity, [1, 0]), (3, b, true, GT, yes, Infinity, [0, 1])," + " (3, b, true, GT, yes, NaN, [1, 0]), (3, b, true, GT, yes, NaN, [0, 1])," + " (3, b, true, GT, no, Infinity, [1, 0]), (3, b, true, GT, no, Infinity, [0, 1])," + " (3, b, true, GT, no, NaN, [1, 0]), (3, b, true, GT, no, NaN, [0, 1])," + " (3, c, false, EQ, yes, Infinity, [1, 0]), (3, c, false, EQ, yes, Infinity, [0, 1])," + " (3, c, false, EQ, yes, NaN, [1, 0]), (3, c, false, EQ, yes, NaN, [0, 1])," + " (3, c, false, EQ, no, Infinity, [1, 0]), (3, c, false, EQ, no, Infinity, [0, 1])," + " (3, c, false, EQ, no, NaN, [1, 0]), (3, c, false, EQ, no, NaN, [0, 1])," + " (3, c, false, LT, yes, Infinity, [1, 0]), (3, c, false, LT, yes, Infinity, [0, 1])," + " (3, c, false, LT, yes, NaN, [1, 0]), (3, c, false, LT, yes, NaN, [0, 1])," + " (3, c, false, LT, no, Infinity, [1, 0]), (3, c, false, LT, no, Infinity, [0, 1])," + " (3, c, false, LT, no, NaN, [1, 0]), (3, c, false, LT, no, NaN, [0, 1])," + " (3, c, true, EQ, yes, Infinity, [1, 0]), (3, c, true, EQ, yes, Infinity, [0, 1])," + " (3, c, true, EQ, yes, NaN, [1, 0]), (3, c, true, EQ, yes, NaN, [0, 1])," + " (3, c, true, EQ, no, Infinity, [1, 0]), (3, c, true, EQ, no, Infinity, [0, 1])," + " (3, c, true, EQ, no, NaN, [1, 0]), (3, c, true, EQ, no, NaN, [0, 1])," + " (3, c, true, LT, yes, Infinity, [1, 0]), (3, c, true, LT, yes, Infinity, [0, 1])," + " (3, c, true, LT, yes, NaN, [1, 0]), (3, c, true, LT, yes, NaN, [0, 1])," + " (3, c, true, LT, no, Infinity, [1, 0]), (3, c, true, LT, no, Infinity, [0, 1])," + " (3, c, true, LT, no, NaN, [1, 0]), (3, c, true, LT, no, NaN, [0, 1])," + " (3, c, false, GT, yes, Infinity, [1, 0]), (3, c, false, GT, yes, Infinity, [0, 1])," + " (3, c, false, GT, yes, NaN, [1, 0]), (3, c, false, GT, yes, NaN, [0, 1])," + " (3, c, false, GT, no, Infinity, [1, 0]), (3, c, false, GT, no, Infinity, [0, 1])," + " (3, c, false, GT, no, NaN, [1, 0]), (3, c, false, GT, no, NaN, [0, 1])," + " (3, c, true, GT, yes, Infinity, [1, 0]), (3, c, true, GT, yes, Infinity, [0, 1])," + " (3, c, true, GT, yes, NaN, [1, 0]), (3, c, true, GT, yes, NaN, [0, 1])," + " (3, c, true, GT, no, Infinity, [1, 0]), (3, c, true, GT, no, Infinity, [0, 1])," + " (3, c, true, GT, no, NaN, [1, 0]), (3, c, true, GT, no, NaN, [0, 1])]"); aeq(septuples( Arrays.asList(1, 2, null, 4), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), Arrays.asList(x, y) ), "[(1, a, false, EQ, yes, Infinity, [1, 0]), (1, a, false, EQ, yes, Infinity, [0, 1])," + " (1, a, false, EQ, yes, NaN, [1, 0]), (1, a, false, EQ, yes, NaN, [0, 1])," + " (1, a, false, EQ, no, Infinity, [1, 0]), (1, a, false, EQ, no, Infinity, [0, 1])," + " (1, a, false, EQ, no, NaN, [1, 0]), (1, a, false, EQ, no, NaN, [0, 1])," + " (1, a, false, LT, yes, Infinity, [1, 0]), (1, a, false, LT, yes, Infinity, [0, 1])," + " (1, a, false, LT, yes, NaN, [1, 0]), (1, a, false, LT, yes, NaN, [0, 1])," + " (1, a, false, LT, no, Infinity, [1, 0]), (1, a, false, LT, no, Infinity, [0, 1])," + " (1, a, false, LT, no, NaN, [1, 0]), (1, a, false, LT, no, NaN, [0, 1])," + " (1, a, true, EQ, yes, Infinity, [1, 0]), (1, a, true, EQ, yes, Infinity, [0, 1])," + " (1, a, true, EQ, yes, NaN, [1, 0]), (1, a, true, EQ, yes, NaN, [0, 1])," + " (1, a, true, EQ, no, Infinity, [1, 0]), (1, a, true, EQ, no, Infinity, [0, 1])," + " (1, a, true, EQ, no, NaN, [1, 0]), (1, a, true, EQ, no, NaN, [0, 1])," + " (1, a, true, LT, yes, Infinity, [1, 0]), (1, a, true, LT, yes, Infinity, [0, 1])," + " (1, a, true, LT, yes, NaN, [1, 0]), (1, a, true, LT, yes, NaN, [0, 1])," + " (1, a, true, LT, no, Infinity, [1, 0]), (1, a, true, LT, no, Infinity, [0, 1])," + " (1, a, true, LT, no, NaN, [1, 0]), (1, a, true, LT, no, NaN, [0, 1])," + " (1, b, false, EQ, yes, Infinity, [1, 0]), (1, b, false, EQ, yes, Infinity, [0, 1])," + " (1, b, false, EQ, yes, NaN, [1, 0]), (1, b, false, EQ, yes, NaN, [0, 1])," + " (1, b, false, EQ, no, Infinity, [1, 0]), (1, b, false, EQ, no, Infinity, [0, 1])," + " (1, b, false, EQ, no, NaN, [1, 0]), (1, b, false, EQ, no, NaN, [0, 1])," + " (1, b, false, LT, yes, Infinity, [1, 0]), (1, b, false, LT, yes, Infinity, [0, 1])," + " (1, b, false, LT, yes, NaN, [1, 0]), (1, b, false, LT, yes, NaN, [0, 1])," + " (1, b, false, LT, no, Infinity, [1, 0]), (1, b, false, LT, no, Infinity, [0, 1])," + " (1, b, false, LT, no, NaN, [1, 0]), (1, b, false, LT, no, NaN, [0, 1])," + " (1, b, true, EQ, yes, Infinity, [1, 0]), (1, b, true, EQ, yes, Infinity, [0, 1])," + " (1, b, true, EQ, yes, NaN, [1, 0]), (1, b, true, EQ, yes, NaN, [0, 1])," + " (1, b, true, EQ, no, Infinity, [1, 0]), (1, b, true, EQ, no, Infinity, [0, 1])," + " (1, b, true, EQ, no, NaN, [1, 0]), (1, b, true, EQ, no, NaN, [0, 1])," + " (1, b, true, LT, yes, Infinity, [1, 0]), (1, b, true, LT, yes, Infinity, [0, 1])," + " (1, b, true, LT, yes, NaN, [1, 0]), (1, b, true, LT, yes, NaN, [0, 1])," + " (1, b, true, LT, no, Infinity, [1, 0]), (1, b, true, LT, no, Infinity, [0, 1])," + " (1, b, true, LT, no, NaN, [1, 0]), (1, b, true, LT, no, NaN, [0, 1])," + " (2, a, false, EQ, yes, Infinity, [1, 0]), (2, a, false, EQ, yes, Infinity, [0, 1])," + " (2, a, false, EQ, yes, NaN, [1, 0]), (2, a, false, EQ, yes, NaN, [0, 1])," + " (2, a, false, EQ, no, Infinity, [1, 0]), (2, a, false, EQ, no, Infinity, [0, 1])," + " (2, a, false, EQ, no, NaN, [1, 0]), (2, a, false, EQ, no, NaN, [0, 1])," + " (2, a, false, LT, yes, Infinity, [1, 0]), (2, a, false, LT, yes, Infinity, [0, 1])," + " (2, a, false, LT, yes, NaN, [1, 0]), (2, a, false, LT, yes, NaN, [0, 1])," + " (2, a, false, LT, no, Infinity, [1, 0]), (2, a, false, LT, no, Infinity, [0, 1])," + " (2, a, false, LT, no, NaN, [1, 0]), (2, a, false, LT, no, NaN, [0, 1])," + " (2, a, true, EQ, yes, Infinity, [1, 0]), (2, a, true, EQ, yes, Infinity, [0, 1])," + " (2, a, true, EQ, yes, NaN, [1, 0]), (2, a, true, EQ, yes, NaN, [0, 1])," + " (2, a, true, EQ, no, Infinity, [1, 0]), (2, a, true, EQ, no, Infinity, [0, 1])," + " (2, a, true, EQ, no, NaN, [1, 0]), (2, a, true, EQ, no, NaN, [0, 1])," + " (2, a, true, LT, yes, Infinity, [1, 0]), (2, a, true, LT, yes, Infinity, [0, 1])," + " (2, a, true, LT, yes, NaN, [1, 0]), (2, a, true, LT, yes, NaN, [0, 1])," + " (2, a, true, LT, no, Infinity, [1, 0]), (2, a, true, LT, no, Infinity, [0, 1])," + " (2, a, true, LT, no, NaN, [1, 0]), (2, a, true, LT, no, NaN, [0, 1])," + " (2, b, false, EQ, yes, Infinity, [1, 0]), (2, b, false, EQ, yes, Infinity, [0, 1])," + " (2, b, false, EQ, yes, NaN, [1, 0]), (2, b, false, EQ, yes, NaN, [0, 1])," + " (2, b, false, EQ, no, Infinity, [1, 0]), (2, b, false, EQ, no, Infinity, [0, 1])," + " (2, b, false, EQ, no, NaN, [1, 0]), (2, b, false, EQ, no, NaN, [0, 1])," + " (2, b, false, LT, yes, Infinity, [1, 0]), (2, b, false, LT, yes, Infinity, [0, 1])," + " (2, b, false, LT, yes, NaN, [1, 0]), (2, b, false, LT, yes, NaN, [0, 1])," + " (2, b, false, LT, no, Infinity, [1, 0]), (2, b, false, LT, no, Infinity, [0, 1])," + " (2, b, false, LT, no, NaN, [1, 0]), (2, b, false, LT, no, NaN, [0, 1])," + " (2, b, true, EQ, yes, Infinity, [1, 0]), (2, b, true, EQ, yes, Infinity, [0, 1])," + " (2, b, true, EQ, yes, NaN, [1, 0]), (2, b, true, EQ, yes, NaN, [0, 1])," + " (2, b, true, EQ, no, Infinity, [1, 0]), (2, b, true, EQ, no, Infinity, [0, 1])," + " (2, b, true, EQ, no, NaN, [1, 0]), (2, b, true, EQ, no, NaN, [0, 1])," + " (2, b, true, LT, yes, Infinity, [1, 0]), (2, b, true, LT, yes, Infinity, [0, 1])," + " (2, b, true, LT, yes, NaN, [1, 0]), (2, b, true, LT, yes, NaN, [0, 1])," + " (2, b, true, LT, no, Infinity, [1, 0]), (2, b, true, LT, no, Infinity, [0, 1])," + " (2, b, true, LT, no, NaN, [1, 0]), (2, b, true, LT, no, NaN, [0, 1])," + " (1, a, false, GT, yes, Infinity, [1, 0]), (1, a, false, GT, yes, Infinity, [0, 1])," + " (1, a, false, GT, yes, NaN, [1, 0]), (1, a, false, GT, yes, NaN, [0, 1])," + " (1, a, false, GT, no, Infinity, [1, 0]), (1, a, false, GT, no, Infinity, [0, 1])," + " (1, a, false, GT, no, NaN, [1, 0]), (1, a, false, GT, no, NaN, [0, 1])," + " (1, a, true, GT, yes, Infinity, [1, 0]), (1, a, true, GT, yes, Infinity, [0, 1])," + " (1, a, true, GT, yes, NaN, [1, 0]), (1, a, true, GT, yes, NaN, [0, 1])," + " (1, a, true, GT, no, Infinity, [1, 0]), (1, a, true, GT, no, Infinity, [0, 1])," + " (1, a, true, GT, no, NaN, [1, 0]), (1, a, true, GT, no, NaN, [0, 1])," + " (1, b, false, GT, yes, Infinity, [1, 0]), (1, b, false, GT, yes, Infinity, [0, 1])," + " (1, b, false, GT, yes, NaN, [1, 0]), (1, b, false, GT, yes, NaN, [0, 1])," + " (1, b, false, GT, no, Infinity, [1, 0]), (1, b, false, GT, no, Infinity, [0, 1])," + " (1, b, false, GT, no, NaN, [1, 0]), (1, b, false, GT, no, NaN, [0, 1])," + " (1, b, true, GT, yes, Infinity, [1, 0]), (1, b, true, GT, yes, Infinity, [0, 1])," + " (1, b, true, GT, yes, NaN, [1, 0]), (1, b, true, GT, yes, NaN, [0, 1])," + " (1, b, true, GT, no, Infinity, [1, 0]), (1, b, true, GT, no, Infinity, [0, 1])," + " (1, b, true, GT, no, NaN, [1, 0]), (1, b, true, GT, no, NaN, [0, 1])," + " (2, a, false, GT, yes, Infinity, [1, 0]), (2, a, false, GT, yes, Infinity, [0, 1])," + " (2, a, false, GT, yes, NaN, [1, 0]), (2, a, false, GT, yes, NaN, [0, 1])," + " (2, a, false, GT, no, Infinity, [1, 0]), (2, a, false, GT, no, Infinity, [0, 1])," + " (2, a, false, GT, no, NaN, [1, 0]), (2, a, false, GT, no, NaN, [0, 1])," + " (2, a, true, GT, yes, Infinity, [1, 0]), (2, a, true, GT, yes, Infinity, [0, 1])," + " (2, a, true, GT, yes, NaN, [1, 0]), (2, a, true, GT, yes, NaN, [0, 1])," + " (2, a, true, GT, no, Infinity, [1, 0]), (2, a, true, GT, no, Infinity, [0, 1])," + " (2, a, true, GT, no, NaN, [1, 0]), (2, a, true, GT, no, NaN, [0, 1])," + " (2, b, false, GT, yes, Infinity, [1, 0]), (2, b, false, GT, yes, Infinity, [0, 1])," + " (2, b, false, GT, yes, NaN, [1, 0]), (2, b, false, GT, yes, NaN, [0, 1])," + " (2, b, false, GT, no, Infinity, [1, 0]), (2, b, false, GT, no, Infinity, [0, 1])," + " (2, b, false, GT, no, NaN, [1, 0]), (2, b, false, GT, no, NaN, [0, 1])," + " (2, b, true, GT, yes, Infinity, [1, 0]), (2, b, true, GT, yes, Infinity, [0, 1])," + " (2, b, true, GT, yes, NaN, [1, 0]), (2, b, true, GT, yes, NaN, [0, 1])," + " (2, b, true, GT, no, Infinity, [1, 0]), (2, b, true, GT, no, Infinity, [0, 1])," + " (2, b, true, GT, no, NaN, [1, 0]), (2, b, true, GT, no, NaN, [0, 1])," + " (1, c, false, EQ, yes, Infinity, [1, 0]), (1, c, false, EQ, yes, Infinity, [0, 1])," + " (1, c, false, EQ, yes, NaN, [1, 0]), (1, c, false, EQ, yes, NaN, [0, 1])," + " (1, c, false, EQ, no, Infinity, [1, 0]), (1, c, false, EQ, no, Infinity, [0, 1])," + " (1, c, false, EQ, no, NaN, [1, 0]), (1, c, false, EQ, no, NaN, [0, 1])," + " (1, c, false, LT, yes, Infinity, [1, 0]), (1, c, false, LT, yes, Infinity, [0, 1])," + " (1, c, false, LT, yes, NaN, [1, 0]), (1, c, false, LT, yes, NaN, [0, 1])," + " (1, c, false, LT, no, Infinity, [1, 0]), (1, c, false, LT, no, Infinity, [0, 1])," + " (1, c, false, LT, no, NaN, [1, 0]), (1, c, false, LT, no, NaN, [0, 1])," + " (1, c, true, EQ, yes, Infinity, [1, 0]), (1, c, true, EQ, yes, Infinity, [0, 1])," + " (1, c, true, EQ, yes, NaN, [1, 0]), (1, c, true, EQ, yes, NaN, [0, 1])," + " (1, c, true, EQ, no, Infinity, [1, 0]), (1, c, true, EQ, no, Infinity, [0, 1])," + " (1, c, true, EQ, no, NaN, [1, 0]), (1, c, true, EQ, no, NaN, [0, 1])," + " (1, c, true, LT, yes, Infinity, [1, 0]), (1, c, true, LT, yes, Infinity, [0, 1])," + " (1, c, true, LT, yes, NaN, [1, 0]), (1, c, true, LT, yes, NaN, [0, 1])," + " (1, c, true, LT, no, Infinity, [1, 0]), (1, c, true, LT, no, Infinity, [0, 1])," + " (1, c, true, LT, no, NaN, [1, 0]), (1, c, true, LT, no, NaN, [0, 1])," + " (1, d, false, EQ, yes, Infinity, [1, 0]), (1, d, false, EQ, yes, Infinity, [0, 1])," + " (1, d, false, EQ, yes, NaN, [1, 0]), (1, d, false, EQ, yes, NaN, [0, 1])," + " (1, d, false, EQ, no, Infinity, [1, 0]), (1, d, false, EQ, no, Infinity, [0, 1])," + " (1, d, false, EQ, no, NaN, [1, 0]), (1, d, false, EQ, no, NaN, [0, 1])," + " (1, d, false, LT, yes, Infinity, [1, 0]), (1, d, false, LT, yes, Infinity, [0, 1])," + " (1, d, false, LT, yes, NaN, [1, 0]), (1, d, false, LT, yes, NaN, [0, 1])," + " (1, d, false, LT, no, Infinity, [1, 0]), (1, d, false, LT, no, Infinity, [0, 1])," + " (1, d, false, LT, no, NaN, [1, 0]), (1, d, false, LT, no, NaN, [0, 1])," + " (1, d, true, EQ, yes, Infinity, [1, 0]), (1, d, true, EQ, yes, Infinity, [0, 1])," + " (1, d, true, EQ, yes, NaN, [1, 0]), (1, d, true, EQ, yes, NaN, [0, 1])," + " (1, d, true, EQ, no, Infinity, [1, 0]), (1, d, true, EQ, no, Infinity, [0, 1])," + " (1, d, true, EQ, no, NaN, [1, 0]), (1, d, true, EQ, no, NaN, [0, 1])," + " (1, d, true, LT, yes, Infinity, [1, 0]), (1, d, true, LT, yes, Infinity, [0, 1])," + " (1, d, true, LT, yes, NaN, [1, 0]), (1, d, true, LT, yes, NaN, [0, 1])," + " (1, d, true, LT, no, Infinity, [1, 0]), (1, d, true, LT, no, Infinity, [0, 1])," + " (1, d, true, LT, no, NaN, [1, 0]), (1, d, true, LT, no, NaN, [0, 1])," + " (2, c, false, EQ, yes, Infinity, [1, 0]), (2, c, false, EQ, yes, Infinity, [0, 1])," + " (2, c, false, EQ, yes, NaN, [1, 0]), (2, c, false, EQ, yes, NaN, [0, 1])," + " (2, c, false, EQ, no, Infinity, [1, 0]), (2, c, false, EQ, no, Infinity, [0, 1])," + " (2, c, false, EQ, no, NaN, [1, 0]), (2, c, false, EQ, no, NaN, [0, 1])," + " (2, c, false, LT, yes, Infinity, [1, 0]), (2, c, false, LT, yes, Infinity, [0, 1])," + " (2, c, false, LT, yes, NaN, [1, 0]), (2, c, false, LT, yes, NaN, [0, 1])," + " (2, c, false, LT, no, Infinity, [1, 0]), (2, c, false, LT, no, Infinity, [0, 1])," + " (2, c, false, LT, no, NaN, [1, 0]), (2, c, false, LT, no, NaN, [0, 1])," + " (2, c, true, EQ, yes, Infinity, [1, 0]), (2, c, true, EQ, yes, Infinity, [0, 1])," + " (2, c, true, EQ, yes, NaN, [1, 0]), (2, c, true, EQ, yes, NaN, [0, 1])," + " (2, c, true, EQ, no, Infinity, [1, 0]), (2, c, true, EQ, no, Infinity, [0, 1])," + " (2, c, true, EQ, no, NaN, [1, 0]), (2, c, true, EQ, no, NaN, [0, 1])," + " (2, c, true, LT, yes, Infinity, [1, 0]), (2, c, true, LT, yes, Infinity, [0, 1])," + " (2, c, true, LT, yes, NaN, [1, 0]), (2, c, true, LT, yes, NaN, [0, 1])," + " (2, c, true, LT, no, Infinity, [1, 0]), (2, c, true, LT, no, Infinity, [0, 1])," + " (2, c, true, LT, no, NaN, [1, 0]), (2, c, true, LT, no, NaN, [0, 1])," + " (2, d, false, EQ, yes, Infinity, [1, 0]), (2, d, false, EQ, yes, Infinity, [0, 1])," + " (2, d, false, EQ, yes, NaN, [1, 0]), (2, d, false, EQ, yes, NaN, [0, 1])," + " (2, d, false, EQ, no, Infinity, [1, 0]), (2, d, false, EQ, no, Infinity, [0, 1])," + " (2, d, false, EQ, no, NaN, [1, 0]), (2, d, false, EQ, no, NaN, [0, 1])," + " (2, d, false, LT, yes, Infinity, [1, 0]), (2, d, false, LT, yes, Infinity, [0, 1])," + " (2, d, false, LT, yes, NaN, [1, 0]), (2, d, false, LT, yes, NaN, [0, 1])," + " (2, d, false, LT, no, Infinity, [1, 0]), (2, d, false, LT, no, Infinity, [0, 1])," + " (2, d, false, LT, no, NaN, [1, 0]), (2, d, false, LT, no, NaN, [0, 1])," + " (2, d, true, EQ, yes, Infinity, [1, 0]), (2, d, true, EQ, yes, Infinity, [0, 1])," + " (2, d, true, EQ, yes, NaN, [1, 0]), (2, d, true, EQ, yes, NaN, [0, 1])," + " (2, d, true, EQ, no, Infinity, [1, 0]), (2, d, true, EQ, no, Infinity, [0, 1])," + " (2, d, true, EQ, no, NaN, [1, 0]), (2, d, true, EQ, no, NaN, [0, 1])," + " (2, d, true, LT, yes, Infinity, [1, 0]), (2, d, true, LT, yes, Infinity, [0, 1])," + " (2, d, true, LT, yes, NaN, [1, 0]), (2, d, true, LT, yes, NaN, [0, 1])," + " (2, d, true, LT, no, Infinity, [1, 0]), (2, d, true, LT, no, Infinity, [0, 1])," + " (2, d, true, LT, no, NaN, [1, 0]), (2, d, true, LT, no, NaN, [0, 1])," + " (1, c, false, GT, yes, Infinity, [1, 0]), (1, c, false, GT, yes, Infinity, [0, 1])," + " (1, c, false, GT, yes, NaN, [1, 0]), (1, c, false, GT, yes, NaN, [0, 1])," + " (1, c, false, GT, no, Infinity, [1, 0]), (1, c, false, GT, no, Infinity, [0, 1])," + " (1, c, false, GT, no, NaN, [1, 0]), (1, c, false, GT, no, NaN, [0, 1])," + " (1, c, true, GT, yes, Infinity, [1, 0]), (1, c, true, GT, yes, Infinity, [0, 1])," + " (1, c, true, GT, yes, NaN, [1, 0]), (1, c, true, GT, yes, NaN, [0, 1])," + " (1, c, true, GT, no, Infinity, [1, 0]), (1, c, true, GT, no, Infinity, [0, 1])," + " (1, c, true, GT, no, NaN, [1, 0]), (1, c, true, GT, no, NaN, [0, 1])," + " (1, d, false, GT, yes, Infinity, [1, 0]), (1, d, false, GT, yes, Infinity, [0, 1])," + " (1, d, false, GT, yes, NaN, [1, 0]), (1, d, false, GT, yes, NaN, [0, 1])," + " (1, d, false, GT, no, Infinity, [1, 0]), (1, d, false, GT, no, Infinity, [0, 1])," + " (1, d, false, GT, no, NaN, [1, 0]), (1, d, false, GT, no, NaN, [0, 1])," + " (1, d, true, GT, yes, Infinity, [1, 0]), (1, d, true, GT, yes, Infinity, [0, 1])," + " (1, d, true, GT, yes, NaN, [1, 0]), (1, d, true, GT, yes, NaN, [0, 1])," + " (1, d, true, GT, no, Infinity, [1, 0]), (1, d, true, GT, no, Infinity, [0, 1])," + " (1, d, true, GT, no, NaN, [1, 0]), (1, d, true, GT, no, NaN, [0, 1])," + " (2, c, false, GT, yes, Infinity, [1, 0]), (2, c, false, GT, yes, Infinity, [0, 1])," + " (2, c, false, GT, yes, NaN, [1, 0]), (2, c, false, GT, yes, NaN, [0, 1])," + " (2, c, false, GT, no, Infinity, [1, 0]), (2, c, false, GT, no, Infinity, [0, 1])," + " (2, c, false, GT, no, NaN, [1, 0]), (2, c, false, GT, no, NaN, [0, 1])," + " (2, c, true, GT, yes, Infinity, [1, 0]), (2, c, true, GT, yes, Infinity, [0, 1])," + " (2, c, true, GT, yes, NaN, [1, 0]), (2, c, true, GT, yes, NaN, [0, 1])," + " (2, c, true, GT, no, Infinity, [1, 0]), (2, c, true, GT, no, Infinity, [0, 1])," + " (2, c, true, GT, no, NaN, [1, 0]), (2, c, true, GT, no, NaN, [0, 1])," + " (2, d, false, GT, yes, Infinity, [1, 0]), (2, d, false, GT, yes, Infinity, [0, 1])," + " (2, d, false, GT, yes, NaN, [1, 0]), (2, d, false, GT, yes, NaN, [0, 1])," + " (2, d, false, GT, no, Infinity, [1, 0]), (2, d, false, GT, no, Infinity, [0, 1])," + " (2, d, false, GT, no, NaN, [1, 0]), (2, d, false, GT, no, NaN, [0, 1])," + " (2, d, true, GT, yes, Infinity, [1, 0]), (2, d, true, GT, yes, Infinity, [0, 1])," + " (2, d, true, GT, yes, NaN, [1, 0]), (2, d, true, GT, yes, NaN, [0, 1])," + " (2, d, true, GT, no, Infinity, [1, 0]), (2, d, true, GT, no, Infinity, [0, 1])," + " (2, d, true, GT, no, NaN, [1, 0]), (2, d, true, GT, no, NaN, [0, 1])," + " (null, a, false, EQ, yes, Infinity, [1, 0]), (null, a, false, EQ, yes, Infinity, [0, 1])," + " (null, a, false, EQ, yes, NaN, [1, 0]), (null, a, false, EQ, yes, NaN, [0, 1])," + " (null, a, false, EQ, no, Infinity, [1, 0]), (null, a, false, EQ, no, Infinity, [0, 1])," + " (null, a, false, EQ, no, NaN, [1, 0]), (null, a, false, EQ, no, NaN, [0, 1])," + " (null, a, false, LT, yes, Infinity, [1, 0]), (null, a, false, LT, yes, Infinity, [0, 1])," + " (null, a, false, LT, yes, NaN, [1, 0]), (null, a, false, LT, yes, NaN, [0, 1])," + " (null, a, false, LT, no, Infinity, [1, 0]), (null, a, false, LT, no, Infinity, [0, 1])," + " (null, a, false, LT, no, NaN, [1, 0]), (null, a, false, LT, no, NaN, [0, 1])," + " (null, a, true, EQ, yes, Infinity, [1, 0]), (null, a, true, EQ, yes, Infinity, [0, 1])," + " (null, a, true, EQ, yes, NaN, [1, 0]), (null, a, true, EQ, yes, NaN, [0, 1])," + " (null, a, true, EQ, no, Infinity, [1, 0]), (null, a, true, EQ, no, Infinity, [0, 1])," + " (null, a, true, EQ, no, NaN, [1, 0]), (null, a, true, EQ, no, NaN, [0, 1])," + " (null, a, true, LT, yes, Infinity, [1, 0]), (null, a, true, LT, yes, Infinity, [0, 1])," + " (null, a, true, LT, yes, NaN, [1, 0]), (null, a, true, LT, yes, NaN, [0, 1])," + " (null, a, true, LT, no, Infinity, [1, 0]), (null, a, true, LT, no, Infinity, [0, 1])," + " (null, a, true, LT, no, NaN, [1, 0]), (null, a, true, LT, no, NaN, [0, 1])," + " (null, b, false, EQ, yes, Infinity, [1, 0]), (null, b, false, EQ, yes, Infinity, [0, 1])," + " (null, b, false, EQ, yes, NaN, [1, 0]), (null, b, false, EQ, yes, NaN, [0, 1])," + " (null, b, false, EQ, no, Infinity, [1, 0]), (null, b, false, EQ, no, Infinity, [0, 1])," + " (null, b, false, EQ, no, NaN, [1, 0]), (null, b, false, EQ, no, NaN, [0, 1])," + " (null, b, false, LT, yes, Infinity, [1, 0]), (null, b, false, LT, yes, Infinity, [0, 1])," + " (null, b, false, LT, yes, NaN, [1, 0]), (null, b, false, LT, yes, NaN, [0, 1])," + " (null, b, false, LT, no, Infinity, [1, 0]), (null, b, false, LT, no, Infinity, [0, 1]), (null, b, false, LT, no, NaN, [1, 0]), (null, b, false, LT, no, NaN, [0, 1]), (null, b, true, EQ, yes, Infinity, [1, 0]), (null, b, true, EQ, yes, Infinity, [0, 1]), (null, b, true, EQ, yes, NaN, [1, 0]), (null, b, true, EQ, yes, NaN, [0, 1]), (null, b, true, EQ, no, Infinity, [1, 0]), (null, b, true, EQ, no, Infinity, [0, 1]), (null, b, true, EQ, no, NaN, [1, 0]), (null, b, true, EQ, no, NaN, [0, 1]), (null, b, true, LT, yes, Infinity, [1, 0]), (null, b, true, LT, yes, Infinity, [0, 1]), (null, b, true, LT, yes, NaN, [1, 0]), (null, b, true, LT, yes, NaN, [0, 1]), (null, b, true, LT, no, Infinity, [1, 0]), (null, b, true, LT, no, Infinity, [0, 1]), (null, b, true, LT, no, NaN, [1, 0]), (null, b, true, LT, no, NaN, [0, 1]), (4, a, false, EQ, yes, Infinity, [1, 0]), (4, a, false, EQ, yes, Infinity, [0, 1]), (4, a, false, EQ, yes, NaN, [1, 0]), (4, a, false, EQ, yes, NaN, [0, 1]), (4, a, false, EQ, no, Infinity, [1, 0]), (4, a, false, EQ, no, Infinity, [0, 1]), (4, a, false, EQ, no, NaN, [1, 0]), (4, a, false, EQ, no, NaN, [0, 1]), (4, a, false, LT, yes, Infinity, [1, 0]), (4, a, false, LT, yes, Infinity, [0, 1]), (4, a, false, LT, yes, NaN, [1, 0]), (4, a, false, LT, yes, NaN, [0, 1]), (4, a, false, LT, no, Infinity, [1, 0]), (4, a, false, LT, no, Infinity, [0, 1]), (4, a, false, LT, no, NaN, [1, 0]), (4, a, false, LT, no, NaN, [0, 1]), (4, a, true, EQ, yes, Infinity, [1, 0]), (4, a, true, EQ, yes, Infinity, [0, 1]), (4, a, true, EQ, yes, NaN, [1, 0]), (4, a, true, EQ, yes, NaN, [0, 1]), (4, a, true, EQ, no, Infinity, [1, 0]), (4, a, true, EQ, no, Infinity, [0, 1]), (4, a, true, EQ, no, NaN, [1, 0]), (4, a, true, EQ, no, NaN, [0, 1]), (4, a, true, LT, yes, Infinity, [1, 0]), (4, a, true, LT, yes, Infinity, [0, 1]), (4, a, true, LT, yes, NaN, [1, 0]), (4, a, true, LT, yes, NaN, [0, 1]), (4, a, true, LT, no, Infinity, [1, 0]), (4, a, true, LT, no, Infinity, [0, 1]), (4, a, true, LT, no, NaN, [1, 0]), (4, a, true, LT, no, NaN, [0, 1]), (4, b, false, EQ, yes, Infinity, [1, 0]), (4, b, false, EQ, yes, Infinity, [0, 1]), (4, b, false, EQ, yes, NaN, [1, 0]), (4, b, false, EQ, yes, NaN, [0, 1]), (4, b, false, EQ, no, Infinity, [1, 0]), (4, b, false, EQ, no, Infinity, [0, 1]), (4, b, false, EQ, no, NaN, [1, 0]), (4, b, false, EQ, no, NaN, [0, 1]), (4, b, false, LT, yes, Infinity, [1, 0]), (4, b, false, LT, yes, Infinity, [0, 1]), (4, b, false, LT, yes, NaN, [1, 0]), (4, b, false, LT, yes, NaN, [0, 1]), (4, b, false, LT, no, Infinity, [1, 0]), (4, b, false, LT, no, Infinity, [0, 1]), (4, b, false, LT, no, NaN, [1, 0]), (4, b, false, LT, no, NaN, [0, 1]), (4, b, true, EQ, yes, Infinity, [1, 0]), (4, b, true, EQ, yes, Infinity, [0, 1]), (4, b, true, EQ, yes, NaN, [1, 0]), (4, b, true, EQ, yes, NaN, [0, 1]), (4, b, true, EQ, no, Infinity, [1, 0]), (4, b, true, EQ, no, Infinity, [0, 1]), (4, b, true, EQ, no, NaN, [1, 0]), (4, b, true, EQ, no, NaN, [0, 1]), (4, b, true, LT, yes, Infinity, [1, 0]), (4, b, true, LT, yes, Infinity, [0, 1]), (4, b, true, LT, yes, NaN, [1, 0]), (4, b, true, LT, yes, NaN, [0, 1]), (4, b, true, LT, no, Infinity, [1, 0]), (4, b, true, LT, no, Infinity, [0, 1]), (4, b, true, LT, no, NaN, [1, 0]), (4, b, true, LT, no, NaN, [0, 1]), (null, a, false, GT, yes, Infinity, [1, 0]), (null, a, false, GT, yes, Infinity, [0, 1]), (null, a, false, GT, yes, NaN, [1, 0]), (null, a, false, GT, yes, NaN, [0, 1]), (null, a, false, GT, no, Infinity, [1, 0]), (null, a, false, GT, no, Infinity, [0, 1]), (null, a, false, GT, no, NaN, [1, 0]), (null, a, false, GT, no, NaN, [0, 1]), (null, a, true, GT, yes, Infinity, [1, 0]), (null, a, true, GT, yes, Infinity, [0, 1]), (null, a, true, GT, yes, NaN, [1, 0]), (null, a, true, GT, yes, NaN, [0, 1]), (null, a, true, GT, no, Infinity, [1, 0]), (null, a, true, GT, no, Infinity, [0, 1]), (null, a, true, GT, no, NaN, [1, 0]), (null, a, true, GT, no, NaN, [0, 1]), (null, b, false, GT, yes, Infinity, [1, 0]), (null, b, false, GT, yes, Infinity, [0, 1]), (null, b, false, GT, yes, NaN, [1, 0]), (null, b, false, GT, yes, NaN, [0, 1]), (null, b, false, GT, no, Infinity, [1, 0]), (null, b, false, GT, no, Infinity, [0, 1]), (null, b, false, GT, no, NaN, [1, 0]), (null, b, false, GT, no, NaN, [0, 1]), (null, b, true, GT, yes, Infinity, [1, 0]), (null, b, true, GT, yes, Infinity, [0, 1]), (null, b, true, GT, yes, NaN, [1, 0]), (null, b, true, GT, yes, NaN, [0, 1]), (null, b, true, GT, no, Infinity, [1, 0]), (null, b, true, GT, no, Infinity, [0, 1]), (null, b, true, GT, no, NaN, [1, 0]), (null, b, true, GT, no, NaN, [0, 1]), (4, a, false, GT, yes, Infinity, [1, 0]), (4, a, false, GT, yes, Infinity, [0, 1]), (4, a, false, GT, yes, NaN, [1, 0]), (4, a, false, GT, yes, NaN, [0, 1]), (4, a, false, GT, no, Infinity, [1, 0]), (4, a, false, GT, no, Infinity, [0, 1]), (4, a, false, GT, no, NaN, [1, 0]), (4, a, false, GT, no, NaN, [0, 1]), (4, a, true, GT, yes, Infinity, [1, 0]), (4, a, true, GT, yes, Infinity, [0, 1]), (4, a, true, GT, yes, NaN, [1, 0]), (4, a, true, GT, yes, NaN, [0, 1]), (4, a, true, GT, no, Infinity, [1, 0]), (4, a, true, GT, no, Infinity, [0, 1]), (4, a, true, GT, no, NaN, [1, 0]), (4, a, true, GT, no, NaN, [0, 1]), (4, b, false, GT, yes, Infinity, [1, 0]), (4, b, false, GT, yes, Infinity, [0, 1]), (4, b, false, GT, yes, NaN, [1, 0]), (4, b, false, GT, yes, NaN, [0, 1]), (4, b, false, GT, no, Infinity, [1, 0]), (4, b, false, GT, no, Infinity, [0, 1]), (4, b, false, GT, no, NaN, [1, 0]), (4, b, false, GT, no, NaN, [0, 1]), (4, b, true, GT, yes, Infinity, [1, 0]), (4, b, true, GT, yes, Infinity, [0, 1]), (4, b, true, GT, yes, NaN, [1, 0]), (4, b, true, GT, yes, NaN, [0, 1]), (4, b, true, GT, no, Infinity, [1, 0]), (4, b, true, GT, no, Infinity, [0, 1]), (4, b, true, GT, no, NaN, [1, 0]), (4, b, true, GT, no, NaN, [0, 1]), (null, c, false, EQ, yes, Infinity, [1, 0]), (null, c, false, EQ, yes, Infinity, [0, 1]), (null, c, false, EQ, yes, NaN, [1, 0]), (null, c, false, EQ, yes, NaN, [0, 1]), (null, c, false, EQ, no, Infinity, [1, 0]), (null, c, false, EQ, no, Infinity, [0, 1]), (null, c, false, EQ, no, NaN, [1, 0]), (null, c, false, EQ, no, NaN, [0, 1]), (null, c, false, LT, yes, Infinity, [1, 0]), (null, c, false, LT, yes, Infinity, [0, 1]), (null, c, false, LT, yes, NaN, [1, 0]), (null, c, false, LT, yes, NaN, [0, 1]), (null, c, false, LT, no, Infinity, [1, 0]), (null, c, false, LT, no, Infinity, [0, 1]), (null, c, false, LT, no, NaN, [1, 0]), (null, c, false, LT, no, NaN, [0, 1]), (null, c, true, EQ, yes, Infinity, [1, 0]), (null, c, true, EQ, yes, Infinity, [0, 1]), (null, c, true, EQ, yes, NaN, [1, 0]), (null, c, true, EQ, yes, NaN, [0, 1]), (null, c, true, EQ, no, Infinity, [1, 0]), (null, c, true, EQ, no, Infinity, [0, 1]), (null, c, true, EQ, no, NaN, [1, 0]), (null, c, true, EQ, no, NaN, [0, 1]), (null, c, true, LT, yes, Infinity, [1, 0]), (null, c, true, LT, yes, Infinity, [0, 1]), (null, c, true, LT, yes, NaN, [1, 0]), (null, c, true, LT, yes, NaN, [0, 1]), (null, c, true, LT, no, Infinity, [1, 0]), (null, c, true, LT, no, Infinity, [0, 1]), (null, c, true, LT, no, NaN, [1, 0]), (null, c, true, LT, no, NaN, [0, 1]), (null, d, false, EQ, yes, Infinity, [1, 0]), (null, d, false, EQ, yes, Infinity, [0, 1]), (null, d, false, EQ, yes, NaN, [1, 0]), (null, d, false, EQ, yes, NaN, [0, 1]), (null, d, false, EQ, no, Infinity, [1, 0]), (null, d, false, EQ, no, Infinity, [0, 1]), (null, d, false, EQ, no, NaN, [1, 0]), (null, d, false, EQ, no, NaN, [0, 1]), (null, d, false, LT, yes, Infinity, [1, 0]), (null, d, false, LT, yes, Infinity, [0, 1]), (null, d, false, LT, yes, NaN, [1, 0]), (null, d, false, LT, yes, NaN, [0, 1]), (null, d, false, LT, no, Infinity, [1, 0]), (null, d, false, LT, no, Infinity, [0, 1]), (null, d, false, LT, no, NaN, [1, 0]), (null, d, false, LT, no, NaN, [0, 1]), (null, d, true, EQ, yes, Infinity, [1, 0]), (null, d, true, EQ, yes, Infinity, [0, 1]), (null, d, true, EQ, yes, NaN, [1, 0]), (null, d, true, EQ, yes, NaN, [0, 1]), (null, d, true, EQ, no, Infinity, [1, 0]), (null, d, true, EQ, no, Infinity, [0, 1]), (null, d, true, EQ, no, NaN, [1, 0]), (null, d, true, EQ, no, NaN, [0, 1]), (null, d, true, LT, yes, Infinity, [1, 0]), (null, d, true, LT, yes, Infinity, [0, 1]), (null, d, true, LT, yes, NaN, [1, 0]), (null, d, true, LT, yes, NaN, [0, 1]), (null, d, true, LT, no, Infinity, [1, 0]), (null, d, true, LT, no, Infinity, [0, 1]), (null, d, true, LT, no, NaN, [1, 0]), (null, d, true, LT, no, NaN, [0, 1]), (4, c, false, EQ, yes, Infinity, [1, 0]), (4, c, false, EQ, yes, Infinity, [0, 1]), (4, c, false, EQ, yes, NaN, [1, 0]), (4, c, false, EQ, yes, NaN, [0, 1]), (4, c, false, EQ, no, Infinity, [1, 0]), (4, c, false, EQ, no, Infinity, [0, 1]), (4, c, false, EQ, no, NaN, [1, 0]), (4, c, false, EQ, no, NaN, [0, 1]), (4, c, false, LT, yes, Infinity, [1, 0]), (4, c, false, LT, yes, Infinity, [0, 1]), (4, c, false, LT, yes, NaN, [1, 0]), (4, c, false, LT, yes, NaN, [0, 1]), (4, c, false, LT, no, Infinity, [1, 0]), (4, c, false, LT, no, Infinity, [0, 1]), (4, c, false, LT, no, NaN, [1, 0]), (4, c, false, LT, no, NaN, [0, 1]), (4, c, true, EQ, yes, Infinity, [1, 0]), (4, c, true, EQ, yes, Infinity, [0, 1]), (4, c, true, EQ, yes, NaN, [1, 0]), (4, c, true, EQ, yes, NaN, [0, 1]), (4, c, true, EQ, no, Infinity, [1, 0]), (4, c, true, EQ, no, Infinity, [0, 1]), (4, c, true, EQ, no, NaN, [1, 0]), (4, c, true, EQ, no, NaN, [0, 1]), (4, c, true, LT, yes, Infinity, [1, 0]), (4, c, true, LT, yes, Infinity, [0, 1]), (4, c, true, LT, yes, NaN, [1, 0]), (4, c, true, LT, yes, NaN, [0, 1]), (4, c, true, LT, no, Infinity, [1, 0]), (4, c, true, LT, no, Infinity, [0, 1]), (4, c, true, LT, no, NaN, [1, 0]), (4, c, true, LT, no, NaN, [0, 1]), (4, d, false, EQ, yes, Infinity, [1, 0]), (4, d, false, EQ, yes, Infinity, [0, 1]), (4, d, false, EQ, yes, NaN, [1, 0]), (4, d, false, EQ, yes, NaN, [0, 1]), (4, d, false, EQ, no, Infinity, [1, 0]), (4, d, false, EQ, no, Infinity, [0, 1]), (4, d, false, EQ, no, NaN, [1, 0]), (4, d, false, EQ, no, NaN, [0, 1]), (4, d, false, LT, yes, Infinity, [1, 0]), (4, d, false, LT, yes, Infinity, [0, 1]), (4, d, false, LT, yes, NaN, [1, 0]), (4, d, false, LT, yes, NaN, [0, 1]), (4, d, false, LT, no, Infinity, [1, 0]), (4, d, false, LT, no, Infinity, [0, 1]), (4, d, false, LT, no, NaN, [1, 0]), (4, d, false, LT, no, NaN, [0, 1]), (4, d, true, EQ, yes, Infinity, [1, 0]), (4, d, true, EQ, yes, Infinity, [0, 1]), (4, d, true, EQ, yes, NaN, [1, 0]), (4, d, true, EQ, yes, NaN, [0, 1]), (4, d, true, EQ, no, Infinity, [1, 0]), (4, d, true, EQ, no, Infinity, [0, 1]), (4, d, true, EQ, no, NaN, [1, 0]), (4, d, true, EQ, no, NaN, [0, 1]), (4, d, true, LT, yes, Infinity, [1, 0]), (4, d, true, LT, yes, Infinity, [0, 1]), (4, d, true, LT, yes, NaN, [1, 0]), (4, d, true, LT, yes, NaN, [0, 1]), (4, d, true, LT, no, Infinity, [1, 0]), (4, d, true, LT, no, Infinity, [0, 1]), (4, d, true, LT, no, NaN, [1, 0]), (4, d, true, LT, no, NaN, [0, 1]), (null, c, false, GT, yes, Infinity, [1, 0]), (null, c, false, GT, yes, Infinity, [0, 1]), (null, c, false, GT, yes, NaN, [1, 0]), (null, c, false, GT, yes, NaN, [0, 1]), (null, c, false, GT, no, Infinity, [1, 0]), (null, c, false, GT, no, Infinity, [0, 1]), (null, c, false, GT, no, NaN, [1, 0]), (null, c, false, GT, no, NaN, [0, 1]), (null, c, true, GT, yes, Infinity, [1, 0]), (null, c, true, GT, yes, Infinity, [0, 1]), (null, c, true, GT, yes, NaN, [1, 0]), (null, c, true, GT, yes, NaN, [0, 1]), (null, c, true, GT, no, Infinity, [1, 0]), (null, c, true, GT, no, Infinity, [0, 1]), (null, c, true, GT, no, NaN, [1, 0]), (null, c, true, GT, no, NaN, [0, 1]), (null, d, false, GT, yes, Infinity, [1, 0]), (null, d, false, GT, yes, Infinity, [0, 1]), (null, d, false, GT, yes, NaN, [1, 0]), (null, d, false, GT, yes, NaN, [0, 1]), (null, d, false, GT, no, Infinity, [1, 0]), (null, d, false, GT, no, Infinity, [0, 1]), (null, d, false, GT, no, NaN, [1, 0]), (null, d, false, GT, no, NaN, [0, 1]), (null, d, true, GT, yes, Infinity, [1, 0]), (null, d, true, GT, yes, Infinity, [0, 1]), (null, d, true, GT, yes, NaN, [1, 0]), (null, d, true, GT, yes, NaN, [0, 1]), (null, d, true, GT, no, Infinity, [1, 0]), (null, d, true, GT, no, Infinity, [0, 1]), (null, d, true, GT, no, NaN, [1, 0]), (null, d, true, GT, no, NaN, [0, 1]), (4, c, false, GT, yes, Infinity, [1, 0]), (4, c, false, GT, yes, Infinity, [0, 1]), (4, c, false, GT, yes, NaN, [1, 0]), (4, c, false, GT, yes, NaN, [0, 1]), (4, c, false, GT, no, Infinity, [1, 0]), (4, c, false, GT, no, Infinity, [0, 1]), (4, c, false, GT, no, NaN, [1, 0]), (4, c, false, GT, no, NaN, [0, 1]), (4, c, true, GT, yes, Infinity, [1, 0]), (4, c, true, GT, yes, Infinity, [0, 1]), (4, c, true, GT, yes, NaN, [1, 0]), (4, c, true, GT, yes, NaN, [0, 1]), (4, c, true, GT, no, Infinity, [1, 0]), (4, c, true, GT, no, Infinity, [0, 1]), (4, c, true, GT, no, NaN, [1, 0]), (4, c, true, GT, no, NaN, [0, 1]), (4, d, false, GT, yes, Infinity, [1, 0]), (4, d, false, GT, yes, Infinity, [0, 1]), (4, d, false, GT, yes, NaN, [1, 0]), (4, d, false, GT, yes, NaN, [0, 1]), (4, d, false, GT, no, Infinity, [1, 0]), (4, d, false, GT, no, Infinity, [0, 1]), (4, d, false, GT, no, NaN, [1, 0]), (4, d, false, GT, no, NaN, [0, 1]), (4, d, true, GT, yes, Infinity, [1, 0]), (4, d, true, GT, yes, Infinity, [0, 1]), (4, d, true, GT, yes, NaN, [1, 0]), (4, d, true, GT, yes, NaN, [0, 1]), (4, d, true, GT, no, Infinity, [1, 0]), (4, d, true, GT, no, Infinity, [0, 1]), (4, d, true, GT, no, NaN, [1, 0]), (4, d, true, GT, no, NaN, [0, 1])]"); aeq(septuples( new ArrayList<Integer>(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), Arrays.asList(x, y) ), "[]"); aeq(septuples( new ArrayList<Integer>(), new ArrayList<Character>(), new ArrayList<Boolean>(), new ArrayList<Ordering>(), new ArrayList<String>(), new ArrayList<Float>(), new ArrayList<List<Integer>>() ), "[]"); aeq(take(20, septuples( P.naturalBigIntegers(), fromString("abcd"), P.booleans(), P.orderings(), Arrays.asList("yes", "no"), (List<Float>) Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), Arrays.asList(x, y) )), "[(0, a, false, EQ, yes, Infinity, [1, 0]), (0, a, false, EQ, yes, Infinity, [0, 1])," + " (0, a, false, EQ, yes, NaN, [1, 0]), (0, a, false, EQ, yes, NaN, [0, 1])," + " (0, a, false, EQ, no, Infinity, [1, 0]), (0, a, false, EQ, no, Infinity, [0, 1])," + " (0, a, false, EQ, no, NaN, [1, 0]), (0, a, false, EQ, no, NaN, [0, 1])," + " (0, a, false, LT, yes, Infinity, [1, 0]), (0, a, false, LT, yes, Infinity, [0, 1])," + " (0, a, false, LT, yes, NaN, [1, 0]), (0, a, false, LT, yes, NaN, [0, 1])," + " (0, a, false, LT, no, Infinity, [1, 0]), (0, a, false, LT, no, Infinity, [0, 1])," + " (0, a, false, LT, no, NaN, [1, 0]), (0, a, false, LT, no, NaN, [0, 1])," + " (0, a, true, EQ, yes, Infinity, [1, 0]), (0, a, true, EQ, yes, Infinity, [0, 1])," + " (0, a, true, EQ, yes, NaN, [1, 0]), (0, a, true, EQ, yes, NaN, [0, 1])]"); aeq(take(20, septuples( fromString("abcd"), P.booleans(), P.naturalBigIntegers(), P.orderings(), Arrays.asList("yes", "no"), Arrays.asList(Float.POSITIVE_INFINITY, Float.NaN), Arrays.asList(x, y) )), "[(a, false, 0, EQ, yes, Infinity, [1, 0]), (a, false, 0, EQ, yes, Infinity, [0, 1])," + " (a, false, 0, EQ, yes, NaN, [1, 0]), (a, false, 0, EQ, yes, NaN, [0, 1])," + " (a, false, 0, EQ, no, Infinity, [1, 0]), (a, false, 0, EQ, no, Infinity, [0, 1])," + " (a, false, 0, EQ, no, NaN, [1, 0]), (a, false, 0, EQ, no, NaN, [0, 1])," + " (a, false, 0, LT, yes, Infinity, [1, 0]), (a, false, 0, LT, yes, Infinity, [0, 1])," + " (a, false, 0, LT, yes, NaN, [1, 0]), (a, false, 0, LT, yes, NaN, [0, 1])," + " (a, false, 0, LT, no, Infinity, [1, 0]), (a, false, 0, LT, no, Infinity, [0, 1])," + " (a, false, 0, LT, no, NaN, [1, 0]), (a, false, 0, LT, no, NaN, [0, 1])," + " (a, false, 1, EQ, yes, Infinity, [1, 0]), (a, false, 1, EQ, yes, Infinity, [0, 1])," + " (a, false, 1, EQ, yes, NaN, [1, 0]), (a, false, 1, EQ, yes, NaN, [0, 1])]"); aeq(take(20, septuples( P.positiveBigIntegers(), P.negativeBigIntegers(), P.characters(), P.strings(), P.floats(), P.lists(P.integers()), P.bigDecimals() )), "[(1, -1, a, , NaN, [], 0), (1, -1, a, , NaN, [], 0.0), (1, -1, a, , NaN, [0], 0)," + " (1, -1, a, , NaN, [0], 0.0), (1, -1, a, , Infinity, [], 0), (1, -1, a, , Infinity, [], 0.0)," + " (1, -1, a, , Infinity, [0], 0), (1, -1, a, , Infinity, [0], 0.0), (1, -1, a, a, NaN, [], 0)," + " (1, -1, a, a, NaN, [], 0.0), (1, -1, a, a, NaN, [0], 0), (1, -1, a, a, NaN, [0], 0.0)," + " (1, -1, a, a, Infinity, [], 0), (1, -1, a, a, Infinity, [], 0.0), (1, -1, a, a, Infinity, [0], 0)," + " (1, -1, a, a, Infinity, [0], 0.0), (1, -1, b, , NaN, [], 0), (1, -1, b, , NaN, [], 0.0)," + " (1, -1, b, , NaN, [0], 0), (1, -1, b, , NaN, [0], 0.0)]"); } private static void aeq(Iterable<?> a, Object b) { assertEquals(IterableUtils.toString(a), b.toString()); } private static void aeq(Object a, Object b) { assertEquals(a.toString(), b.toString()); } }
package com.ejlchina.searcher.implement; import com.ejlchina.searcher.*; import com.ejlchina.searcher.util.StringUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /*** * * @author Troy.Zhou @ 2021-10-30 * @since v3.0.0 */ public class DefaultMetaResolver implements MetaResolver { private final Map<Class<?>, BeanMeta<?>> cache = new ConcurrentHashMap<>(); private SnippetResolver snippetResolver = new DefaultSnippetResolver(); private DbMapping dbMapping; public DefaultMetaResolver() { this(new DefaultDbMapping()); } public DefaultMetaResolver(DbMapping dbMapping) { this.dbMapping = dbMapping; } @Override public <T> BeanMeta<T> resolve(Class<T> beanClass) { @SuppressWarnings("unchecked") BeanMeta<T> beanMeta = (BeanMeta<T>) cache.get(beanClass); if (beanMeta != null) { return beanMeta; } synchronized (cache) { beanMeta = resolveMetadata(beanClass); cache.put(beanClass, beanMeta); return beanMeta; } } protected <T> BeanMeta<T> resolveMetadata(Class<T> beanClass) { DbMapping.Table table = dbMapping.table(beanClass); if (table == null) { throw new SearchException("The class [" + beanClass.getName() + "] can not be searched, because it can not be resolved by " + dbMapping.getClass()); } BeanMeta<T> beanMeta = new BeanMeta<>(beanClass, table.getDataSource(), snippetResolver.resolve(table.getTables()), snippetResolver.resolve(table.getJoinCond()), snippetResolver.resolve(table.getGroupBy()), table.isDistinct()); Field[] fields = beanClass.getDeclaredFields(); for (int index = 0; index < fields.length; index++) { Field field = fields[index]; if (Modifier.isStatic(field.getModifiers())) { continue; } DbMapping.Column column = dbMapping.column(fields[index]); if (column == null) { continue; } FieldMeta fieldMeta = resolveFieldMeta(beanMeta, column, field, index); beanMeta.addFieldMeta(field.getName(), fieldMeta); } if (beanMeta.getFieldCount() == 0) { throw new SearchException("[" + beanClass.getName() + "] is not a valid SearchBean, because there is no field mapping to database."); } return beanMeta; } protected FieldMeta resolveFieldMeta(BeanMeta<?> beanMeta, DbMapping.Column column, Field field, int index) { Method setter = getSetterMethod(beanMeta.getBeanClass(), field); SqlSnippet snippet = snippetResolver.resolve(column.getFieldSql()); // Oracle return new FieldMeta(beanMeta, field, setter, snippet, "c_" + index, column.isConditional(), column.getOnlyOn()); } protected Method getSetterMethod(Class<?> beanClass, Field field) { String fieldName = field.getName(); try { return beanClass.getMethod("set" + StringUtils.firstCharToUpperCase(fieldName), field.getType()); } catch (Exception e) { throw new SearchException("[" + beanClass.getName() + ": " + fieldName + "] is annotated by @DbField, but there is no correctly setter for it.", e); } } public SnippetResolver getSnippetResolver() { return snippetResolver; } public void setSnippetResolver(SnippetResolver snippetResolver) { this.snippetResolver = Objects.requireNonNull(snippetResolver); } public DbMapping getDbMapping() { return dbMapping; } public void setDbMapping(DbMapping dbMapping) { this.dbMapping = Objects.requireNonNull(dbMapping); } }
package com.thedeanda.ajaxproxy.ui; import java.awt.BorderLayout; import java.io.StringWriter; import java.util.Iterator; import java.util.concurrent.ExecutionException; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.SwingWorker; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import org.apache.commons.lang3.StringUtils; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thedeanda.javajson.JsonArray; import com.thedeanda.javajson.JsonObject; import com.thedeanda.javajson.JsonValue; /** * this is a content viewer used to show input/ouput content of http requests. * it may have a nested tab view to switch between raw, formatted and tree view * * @author mdeanda * */ public class ContentViewer extends JPanel { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory .getLogger(ContentViewer.class); private JTabbedPane tabs; public ContentViewer() { setLayout(new BorderLayout()); tabs = new JTabbedPane(); add(BorderLayout.CENTER, tabs); tabs.add("", new JButton("")); setBorder(BorderFactory.createEmptyBorder()); tabs.setBorder(BorderFactory.createEmptyBorder()); } private class WorkerData { public String rawText; public String formattedText; public TreeNode treeNode; } public void setContent(final String input) { log.trace("setting content"); tabs.removeAll(); if (StringUtils.isBlank(input)) { return; } new TreeLoader(input).execute(); } private class TreeLoader extends SwingWorker<WorkerData, WorkerData> { private String input; public TreeLoader(String input) { this.input = input; } @Override protected WorkerData doInBackground() throws Exception { WorkerData data = new WorkerData(); data.rawText = input; TreeNode node = null; String formattedText = null; Document doc = null; if (input != null) { if (input.trim().startsWith("{")) { try { JsonObject json = JsonObject.parse(input); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode( "{}"); initTree(rootNode, json); node = rootNode; formattedText = json.toString(4); } catch (Exception e) { log.trace(e.getMessage(), e); } } if (formattedText == null && input.trim().startsWith("[")) { try { JsonArray json = JsonArray.parse(input); DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode( "[]"); initTree(rootNode, json); node = rootNode; formattedText = json.toString(4); } catch (Exception e) { log.trace(e.getMessage(), e); } } if (formattedText == null && !"".equals(formattedText)) { if (input.trim().startsWith("<")) { // try xml formatting try { doc = DocumentHelper.parseText(input); node = initTree(doc); formattedText = formatXml(doc); } catch (DocumentException e) { log.trace(e.getMessage(), e); } } } } data.formattedText = formattedText; data.treeNode = node; return data; } @Override protected void done() { WorkerData data; try { data = get(); } catch (InterruptedException | ExecutionException e) { log.error(e.getMessage(), e); return; } if (data.rawText != null) { tabs.add("Raw Text", new JScrollPane( new JTextArea(data.rawText))); } if (data.formattedText != null) { tabs.add("Formatted", new JScrollPane(new JTextArea( data.formattedText))); } if (data.treeNode != null) { JTree tree = new JTree(new DefaultTreeModel(data.treeNode)); tree.setBorder(BorderFactory.createEmptyBorder()); tree.setShowsRootHandles(true); JScrollPane scroll = new JScrollPane(tree); scroll.setBorder(BorderFactory.createEmptyBorder()); tabs.add("Tree View", scroll); } if (tabs.getTabCount() > 1) { tabs.setSelectedIndex(1); } } private DefaultMutableTreeNode initTree(Document doc) { Element rootEl = doc.getRootElement(); DefaultMutableTreeNode rootNode = createElementNodes(rootEl); initTree(rootNode, rootEl); return rootNode; } @SuppressWarnings("rawtypes") private void initTree(DefaultMutableTreeNode root, Element element) { for (Iterator i = element.elementIterator(); i.hasNext();) { Element el = (Element) i.next(); DefaultMutableTreeNode tmp = createElementNodes(el); if (tmp == null) continue; root.add(tmp); initTree(tmp, el); String txt = el.getTextTrim(); if (txt != null && !"".equals(txt)) { DefaultMutableTreeNode txtNode = new DefaultMutableTreeNode( txt); tmp.add(txtNode); } } } @SuppressWarnings("rawtypes") private DefaultMutableTreeNode createElementNodes(Element element) { String name = element.getName(); if (name == null || "".equals(name)) return null; DefaultMutableTreeNode ret = new DefaultMutableTreeNode(name); for (Iterator i = element.attributeIterator(); i.hasNext();) { Attribute attr = (Attribute) i.next(); DefaultMutableTreeNode tmp = new DefaultMutableTreeNode( attr.getName() + " = " + attr.getText()); ret.add(tmp); } return ret; } private void initTree(DefaultMutableTreeNode top, JsonObject obj) { for (String key : obj) { JsonValue val = obj.get(key); if (val.isJsonObject()) { String name = String.format("%s: {%d}", key, val .getJsonObject().size()); DefaultMutableTreeNode node = new DefaultMutableTreeNode( name); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { String name = String.format("%s: [%d]", key, val .getJsonArray().size()); DefaultMutableTreeNode node = new DefaultMutableTreeNode( name); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode( key + "=" + val.toString()); top.add(node); } } } private void initTree(DefaultMutableTreeNode top, JsonArray arr) { int i = 0; for (JsonValue val : arr) { if (val.isJsonObject()) { String name = String.format("%s: {%d}", String.valueOf(i), val.getJsonObject().size()); DefaultMutableTreeNode node = new DefaultMutableTreeNode( name); top.add(node); initTree(node, val.getJsonObject()); } else if (val.isJsonArray()) { String name = String.format("%s: [%d]", i, val .getJsonArray().size()); DefaultMutableTreeNode node = new DefaultMutableTreeNode( name); top.add(node); initTree(node, val.getJsonArray()); } else { DefaultMutableTreeNode node = new DefaultMutableTreeNode( val.toString()); top.add(node); } i++; } } private String formatXml(Document doc) { StringWriter out = new StringWriter(); try { OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(out, outformat); writer.write(doc); writer.flush(); } catch (Exception e) { } return out.toString(); } } }
package org.aeonbits.owner; import org.aeonbits.owner.event.ReloadEvent; import org.aeonbits.owner.event.ReloadListener; import org.aeonbits.owner.event.RollbackBatchException; import org.aeonbits.owner.event.RollbackException; import org.aeonbits.owner.event.RollbackOperationException; import org.aeonbits.owner.event.TransactionalPropertyChangeListener; import org.aeonbits.owner.event.TransactionalReloadListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.Collections.synchronizedList; import static org.aeonbits.owner.Config.LoadType.FIRST; import static org.aeonbits.owner.PropertiesMapper.defaults; import static org.aeonbits.owner.Util.asString; import static org.aeonbits.owner.Util.eq; import static org.aeonbits.owner.Util.ignore; import static org.aeonbits.owner.Util.reverse; import static org.aeonbits.owner.Util.unsupported; /** * Loads properties and manages access to properties handling concurrency. * * @author Luigi R. Viggiano */ class PropertiesManager implements Reloadable, Accessible, Mutable { private final Class<? extends Config> clazz; private final Map<?, ?>[] imports; private final Properties properties; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final ReadLock readLock = lock.readLock(); private final WriteLock writeLock = lock.writeLock(); private final LoadType loadType; private final List<URL> urls; private final ConfigURLFactory urlFactory; private HotReloadLogic hotReloadLogic = null; private volatile boolean loading = false; final List<ReloadListener> reloadListeners = synchronizedList(new LinkedList<ReloadListener>()); private Object proxy; private final LoadersManager loaders; final List<PropertyChangeListener> propertyChangeListeners = synchronizedList( new LinkedList<PropertyChangeListener>() { @Override public boolean remove(Object o) { Iterator iterator = iterator(); while (iterator.hasNext()) { Object item = iterator.next(); if (item.equals(o)) { iterator.remove(); return true; } } return false; } }); @Retention(RUNTIME) @Target(METHOD) @interface Delegate { } PropertiesManager(Class<? extends Config> clazz, Properties properties, ScheduledExecutorService scheduler, VariablesExpander expander, LoadersManager loaders, Map<?, ?>... imports) { this.clazz = clazz; this.properties = properties; this.loaders = loaders; this.imports = imports; urlFactory = new ConfigURLFactory(clazz.getClassLoader(), expander); urls = toURLs(clazz.getAnnotation(Sources.class)); LoadPolicy loadPolicy = clazz.getAnnotation(LoadPolicy.class); loadType = (loadPolicy != null) ? loadPolicy.value() : FIRST; setupHotReload(clazz, scheduler); } private List<URL> toURLs(Sources sources) { String[] specs = specs(sources); ArrayList<URL> result = new ArrayList<URL>(); for (String spec : specs) { try { URL url = urlFactory.newURL(spec); if (url != null) result.add(url); } catch (MalformedURLException e) { throw unsupported(e, "Can't convert '%s' to a valid URL", spec); } } return result; } private String[] specs(Sources sources) { if (sources != null) return sources.value(); return defaultSpecs(); } private String[] defaultSpecs() { String prefix = urlFactory.toClasspathURLSpec(clazz.getName()); return new String[] {prefix + ".properties", prefix + ".xml"}; } private void setupHotReload(Class<? extends Config> clazz, ScheduledExecutorService scheduler) { HotReload hotReload = clazz.getAnnotation(HotReload.class); if (hotReload != null) { hotReloadLogic = new HotReloadLogic(hotReload, urls, this); if (hotReloadLogic.isAsync()) scheduler.scheduleAtFixedRate(new Runnable() { public void run() { hotReloadLogic.checkAndReload(); } }, hotReload.value(), hotReload.value(), hotReload.unit()); } } Properties load() { writeLock.lock(); try { return load(properties); } finally { writeLock.unlock(); } } private Properties load(Properties props) { try { loading = true; defaults(props, clazz); Properties loadedFromFile = doLoad(); merge(props, loadedFromFile); merge(props, reverse(imports)); return props; } finally { loading = false; } } @Delegate public void reload() { writeLock.lock(); try { Properties loaded = load(new Properties()); List<PropertyChangeEvent> events = fireBeforePropertyChangeEvents(keys(properties, loaded), properties, loaded); ReloadEvent reloadEvent = fireBeforeReloadEvent(events, properties, loaded); applyPropertyChangeEvents(events); firePropertyChangeEvents(events); fireReloadEvent(reloadEvent); } catch (RollbackBatchException e) { ignore(); } finally { writeLock.unlock(); } } private Set<?> keys(Map<?, ?>... maps) { Set<Object> keys = new HashSet<Object>(); for (Map<?, ?> map : maps) keys.addAll(map.keySet()); return keys; } private void applyPropertyChangeEvents(List<PropertyChangeEvent> events) { for (PropertyChangeEvent event : events) performSetProperty(event.getPropertyName(), event.getNewValue()); } private void fireReloadEvent(ReloadEvent reloadEvent) { for (ReloadListener listener : reloadListeners) listener.reloadPerformed(reloadEvent); } private ReloadEvent fireBeforeReloadEvent(List<PropertyChangeEvent> events, Properties oldProperties, Properties newProperties) throws RollbackBatchException { ReloadEvent reloadEvent = new ReloadEvent(proxy, events, oldProperties, newProperties); for (ReloadListener listener : reloadListeners) if (listener instanceof TransactionalReloadListener) ((TransactionalReloadListener) listener).beforeReload(reloadEvent); return reloadEvent; } @Delegate public void addReloadListener(ReloadListener listener) { if (listener != null) reloadListeners.add(listener); } @Delegate public void removeReloadListener(ReloadListener listener) { if (listener != null) reloadListeners.remove(listener); } @Delegate public void addPropertyChangeListener(PropertyChangeListener listener) { if (listener != null) propertyChangeListeners.add(listener); } @Delegate public void removePropertyChangeListener(PropertyChangeListener listener) { if (listener != null) propertyChangeListeners.remove(listener); } @Delegate public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { if (propertyName == null || listener == null) return; final boolean transactional = listener instanceof TransactionalPropertyChangeListener; propertyChangeListeners.add(new PropertyChangeListenerWrapper(propertyName, listener, transactional)); } private static class PropertyChangeListenerWrapper implements TransactionalPropertyChangeListener, Serializable { private final String propertyName; private final PropertyChangeListener listener; private final boolean transactional; public PropertyChangeListenerWrapper(String propertyName, PropertyChangeListener listener, boolean transactional) { this.propertyName = propertyName; this.listener = listener; this.transactional = transactional; } public void beforePropertyChange(PropertyChangeEvent evt) throws RollbackOperationException, RollbackBatchException { if (transactional && propertyNameMatches(evt)) ((TransactionalPropertyChangeListener) listener).beforePropertyChange(evt); } private boolean propertyNameMatches(PropertyChangeEvent evt) { return propertyName.equals(evt.getPropertyName()); } public void propertyChange(PropertyChangeEvent evt) { if (propertyNameMatches(evt)) listener.propertyChange(evt); } @Override public boolean equals(Object obj) { return listener.equals(obj); } @Override public int hashCode() { return listener.hashCode(); } } Properties doLoad() { return loadType.load(urls, loaders); } private static void merge(Properties results, Map<?, ?>... inputs) { for (Map<?, ?> input : inputs) results.putAll(input); } @Delegate public String getProperty(String key) { readLock.lock(); try { return properties.getProperty(key); } finally { readLock.unlock(); } } void syncReloadCheck() { if (hotReloadLogic != null && hotReloadLogic.isSync()) hotReloadLogic.checkAndReload(); } @Delegate public String getProperty(String key, String defaultValue) { readLock.lock(); try { return properties.getProperty(key, defaultValue); } finally { readLock.unlock(); } } @Delegate public void storeToXML(OutputStream os, String comment) throws IOException { readLock.lock(); try { properties.storeToXML(os, comment); } finally { readLock.unlock(); } } @Delegate public Set<String> propertyNames() { readLock.lock(); try { LinkedHashSet<String> result = new LinkedHashSet<String>(); for (Enumeration<?> propertyNames = properties.propertyNames(); propertyNames.hasMoreElements(); ) result.add((String) propertyNames.nextElement()); return result; } finally { readLock.unlock(); } } @Delegate public void list(PrintStream out) { readLock.lock(); try { properties.list(out); } finally { readLock.unlock(); } } @Delegate public void list(PrintWriter out) { readLock.lock(); try { properties.list(out); } finally { readLock.unlock(); } } @Delegate public void store(OutputStream out, String comments) throws IOException { readLock.lock(); try { properties.store(out, comments); } finally { readLock.unlock(); } } @Delegate public String setProperty(String key, String newValue) { writeLock.lock(); try { String oldValue = properties.getProperty(key); try { if (eq(oldValue, newValue)) return oldValue; PropertyChangeEvent event = new PropertyChangeEvent(proxy, key, oldValue, newValue); fireBeforePropertyChange(event); String result = performSetProperty(key, newValue); firePropertyChange(event); return result; } catch (RollbackException e) { return oldValue; } } finally { writeLock.unlock(); } } private String performSetProperty(String key, Object value) { return (value == null) ? performRemoveProperty(key) : asString(properties.setProperty(key, asString(value))); } @Delegate public String removeProperty(String key) { writeLock.lock(); try { String oldValue = properties.getProperty(key); String newValue = null; PropertyChangeEvent event = new PropertyChangeEvent(proxy, key, oldValue, newValue); fireBeforePropertyChange(event); String result = performRemoveProperty(key); firePropertyChange(event); return result; } catch (RollbackException e) { return properties.getProperty(key); } finally { writeLock.unlock(); } } private String performRemoveProperty(String key) { return asString(properties.remove(key)); } @Delegate public void clear() { writeLock.lock(); try { List<PropertyChangeEvent> events = fireBeforePropertyChangeEvents(keys(properties), properties, new Properties()); applyPropertyChangeEvents(events); firePropertyChangeEvents(events); } catch (RollbackBatchException e) { ignore(); } finally { writeLock.unlock(); } } @Delegate public void load(InputStream inStream) throws IOException { writeLock.lock(); try { Properties loaded = new Properties(); loaded.load(inStream); performLoad(keys(loaded), loaded); } catch (RollbackBatchException ex) { ignore(); } finally { writeLock.unlock(); } } private void performLoad(Set keys, Properties props) throws RollbackBatchException { List<PropertyChangeEvent> events = fireBeforePropertyChangeEvents(keys, properties, props); applyPropertyChangeEvents(events); firePropertyChangeEvents(events); } @Delegate public void load(Reader reader) throws IOException { writeLock.lock(); try { Properties loaded = new Properties(); loaded.load(reader); performLoad(keys(loaded), loaded); } catch (RollbackBatchException ex) { ignore(); } finally { writeLock.unlock(); } } void setProxy(Object proxy) { this.proxy = proxy; } @Delegate @Override public String toString() { readLock.lock(); try { return properties.toString(); } finally { readLock.unlock(); } } boolean isLoading() { return loading; } private List<PropertyChangeEvent> fireBeforePropertyChangeEvents( Set keys, Properties oldValues, Properties newValues) throws RollbackBatchException { List<PropertyChangeEvent> events = new ArrayList<PropertyChangeEvent>(); for (Object keyObject : keys) { String key = (String) keyObject; String oldValue = oldValues.getProperty(key); String newValue = newValues.getProperty(key); if (!eq(oldValue, newValue)) { PropertyChangeEvent event = new PropertyChangeEvent(proxy, key, oldValue, newValue); try { fireBeforePropertyChange(event); events.add(event); } catch (RollbackOperationException e) { ignore(); } } } return events; } private void firePropertyChangeEvents(List<PropertyChangeEvent> events) { for (PropertyChangeEvent event : events) firePropertyChange(event); } private void fireBeforePropertyChange(PropertyChangeEvent event) throws RollbackBatchException, RollbackOperationException { for (PropertyChangeListener listener : propertyChangeListeners) if (listener instanceof TransactionalPropertyChangeListener) ((TransactionalPropertyChangeListener) listener).beforePropertyChange(event); } private void firePropertyChange(PropertyChangeEvent event) { for (PropertyChangeListener listener : propertyChangeListeners) listener.propertyChange(event); } @Delegate @Override public boolean equals(Object obj) { if (! (obj instanceof Proxy)) return false; InvocationHandler handler = Proxy.getInvocationHandler(obj); if (! (handler instanceof PropertiesInvocationHandler)) return false; PropertiesInvocationHandler propsInvocationHandler = (PropertiesInvocationHandler)handler; PropertiesManager that = propsInvocationHandler.propertiesManager; return this.equals(that); } private boolean equals(PropertiesManager that) { if (! this.isAssignationCompatibleWith(that)) return false; this.readLock.lock(); try { that.readLock.lock(); try { return this.properties.equals(that.properties); } finally { that.readLock.unlock(); } } finally { this.readLock.unlock(); } } private boolean isAssignationCompatibleWith(PropertiesManager that) { return this.clazz.isAssignableFrom(that.clazz) || that.clazz.isAssignableFrom(this.clazz); } @Delegate @Override public int hashCode() { readLock.lock(); try { return properties.hashCode(); } finally { readLock.unlock(); } } }
package mho.wheels.iterables; import mho.wheels.misc.Readers; import org.jetbrains.annotations.NotNull; import org.junit.Ignore; import org.junit.Test; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.List; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.testing.Testing.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; // @formatter:off public class RandomProviderTest { private static final RandomProvider P = RandomProvider.EXAMPLE; private static final int DEFAULT_SAMPLE_SIZE = 1000000; private static final int DEFAULT_TOP_COUNT = 10; private static final int TINY_LIMIT = 20; @Test public void testConstructor() { RandomProvider provider = new RandomProvider(); aeq(provider.getScale(), 32); aeq(provider.getSecondaryScale(), 8); } @Test public void testConstructor_int() { aeq(new RandomProvider(toList(replicate(256, 0))), "RandomProvider[@405143795, 32, 8]"); aeq(new RandomProvider(toList(IterableUtils.range(1, 256))), "RandomProvider[@87945096, 32, 8]"); aeq(new RandomProvider(toList(IterableUtils.rangeBy(-1, -1, -256))), "RandomProvider[@-1665377083, 32, 8]"); } @Test public void testGetScale() { aeq(P.getScale(), 32); aeq(new RandomProvider().withScale(100).getScale(), 100); aeq(new RandomProvider().withScale(3).getScale(), 3); } @Test public void testGetSecondaryScale() { aeq(P.getSecondaryScale(), 8); aeq(new RandomProvider().withSecondaryScale(100).getSecondaryScale(), 100); aeq(new RandomProvider().withSecondaryScale(3).getSecondaryScale(), 3); } @Test public void testGetSeed() { aeq( P.getSeed(), "[-1740315277, -1661427768, 842676458, -1268128447, -121858045, 1559496322, -581535260, -1819723670," + " -334232530, 244755020, -534964695, 301563516, -1795957210, 1451814771, 1299826235, -666749112," + " -1729602324, -565031294, 1897952431, 1118663606, -299718943, -1499922009, -837624734, 1439650052," + " 312777359, -1140199484, 688524765, 739702138, 1480517762, 1622590976, 835969782, -204259962," + " -606452012, -1671898934, 368548728, -333429570, -1477682221, -638975525, -402896626, 1106834480," + " -1454735450, 1532680389, 1878326075, 1597781004, 619389131, -898266263, 1900039432, 1228960795," + " 1091764975, -1435988581, 1465994011, -241076337, 980038049, -821307198, -25801148, -1278802989," + " -290171171, 1063693093, 1718162965, -297113539, -1723402396, 1063795076, 1779331877, 1606303707," + " 1342330210, -2115595746, -718013617, 889248973, 1553964562, -2000156621, 1009070370, 998677106," + " 309828058, -816607592, 347096084, -565436493, -1836536982, -39909763, -1384351460, 586300570," + " -1545743273, -118730601, -1026888351, -643914920, 159473612, -509882909, 2003784095, -1582123439," + " 1199200850, -980627072, 589064158, 1351400003, 1083549876, -1039880174, 1634495699, -1583272739," + " 1765688283, -316629870, 577895752, -145082312, -645859550, 1496562313, 1970005163, -104842168," + " 285710655, 970623004, 375952155, -1114509491, 9760898, 272385973, 1160942220, 79933456, 642681904," + " -1291288677, -238849129, 1196057424, -587416967, -2000013062, 953214572, -2003974223, -179005208," + " -1599818904, 1963556499, -1494628627, 293535669, -1033907228, 1690848472, 1958730707, 1679864529," + " -450182832, -1398178560, 2092043951, 892850383, 662556689, -1954880564, -1297875796, -562200510," + " 1753810661, 612072956, -1182875, 294510681, -485063306, 1608426289, 1466734719, 2978810," + " -2134449847, 855495682, -1563923271, -306227772, 147934567, 926758908, 1903257258, 1602676310," + " -1151393146, 303067731, -1371065668, 1908028886, -425534720, 1241120323, -2101606174, 545122109," + " 1781213901, -146337786, -1205949803, -235261172, 1019855899, -193216104, -1286568040, -294909212," + " 1086948319, 1903298288, 2119132684, -581936319, -2070422261, 2086926428, -1303966999, -1365365119," + " -1891227288, 346044744, 488440551, -790513873, -2045294651, -1270631847, -2126290563, -1816128137," + " 1473769929, 784925032, 292983675, -325413283, -2117417065, 1156099828, -1188576148, -1134724577," + " 937972245, -924106996, 1553688888, 324720865, 2001615528, 998833644, 137816765, 1901776632," + " 2000206935, 942793606, -1742718537, 1909590681, -1332632806, -1355397404, 152253803, -193623640," + " 1601921213, -427930872, 1154642563, 1204629137, 581648332, 1921167008, 2054160403, -1709752639," + " -402951456, 1597748885, 351809052, -1039041413, 1958075309, 1071372680, 1249922658, -2077011328," + " -2088560037, 643876593, -691661336, 2124992669, -534970427, 1061266818, -1731083093, 195764083," + " 1773077546, 304479557, 244603812, 834384133, 1684120407, 1493413139, 1731211584, -2062213553," + " -270682579, 44310291, 564559440, 957643125, 1374924466, 962420298, 1319979537, 1206138289," + " -948832823, -909756549, -664108386, -1355112330, -125435854, -1502071736, -790593389]" ); aeq( new RandomProvider(toList(replicate(256, 0))).getSeed(), "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0," + " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]" ); aeq( new RandomProvider(toList(IterableUtils.range(1, 256))).getSeed(), "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27," + " 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51," + " 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75," + " 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99," + " 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118," + " 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137," + " 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156," + " 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175," + " 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194," + " 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213," + " 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232," + " 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251," + " 252, 253, 254, 255, 256]" ); try { new RandomProvider(Collections.emptyList()); fail(); } catch (IllegalArgumentException ignored) {} try { new RandomProvider(Arrays.asList(1, 2, 3)); fail(); } catch (IllegalArgumentException ignored) {} } @Test public void testAlt() { aeq(P.alt(), "RandomProvider[@-574662335, 32, 8]"); aeq(new RandomProvider(toList(replicate(256, 0))).alt(), "RandomProvider[@1547733404, 32, 8]"); aeq(new RandomProvider(toList(IterableUtils.range(1, 256))).alt(), "RandomProvider[@-669351379, 32, 8]"); } @Test public void testWithScale() { aeq(P.withScale(100), "RandomProvider[@-1084795351, 100, 8]"); aeq(new RandomProvider(toList(replicate(256, 0))).withScale(3), "RandomProvider[@405143795, 3, 8]"); aeq(new RandomProvider(toList(IterableUtils.range(1, 256))).withScale(0), "RandomProvider[@87945096, 0, 8]"); } @Test public void testWithSecondaryScale() { aeq(P.withSecondaryScale(100), "RandomProvider[@-1084795351, 32, 100]"); aeq(new RandomProvider(toList(replicate(256, 0))).withSecondaryScale(3), "RandomProvider[@405143795, 32, 3]"); aeq( new RandomProvider(toList(IterableUtils.range(1, 256))).withSecondaryScale(0), "RandomProvider[@87945096, 32, 0]" ); } private static <T> void simpleProviderHelper( @NotNull Iterable<T> xs, @NotNull String output, @NotNull String sampleCountOutput ) { aeqit(take(TINY_LIMIT, xs), output); aeqit(sampleCount(DEFAULT_SAMPLE_SIZE, xs).entrySet(), sampleCountOutput); } @Test public void testBooleans() { simpleProviderHelper( P.booleans(), "[true, false, false, true, false, true, false, false, false, true, true, false, true, false, true," + " false, true, true, true, false]", "[true=499545, false=500455]" ); } @Test public void testIntegers() { aeqit( take(TINY_LIMIT, P.integers()), "[-1084795351, 1143001545, -1986160253, -1177145870, -968883275, -1465892161, -470080200," + " -2011352603, -248472835, 1997176995, 293205759, -106693423, -1593537177, -206249451, " + "565581811," + " -195502731, 102870776, -1612587755, -483804495, -831718234]" ); } @Test public void testLongs() { aeqit( take(TINY_LIMIT, P.longs()), "[-4659160554254839351, -8530493328132264462, -4161321976937299265, -2018979083213524507," + " -1067182698272227165, 1259309150092131537, -6844190056086445547, 2429155385556917621," + " 441826621316521237, -2077924480219546458, 404281420475794401, -3799772176394282532," + " -3259952746839854786, -1600663848124449857, 7874913887470575742, -6974357164754656982," + " 8454731288392606713, 347198304573602423, -601743751419410562, -2127248600113938899]" ); } private static void uniformSample_Iterable_helper_1(@NotNull String xs, @NotNull String output) { aeqit(TINY_LIMIT, P.uniformSample(readIntegerList(xs)), output); } private static void uniformSample_Iterable_helper_2(@NotNull String xs, @NotNull String output) { aeqit(TINY_LIMIT, P.uniformSample(readIntegerListWithNulls(xs)), output); } @Test public void testUniformSample_Iterable() { uniformSample_Iterable_helper_1( "[3, 1, 4, 1]", "[1, 4, 1, 1, 1, 1, 1, 1, 1, 4, 1, 3, 4, 1, 4, 4, 1, 1, 4, 1, ...]" ); uniformSample_Iterable_helper_1("[]", "[]"); uniformSample_Iterable_helper_2( "[3, 1, null, 1]", "[1, null, 1, 1, 1, 1, 1, 1, 1, null, 1, 3, null, 1, null, null, 1, 1, null, 1, ...]" ); } private static void uniformSample_String_helper(@NotNull String s, @NotNull String output) { aeqcs(P.uniformSample(s), output); } @Test public void testUniformSample_String() { uniformSample_String_helper( "hello", "elleeoleleolohlllhlholeeolllllolloelhlooelllhllllolhhllooolllhloohheoeolleeohlhooehhhllhhehllleoell" + "eohlehlllhholhollleeheellolll" ); uniformSample_String_helper("", ""); } @Test public void testOrderings() { simpleProviderHelper( P.orderings(), "[LT, GT, LT, LT, LT, LT, LT, GT, LT, EQ, GT, GT, GT, LT, GT, LT, GT, LT, EQ, LT]", "[LT=333773, GT=333384, EQ=332843]" ); } @Test public void testRoundingModes() { simpleProviderHelper( P.roundingModes(), "[UP, DOWN, HALF_EVEN, HALF_UP, CEILING, UP, HALF_UP, HALF_UP, HALF_UP, HALF_DOWN, UP, FLOOR," + " HALF_DOWN, HALF_EVEN, HALF_DOWN, DOWN, UP, HALF_EVEN, HALF_DOWN, HALF_UP]", "[UP=125201, DOWN=124277, HALF_EVEN=125246, HALF_UP=125207, CEILING=125091, HALF_DOWN=125195," + " FLOOR=124976, UNNECESSARY=124807]" ); } @Test public void testPositiveBytes() { aeqit(take(TINY_LIMIT, P.positiveBytes()), "[41, 73, 3, 114, 53, 63, 56, 101, 125, 35, 127, 81, 103, 21, 115, 117, 120, 21, 49, 38]"); } @Test public void testPositiveShorts() { aeqit(take(TINY_LIMIT, P.positiveShorts()), "[22057, 20937, 6531, 11762, 949, 17087, 9528, 12773, 6909, 163, 30463, 31953, 3431, 25109, 6131," + " 23925, 12024, 23829, 15025, 31910]"); } @Test public void testPositiveIntegers() { aeqit(take(TINY_LIMIT, P.positiveIntegers()), "[1143001545, 1997176995, 293205759, 565581811, 102870776, 94129103, 1488978913, 1855658460," + " 1833521269, 595157118, 1108943146, 1968520527, 80838404, 181782398, 960691757, 442512834," + " 474345991, 896325532, 1936225302, 419244611]"); } @Test public void testPositiveLongs() { aeqit(take(TINY_LIMIT, P.positiveLongs()), "[1259309150092131537, 2429155385556917621, 441826621316521237, 404281420475794401," + " 7874913887470575742, 8454731288392606713, 347198304573602423, 1900578154019506034," + " 2037300520516627497, 3849688850220341092, 8316024350196968003, 8774587835203863104," + " 7027759477968838149, 4582566483620040494, 104407546425062322, 7601919310667137530," + " 8935450729811208701, 1568186602409462170, 8008008025538113060, 2525682745804362002]"); } @Test public void testNegativeBytes() { aeqit(take(TINY_LIMIT, P.negativeBytes()), "[-42, -74, -4, -115, -54, -64, -57, -102, -126, -36, -128, -82, -104, -22, -116, -118, -121, -22," + " -50, -39]"); } @Test public void testNegativeShorts() { aeqit(take(TINY_LIMIT, P.negativeShorts()), "[-22058, -20938, -6532, -11763, -950, -17088, -9529, -12774, -6910, -164, -30464, -31954, -3432," + " -25110, -6132, -23926, -12025, -23830, -15026, -31911]"); } @Test public void testNegativeIntegers() { aeqit(take(TINY_LIMIT, P.negativeIntegers()), "[-1084795351, -1986160253, -1177145870, -968883275, -1465892161, -470080200, -2011352603," + " -248472835, -106693423, -1593537177, -206249451, -195502731, -1612587755, -483804495, -831718234," + " -884703402, -759016897, -1408421570, -372683595, -138708033]"); } @Test public void testNegativeLongs() { aeqit(take(TINY_LIMIT, P.negativeLongs()), "[-4659160554254839351, -8530493328132264462, -4161321976937299265, -2018979083213524507," + " -1067182698272227165, -6844190056086445547, -2077924480219546458, -3799772176394282532," + " -3259952746839854786, -1600663848124449857, -6974357164754656982, -601743751419410562," + " -2127248600113938899, -8615999285391660475, -3152269795703421596, -279738421105985993," + " -9128636656372363642, -4787870135943121859, -4018571045884316278, -3622924013254235408]"); } @Test public void testNaturalBytes() { aeqit(take(TINY_LIMIT, P.naturalBytes()), "[41, 73, 3, 114, 53, 63, 56, 101, 125, 35, 127, 81, 103, 21, 115, 117, 120, 21, 49, 38]"); } @Test public void testNaturalShorts() { aeqit(take(TINY_LIMIT, P.naturalShorts()), "[22057, 20937, 6531, 11762, 949, 17087, 9528, 12773, 6909, 163, 30463, 31953, 3431, 25109, 6131," + " 23925, 12024, 23829, 15025, 31910]"); } @Test public void testNaturalIntegers() { aeqit(take(TINY_LIMIT, P.naturalIntegers()), "[1062688297, 1143001545, 161323395, 970337778, 1178600373, 681591487, 1677403448, 136131045," + " 1899010813, 1997176995, 293205759, 2040790225, 553946471, 1941234197, 565581811, 1951980917," + " 102870776, 534895893, 1663679153, 1315765414]"); } @Test public void testNaturalLongs() { aeqit(take(TINY_LIMIT, P.naturalLongs()), "[4564211482599936457, 692878708722511346, 5062050059917476543, 7204392953641251301," + " 8156189338582548643, 1259309150092131537, 2379181980768330261, 2429155385556917621," + " 441826621316521237, 7145447556635229350, 404281420475794401, 5423599860460493276," + " 5963419290014921022, 7622708188730325951, 7874913887470575742, 2249014872100118826," + " 8454731288392606713, 347198304573602423, 8621628285435365246, 7096123436740836909]"); } @Test public void testNonzeroBytes() { aeqit(take(TINY_LIMIT, P.nonzeroBytes()), "[41, -55, -125, -14, -75, -65, 56, -27, -3, -93, -1, -47, 103, 21, -13, 117, -8, 21, -79, -90]"); } @Test public void testNonzeroShorts() { aeqit(take(TINY_LIMIT, P.nonzeroShorts()), "[22057, -11831, -26237, 11762, 949, 17087, 9528, 12773, -25859, -32605, -2305, -815, -29337, -7659," + " 6131, -8843, -20744, -8939, -17743, -858]"); } @Test public void testNonzeroIntegers() { aeqit(take(TINY_LIMIT, P.nonzeroIntegers()), "[-1084795351, 1143001545, -1986160253, -1177145870, -968883275, -1465892161, -470080200," + " -2011352603, -248472835, 1997176995, 293205759, -106693423, -1593537177, -206249451, 565581811," + " -195502731, 102870776, -1612587755, -483804495, -831718234]"); } @Test public void testNonzeroLongs() { aeqit(take(TINY_LIMIT, P.nonzeroLongs()), "[-4659160554254839351, -8530493328132264462, -4161321976937299265, -2018979083213524507," + " -1067182698272227165, 1259309150092131537, -6844190056086445547, 2429155385556917621," + " 441826621316521237, -2077924480219546458, 404281420475794401, -3799772176394282532," + " -3259952746839854786, -1600663848124449857, 7874913887470575742, -6974357164754656982," + " 8454731288392606713, 347198304573602423, -601743751419410562, -2127248600113938899]"); } @Test public void testBytes() { aeqit(take(TINY_LIMIT, P.bytes()), "[41, -55, -125, -14, -75, -65, 56, -27, -3, -93, -1, -47, 103, 21, -13, 117, -8, 21, -79, -90]"); } @Test public void testShorts() { aeqit(take(TINY_LIMIT, P.shorts()), "[22057, -11831, -26237, 11762, 949, 17087, 9528, 12773, -25859, -32605, -2305, -815, -29337, -7659," + " 6131, -8843, -20744, -8939, -17743, -858]"); } @Test public void testAsciiCharacters() { aeqcs(P.asciiCharacters(), ")I\3r5?8e}#\177Qg\25sux\u00151&OaV\\?>5?u~\34*Oy\4w?~+-Br\7)\34d\26CLERd%@c7\2\5o.\u001c2S\6z=Vz\30" + "}l\nNph\32Xx^$x.\23\22\3oK10)\177u;\u001c2nEZF\17If`5f\23OSS\5\3v\5s\u000b2Y\\oKo;\1|CQ7&"); } @Test public void testCharacters() { aeqcs(P.characters(), "\u2df2ε\u2538\u31e5\uf6ff\ue215\u17f3\udd75\udd15ϡ\u19dcᬜK" + "\ufe2d\uf207\u2a43\uea45\ue352\u2b63\uf637\uee1c\u33b2ᅺᤘ" + "\ue9fd\u2aec\uaaf0\u28de\u2e24\uf878ሮܓ\uff03\ue5cb\ua7b1\uecf5\ue8b2\ue2da" + "\ue78f\u3353\ue2d3\ud805ឃᳶ\u2832\uf36f\ue87cࢦ"); } private static void rangeUp_byte_helper(byte a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeUp(a)), output); } @Test public void testRangeUp_byte() { rangeUp_byte_helper( (byte) 0, "[41, 73, 3, 114, 53, 63, 56, 101, 125, 35, 127, 81, 103, 21, 115, 117, 120, 21, 49, 38]" ); rangeUp_byte_helper( (byte) (1 << 6), "[105, 73, 67, 114, 117, 127, 120, 101, 125, 99, 127, 81, 103, 85, 115, 117, 120, 85, 113, 102]" ); rangeUp_byte_helper( (byte) (-1 << 6), "[-23, 67, 117, 127, -8, 99, 39, -43, 53, -43, 113, 102, 22, -1, -2, 117, 127, 53, 62, -36]" ); rangeUp_byte_helper( Byte.MAX_VALUE, "[127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127]" ); rangeUp_byte_helper( Byte.MIN_VALUE, "[-87, 73, 3, 114, 53, 63, -72, 101, 125, 35, 127, 81, -25, -107, 115, -11, 120, -107, 49, 38]" ); } private static void rangeUp_short_helper(short a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeUp(a)), output); } @Test public void testRangeUp_short() { rangeUp_short_helper( (short) 0, "[22057, 20937, 6531, 11762, 949, 17087, 9528, 12773, 6909, 163, 30463, 31953, 3431, 25109, 6131," + " 23925, 12024, 23829, 15025, 31910]" ); rangeUp_short_helper( (short) (1 << 14), "[22057, 20937, 22915, 28146, 17333, 17087, 25912, 29157, 23293, 16547, 30463, 31953, 19815, 25109," + " 22515, 23925, 28408, 23829, 31409, 31910]" ); rangeUp_short_helper( (short) (-1 << 14), "[5673, 22915, -4622, -15435, 703, -6856, -3611, 23293, 16547, 19815, -10253, 28408, 31409, 3023," + " -15391, 16214, -9764, 4671, -3778, 3253]" ); rangeUp_short_helper( Short.MAX_VALUE, "[32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767, 32767," + " 32767, 32767, 32767, 32767, 32767, 32767]" ); rangeUp_short_helper( Short.MIN_VALUE, "[-10711, 20937, 6531, -21006, -31819, -15681, -23240, -19995, 6909, 163, 30463, 31953, 3431, 25109," + " -26637, 23925, 12024, 23829, 15025, 31910]" ); } private static void rangeUp_int_helper(int a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeUp(a)), output); } @Test public void testRangeUp_int() { rangeUp_int_helper( 0, "[1143001545, 970337778, 681591487, 136131045, 1997176995, 2040790225, 1941234197, 1951980917," + " 534895893, 1315765414, 1488978913, 1855658460, 739062078, 2008775615, 595157118, 1108943146," + " 1275438073, 985283191, 181782398, 960691757]" ); rangeUp_int_helper( 1 << 30, "[1143001545, 2044079602, 1755333311, 1209872869, 1997176995, 2040790225, 1941234197, 1951980917," + " 1608637717, 1315765414, 1488978913, 1855658460, 1812803902, 2008775615, 1668898942, 1108943146," + " 1275438073, 2059025015, 1255524222, 2034433581]" ); rangeUp_int_helper( -1 << 30, "[69259721, 2044079602, 1755333311, 1209872869, 923435171, 1608637717, 415237089, 781916636," + " 1812803902, -478584706, 35201322, 2059025015, -891959426, -113050067, 1109175337, -654497213," + " 1765141061, 1055360356, 936002112, 468907575]" ); rangeUp_int_helper( Integer.MAX_VALUE, "[2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647," + " 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647, 2147483647," + " 2147483647, 2147483647, 2147483647, 2147483647]" ); rangeUp_int_helper( Integer.MIN_VALUE, "[-1004482103, 970337778, 681591487, 136131045, -150306653, 2040790225, 1941234197, 1951980917," + " 534895893, 1315765414, -658504735, -291825188, 739062078, 2008775615, -1552326530, " + "-1038540502, 1275438073, 985283191, -1965701250, -1186791891]" ); } private static void rangeUp_long_helper(long a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeUp(a)), output); } @Test public void testRangeUp_long() { rangeUp_long_helper( 0L, "[2978664684788457540, 259411669349684921, 3819968131296829608, 4045916796483607944," + " 9050600215542762103, 9220690404532069369, 7461625247526204659, 8293297493653674228," + " 8695924240519389599, 3583222511262526670, 5713832101313495128, 6232776051665771374," + " 4562923580722056620, 3840666588017310711, 8453337235194935587, 2025272514667682114," + " 5709813867763402188, 324207515304377018, 4552478380255597834, 3134077502549279289]" ); rangeUp_long_helper( 1L << 62, "[7590350703215845444, 4871097687777072825, 8431654149724217512, 8657602814910995848," + " 9050600215542762103, 9220690404532069369, 7461625247526204659, 8293297493653674228," + " 8695924240519389599, 8194908529689914574, 5713832101313495128, 6232776051665771374," + " 9174609599149444524, 8452352606444698615, 8453337235194935587, 6636958533095070018," + " 5709813867763402188, 4935893533731764922, 9164164398682985738, 7745763520976667193]" ); rangeUp_long_helper( -1L << 62, "[1609966265326126211, -1308654454609754433, -1874654246358644483, 4614632709429989841," + " 5549737756197188595, 8802817253011410639, -4341372912259511332, 1351874002717355189," + " 4304305952112864638, -2650756327368211889, 7135333504334759031, -1322097316696094037," + " 1669389700406211395, 5037133408195934528, -1504487908198687998, 6789092804704878382," + " 3566685953462311704, 5270340593672846712, -1719689906509449096, -3246513607960354030]" ); rangeUp_long_helper( Long.MAX_VALUE, "[9223372036854775807, 9223372036854775807, 9223372036854775807, 9223372036854775807," + " 9223372036854775807, 9223372036854775807, 9223372036854775807, 9223372036854775807," + " 9223372036854775807, 9223372036854775807, 9223372036854775807, 9223372036854775807," + " 9223372036854775807, 9223372036854775807, 9223372036854775807, 9223372036854775807," + " 9223372036854775807, 9223372036854775807, 9223372036854775807, 9223372036854775807]" ); rangeUp_long_helper( Long.MIN_VALUE, "[-3001719753101261693, -5920340473037142337, -6486340264786032387, 2946691002601937," + " 938051737769800691, 6726395392388302357, 4191131234584022735, -8953058930686899236," + " -3259812015710032715, -307380066314523266, -7262442345795599793, 2523647485907371127," + " -5933783335123481941, 9097897703523752562, 8234018459023606428, -2942296318021176509," + " 5939553317435058514, 425447389768546624, -6116173926626075902, 2177406786277490478]" ); } private static void rangeUp_char_helper(char a, @NotNull String output) { aeqcs(P.rangeUp(a), output); } @Test public void testRangeUp_char() { rangeUp_char_helper( '\0', "\u2df2ε\u2538\u31e5\uf6ff\ue215\u17f3\udd75\udd15ϡ\u19dc" + "ᬜK\ufe2d\uf207\u2a43\uea45\ue352\u2b63\uf637\uee1c\u33b2ᅺ" + "ᤘ\ue9fd\u2aec\uaaf0\u28de\u2e24\uf878ሮܓ\uff03\ue5cb\ua7b1\uecf5\ue8b2" + "\ue2da\ue78f\u3353\ue2d3\ud805ឃᳶ\u2832\uf36f\ue87cࢦ" ); rangeUp_char_helper( 'a', "\u2e53Ж\u2599\u3246\uf760\ue276ᡔ\uddd6\udd76тᨽ\u319f\u1b7d\u218b" + "\uf268\ud7fd\u2aa4\ueaa6\ue3b3\u2bc4\uf698\uee7dᇛ\u1979" + "\uea5e\u2b4d\uab51\u293f\u2e85\uf8d9\u128fݴ\uff64\ue62c\ued56\uab1c\ue913" + "\ue33b\ue7f0\u33b4\ue334\ud866\u17e4ᵗ\u2893\ufbba\uf3d0\ue8ddइ" ); rangeUp_char_helper( 'Ш', "\u321aߝ\u2960\ue63dᰛ\ue19d\ue13dࠉḄὄ\u2552\uf62f" + "\udbc4\u2e6b\uee6d\ue77a\u2f8b\uf244ᖢᵀ\uee25\u2f14\u324cᙖ" + "\u0b3b\ue9f3\ufdd8\uf11d\uecda\ue702\uebb7\ue6fb\udc2d\u1bab\u211e" + "\uf797\ueca4\uda6b\u0cce\uf0adᓦၽ" ); rangeUp_char_helper( Character.MAX_VALUE, "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" + "\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff\uffff" ); } private static void rangeDown_byte_helper(byte a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeDown(a)), output); } @Test public void testRangeDown_byte() { rangeDown_byte_helper( (byte) 0, "[-87, -72, -25, -107, -11, -107, -42, -65, -66, -11, -2, -100, -86, -49, -124, -9, -65, -2, -83, -14]" ); rangeDown_byte_helper( (byte) (1 << 6), "[-87, 3, 53, 63, -72, 35, -25, -107, -11, -107, 49, 38, -42, -65, -66, 53, 63, -11, -2, -100]" ); rangeDown_byte_helper( (byte) (-1 << 6), "[-87, -125, -75, -65, -72, -93, -107, -107, -79, -90, -65, -66, -75, -65, -100, -86, -124, -65," + " -85, -83]" ); rangeDown_byte_helper( Byte.MAX_VALUE, "[-87, 73, 3, 114, 53, 63, -72, 101, 125, 35, 127, 81, -25, -107, 115, -11, 120, -107, 49, 38]" ); rangeDown_byte_helper( Byte.MIN_VALUE, "[-128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128, -128," + " -128, -128, -128, -128]" ); } private static void rangeDown_short_helper(short a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeDown(a)), output); } @Test public void testRangeDown_short() { rangeDown_short_helper( (short) 0, "[-10711, -21006, -31819, -15681, -23240, -19995, -26637, -13361, -31775, -170, -26148, -11713," + " -20162, -13131, -1089, -12171, -8066, -25828, -24278, -17073]" ); rangeDown_short_helper( (short) (1 << 14), "[-10711, 6531, -21006, -31819, -15681, -23240, -19995, 6909, 163, 3431, -26637, 12024, 15025," + " -13361, -31775, -170, -26148, -11713, -20162, -13131]" ); rangeDown_short_helper( (short) (-1 << 14), "[-26237, -21006, -31819, -23240, -19995, -25859, -32605, -29337, -26637, -20744, -17743, -31775," + " -26148, -20162, -25828, -24278, -17073, -23559, -17801, -21185]" ); rangeDown_short_helper( Short.MAX_VALUE, "[-10711, 20937, 6531, -21006, -31819, -15681, -23240, -19995, 6909, 163, 30463, 31953, 3431, 25109," + " -26637, 23925, 12024, 23829, 15025, 31910]" ); rangeDown_short_helper( Short.MIN_VALUE, "[-32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768," + " -32768, -32768, -32768, -32768, -32768, -32768, -32768, -32768]" ); } private static void rangeDown_int_helper(int a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeDown(a)), output); } @Test public void testRangeDown_int() { rangeDown_int_helper( 0, "[-1004482103, -150306653, -658504735, -291825188, -1552326530, -1038540502, -1965701250," + " -1186791891, -1728239037, -18381468, -137739712, -604834249, -1131859022, -1686158854," + " -1782600976, -2111534694, -1846406610, -553610990, -96510935, -2032484754]" ); rangeDown_int_helper( 1 << 30, "[-1004482103, 970337778, 681591487, 136131045, -150306653, 534895893, -658504735, -291825188," + " 739062078, -1552326530, -1038540502, 985283191, -1965701250, -1186791891, 35433513, -1728239037," + " 691399237, -18381468, -137739712, -604834249]" ); rangeDown_int_helper( -1 << 30, "[-1177145870, -1465892161, -2011352603, -1612587755, -1408421570, -1552326530, -1162200457," + " -1965701250, -1186791891, -2112050135, -1728239037, -1456084411, -1288200699, -1131859022," + " -1655648634, -2073512899, -1686158854, -1782600976, -2111534694, -1846406610]" ); rangeDown_int_helper( Integer.MAX_VALUE, "[-1004482103, 970337778, 681591487, 136131045, -150306653, 2040790225, 1941234197, 1951980917," + " 534895893, 1315765414, -658504735, -291825188, 739062078, 2008775615, -1552326530, -1038540502," + " 1275438073, 985283191, -1965701250, -1186791891]" ); rangeDown_int_helper( Integer.MIN_VALUE, "[-2147483648, -2147483648, -2147483648, -2147483648, -2147483648, -2147483648, -2147483648," + " -2147483648, -2147483648, -2147483648, -2147483648, -2147483648, -2147483648, -2147483648," + " -2147483648, -2147483648, -2147483648, -2147483648, -2147483648, -2147483648]" ); } private static void rangeDown_long_helper(long a, @NotNull String output) { aeqit(take(TINY_LIMIT, P.rangeDown(a)), output); } @Test public void testRangeDown_long() { rangeDown_long_helper( 0L, "[-3001719753101261693, -5920340473037142337, -6486340264786032387, -8953058930686899236," + " -3259812015710032715, -307380066314523266, -7262442345795599793, -5933783335123481941," + " -2942296318021176509, -6116173926626075902, -1045000064965076200, -6331375924936837000," + " -7858199626387741934, -750497281407653010, -4964572946333319706, -3265594823497196973," + " -7169158286100765709, -3899242950132782503, -354726065181537090, -8326391862079061231]" ); rangeDown_long_helper( 1L << 62, "[-3001719753101261693, -5920340473037142337, -6486340264786032387, 2946691002601937," + " 938051737769800691, 4191131234584022735, -8953058930686899236, -3259812015710032715," + " -307380066314523266, -7262442345795599793, 2523647485907371127, -5933783335123481941," + " -2942296318021176509, 425447389768546624, -6116173926626075902, 2177406786277490478," + " -1045000064965076200, 658654575245458808, -6331375924936837000, -7858199626387741934]" ); rangeDown_long_helper( -1L << 62, "[-6244707352066318268, -8963960367505090887, -5403403905557946200, -5177455240371167864," + " -5640149525592249138, -4660448456132719188, -5382705448837465097, -7198099522187093694," + " -8899164521550398790, -4670893656599177974, -6089294534305496519, -8650775946964755326," + " -7145123307227501859, -7605339026464506600, -6513958261454878089, -9034634951682803789," + " -7138643007725401796, -7486951269179234622, -7852292981010661281, -8935306705831985167]" ); rangeDown_long_helper( Long.MAX_VALUE, "[-3001719753101261693, -5920340473037142337, -6486340264786032387, 2946691002601937," + " 938051737769800691, 6726395392388302357, 4191131234584022735, -8953058930686899236," + " -3259812015710032715, -307380066314523266, -7262442345795599793, 2523647485907371127," + " -5933783335123481941, 9097897703523752562, 8234018459023606428, -2942296318021176509," + " 5939553317435058514, 425447389768546624, -6116173926626075902, 2177406786277490478]" ); rangeDown_long_helper( Long.MIN_VALUE, "[-9223372036854775808, -9223372036854775808, -9223372036854775808, -9223372036854775808," + " -9223372036854775808, -9223372036854775808, -9223372036854775808, -9223372036854775808," + " -9223372036854775808, -9223372036854775808, -9223372036854775808, -9223372036854775808," + " -9223372036854775808, -9223372036854775808, -9223372036854775808, -9223372036854775808," + " -9223372036854775808, -9223372036854775808, -9223372036854775808, -9223372036854775808]" ); } private static void rangeDown_char_helper(char a, @NotNull String output) { aeqcs(P.rangeDown(a), output); } @Test public void testRangeDown_char() { rangeDown_char_helper( '\0', "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" + "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ); rangeDown_char_helper( 'a', ")I\u00035?8#Q\25\u00151&OaV\\?>5?\34*O\4?+-B\7)\34\26CLER%@7\2\5.\u001c2S\6=V\30\nN\32X^$.\23\22\3K" + "10);\u001c2EZF\17I`5\23OSS\5\3\5\u000b2Y\\K;\1CQ7&W\5>U7\21(Y\2+'\32\24V<T@)B\2?3+\6\u00129CZ\35BW" + "\\FF\13[J" ); rangeDown_char_helper( 'Ш', "ljƃεʿǥ\u02fd£ȕʱϏϡǜȿľοu~\u031cĪϹɷȇЖɃɌɅ\u0352ĥɀ\u0363ϯβœźŖǺĘǽˬǎ\u02f0ŨƚϘÞxȮĒưʻ²\u02da\u03605ȓ\u0353" + "\u02d3\5ʅϳƋ2\u0359\u02ef\u036f\u033b|ɑʷ¦ϲ¾·\21ΨÙɨŔ\u0329ο\u0306\u0092\u0339σŚ\u036bBɗŪŤͽЋɵÊ\u037eʡɪ" + "\35\u0366țdžɐʓΤǔȪĢͽ¬ü\u0300\u009bϖɕdžĖƣ,\u02d6nj\u02f7\3ɌÄʓϨͺɎ" ); rangeDown_char_helper( Character.MAX_VALUE, "\u2df2ε\u2538\u31e5\uf6ff\ue215\u17f3\udd75\udd15ϡ\u19dcᬜK" + "\ufe2d\uf207\u2a43\uea45\ue352\u2b63\uf637\uee1c\u33b2ᅺᤘ\ue9fd" + "\u2aec\uaaf0\u28de\u2e24\uf878ሮܓ\uff03\ue5cb\ua7b1\uecf5\ue8b2\ue2da\ue78f" + "\u3353\ue2d3\ud805ឃᳶ\u2832\uf36f\ue87cࢦ" ); } private static void range_byte_byte_helper(byte a, byte b, @NotNull String output) { aeqit(TINY_LIMIT, P.range(a, b), output); } @Test public void testRange_byte_byte() { range_byte_byte_helper( (byte) 10, (byte) 20, "[19, 19, 13, 12, 15, 18, 15, 13, 11, 17, 15, 13, 15, 18, 15, 11, 16, 11, 16, 15, ...]" ); range_byte_byte_helper( (byte) 10, (byte) 10, "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...]" ); range_byte_byte_helper((byte) 10, (byte) 9, "[]"); range_byte_byte_helper( (byte) -20, (byte) -10, "[-11, -11, -17, -18, -15, -12, -15, -17, -19, -13, -15, -17, -15, -12, -15, -19, -14, -19, -14," + " -15, ...]" ); range_byte_byte_helper( (byte) -20, (byte) -20, "[-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20," + " -20, ...]" ); range_byte_byte_helper((byte) -20, (byte) -21, "[]"); range_byte_byte_helper( (byte) 0, (byte) 0, "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]" ); range_byte_byte_helper( (byte) 0, (byte) 10, "[9, 9, 3, 2, 5, 8, 5, 3, 1, 7, 5, 3, 5, 8, 5, 1, 6, 1, 6, 5, ...]" ); range_byte_byte_helper( (byte) -5, (byte) 0, "[-4, -4, -2, -3, 0, -5, 0, 0, -2, -4, 0, -2, 0, -5, 0, -4, -4, -1, 0, 0, ...]" ); range_byte_byte_helper( (byte) -5, (byte) 10, "[4, 4, -2, -3, 0, 10, 3, 0, 8, -2, 10, -4, 2, 0, -2, 0, 3, 0, -4, 1, ...]" ); range_byte_byte_helper( (byte) -10, (byte) 5, "[-1, -1, -7, -8, -5, 5, -2, -5, 3, -7, 5, -9, -3, -5, -7, -5, -2, -5, -9, -4, ...]" ); range_byte_byte_helper((byte) 5, (byte) -10, "[]"); } private static void range_short_short_helper(short a, short b, @NotNull String output) { aeqit(TINY_LIMIT, P.range(a, b), output); } @Test public void testRange_short_short() { range_short_short_helper( (short) 10, (short) 20, "[19, 19, 13, 12, 15, 18, 15, 13, 11, 17, 15, 13, 15, 18, 15, 11, 16, 11, 16, 15, ...]" ); range_short_short_helper( (short) 10, (short) 10, "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...]" ); range_short_short_helper((short) 10, (short) 9, "[]"); range_short_short_helper( (short) -20, (short) -10, "[-11, -11, -17, -18, -15, -12, -15, -17, -19, -13, -15, -17, -15, -12, -15, -19, -14, -19, -14," + " -15, ...]" ); range_short_short_helper( (short) -20, (short) -20, "[-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20," + " -20, ...]" ); range_short_short_helper((short) -20, (short) -21, "[]"); range_short_short_helper( (short) 0, (short) 0, "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]" ); range_short_short_helper( (short) 0, (short) 10, "[9, 9, 3, 2, 5, 8, 5, 3, 1, 7, 5, 3, 5, 8, 5, 1, 6, 1, 6, 5, ...]" ); range_short_short_helper( (short) -5, (short) 0, "[-4, -4, -2, -3, 0, -5, 0, 0, -2, -4, 0, -2, 0, -5, 0, -4, -4, -1, 0, 0, ...]" ); range_short_short_helper( (byte) -5, (byte) 10, "[4, 4, -2, -3, 0, 10, 3, 0, 8, -2, 10, -4, 2, 0, -2, 0, 3, 0, -4, 1, ...]" ); range_short_short_helper( (short) -10, (short) 5, "[-1, -1, -7, -8, -5, 5, -2, -5, 3, -7, 5, -9, -3, -5, -7, -5, -2, -5, -9, -4, ...]" ); range_short_short_helper((short) 5, (short) -10, "[]"); } private static void range_int_int_helper(int a, int b, @NotNull String output) { aeqit(TINY_LIMIT, P.range(a, b), output); } @Test public void testRange_int_int() { range_int_int_helper( 10, 20, "[19, 12, 15, 13, 11, 15, 15, 15, 16, 11, 20, 19, 17, 12, 19, 14, 13, 15, 14, 10, ...]" ); range_int_int_helper( 10, 10, "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...]" ); range_int_int_helper(10, 9, "[]"); range_int_int_helper( -20, -10, "[-11, -18, -15, -17, -19, -15, -15, -15, -14, -19, -10, -11, -13, -18, -11, -16, -17, -15, -16," + " -20, ...]" ); range_int_int_helper( -20, -20, "[-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20," + " -20, ...]" ); range_int_int_helper(-20, -21, "[]"); range_int_int_helper(0, 0, "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]"); range_int_int_helper(0, 10, "[9, 2, 5, 3, 1, 5, 5, 5, 6, 1, 10, 9, 7, 2, 9, 4, 3, 5, 4, 0, ...]"); range_int_int_helper(-5, 0, "[-4, -3, 0, -2, -4, 0, 0, 0, -4, -1, -3, -4, 0, -3, -4, -1, -2, 0, -1, -5, ...]"); range_int_int_helper(-5, 10, "[4, -3, 10, 0, -2, -4, 0, 0, 0, 1, -4, 7, 9, 10, 9, 5, 4, 2, 9, 8, ...]"); range_int_int_helper(-10, 5, "[-1, -8, 5, -5, -7, -9, -5, -5, -5, -4, -9, 2, 4, 5, 4, 0, -1, -3, 4, 3, ...]"); range_int_int_helper(5, -10, "[]"); } private static void range_long_long_helper(long a, long b, @NotNull String output) { aeqit(TINY_LIMIT, P.range(a, b), output); } @Test public void testRange_long_long() { range_long_long_helper( 10L, 20L, "[19, 19, 13, 12, 15, 18, 15, 13, 11, 17, 15, 13, 15, 18, 15, 11, 16, 11, 16, 15, ...]" ); range_long_long_helper( 10L, 10L, "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...]" ); range_long_long_helper(10L, 9L, "[]"); range_long_long_helper( -20L, -10L, "[-11, -11, -17, -18, -15, -12, -15, -17, -19, -13, -15, -17, -15, -12, -15, -19, -14, -19, -14," + " -15, ...]" ); range_long_long_helper( -20L, -20L, "[-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20," + " -20, ...]" ); range_long_long_helper(-20L, -21L, "[]"); range_long_long_helper(0L, 0L, "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]"); range_long_long_helper(0L, 10L, "[9, 9, 3, 2, 5, 8, 5, 3, 1, 7, 5, 3, 5, 8, 5, 1, 6, 1, 6, 5, ...]"); range_long_long_helper( -5L, 0L, "[-4, -4, -2, -3, 0, -5, 0, 0, -2, -4, 0, -2, 0, -5, 0, -4, -4, -1, 0, 0, ...]" ); range_long_long_helper(-5L, 10L, "[4, 4, -2, -3, 0, 10, 3, 0, 8, -2, 10, -4, 2, 0, -2, 0, 3, 0, -4, 1, ...]"); range_long_long_helper( -10L, 5L, "[-1, -1, -7, -8, -5, 5, -2, -5, 3, -7, 5, -9, -3, -5, -7, -5, -2, -5, -9, -4, ...]" ); range_long_long_helper(5L, -10L, "[]"); } private static void range_BigInteger_BigInteger_helper(int a, int b, @NotNull String output) { aeqit(TINY_LIMIT, P.range(BigInteger.valueOf(a), BigInteger.valueOf(b)), output); } @Test public void testRange_BigInteger_BigInteger() { range_BigInteger_BigInteger_helper( 10, 20, "[19, 19, 13, 12, 15, 18, 15, 13, 11, 17, 15, 13, 15, 18, 15, 11, 16, 11, 16, 15, ...]" ); range_BigInteger_BigInteger_helper( 10, 10, "[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...]" ); range_BigInteger_BigInteger_helper(10, 9, "[]"); range_BigInteger_BigInteger_helper( -20, -10, "[-11, -11, -17, -18, -15, -12, -15, -17, -19, -13, -15, -17, -15, -12, -15, -19, -14, -19, -14," + " -15, ...]" ); range_BigInteger_BigInteger_helper( -20, -20, "[-20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20," + " -20, ...]" ); range_BigInteger_BigInteger_helper(-20, -21, "[]"); range_BigInteger_BigInteger_helper(0, 0, "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]"); range_BigInteger_BigInteger_helper(0, 10, "[9, 9, 3, 2, 5, 8, 5, 3, 1, 7, 5, 3, 5, 8, 5, 1, 6, 1, 6, 5, ...]"); range_BigInteger_BigInteger_helper( -5, 0, "[-4, -4, -2, -3, 0, -5, 0, 0, -2, -4, 0, -2, 0, -5, 0, -4, -4, -1, 0, 0, ...]" ); range_BigInteger_BigInteger_helper( -5, 10, "[4, 4, -2, -3, 0, 10, 3, 0, 8, -2, 10, -4, 2, 0, -2, 0, 3, 0, -4, 1, ...]" ); range_BigInteger_BigInteger_helper( -10, 5, "[-1, -1, -7, -8, -5, 5, -2, -5, 3, -7, 5, -9, -3, -5, -7, -5, -2, -5, -9, -4, ...]" ); range_BigInteger_BigInteger_helper(5, -10, "[]"); } private static void range_char_char_helper(char a, char b, @NotNull String output) { aeqcs(P.range(a, b), output); } @Test public void testRange_char_char() { range_char_char_helper( 'a', 'z', "jjdsvyfdrhvtvyvrgpbwvvkpzexlncshjewdmfsefadxcfpostgwymkoqiyyeyotsdplrqjvsofgpjgavgtpttfdwftlszplpbd" + "rxgxsfvxrizclhuiwuagojhcctlgs" ); range_char_char_helper( 'a', 'a', "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ); range_char_char_helper('a', 'A', ""); range_char_char_helper( '!', '9', "**$369&$2(646962'0\"766+0%8,.#3(*%7$-&3%&!$8#&0/34'79-+/1)99%9/43$0,21*63/&'0*'!6'4044&$7&4,30,0\"$" +
package org.sbolstandard.core2.test; import java.io.InputStream; import org.sbolstandard.core2.SBOLDocument; import org.sbolstandard.core2.SBOLReader; import org.sbolstandard.core2.SBOLWriter; public class readTester { public static String filenameRdf = "writeTesterString_v1.3.rdf"; public static String filenameJson = "writeTesterString_v1.3.json"; public static String filenameTurtle = "writeTesterString_v1.3.ttl"; public static String filenameV1_1 = "partial_pIKE_left_cassette.xml"; public static String filenameV1_2 = "partial_pIKE_right_casette.xml"; public static String filenameV1_3 = "partial_pIKE_right_cassette.xml"; public static String filenameV1_4 = "partial_pTAK_left_cassette.xml"; public static String filenameV1_5 = "partial_pTAK_right_cassette.xml"; public static String filenameV1_6 = "pIKE_pTAK_cassettes 2.xml"; public static String filenameV1_7 = "pIKE_pTAK_cassettes.xml"; public static String filenameV1_8 = "pIKE_pTAK_left_right_cassettes.xml"; public static String filenameV1_9 = "pIKE_pTAK_toggle_switches.xml"; public static String filenameV1_10 = "miRNA.sbol.xml"; public static String path = "/org/sbolstandard/core2/test/files/"; public static void main(String[] args) { try { InputStream file = readTester.class.getResourceAsStream(path + filenameV1_9); SBOLDocument document1 = SBOLReader.read(file); // SBOLDocument document = SBOLReader.read(filenameRdf); // SBOLDocument document1 = SBOLReader.readRdf(filenameV1_8); // SBOLDocument document2 = SBOLReader.readJson(filenameJson); // SBOLDocument document3 = SBOLReader.readTurtle(filenameTurtle); // SBOLWriter.writeRdf(document,(System.out)); SBOLWriter.writeRdf(document1,(System.out)); // SBOLWriter.writeJson(document2,(System.out)); // SBOLWriter.writeTurtle(document3,(System.out)); } catch (Throwable e) { e.printStackTrace(); } } }
package nl.github.martijn9612.fishy; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import nl.github.martijn9612.fishy.models.DrawRectangle; import nl.github.martijn9612.fishy.models.MousePosition; import nl.github.martijn9612.fishy.models.MouseRectangle; public class MenuState extends BasicGameState { public String menu = "Menu"; private Image play; private Image exit; private MousePosition mouse; private DrawRectangle playButtonDR; private DrawRectangle exitButtonDR; private MouseRectangle playButtonMR; private MouseRectangle exitButtonMR; private static int MENU_TEXT_DRAW_X = 280; private static int MENU_TEXT_DRAW_Y = 10; private static int PLAY_BUTTON_DRAW_X = 150; private static int PLAY_BUTTON_DRAW_Y = 200; private static int EXIT_BUTTON_DRAW_X = 150; private static int EXIT_BUTTON_DRAW_Y = 375; public MenuState(int state) { // Blank } public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { play = new Image("resources/play-button.gif"); exit = new Image("resources/exit-button.gif"); playButtonDR = new DrawRectangle(PLAY_BUTTON_DRAW_X, PLAY_BUTTON_DRAW_Y, play.getWidth(), play.getHeight()); exitButtonDR = new DrawRectangle(EXIT_BUTTON_DRAW_X, EXIT_BUTTON_DRAW_Y, play.getWidth(), play.getHeight()); playButtonMR = playButtonDR.getMouseRectangle(); exitButtonMR = exitButtonDR.getMouseRectangle(); mouse = new MousePosition(); } public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { g.drawString(menu, MENU_TEXT_DRAW_X, MENU_TEXT_DRAW_Y); g.drawImage(play, playButtonDR.getPositionX(), playButtonDR.getPositionY()); g.drawImage(exit, exitButtonDR.getPositionX(), exitButtonDR.getPositionY()); } public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { mouse.updatePosition(); menu = "("+mouse.getPositionX()+","+mouse.getPositionY()+")"; if(mouse.isInRectangle(playButtonMR)) { if(mouse.isLeftButtonDown()) { sbg.enterState(Main.PLAY_STATE); } } if(mouse.isInRectangle(exitButtonMR)) { if(mouse.isLeftButtonDown()) { System.exit(0); } } } public int getID() { return Main.MENU_STATE; } }
package net.imagej.ops.logic; import net.imagej.ops.AbstractNamespaceTest; import net.imagej.ops.LogicOps.And; import net.imagej.ops.LogicOps.Equal; import net.imagej.ops.LogicOps.GreaterThan; import net.imagej.ops.LogicOps.GreaterThanOrEqual; import net.imagej.ops.LogicOps.LessThan; import org.junit.Test; /** * Tests that the ops of the logic namespace have corresponding type-safe Java * method signatures declared in the {@link LogicNamespace} class. * * @author Curtis Rueden */ public class LogicNamespaceTest extends AbstractNamespaceTest { /** Tests for {@link And} method convergence. */ @Test public void testAnd() { assertComplete("logic", LogicNamespace.class, And.NAME); } /** Tests for {@link Equal} method convergence. */ @Test public void testEqual() { assertComplete("logic", LogicNamespace.class, Equal.NAME); } /** Tests for {@link GreaterThan} method convergence. */ @Test public void testGreaterThan() { assertComplete("logic", LogicNamespace.class, GreaterThan.NAME); } /** Tests for {@link GreaterThanOrEqual} method convergence. */ @Test public void testGreaterThanOrEqual() { assertComplete("logic", LogicNamespace.class, GreaterThanOrEqual.NAME); } /** Tests for {@link LessThan} method convergence. */ @Test public void testLessThan() { assertComplete("logic", LogicNamespace.class, LessThan.NAME); } }
package net.bytebuddy.instrumentation.type; import net.bytebuddy.instrumentation.ByteCodeElement; import net.bytebuddy.instrumentation.ModifierReviewable; import net.bytebuddy.instrumentation.field.FieldList; import net.bytebuddy.instrumentation.method.MethodDescription; import net.bytebuddy.instrumentation.method.MethodList; import net.bytebuddy.instrumentation.method.bytecode.stack.StackSize; import org.objectweb.asm.Type; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Implementations of this interface represent a Java type, i.e. a class or interface. */ public interface TypeDescription extends ByteCodeElement, DeclaredInType, ModifierReviewable, AnnotatedElement { /** * Checks if {@code object} is an instance of the type represented by this instance. * * @param object The object of interest. * @return {@code true} if the object is an instance of the type described by this instance. */ boolean isInstance(Object object); /** * Checks if this type is assignable from the type described by this instance, for example for * {@code class Foo} and {@code class Bar extends Foo}, this method would return {@code true} for * {@code Foo.class.isAssignableFrom(Bar.class)}. * * @param type The type of interest. * @return {@code true} if this type is assignable from {@code type}. */ boolean isAssignableFrom(Class<?> type); /** * Checks if this type is assignable from the type described by this instance, for example for * {@code class Foo} and {@code class Bar extends Foo}, this method would return {@code true} for * {@code Foo.class.isAssignableFrom(Bar.class)}. * <p>&nbsp;</p> * Implementations of this methods are allowed to delegate to * {@link net.bytebuddy.instrumentation.type.TypeDescription#isAssignableFrom(Class)} * * @param typeDescription The type of interest. * @return {@code true} if this type is assignable from {@code type}. */ boolean isAssignableFrom(TypeDescription typeDescription); /** * Checks if this type is assignable from the type described by this instance, for example for * {@code class Foo} and {@code class Bar extends Foo}, this method would return {@code true} for * {@code Bar.class.isAssignableTo(Foo.class)}. * * @param type The type of interest. * @return {@code true} if this type is assignable to {@code type}. */ boolean isAssignableTo(Class<?> type); /** * Checks if this type is assignable from the type described by this instance, for example for * {@code class Foo} and {@code class Bar extends Foo}, this method would return {@code true} for * {@code Bar.class.isAssignableFrom(Foo.class)}. * <p>&nbsp;</p> * Implementations of this methods are allowed to delegate to * {@link net.bytebuddy.instrumentation.type.TypeDescription#isAssignableTo(Class)} * * @param typeDescription The type of interest. * @return {@code true} if this type is assignable to {@code type}. */ boolean isAssignableTo(TypeDescription typeDescription); /** * Checks if the type described by this instance represents {@code type}. * * @param type The type of interest. * @return {@code true} if the type described by this instance represents {@code type}. */ boolean represents(Class<?> type); /** * Checks if the type described by this entity is an array. * * @return {@code true} if this type description represents an array. */ boolean isArray(); /** * Returns the component type of this type. * * @return The component type of this array or {@code null} if this type description does not represent an array. */ TypeDescription getComponentType(); /** * Checks if the type described by this entity is a primitive type. * * @return {@code true} if this type description represents a primitive type. */ boolean isPrimitive(); /** * Returns the component type of this type. * * @return The component type of this array or {@code null} if type does not have a super type as for the * {@link java.lang.Object} type. */ TypeDescription getSupertype(); /** * Returns a list of interfaces that are implemented by this type. * * @return A list of interfaces that are implemented by this type. */ TypeList getInterfaces(); /** * Returns a description of the enclosing method of this type. * * @return A description of the enclosing method of this type or {@code null} if there is no such method. */ MethodDescription getEnclosingMethod(); /** * Returns a description of the enclosing type of this type. * * @return A description of the enclosing type of this type or {@code null} if there is no such type. */ TypeDescription getEnclosingClass(); /** * Returns the simple internalName of this type. * * @return The simple internalName of this type. */ String getSimpleName(); /** * Returns the canonical internalName of this type. * * @return The canonical internalName of this type. */ String getCanonicalName(); /** * Checks if this type description represents an anonymous type. * * @return {@code true} if this type description represents an anonymous type. */ boolean isAnonymousClass(); /** * Checks if this type description represents a local type. * * @return {@code true} if this type description represents a local type. */ boolean isLocalClass(); /** * Checks if this type description represents a member type. * * @return {@code true} if this type description represents a member type. */ boolean isMemberClass(); /** * Returns a list of fields that are declared by this type. * * @return A list of fields that are declared by this type. */ FieldList getDeclaredFields(); /** * Returns a list of methods that are declared by this type. * * @return A list of methods that are declared by this type. */ MethodList getDeclaredMethods(); /** * Returns the package internalName of the type described by this instance. * * @return The package internalName of the type described by this instance. */ String getPackageName(); /** * Returns the size of the type described by this instance. * * @return The size of the type described by this instance. */ StackSize getStackSize(); /** * Checks if this type is defined in a sealed package. * * @return {@code true} if the class is defined in a sealed package. */ boolean isSealed(); /** * An abstract base implementation of a type description. */ abstract static class AbstractTypeDescription extends AbstractModifierReviewable implements TypeDescription { @Override public boolean isInstance(Object object) { return isAssignableFrom(object.getClass()); } @Override public String getInternalName() { return getName().replace('.', '/'); } @Override public boolean isVisibleTo(TypeDescription typeDescription) { return isPublic() || typeDescription.getPackageName().equals(getPackageName()); } @Override public boolean equals(Object other) { return other == this || other instanceof TypeDescription && getName().equals(((TypeDescription) other).getName()); } @Override public int hashCode() { return getName().hashCode(); } } /** * A type description implementation that represents a loaded type. */ static class ForLoadedType extends AbstractTypeDescription { /** * The loaded type this instance represents. */ private final Class<?> type; /** * Creates a new immutable type description for a loaded type. * * @param type The type to be represented by this type description. */ public ForLoadedType(Class<?> type) { this.type = type; } @Override public boolean isInstance(Object object) { return type.isInstance(object); } @Override public boolean isAssignableFrom(Class<?> type) { return this.type.isAssignableFrom(type); } @Override public boolean isAssignableFrom(TypeDescription typeDescription) { return typeDescription.isAssignableTo(type); } @Override public boolean isAssignableTo(Class<?> type) { return type.isAssignableFrom(this.type); } @Override public boolean isAssignableTo(TypeDescription typeDescription) { return typeDescription.isAssignableFrom(type); } @Override public boolean represents(Class<?> type) { return type == this.type; } @Override public boolean isInterface() { return type.isInterface(); } @Override public boolean isArray() { return type.isArray(); } @Override public TypeDescription getComponentType() { return type.getComponentType() == null ? null : new TypeDescription.ForLoadedType(type.getComponentType()); } @Override public boolean isPrimitive() { return type.isPrimitive(); } @Override public boolean isAnnotation() { return type.isAnnotation(); } @Override public boolean isSynthetic() { return type.isSynthetic(); } @Override public TypeDescription getSupertype() { return type.getSuperclass() == null ? null : new TypeDescription.ForLoadedType(type.getSuperclass()); } @Override public TypeList getInterfaces() { return new TypeList.ForLoadedType(type.getInterfaces()); } @Override public TypeDescription getDeclaringType() { Class<?> declaringType = type.getDeclaringClass(); return declaringType == null ? null : new TypeDescription.ForLoadedType(declaringType); } @Override public MethodDescription getEnclosingMethod() { Method enclosingMethod = type.getEnclosingMethod(); Constructor<?> enclosingConstructor = type.getEnclosingConstructor(); if (enclosingMethod != null) { return new MethodDescription.ForLoadedMethod(enclosingMethod); } else if (enclosingConstructor != null) { return new MethodDescription.ForLoadedConstructor(enclosingConstructor); } else { return null; } } @Override public TypeDescription getEnclosingClass() { Class<?> enclosingType = type.getEnclosingClass(); return enclosingType == null ? null : new TypeDescription.ForLoadedType(enclosingType); } @Override public String getSimpleName() { return type.getSimpleName(); } @Override public String getCanonicalName() { return type.getCanonicalName(); } @Override public boolean isAnonymousClass() { return type.isAnonymousClass(); } @Override public boolean isLocalClass() { return type.isLocalClass(); } @Override public boolean isMemberClass() { return type.isMemberClass(); } @Override public FieldList getDeclaredFields() { return new FieldList.ForLoadedField(type.getDeclaredFields()); } @Override public MethodList getDeclaredMethods() { return new MethodList.ForLoadedType(type); } @Override public String getPackageName() { return type.getPackage().getName(); } @Override public StackSize getStackSize() { return StackSize.of(type); } @Override public String getName() { return type.getName(); } @Override public String getDescriptor() { return Type.getDescriptor(type); } @Override public int getModifiers() { return type.getModifiers(); } @Override public <T extends Annotation> T getAnnotation(Class<T> annotationType) { return type.getAnnotation(annotationType); } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return type.isAnnotationPresent(annotationClass); } @Override public Annotation[] getAnnotations() { return type.getAnnotations(); } @Override public Annotation[] getDeclaredAnnotations() { return type.getDeclaredAnnotations(); } @Override public boolean isSealed() { return type.getPackage() != null && type.getPackage().isSealed(); } @Override public String toString() { return "TypeDescription.ForLoadedType{" + type + "}"; } } }
package com.walmart.otto.tools; import com.walmart.otto.configurator.Configurator; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class ProcessExecutor { private Configurator configurator; public ProcessExecutor(Configurator configurator) { this.configurator = configurator; } // skip: ' - [113/113 files][ 2.1 MiB/ 2.1 MiB] 100% Done ' private static Pattern uploadProgress = Pattern.compile(".*\\[\\d*/\\d* files]\\[.*% Done.*"); public void executeCommand(final String[] commands, List<String> inputStream, List<String> errorStream) { Boolean isDebug = configurator.isDebug(); String debugString = ""; try { if (isDebug) { StringBuilder command = new StringBuilder(); command.append("\u001B[32m"); // green for (String cmd : commands) { command.append(cmd).append(" "); } command.append("\u001B[0m"); debugString = command.toString(); System.out.println("$ " + debugString); } new ProcessBuilder(commands, inputStream, errorStream); if (isDebug) { List<String> cleanErrorStream = new ArrayList<>(); for (String line : errorStream) { if (!uploadProgress.matcher(line).matches()) { cleanErrorStream.add(line); } } printStreams(inputStream, cleanErrorStream); } } catch (Exception e) { e.printStackTrace(); } } private void printStreams(List<String> inputStream, List<String> errorStream) { for (String line : inputStream) { System.out.println(line); } for (String line : errorStream) { System.out.println(line); } } }
package no.ntnu.okse.protocol.mqtt; import io.moquette.BrokerConstants; import io.moquette.interception.AbstractInterceptHandler; import io.moquette.interception.InterceptHandler; import io.moquette.interception.messages.InterceptDisconnectMessage; import io.moquette.interception.messages.InterceptPublishMessage; import io.moquette.interception.messages.InterceptSubscribeMessage; import io.moquette.interception.messages.InterceptUnsubscribeMessage; import io.moquette.parser.proto.messages.AbstractMessage; import io.moquette.parser.proto.messages.PublishMessage; import io.moquette.server.Server; import io.moquette.server.config.IConfig; import io.moquette.server.config.MemoryConfig; import io.netty.channel.Channel; import no.ntnu.okse.core.messaging.Message; import no.ntnu.okse.core.messaging.MessageService; import no.ntnu.okse.core.topic.TopicService; import org.apache.log4j.Logger; import javax.validation.constraints.NotNull; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class MQTTServer extends Server { private static Logger log = Logger.getLogger(Server.class); private static String protocolServerType; private MQTTProtocolServer ps; private final IConfig config; private List<InterceptHandler> interceptHandlers; private MQTTSubscriptionManager subscriptionManager; /** * Class for the interceptors to be used in Moquette */ protected class MQTTListener extends AbstractInterceptHandler { @Override public void onPublish(InterceptPublishMessage message) { HandlePublish(message); } @Override public void onSubscribe(InterceptSubscribeMessage message) { HandleSubscribe(message); } @Override public void onUnsubscribe(InterceptUnsubscribeMessage message) { HandleUnsubscribe(message); } @Override public void onDisconnect(InterceptDisconnectMessage message) { HandleDisconnect(message); } } /** * Constructor, sets the protocolServer and instantiates and adds the interceptors for Moquette messages. * Also sets the host and port for the server to listen to * @param ps the MQTTprotocolserver instance * @param host the host to listen to * @param port the port to listen to */ public MQTTServer(MQTTProtocolServer ps, String host, int port) { this.ps = ps; protocolServerType = "mqtt"; interceptHandlers = new ArrayList<>(); interceptHandlers.add(createListeners()); config = new MemoryConfig(getConfig(host, port)); } /** * Starts the server */ public void start() { try { startServer(config, interceptHandlers); } catch (IOException e) { ps.incrementTotalErrors(); e.printStackTrace(); } } /** * Method to handle a published message, one that comes from Moquette and should be forwarded to OKSE * @param message the message to forward to OKSE */ void HandlePublish(InterceptPublishMessage message) { log.info("MQTT message received on topic: " + message.getTopicName() + " from ID: " + message.getClientID()); Channel channel = getChannelByClientId(message.getClientID()); if (channel == null) return; String topic = message.getTopicName(); String payload = getPayload(message); TopicService.getInstance().addTopic(topic); Message msg = new Message(payload, topic, null, protocolServerType); msg.setAttribute("qos", String.valueOf(message.getQos().byteValue())); sendMessageToOKSE(msg); ps.incrementTotalMessagesReceived(); } /** * Method to handle an unsubscribe message from Moquette. * @param message the unsubscribe message that was sent to Moquette from a client */ public void HandleUnsubscribe(InterceptUnsubscribeMessage message) { log.info("Client unsubscribed from: " + message.getTopicFilter() + " ID: " + message.getClientID()); Channel channel = getChannelByClientId(message.getClientID()); int port = getPort(channel); String host = getHost(channel); String topic = message.getTopicFilter(); subscriptionManager.removeSubscriber(host, port, topic); } /** * Handles a disconnect message * @param message the disconnect message that was sent to Moquette from a client */ void HandleDisconnect(InterceptDisconnectMessage message) { log.info("Client disconnected ID: " + message.getClientID()); String clientID = message.getClientID(); subscriptionManager.removeSubscribers(clientID); } /** * Handles the subscribe message * @param message the subscribe message that was sent to Moquette from a client */ void HandleSubscribe(InterceptSubscribeMessage message) { log.info("Client subscribed to: " + message.getTopicFilter() + " ID: " + message.getClientID()); TopicService.getInstance().addTopic(message.getTopicFilter()); Channel channel = getChannelByClientId(message.getClientID()); if (channel == null) return; int port = getPort(channel); String host = getHost(channel); subscriptionManager.addSubscriber(host, port, message.getTopicFilter(), message.getClientID()); } /** * Sends a message into the OKSE core * @param msg the OKSE message to send into the core */ public void sendMessageToOKSE(Message msg) { MessageService.getInstance().distributeMessage(msg); } /** * This method returns the payload of a publish message * @param message the publish message that was sent to Moquette from, a client. * @return the payload of the message */ private String getPayload(InterceptPublishMessage message) { ByteBuffer buffer = message.getPayload(); String payload = new String(buffer.array(), buffer.position(), buffer.limit()); return payload; } /** * This method returns the port from a channel * @param channel the channel to return the port for * @return the port number of the channel */ private int getPort(Channel channel) { return ((InetSocketAddress) channel.remoteAddress()).getPort(); } /** * This method returns the host from a channel * @param channel the channel to return the host for * @return the host of the channel */ private String getHost(Channel channel) { return ((InetSocketAddress) channel.remoteAddress()).getHostString(); } /** * Sets the subscription manager * @param subscriptionManager the MQTT subscription manager instance */ public void setSubscriptionManager(MQTTSubscriptionManager subscriptionManager) { this.subscriptionManager = subscriptionManager; } /** * Returns the config of the server * @param host the host of the server * @param port the port of the server * @return returns a Proprties object of the config of the server */ private Properties getConfig(String host, int port) { Properties properties = new Properties(); properties.setProperty(BrokerConstants.HOST_PROPERTY_NAME, host); properties.setProperty(BrokerConstants.PORT_PROPERTY_NAME, "" + port); // Disable automatic publishing (handled by the broker instead) properties.setProperty(BrokerConstants.PUBLISH_TO_CONSUMERS, "false"); return properties; } /** * Sends the message to any subscriber that is subscribed to the topic that the message was sent to * * @param message is the message that is sent from OKSE core */ public void sendMessage(@NotNull Message message) { log.debug("Byte size of message, assuming ascii: " + message.getMessage().length() * 8); PublishMessage msg = createMQTTMessage(message); ArrayList<MQTTSubscriber> subscribers = subscriptionManager.getAllSubscribersFromTopic(message.getTopic()); if (subscribers.size() > 0) { //This will incremenet the total messages sent for each of the subscribers that the subscription manager found. //We should never send fewer or more messages than the number of subscriptions. for (int i = 0; i < subscribers.size(); i++) { ps.incrementTotalMessagesSent(); } internalPublish(msg); } } /** * Creates an MQTT message from the given arguments * * @param message The OKSE message to use when creating MQTT message */ protected PublishMessage createMQTTMessage(@NotNull Message message) { System.out.println(message); PublishMessage msg = new PublishMessage(); ByteBuffer payload = ByteBuffer.wrap(message.getMessage().getBytes()); String topicName = message.getTopic(); msg.setPayload(payload); msg.setTopicName(topicName); if (message.getAttribute("qos") == null) msg.setQos(AbstractMessage.QOSType.EXACTLY_ONCE); else msg.setQos(AbstractMessage.QOSType.valueOf(Byte.valueOf(message.getAttribute("qos")))); return msg; } public MQTTListener createListeners(){ return new MQTTListener(); } }
package com.rgi.geopackage; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystems; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; import org.junit.Assert; import org.junit.Test; import store.GeoPackageReader; import store.GeoPackageWriter; import com.rgi.common.BoundingBox; import com.rgi.common.coordinate.CoordinateReferenceSystem; import com.rgi.common.coordinate.CrsCoordinate; import com.rgi.common.coordinate.referencesystem.profile.SphericalMercatorCrsProfile; import com.rgi.common.tile.scheme.TileMatrixDimensions; import com.rgi.common.tile.scheme.TileScheme; import com.rgi.common.tile.scheme.ZoomTimesTwo; import com.rgi.common.tile.store.TileStoreException; import com.rgi.common.util.ImageUtility; import com.rgi.geopackage.GeoPackage.OpenMode; import com.rgi.geopackage.core.SpatialReferenceSystem; import com.rgi.geopackage.tiles.RelativeTileCoordinate; import com.rgi.geopackage.tiles.Tile; import com.rgi.geopackage.tiles.TileMatrix; import com.rgi.geopackage.tiles.TileSet; import com.rgi.geopackage.verification.ConformanceException; /** * @author Jenifer Cochran * */ @SuppressWarnings("javadoc") public class GeopackageTileStoreTest { private final Random randomGenerator = new Random(); @Test(expected = IllegalArgumentException.class) public void geopackageReaderIllegalArgumentException() throws SQLException, ClassNotFoundException, ConformanceException, IOException { final File testFile = this.getRandomFile(9); try(final GeoPackageReader reader = new GeoPackageReader(testFile, null)) { fail("Expected GeoPackage Reader to throw an IllegalArguementException when passing a null value for tileSet"); } finally { if(testFile.exists()) { if(!testFile.delete()) { throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile)); } } } } @Test(expected = IllegalArgumentException.class) public void geopackageReaderIllegalArgumentException2() throws SQLException, ClassNotFoundException, ConformanceException, IOException { final File testFile = this.getRandomFile(9); try(final GeoPackageReader reader = new GeoPackageReader(null, "tablename")) { fail("Expected GeoPackage Reader to throw an IllegalArguementException when passing a null value for GeoPackage"); } finally { if(testFile.exists()) { if(!testFile.delete()) { throw new RuntimeException(String.format("Unable to delete testFile. testFile: %s", testFile)); } } } } @Test(expected = IllegalArgumentException.class) public void geopackageReaderIllegalArgumentException3() throws ClassNotFoundException, SQLException, ConformanceException, IOException { File testFile = this.getRandomFile(11); try(GeoPackage gpkg = new GeoPackage(testFile)) { try(GeoPackageReader reader = new GeoPackageReader(testFile, "A TileSet that doesn't Exist");) { fail("Expected GeoPackageReader to throw an illegalArgumentException when trying to read from a tileSet that doesn't exist"); } } finally { deleteFile(testFile); } } /** * Tests if the getBounds method in geopackage reader * returns the expected bounding box * @throws SQLException * @throws ConformanceException * @throws FileNotFoundException * @throws ClassNotFoundException * @throws FileAlreadyExistsException * @throws TileStoreException * */ @Test public void geopackageReaderGetBounds()throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; final BoundingBox bBoxGiven = new BoundingBox(0.0,0.0,180.0,180.0); try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { gpkg.tiles().addTileSet(tableName, "identifier", "description", bBoxGiven, gpkg.core().getSpatialReferenceSystem(4326)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final BoundingBox bBoxReturned = gpkgReader.getBounds(); Assert.assertTrue("The bounding box returned from GeoPackageReader was not the same that was given.", bBoxGiven.equals(bBoxReturned)); } } finally { deleteFile(testFile); } } /** * Tests if countTiles method from GeoPackage Reader * returns the expected value * * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws TileStoreException * @throws IOException */ @Test public void geopackageReaderCountTiles() throws ClassNotFoundException, SQLException, ConformanceException, TileStoreException, IOException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0,0.0,180.0,180.0); final TileSet tileSet = gpkg.tiles().addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final int zoomLevel = 2; final int matrixWidth = 3; final int matrixHeight = 3; final int tileWidth = 256; final int tileHeight = 256; final double pixelXSize = bBox.getWidth()/matrixWidth/tileWidth; final double pixelYSize = bBox.getHeight()/matrixHeight/tileHeight; final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize); final RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 0, 2); //add tiles gpkg.tiles().addTile(tileSet, tileMatrix, coordinate, createImageBytes(BufferedImage.TYPE_3BYTE_BGR)); gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 1, 2), createImageBytes(BufferedImage.TYPE_3BYTE_BGR)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final long numberOfTiles = gpkgReader.countTiles(); Assert.assertTrue(String.format("Expected the GeoPackage Reader countTiles to return a value of 2 but instead returned %d", numberOfTiles), numberOfTiles == 2); } } finally { deleteFile(testFile); } } /** * Tests if GeoPackage Reader Returns the expected * value for getByteSize() of the file * * @throws FileAlreadyExistsException * @throws ClassNotFoundException * @throws FileNotFoundException * @throws SQLException * @throws ConformanceException * @throws TileStoreException */ @Test public void getByteSize() throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBoxGiven = new BoundingBox(0.0,0.0,180.0,180.0); gpkg.tiles().addTileSet(tableName, "identifier", "description", bBoxGiven, gpkg.core().getSpatialReferenceSystem(4326)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final long byteSizeReturned = gpkgReader.getByteSize(); final long byteSizeExpected = testFile.getTotalSpace(); Assert.assertTrue(String.format("The GeoPackage Reader did not return the expected value. \nExpected: %d Actual: %d", byteSizeReturned, byteSizeExpected), byteSizeReturned == byteSizeExpected); } } finally { deleteFile(testFile); } } /** * Tests if the tile retrieved is the same as it was given * (or as expected) using getTile from GeoPackage Reader * getTile (row, column, zoom) * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws IOException * @throws TileStoreException */ @Test public void getTile() throws ClassNotFoundException, SQLException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0, 0.0, 180.0, 180.0); final TileSet tileSet = gpkg.tiles().addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final int zoomLevel = 2; final int matrixWidth = 3; final int matrixHeight = 3; final int tileWidth = 256; final int tileHeight = 256; final double pixelXSize = bBox.getWidth()/matrixWidth/tileWidth; final double pixelYSize = bBox.getHeight()/matrixHeight/tileHeight; final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize); final RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 0, 2); final Tile tileExpected = gpkg.tiles().addTile(tileSet, tileMatrix, coordinate, createImageBytes(BufferedImage.TYPE_4BYTE_ABGR)); gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 1, 2), createImageBytes(BufferedImage.TYPE_4BYTE_ABGR)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final BufferedImage returnedImage = gpkgReader.getTile(coordinate.getRow(), coordinate.getColumn(), coordinate.getZoomLevel()); Assert.assertArrayEquals("The tile image data returned from getTile in GeoPackage reader wasn't the same as the one given.", tileExpected.getImageData(), ImageUtility.bufferedImageToBytes(returnedImage, "PNG")); } } finally { deleteFile(testFile); } } /** * Tests if it will return the correct tile given the * crs tile coordinate * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws IOException * @throws TileStoreException */ @Test public void getTile2WithCrsCoordinate() throws ClassNotFoundException, SQLException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0, 0.0, 180.0, 180.0); final TileSet tileSet = gpkg.tiles().addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final int zoomLevel = 2; final int matrixWidth = 3; final int matrixHeight = 3; final int tileWidth = 256; final int tileHeight = 256; final double pixelXSize = bBox.getWidth()/matrixWidth/tileWidth; final double pixelYSize = bBox.getHeight()/matrixHeight/tileHeight; final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize); final RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 0, 2); //add tiles final Tile tileExpected = gpkg.tiles().addTile(tileSet, tileMatrix, coordinate, createImageBytes(BufferedImage.TYPE_4BYTE_ABGR)); gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(0, 1, 2), createImageBytes(BufferedImage.TYPE_4BYTE_ABGR)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final CrsCoordinate crsTileCoordinate = new CrsCoordinate(130.0, 60.0, "epsg", 4326); final BufferedImage returnedImage = gpkgReader.getTile(crsTileCoordinate, zoomLevel); Assert.assertArrayEquals("The tile image data returned from getTile in GeoPackage reader wasn't the same as the one given.", tileExpected.getImageData(), ImageUtility.bufferedImageToBytes(returnedImage, "PNG")); } } finally { deleteFile(testFile); } } /** * Tests if it will return the correct Tile * when given a Crscoordinate. This is an edge case. * * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws IOException * @throws TileStoreException */ @Test public void getTile3CrsCoordinate() throws ClassNotFoundException, SQLException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(8); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0, 0.0, 180.0, 180.0); final TileSet tileSet = gpkg.tiles().addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final int zoomLevel = 2; final int matrixWidth = 3; final int matrixHeight = 3; final int tileWidth = 256; final int tileHeight = 256; final double pixelXSize = bBox.getWidth()/matrixWidth/tileWidth; final double pixelYSize = bBox.getHeight()/matrixHeight/tileHeight; final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, pixelXSize, pixelYSize); final RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 0, 2); //add tiles gpkg.tiles().addTile(tileSet, tileMatrix, coordinate, createImageBytes(BufferedImage.TYPE_BYTE_GRAY)); final Tile tileExpected = gpkg.tiles().addTile(tileSet, tileMatrix, new RelativeTileCoordinate(2, 0, 2), createImageBytes(BufferedImage.TYPE_BYTE_GRAY)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final CrsCoordinate crsTileCoordinate = new CrsCoordinate(60.0, 59.0, "epsg", 4326); final BufferedImage returnedImage = gpkgReader.getTile(crsTileCoordinate, zoomLevel); Assert.assertArrayEquals("The tile image data returned from getTile in GeoPackage reader wasn't the same as the one given.", tileExpected.getImageData(), ImageUtility.bufferedImageToBytes(returnedImage, "PNG")); } } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void getTileIllegalArgumentException() throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(12); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { gpkg.tiles().addTileSet(tableName, "identifier", "description", new BoundingBox(0.0,0.0,30.0,60.0), gpkg.core().getSpatialReferenceSystem(4326)); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { gpkgReader.getTile(null, 2); fail("Expected GeoPackageReader to throw an IllegalArgumentException when passing a null value to coordinate in getTile method"); } } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void getTileIllegalArgumentException2() throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(12); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { gpkg.tiles().addTileSet(tableName, "identifier", "description", new BoundingBox(0.0,0.0,30.0,60.0), gpkg.core().addSpatialReferenceSystem("Srs Name", 3857, "EPSG", 3857, "definition", "description")); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final CrsCoordinate crsCoord = new CrsCoordinate(2, 0, "EPSG", 3395); gpkgReader.getTile(crsCoord, 2); fail("Expected GeoPackageReader to throw an IllegalArgumentException when passing a null value to coordinate in getTile method"); } } finally { deleteFile(testFile); } } /** * Tests if GeoPackageReader returns a null value for * a buffered image when asking for a tile that is not * in the geopackage * @throws FileAlreadyExistsException * @throws ClassNotFoundException * @throws FileNotFoundException * @throws SQLException * @throws ConformanceException * @throws TileStoreException */ @Test public void getTileThatDoesntExist() throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(9); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { gpkg.tiles().addTileSet(tableName, "identifier", "description", new BoundingBox(0.0,0.0,30.0,60.0), gpkg.core().addSpatialReferenceSystem("Srs Name", 3857, "EPSG", 3857, "definition", "description")); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final CrsCoordinate coordinate = new CrsCoordinate(2, 0, "EPSG", 3857); final BufferedImage imageReturned = gpkgReader.getTile(coordinate, 4); assertTrue("Asked for a tile that didn't exist in the gpkg and didn't return a null value for the buffer image", imageReturned == null); } } finally { deleteFile(testFile); } } /** * Tests if the GeoPackage Reader returns the expected * coordinate reference system * @throws FileAlreadyExistsException * @throws ClassNotFoundException * @throws FileNotFoundException * @throws SQLException * @throws ConformanceException */ @Test public void getCoordinateReferenceSystem() throws SQLException, ClassNotFoundException, ConformanceException, IOException { final File testFile = this.getRandomFile(7); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final SpatialReferenceSystem spatialReferenceSystem = gpkg.core().addSpatialReferenceSystem("WebMercator", 3857, "epsg", 3857, "definition", "description"); gpkg.tiles().addTileSet(tableName, "identifier", "description", new BoundingBox(0.0,0.0,30.0,60.0), spatialReferenceSystem); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final CoordinateReferenceSystem coordinateReferenceSystemReturned = gpkgReader.getCoordinateReferenceSystem(); Assert.assertTrue(String.format("The coordinate reference system returned is not what was expected. Actual authority: %s Actual Identifer: %d\nExpected authority: %s Expected Identifier: %d.", coordinateReferenceSystemReturned.getAuthority(), coordinateReferenceSystemReturned.getIdentifier(), spatialReferenceSystem.getOrganization(), spatialReferenceSystem.getIdentifier()), coordinateReferenceSystemReturned.getAuthority().equalsIgnoreCase(spatialReferenceSystem.getOrganization()) && coordinateReferenceSystemReturned.getIdentifier() == spatialReferenceSystem.getIdentifier()); } } finally { deleteFile(testFile); } } /** * Tests if the GeoPackage Reader returns the expected zoom levels * for a given geopackage and tile set * @throws FileAlreadyExistsException * @throws ClassNotFoundException * @throws FileNotFoundException * @throws SQLException * @throws ConformanceException * @throws TileStoreException */ @Test public void getZoomLevels() throws SQLException, ClassNotFoundException, ConformanceException, IOException, TileStoreException { final File testFile = this.getRandomFile(10); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0,0.0,30.0,60.0); final TileSet tileSet = gpkg.tiles() .addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final TileSet tileSet2 = gpkg.tiles() .addTileSet("tabelName2", "identifier2", "description2", bBox, gpkg.core().getSpatialReferenceSystem(-1)); final Set<Integer> zoomLevelsExpected = new HashSet<>(); zoomLevelsExpected.add(2); zoomLevelsExpected.add(5); zoomLevelsExpected.add(9); zoomLevelsExpected.add(20); final int tileWidth = 256; final int tileHeight = 256; final TileScheme tileScheme = new ZoomTimesTwo(2, 20, 1, 1); addTileMatriciesToGpkg(zoomLevelsExpected, tileSet, gpkg, tileScheme, tileWidth, tileHeight); gpkg.tiles().addTileMatrix(tileSet2, 7, 2, 2, tileWidth, tileHeight, bBox.getWidth() / 2 / tileWidth, bBox.getHeight() / 2 / tileHeight); //this one is not included in zooms because it is a different tileset try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final Set<Integer> zoomLevelsReturned = gpkgReader.getZoomLevels(); Assert.assertTrue(String.format("The GeoPackage Reader did not return all of the zoom levels expected. Expected Zooms: %s. Actual Zooms: %s", zoomLevelsExpected.stream().map(integer -> integer.toString()).collect(Collectors.joining(", ")), zoomLevelsReturned.stream().map(integer -> integer.toString()).collect(Collectors.joining(", "))), zoomLevelsReturned.containsAll(zoomLevelsExpected)); } } finally { deleteFile(testFile); } } /** * Tests if the GeoPackage Reader returns the correct TileScheme given a GeoPackage * with various zoom levels and matrices * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws IOException */ @Test public void geoPackageReaderGetTileScheme() throws ClassNotFoundException, SQLException, ConformanceException, IOException { final File testFile = this.getRandomFile(10); final String tableName = "tablename"; try(GeoPackage gpkg = new GeoPackage(testFile, OpenMode.Create)) { final BoundingBox bBox = new BoundingBox(0.0,0.0,90.0,90.0); final TileSet tileSet = gpkg.tiles() .addTileSet(tableName, "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); final Set<Integer> zoomLevelsExpected = new HashSet<>(); zoomLevelsExpected.add(2); zoomLevelsExpected.add(5); zoomLevelsExpected.add(9); zoomLevelsExpected.add(20); final int tileWidth = 256; final int tileHeight = 256; final TileScheme tileScheme = new ZoomTimesTwo(2, 20, 1, 1); final Set<TileMatrixDimensions> tileMatrixDimensionsExpected = new HashSet<>(); addTileMatriciesToGpkg(zoomLevelsExpected, tileSet, gpkg, tileScheme, tileWidth, tileHeight); try(final GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { TileScheme tileSchemeReturned = gpkgReader.getTileScheme(); List<TileMatrixDimensions> tileMatrixDimensionsReturned = zoomLevelsExpected.stream().map(zoomLevel -> tileSchemeReturned.dimensions(zoomLevel)).collect(Collectors.toList()); assertTrue(String.format("The TileScheme from the gpkgReader did not return all the dimensions expected or they were incorrect from what was given to the geopackage"), tileMatrixDimensionsExpected.stream().allMatch(expectedDimension -> tileMatrixDimensionsReturned.stream().anyMatch(returnedDimension -> expectedDimension.getWidth() == returnedDimension.getWidth() && expectedDimension.getHeight() == returnedDimension.getWidth()))); } } finally { deleteFile(testFile); } } /** * Tests if the method .stream() in GeoPackageReader returns the expected tile handles * with the correct values * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws IOException * @throws TileStoreException */ @Test public void getStreamofTileHandles() throws ClassNotFoundException, SQLException, ConformanceException, IOException, TileStoreException { File testFile = this.getRandomFile(12); try(GeoPackage gpkg = new GeoPackage(testFile)) { //create a tileSet final BoundingBox bBox = new BoundingBox(0.0,0.0,40.0,80.0); final TileSet tileSet = gpkg.tiles() .addTileSet("tableName", "identifier", "description", bBox, gpkg.core().getSpatialReferenceSystem(4326)); int matrixWidth = 2; int matrixHeight = 4; int tileWidth = 256; int tileHeight = 256; int zoomLevel = 9; //create matrix final TileMatrix tileMatrix = gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, bBox.getWidth() / matrixWidth / tileWidth, bBox.getHeight() / matrixHeight / tileHeight); RelativeTileCoordinate coordinate = new RelativeTileCoordinate(0, 0, zoomLevel); //add three tiles Tile tile = gpkg.tiles().addTile(tileSet, tileMatrix, coordinate, createImageBytes(BufferedImage.TYPE_INT_ARGB)); RelativeTileCoordinate coordinate2 = new RelativeTileCoordinate(1, 0, zoomLevel); Tile tile2 = gpkg.tiles().addTile(tileSet, tileMatrix, coordinate2, createImageBytes(BufferedImage.TYPE_3BYTE_BGR)); RelativeTileCoordinate coordinate3 = new RelativeTileCoordinate(0, 1, zoomLevel); Tile tile3 = gpkg.tiles().addTile(tileSet, tileMatrix, coordinate3, createImageBytes(BufferedImage.TYPE_BYTE_GRAY)); //create a list of the expected tiles List<Tile> expectedTiles = Arrays.asList(tile, tile2, tile3); //create a geopackage reader try(GeoPackageReader reader = new GeoPackageReader(testFile, tileSet.getTableName())) { //check to see if tiles match boolean tilesEqual = false; tilesEqual = expectedTiles.stream().allMatch(expectedTile -> { try { return reader.stream().anyMatch(tileHandle -> { try { return tileHandle.getRow() == expectedTile.getRow() && tileHandle.getColumn() == expectedTile.getColumn() && tileHandle.getZoomLevel() == expectedTile.getZoomLevel() && tileHandle.getImage().getType() == ImageUtility.bytesToBufferedImage(expectedTile.getImageData()).getType(); } catch(IOException | TileStoreException ex) { return false; } }); } catch(TileStoreException ex) { return false; } }); assertTrue("GeoPackage reader returned tiles that were not equal to the ones in the GeoPackage.", tilesEqual); } } finally { deleteFile(testFile); } } /** * Tests if GeoPackage Writer will be able to add a tile to * an existing GeoPackage * @throws ClassNotFoundException * @throws SQLException * @throws ConformanceException * @throws MimeTypeParseException * @throws IOException * @throws TileStoreException */ @Test public void geopackageWriterAddTile() throws Exception { final File testFile = this.getRandomFile(6); final String tableName = "tableName"; final int row = 0; final int column = 1; final int zoomLevel = 0; try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), tableName, "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { final BufferedImage bufferedImage = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY); gpkgWriter.addTile(row, column, zoomLevel, bufferedImage); } try(GeoPackageReader gpkgReader = new GeoPackageReader(testFile, tableName)) { final BufferedImage tile = gpkgReader.getTile(row, column, zoomLevel); assertTrue("GeoPackageWriter was unable to add a tile to a GeoPackage", tile != null); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void addTileIllegalArgumentException() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException, TileStoreException { final File testFile = this.getRandomFile(6); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { gpkgWriter.addTile(0, 0, 0, null); fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter image."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void addTileIllegalArgumentException2() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException, TileStoreException { final File testFile = this.getRandomFile(6); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { gpkgWriter.addTile(new CrsCoordinate(20.0,30.0, "epsg", 4326), 0, null); fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter image."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void addTileIllegalArgumentException3() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException, TileStoreException { final File testFile = this.getRandomFile(6); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { gpkgWriter.addTile(null, 0, new BufferedImage(256,256, BufferedImage.TYPE_INT_ARGB)); fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter crsCoordinate."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void addTileIllegalArgumentException4() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException, TileStoreException { final File testFile = this.getRandomFile(6); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { gpkgWriter.addTile(new CrsCoordinate(20.0, 30.0, "epsg", 3395), 0, new BufferedImage(256,256, BufferedImage.TYPE_INT_ARGB)); fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user adds a tile that is a different crs coordinate reference system than the profile."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException { final File testFile = this.getRandomFile(8); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), null, "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter tile set table name."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException2() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException { final File testFile = this.getRandomFile(8); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(null, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter geo package file."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException3() throws SQLException, ClassNotFoundException, ConformanceException, IOException { final File testFile = this.getRandomFile(8); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), null, null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in a null value for the parameter imageOutputFormat."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException4() throws SQLException, ClassNotFoundException, ConformanceException, IOException, MimeTypeParseException { final File testFile = this.getRandomFile(8); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("text/xml"), null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in an unsupported image output format."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException5() throws ClassNotFoundException, SQLException, ConformanceException, IOException, MimeTypeParseException { final File testFile = this.getRandomFile(8); try(GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, null, "foo", "identifier", "description", new BoundingBox(0.0,0.0,90.0,90.0), new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in null for the crs."); } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException6() throws ClassNotFoundException, SQLException, ConformanceException, IOException, MimeTypeParseException { final File testFile = this.getRandomFile(8); try (GeoPackage gpkg = new GeoPackage(testFile)) { String tableName = "tableName"; String identifier = "identifier"; String description = "description"; BoundingBox boundingBox = new BoundingBox(0.0, 0.0, 90.0, 90.0); SpatialReferenceSystem spatialReferenceSystem = gpkg.core().getSpatialReferenceSystem(4326); gpkg.tiles().addTileSet(tableName, identifier, description, boundingBox, spatialReferenceSystem); try (GeoPackageWriter gpkgWriter = new GeoPackageWriter(testFile, new CoordinateReferenceSystem("EPSG", 4326), tableName, identifier, description, boundingBox, new ZoomTimesTwo(0, 0, 2, 4), new MimeType("image/jpeg"), null)) { fail("Expected GeoPackageWriter to throw an IllegalArgumentException if a user puts in null for the crs."); } } finally { deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void geoPackageWriterIllegalArgumentException7() throws ClassNotFoundException, SQLException, ConformanceException, IOException, MimeTypeParseException { File testFile = this.getRandomFile(9); try(GeoPackage gpkg = new GeoPackage(testFile)) { SphericalMercatorCrsProfile spherical = new SphericalMercatorCrsProfile(); BoundingBox tileSetBounds = new BoundingBox(SphericalMercatorCrsProfile.Bounds.getMinY()/2, SphericalMercatorCrsProfile.Bounds.getMinX()/4, SphericalMercatorCrsProfile.Bounds.getMaxY()/8, SphericalMercatorCrsProfile.Bounds.getMaxX()/10); String tileSetName = "tableName"; String identifier = "identifier"; String description = "description"; int zoomLevel = 6; int tileWidth = 256; int tileHeight = 256; int matrixWidth = 10; int matrixHeight = 6; TileSet tileSet = gpkg.tiles().addTileSet(tileSetName, identifier, description, tileSetBounds, gpkg.core().addSpatialReferenceSystem(spherical.getName(), spherical.getCoordinateReferenceSystem().getIdentifier(), spherical.getCoordinateReferenceSystem().getAuthority(), spherical.getCoordinateReferenceSystem().getIdentifier(), spherical.getWellKnownText(), spherical.getDescription())); gpkg.tiles().addTileMatrix(tileSet, zoomLevel, matrixWidth, matrixHeight, tileWidth, tileHeight, tileSetBounds.getWidth()/matrixWidth/tileWidth, tileSetBounds.getHeight()/matrixHeight/tileHeight); try(GeoPackageWriter writer = new GeoPackageWriter(testFile, spherical.getCoordinateReferenceSystem(), tileSetName, identifier, description, tileSetBounds, new ZoomTimesTwo(5, 8, 3, 5), new MimeType("image/png"), null);) { fail("Expected GeoPackageWriter to throw when the tileSet already exists in the GeoPackage"); } } finally { deleteFile(testFile); } } /** * Tests if the GeoPackageWriter can write a tile to a GeopPackage * and if the GeoPackageReader can read that tile by retrieving it by * crs coordinate and tile coordinate * @throws ClassNotFoundException * @throws ConformanceException * @throws IOException * @throws SQLException * @throws MimeTypeParseException * @throws TileStoreException */ @Test public void addTileCrsCoordinate() throws ClassNotFoundException, ConformanceException, IOException, SQLException, MimeTypeParseException, TileStoreException { File testFile = this.getRandomFile(9); try { SphericalMercatorCrsProfile spherical = new SphericalMercatorCrsProfile(); BoundingBox tileSetBounds = new BoundingBox(spherical.getBounds().getMinY()/2, spherical.getBounds().getMinX()/3, spherical.getBounds().getMaxY()-100, spherical.getBounds().getMaxX()-100); String tileSetName = "tableName"; //create a geopackage writer try(GeoPackageWriter writer = new GeoPackageWriter(testFile, spherical.getCoordinateReferenceSystem(), tileSetName, "identifier", "description", tileSetBounds, new ZoomTimesTwo(5, 8, 3, 5), new MimeType("image/png"), null);) { int zoomLevel = 6; BufferedImage imageExpected = createBufferedImage(BufferedImage.TYPE_BYTE_GRAY); CrsCoordinate crsCoordinate = new CrsCoordinate(tileSetBounds.getMaxY(), tileSetBounds.getMinX(), spherical.getCoordinateReferenceSystem());//upper left tile //add an image to the writer writer.addTile(crsCoordinate, zoomLevel, imageExpected); //create a reader try(GeoPackageReader reader = new GeoPackageReader(testFile,tileSetName);) { //check if the images are returned as expected from a crs coordinate and relative tile coordinate BufferedImage imageReturnedCrs = reader.getTile(crsCoordinate, zoomLevel); BufferedImage imageReturnedTileCoordinate = reader.getTile(0, 0, zoomLevel); //upper left tile assertTrue("The images returned by the reader were null when they should have returned a buffered image.",imageReturnedCrs != null && imageReturnedTileCoordinate != null); } } } finally { deleteFile(testFile); } } private static void deleteFile(final File testFile) { if (testFile.exists()) { if (!testFile.delete()) { throw new RuntimeException(String.format( "Unable to delete testFile. testFile: %s", testFile)); } } } private String getRanString(final int length) { final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(this.randomGenerator.nextInt(characters.length())); } return new String(text); } private File getRandomFile(final int length) { File testFile; do { testFile = new File(String.format(FileSystems.getDefault().getPath(this.getRanString(length)).toString() + ".gpkg")); } while (testFile.exists()); return testFile; } private static BufferedImage createBufferedImage(final int bufferedImageType) { return new BufferedImage(256,256, bufferedImageType); } private static byte[] createImageBytes(final int bufferedImageType) throws IOException { return ImageUtility.bufferedImageToBytes(new BufferedImage(256, 256, bufferedImageType), "png"); } private static Set<TileMatrixDimensions> addTileMatriciesToGpkg(Set<Integer> zoomLevels, TileSet tileSet, GeoPackage gpkg, TileScheme tileScheme, int tileWidth, int tileHeight) throws SQLException { Set<TileMatrixDimensions> tileMatrixDimensionsExpected = new HashSet<>(); BoundingBox bBox = tileSet.getBoundingBox(); for(final int zoomLevel : zoomLevels) { final TileMatrixDimensions dimensions = tileScheme.dimensions(zoomLevel); tileMatrixDimensionsExpected.add(dimensions); final double pixelXSize = bBox.getWidth() / dimensions.getWidth() / tileWidth; final double pixelYSize = bBox.getHeight() / dimensions.getHeight() / tileHeight; gpkg.tiles().addTileMatrix(tileSet, zoomLevel, dimensions.getWidth(), dimensions.getHeight(), tileWidth, tileHeight, pixelXSize, pixelYSize); } return tileMatrixDimensionsExpected; } }
package org.neo4j.kernel.impl.nioneo.store; import static org.neo4j.kernel.Config.ARRAY_BLOCK_SIZE; import static org.neo4j.kernel.Config.STRING_BLOCK_SIZE; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.neo4j.helpers.UTF8; import org.neo4j.kernel.IdGeneratorFactory; import org.neo4j.kernel.IdType; /** * Implementation of the property store. This implementation has two dynamic * stores. One used to store keys and another for string property values. */ public class PropertyStore extends AbstractStore implements Store { public static final int DEFAULT_DATA_BLOCK_SIZE = 120; public static final int DEFAULT_PAYLOAD_SIZE = 32; public static final String TYPE_DESCRIPTOR = "PropertyStore"; public static final int RECORD_SIZE = 1/*next and prev high bits*/ + 4/*next*/ + 4/*prev*/ + DEFAULT_PAYLOAD_SIZE /*property blocks*/; private DynamicStringStore stringPropertyStore; private PropertyIndexStore propertyIndexStore; private DynamicArrayStore arrayPropertyStore; public PropertyStore( String fileName, Map<?,?> config ) { super( fileName, config, IdType.PROPERTY ); } @Override protected void initStorage() { stringPropertyStore = new DynamicStringStore( getStorageFileName() + ".strings", getConfig(), IdType.STRING_BLOCK ); propertyIndexStore = new PropertyIndexStore( getStorageFileName() + ".index", getConfig() ); arrayPropertyStore = new DynamicArrayStore( getStorageFileName() + ".arrays", getConfig(), IdType.ARRAY_BLOCK ); } @Override protected void setRecovered() { super.setRecovered(); stringPropertyStore.setRecovered(); propertyIndexStore.setRecovered(); arrayPropertyStore.setRecovered(); } @Override protected void unsetRecovered() { super.unsetRecovered(); stringPropertyStore.unsetRecovered(); propertyIndexStore.unsetRecovered(); arrayPropertyStore.unsetRecovered(); } @Override protected void closeStorage() { if ( stringPropertyStore != null ) { stringPropertyStore.close(); stringPropertyStore = null; } if ( propertyIndexStore != null ) { propertyIndexStore.close(); propertyIndexStore = null; } if ( arrayPropertyStore != null ) { arrayPropertyStore.close(); arrayPropertyStore = null; } } @Override public void flushAll() { stringPropertyStore.flushAll(); propertyIndexStore.flushAll(); arrayPropertyStore.flushAll(); super.flushAll(); } @Override public String getTypeDescriptor() { return TYPE_DESCRIPTOR; } @Override public int getRecordSize() { return RECORD_SIZE; } /** * Creates a new property store contained in <CODE>fileName</CODE> If * filename is <CODE>null</CODE> or the file already exists an * <CODE>IOException</CODE> is thrown. * * @param fileName * File name of the new property store * @throws IOException * If unable to create property store or name null */ public static void createStore( String fileName, Map<?,?> config ) { IdGeneratorFactory idGeneratorFactory = (IdGeneratorFactory) config.get( IdGeneratorFactory.class ); createEmptyStore( fileName, buildTypeDescriptorAndVersion( TYPE_DESCRIPTOR ), idGeneratorFactory ); int stringStoreBlockSize = DEFAULT_DATA_BLOCK_SIZE; int arrayStoreBlockSize = DEFAULT_DATA_BLOCK_SIZE; try { String stringBlockSize = (String) config.get( STRING_BLOCK_SIZE ); String arrayBlockSize = (String) config.get( ARRAY_BLOCK_SIZE ); if ( stringBlockSize != null ) { int value = Integer.parseInt( stringBlockSize ); if ( value > 0 ) { stringStoreBlockSize = value; } } if ( arrayBlockSize != null ) { int value = Integer.parseInt( arrayBlockSize ); if ( value > 0 ) { arrayStoreBlockSize = value; } } } catch ( Exception e ) { logger.log( Level.WARNING, "Exception creating store", e ); } DynamicStringStore.createStore( fileName + ".strings", stringStoreBlockSize, idGeneratorFactory, IdType.STRING_BLOCK ); PropertyIndexStore.createStore( fileName + ".index", idGeneratorFactory ); DynamicArrayStore.createStore( fileName + ".arrays", arrayStoreBlockSize, idGeneratorFactory ); } private long nextStringBlockId() { return stringPropertyStore.nextBlockId(); } public void freeStringBlockId( long blockId ) { stringPropertyStore.freeBlockId( blockId ); } private long nextArrayBlockId() { return arrayPropertyStore.nextBlockId(); } public void freeArrayBlockId( long blockId ) { arrayPropertyStore.freeBlockId( blockId ); } public PropertyIndexStore getIndexStore() { return propertyIndexStore; } public void updateRecord( PropertyRecord record, boolean recovered ) { assert recovered; setRecovered(); try { updateRecord( record ); registerIdFromUpdateRecord( record.getId() ); } finally { unsetRecovered(); } } public void updateRecord( PropertyRecord record ) { PersistenceWindow window = acquireWindow( record.getId(), OperationType.WRITE ); try { updateRecord( record, window ); } finally { releaseWindow( window ); } } private void updateRecord( PropertyRecord record, PersistenceWindow window ) { long id = record.getId(); Buffer buffer = window.getOffsettedBuffer( id ); if ( record.inUse() ) { // Set up the record header short prevModifier = record.getPrevProp() == Record.NO_NEXT_RELATIONSHIP.intValue() ? 0 : (short) ( ( record.getPrevProp() & 0xF00000000L ) >> 28 ); short nextModifier = record.getNextProp() == Record.NO_NEXT_RELATIONSHIP.intValue() ? 0 : (short) ( ( record.getNextProp() & 0xF00000000L ) >> 32 ); byte modifiers = (byte) ( prevModifier | nextModifier ); /* * [pppp,nnnn] previous, next high bits */ buffer.put( modifiers ); buffer.putInt( (int) record.getPrevProp() ).putInt( (int) record.getNextProp() ); // Then go through the blocks int longsAppended = 0; // For marking the end of blocks List<PropertyBlock> blocks = record.getPropertyBlocks(); for ( int i = 0; i < blocks.size(); i++ ) { PropertyBlock block = blocks.get( i ); long[] propBlockValues = block.getValueBlocks(); for ( int k = 0; k < propBlockValues.length; k++ ) { buffer.putLong( propBlockValues[k] ); } longsAppended += propBlockValues.length; /* * For each block we need to update its dynamic record chain if * it is just created. Deleted dynamic records are in the property * record and dynamic records are never modified. Also, they are * assigned as a whole, so just checking the first should be enough. */ if ( !block.isLight() && block.getValueRecords().get( 0 ).isCreated() ) { updateDynamicRecords( block.getValueRecords() ); } } if ( longsAppended < PropertyType.getPayloadSizeLongs() ) { buffer.putLong( 0 ); } } else { if ( !isInRecoveryMode() ) { freeId( id ); } // skip over the record header, nothing useful there buffer.setOffset( buffer.getOffset() + 9 ); buffer.putLong( 0 ); } updateDynamicRecords( record.getDeletedRecords() ); } private void updateDynamicRecords( List<DynamicRecord> records ) { for (int i = 0; i < records.size(); i++) { DynamicRecord valueRecord = records.get( i ); if ( valueRecord.getType() == PropertyType.STRING.intValue() ) { stringPropertyStore.updateRecord( valueRecord ); } else if ( valueRecord.getType() == PropertyType.ARRAY.intValue() ) { arrayPropertyStore.updateRecord( valueRecord ); } else { throw new InvalidRecordException( "Unknown dynamic record" + valueRecord ); } } } public PropertyRecord getLightRecord( long id ) { PersistenceWindow window = acquireWindow( id, OperationType.READ ); try { PropertyRecord record = getRecord( id, window ); return record; } finally { releaseWindow( window ); } } /* * This will add the value records without checking if they are already * in the block - so make sure to call this after checking isHeavy() or * you will end up with duplicates. */ public void makeHeavy( PropertyBlock record ) { if ( record.getType() == PropertyType.STRING ) { Collection<DynamicRecord> stringRecords = stringPropertyStore.getLightRecords( record.getSingleValueLong() ); for ( DynamicRecord stringRecord : stringRecords ) { stringRecord.setType( PropertyType.STRING.intValue() ); record.addValueRecord( stringRecord ); } } else if ( record.getType() == PropertyType.ARRAY ) { Collection<DynamicRecord> arrayRecords = arrayPropertyStore.getLightRecords( record.getSingleValueLong() ); for ( DynamicRecord arrayRecord : arrayRecords ) { arrayRecord.setType( PropertyType.ARRAY.intValue() ); record.addValueRecord( arrayRecord ); } } } public PropertyRecord getRecord( long id ) { PropertyRecord record; PersistenceWindow window = acquireWindow( id, OperationType.READ ); try { record = getRecord( id, window ); } finally { releaseWindow( window ); } for ( PropertyBlock block : record.getPropertyBlocks() ) { // assert block.inUse(); if ( block.getType() == PropertyType.STRING ) { Collection<DynamicRecord> stringRecords = stringPropertyStore.getLightRecords( block.getSingleValueLong() ); for ( DynamicRecord stringRecord : stringRecords ) { stringRecord.setType( PropertyType.STRING.intValue() ); block.addValueRecord( stringRecord ); } } else if ( block.getType() == PropertyType.ARRAY ) { Collection<DynamicRecord> arrayRecords = arrayPropertyStore.getLightRecords( block.getSingleValueLong() ); for ( DynamicRecord arrayRecord : arrayRecords ) { arrayRecord.setType( PropertyType.ARRAY.intValue() ); block.addValueRecord( arrayRecord ); } } } return record; } private PropertyRecord getRecordFromBuffer( long id, Buffer buffer ) { int offsetAtBeggining = buffer.getOffset(); PropertyRecord record = new PropertyRecord( id ); /* * [pppp,nnnn] previous, next high bits */ byte modifiers = buffer.get(); long prevMod = ( ( modifiers & 0xF0L ) << 28 ); long nextMod = ( ( modifiers & 0x0FL ) << 32 ); long prevProp = buffer.getUnsignedInt(); long nextProp = buffer.getUnsignedInt(); record.setPrevProp( longFromIntAndMod( prevProp, prevMod ) ); record.setNextProp( longFromIntAndMod( nextProp, nextMod ) ); while ( buffer.getOffset() - offsetAtBeggining < RECORD_SIZE ) { PropertyBlock newBlock = getPropertyBlock( buffer ); if ( newBlock != null ) { record.addPropertyBlock( newBlock ); record.setInUse( true ); } else { // We assume that storage is defragged break; } } return record; } private PropertyRecord getRecord( long id, PersistenceWindow window ) { Buffer buffer = window.getOffsettedBuffer( id ); PropertyRecord toReturn = getRecordFromBuffer( id, buffer ); if ( !toReturn.inUse() ) { throw new InvalidRecordException( "Record[" + id + "] not in use" ); } return toReturn; } /* * It is assumed that the argument does hold a property block - all zeros is * a valid (not in use) block, so even if the Bits object has been exhausted a * result is returned, that has inUse() return false. Also, the argument is not * touched. */ private static PropertyBlock getPropertyBlock( Buffer buffer ) { long header = buffer.getLong(); PropertyType type = PropertyType.getPropertyType( header, true ); if ( type == null ) { return null; } PropertyBlock toReturn = new PropertyBlock(); // toReturn.setInUse( true ); int numBlocks = type.calculateNumberOfBlocksUsed( header ); long[] blockData = new long[numBlocks]; blockData[0] = header; // we already have that for ( int i = 1; i < numBlocks; i++ ) { blockData[i] = buffer.getLong(); } toReturn.setValueBlocks( blockData ); return toReturn; } public Object getValue( PropertyBlock propertyBlock ) { return propertyBlock.getType().getValue( propertyBlock, this ); } @Override public void makeStoreOk() { propertyIndexStore.makeStoreOk(); stringPropertyStore.makeStoreOk(); arrayPropertyStore.makeStoreOk(); super.makeStoreOk(); } @Override public void rebuildIdGenerators() { propertyIndexStore.rebuildIdGenerators(); stringPropertyStore.rebuildIdGenerators(); arrayPropertyStore.rebuildIdGenerators(); super.rebuildIdGenerators(); } public void updateIdGenerators() { propertyIndexStore.updateIdGenerators(); stringPropertyStore.updateHighId(); arrayPropertyStore.updateHighId(); this.updateHighId(); } private Collection<DynamicRecord> allocateStringRecords( long valueBlockId, byte[] chars ) { return stringPropertyStore.allocateRecords( valueBlockId, chars ); } private Collection<DynamicRecord> allocateArrayRecords( long valueBlockId, Object array ) { return arrayPropertyStore.allocateRecords( valueBlockId, array ); } public void encodeValue( PropertyBlock block, int keyId, Object value ) { if ( value instanceof String ) { // Try short string first, i.e. inlined in the property block String string = (String) value; if ( LongerShortString.encode( keyId, string, block, PropertyType.getPayloadSize() ) ) return; // Fall back to dynamic string store long stringBlockId = nextStringBlockId(); setSingleBlockValue( block, keyId, PropertyType.STRING, stringBlockId ); byte[] encodedString = encodeString( string ); Collection<DynamicRecord> valueRecords = allocateStringRecords( stringBlockId, encodedString ); for ( DynamicRecord valueRecord : valueRecords ) { valueRecord.setType( PropertyType.STRING.intValue() ); block.addValueRecord( valueRecord ); } } else if ( value instanceof Integer ) setSingleBlockValue( block, keyId, PropertyType.INT, ((Integer)value).longValue() ); else if ( value instanceof Boolean ) setSingleBlockValue( block, keyId, PropertyType.BOOL, (((Boolean)value).booleanValue()?1L:0L) ); else if ( value instanceof Float ) setSingleBlockValue( block, keyId, PropertyType.FLOAT, Float.floatToRawIntBits( ((Float) value).floatValue() ) ); else if ( value instanceof Long ) { long keyAndType = keyId | (((long)PropertyType.LONG.intValue()) << 24); if ( ShortArray.LONG.getRequiredBits( value ) <= 35 ) { // We only need one block for this value, special layout compared to, say, an integer block.setSingleBlock( keyAndType | (1L << 28) | (((Long)value).longValue() << 29) ); } else { // We need two blocks for this value block.setValueBlocks( new long[] {keyAndType, ((Long)value).longValue()} ); } } else if ( value instanceof Double ) block.setValueBlocks( new long[] { keyId | (((long)PropertyType.DOUBLE.intValue()) << 24), Double.doubleToRawLongBits( ((Double)value).doubleValue() ) } ); else if ( value instanceof Byte ) setSingleBlockValue( block, keyId, PropertyType.BYTE, ((Byte)value).longValue() ); else if ( value instanceof Character ) setSingleBlockValue( block, keyId, PropertyType.CHAR, ((Character)value).charValue() ); else if ( value instanceof Short ) setSingleBlockValue( block, keyId, PropertyType.SHORT, ((Short)value).longValue() ); else if ( value.getClass().isArray() ) { // Try short array first, i.e. inlined in the property block if ( ShortArray.encode( keyId, value, block, DEFAULT_PAYLOAD_SIZE ) ) return; // Fall back to dynamic array store long arrayBlockId = nextArrayBlockId(); setSingleBlockValue( block, keyId, PropertyType.ARRAY, arrayBlockId ); Collection<DynamicRecord> arrayRecords = allocateArrayRecords( arrayBlockId, value ); for ( DynamicRecord valueRecord : arrayRecords ) { valueRecord.setType( PropertyType.ARRAY.intValue() ); block.addValueRecord( valueRecord ); } } else { throw new IllegalArgumentException( "Unknown property type on: " + value + ", " + value.getClass() ); } } private void setSingleBlockValue( PropertyBlock block, int keyId, PropertyType type, long longValue ) { block.setSingleBlock( keyId | (((long) type.intValue()) << 24) | (longValue << 28) ); } public static byte[] encodeString( String string ) { return UTF8.encode( string ); } public Object getStringFor( PropertyBlock propertyBlock ) { return getStringFor( stringPropertyStore, propertyBlock ); } public static Object getStringFor( AbstractDynamicStore store, PropertyBlock propertyBlock ) { return getStringFor( store, propertyBlock.getSingleValueLong(), propertyBlock.getValueRecords() ); } public static Object getStringFor( AbstractDynamicStore store, long startRecord, Collection<DynamicRecord> dynamicRecords ) { byte[] source = readFullByteArray( startRecord, dynamicRecords, store ); return getStringFor( source ); } public static Object getStringFor( byte[] byteArray ) { return UTF8.decode( byteArray ); } public Object getArrayFor( PropertyBlock propertyBlock ) { assert !propertyBlock.isLight(); return getArrayFor( propertyBlock.getSingleValueLong(), propertyBlock.getValueRecords(), arrayPropertyStore ); } public static Object getArrayFor( long startRecord, Iterable<DynamicRecord> records, DynamicArrayStore arrayPropertyStore ) { return arrayPropertyStore.getRightArray( readFullByteArray( startRecord, records, arrayPropertyStore ) ); } public static byte[] readFullByteArray( long startRecord, Iterable<DynamicRecord> records, AbstractDynamicStore store ) { long recordToFind = startRecord; Map<Long,DynamicRecord> recordsMap = new HashMap<Long,DynamicRecord>(); for ( DynamicRecord record : records ) { recordsMap.put( record.getId(), record ); } List<byte[]> byteList = new LinkedList<byte[]>(); int totalSize = 0; while ( recordToFind != Record.NO_NEXT_BLOCK.intValue() ) { DynamicRecord record = recordsMap.get( recordToFind ); if ( record.isLight() ) { store.makeHeavy( record ); } assert record.getData().length > 0; // assert ( ( record.getData().length == ( DEFAULT_DATA_BLOCK_SIZE - // AbstractDynamicStore.BLOCK_HEADER_SIZE ) ) && ( // record.getNextBlock() != Record.NO_NEXT_BLOCK.intValue() ) ) // || ( ( record.getData().length < ( DEFAULT_DATA_BLOCK_SIZE - // AbstractDynamicStore.BLOCK_HEADER_SIZE ) ) && ( // record.getNextBlock() == Record.NO_NEXT_BLOCK.intValue() ) ); ByteBuffer buf = ByteBuffer.wrap( record.getData() ); byte[] bytes = new byte[record.getData().length]; totalSize += bytes.length; buf.get( bytes ); byteList.add( bytes ); recordToFind = record.getNextBlock(); } byte[] bArray = new byte[totalSize]; int offset = 0; for ( byte[] currentArray : byteList ) { System.arraycopy( currentArray, 0, bArray, offset, currentArray.length ); offset += currentArray.length; } assert bArray.length > 0; return bArray; } @Override public List<WindowPoolStats> getAllWindowPoolStats() { List<WindowPoolStats> list = new ArrayList<WindowPoolStats>(); list.add( stringPropertyStore.getWindowPoolStats() ); list.add( arrayPropertyStore.getWindowPoolStats() ); list.add( getWindowPoolStats() ); return list; } public int getStringBlockSize() { return stringPropertyStore.getBlockSize(); } public int getArrayBlockSize() { return arrayPropertyStore.getBlockSize(); } @Override protected boolean isRecordInUse( ByteBuffer buffer ) { // TODO: The next line is an ugly hack, but works. Buffer fromByteBuffer = new Buffer( null, buffer ); return getRecordFromBuffer( 0, fromByteBuffer ).inUse(); } }
package de.hpi.bpt.chimera.rest; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import de.hpi.bpt.chimera.execution.Case; import de.hpi.bpt.chimera.execution.CaseExecutioner; import de.hpi.bpt.chimera.execution.ExecutionService; import de.hpi.bpt.chimera.execution.controlnodes.event.AbstractEventInstance; import de.hpi.bpt.chimera.execution.controlnodes.event.behavior.MessageReceiveEventBehavior; import de.hpi.bpt.chimera.execution.controlnodes.event.eventhandling.CaseStarter; import de.hpi.bpt.chimera.execution.controlnodes.event.eventhandling.SseNotifier; import de.hpi.bpt.chimera.execution.exception.IllegalCaseModelIdException; import de.hpi.bpt.chimera.model.CaseModel; import de.hpi.bpt.chimera.model.condition.CaseStartTrigger; import de.hpi.bpt.chimera.persistencemanager.CaseModelManager; import de.hpi.bpt.chimera.rest.beans.miscellaneous.ReceiveEventJaxBean; /** * The event dispatcher class is responsible for manage registrations from * Events to RestQueries. */ @Path("eventdispatcher/") public class EventRestService extends AbstractRestService { private static Logger log = Logger.getLogger(EventRestService.class); /** * This method notifies that a certain event instance received Event was * received. In addition the event instance will be terminated. * * @param cmId * The id of a case model. * @param caseId * - the id of case. * @param requestId * - the id of the event instance receiving the event * @param eventJson * - the json content for updating the data object the event * instance * @return Response 202 because the Event was received by Chimera */ @POST @Consumes(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/instance/{instanceId}/events/{requestKey}") public Response receiveEvent(@PathParam("scenarioId") String cmId, @PathParam("instanceId") String caseId, @PathParam("requestKey") String requestId, String eventJson) { log.info("Receiving an event..."); try { CaseExecutioner caseExecutioner = ExecutionService.getCaseExecutioner(cmId, caseId); MessageReceiveEventBehavior receiveBehavior = caseExecutioner.getRegisteredEventBehavior(requestId); if (eventJson.isEmpty() || "{}".equals(eventJson)) { receiveBehavior.setEventJson(""); } else { receiveBehavior.setEventJson(eventJson); } AbstractEventInstance eventInstance = receiveBehavior.getEventInstance(); caseExecutioner.terminateDataControlNodeInstance(eventInstance); SseNotifier.notifyRefresh(); } catch (Exception e) { log.error("Error while processing a received event", e); return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(buildError(e.getMessage())).build(); } return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity("{\"message\":\"Event received.\"}").build(); } /** * Start a new Case of a specific {@link CaseModel} by one of the case * model's registered CaseStartTriggers. * * @param cmId * The id of a case model. * @param requestKey * - the id of the {@link CaseStartTrigger} receiving the event * @param eventJson * - the json content for writing at the first data objects of * the new case * @return Response 200 because the Event was received by Chimera */ @POST @Consumes(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/casestart/{requestKey}") public Response startCase(@PathParam("scenarioId") String cmId, @PathParam("requestKey") String requestKey, String eventJson) { log.info("An Event started a Case via REST-Interface."); try { CaseModel cm = CaseModelManager.getCaseModel(cmId); Optional<CaseStartTrigger> caseStartTrigger = cm.getStartCaseTrigger().stream().filter(c -> c.getId().equals(requestKey)).findFirst(); if (!caseStartTrigger.isPresent()) { String message = String.format("The case start trigger id: %s is not assigned", requestKey); log.error(message); return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(buildError(message)).build(); } CaseExecutioner caseExecutioner = ExecutionService.createCaseExecutioner(cm, "Automatically Created Case"); CaseStarter caseStarter = new CaseStarter(caseStartTrigger.get()); caseStarter.startCase(eventJson, caseExecutioner); SseNotifier.notifyRefresh(); } catch (IllegalCaseModelIdException e) { log.error("Could not start case from query", e); return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(e.getMessage()).build(); } return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity("{\"message\":\"Event received.\"}").build(); } /** * Get the case start triggers of a case model. * * @param cmId - the id of the case model * @return {@link CaseStartTrigger} ids and the respective event queries. */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/casestart") public Response getCaseStartTriggers(@PathParam("scenarioId") String cmId) { try { CaseModel cm = CaseModelManager.getCaseModel(cmId); Object[] caseStartTriggers = cm.getStartCaseTrigger().toArray(); JSONArray jsonArray = new JSONArray(); for (Object cst : caseStartTriggers) { String id = ((CaseStartTrigger) cst).getId(); String plan = ((CaseStartTrigger) cst).getQueryExecutionPlan(); JSONObject jsonObject = new JSONObject(); jsonObject.put("id", id); jsonObject.put("plan", plan); jsonArray.put(jsonObject); } return Response.ok(jsonArray.toString(), MediaType.APPLICATION_JSON).build(); } catch (IllegalCaseModelIdException e) { log.error("Could not get case model from query", e); return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(e.getMessage()).build(); } } /** * Retrieve all registered events for an specific {@link Case}. * * @param cmId * - Id of the CaseModel * @param caseId * - Id of the Case * @return Response 200 if the request succeeded with a list of the * registered events. Response 404 if the case was not found. */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("scenario/{scenarioId}/instance/{instanceId}/events") public Response getRegisteredEvents(@PathParam("scenarioId") String cmId, @PathParam("instanceId") String caseId) { try { CaseExecutioner caseExecutioner = ExecutionService.getCaseExecutioner(cmId, caseId); List<ReceiveEventJaxBean> a = caseExecutioner.getRegisteredEventBehaviors().stream().map(ReceiveEventJaxBean::new).collect(Collectors.toList()); JSONArray result = new JSONArray(a); return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity(result.toString()).build(); } catch (IllegalArgumentException e) { return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(buildError(e.getMessage())).build(); } } }
package nu.studer.java.util; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.util.Comparator; import java.util.Enumeration; import java.util.InvalidPropertiesFormatException; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.Vector; /** * This class provides a drop-in replacement for the java.util.Properties class. It fixes the design flaw * of using inheritance over composition, while keeping up the same APIs as the original class. As additional * functionality, this class keeps its properties in a well-defined order. By default, the order is the one * in which the individual properties have been added, either through explicit API calls or through reading * them top-to-bottom from a properties file. Also, writing the comment that contains the current date when * storing the properties can be suppressed. * * This class is thread-safe. * * @see Properties */ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") public final class OrderedProperties { private static final Object LOCK = new Object(); private final Map<String, String> properties; private final boolean suppressDate; /** * Creates a new instance that will keep the properties in the order they have been added. Other than * the ordering of the keys, this instance behaves like an instance of the {@link Properties} class. */ public OrderedProperties() { this(new LinkedHashMap<String, String>(), false); } private OrderedProperties(Map<String, String> properties, boolean suppressDate) { this.properties = properties; this.suppressDate = suppressDate; } /** * See {@link Properties#getProperty(String)}. */ public String getProperty(String key) { synchronized (LOCK) { return properties.get(key); } } /** * See {@link Properties#getProperty(String, String)}. */ public String getProperty(String key, String defaultValue) { synchronized (LOCK) { String value = properties.get(key); return (value == null) ? defaultValue : value; } } /** * See {@link Properties#setProperty(String, String)}. */ public String setProperty(String key, String value) { synchronized (LOCK) { return properties.put(key, value); } } /** * See {@link Properties#isEmpty()}. */ public boolean isEmpty() { synchronized (LOCK) { return properties.isEmpty(); } } /** * See {@link Properties#propertyNames()}. */ public Enumeration<?> propertyNames() { synchronized (LOCK) { return new Vector<String>(properties.keySet()).elements(); } } /** * See {@link Properties#stringPropertyNames()}. */ public Set<String> stringPropertyNames() { synchronized (LOCK) { return new LinkedHashSet<String>(properties.keySet()); } } /** * See {@link Properties#load(InputStream)}. */ public void load(InputStream stream) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { customProperties.load(stream); } } /** * See {@link Properties#load(Reader)}. */ public void load(Reader reader) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { customProperties.load(reader); } } /** * See {@link Properties#loadFromXML(InputStream)}. */ @SuppressWarnings("DuplicateThrows") public void loadFromXML(InputStream stream) throws IOException, InvalidPropertiesFormatException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { customProperties.loadFromXML(stream); } } /** * See {@link Properties#store(OutputStream, String)}. */ public void store(OutputStream stream, String comments) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { if (suppressDate) { customProperties.store(new DateSuppressingPropertiesBufferedWriter(new OutputStreamWriter(stream, "8859_1")), comments); } else { customProperties.store(stream, comments); } } } /** * See {@link Properties#store(Writer, String)}. */ public void store(Writer writer, String comments) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { if (suppressDate) { customProperties.store(new DateSuppressingPropertiesBufferedWriter(writer), comments); } else { customProperties.store(writer, comments); } } } /** * See {@link Properties#storeToXML(OutputStream, String)}. */ public void storeToXML(OutputStream stream, String comment) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { customProperties.storeToXML(stream, comment); } } /** * See {@link Properties#storeToXML(OutputStream, String, String)}. */ public void storeToXML(OutputStream stream, String comment, String encoding) throws IOException { CustomProperties customProperties = new CustomProperties(this.properties); synchronized (LOCK) { customProperties.storeToXML(stream, comment, encoding); } } /** * See {@link Properties#toString()}. */ @Override public String toString() { synchronized (LOCK) { return properties.toString(); } } /** * Builder for {@link OrderedProperties} instances. */ public static final class OrderedPropertiesBuilder { private Comparator<? super String> comparator; private boolean suppressDate; /** * Use a custom ordering of the keys. * * @param comparator the ordering to apply on the keys * @return the builder */ public OrderedPropertiesBuilder withOrdering(Comparator<? super String> comparator) { this.comparator = comparator; return this; } /** * Suppress the comment that contains the current date when storing the properties. * * @param suppressDate whether to suppress the comment that contains the current date * @return the builder */ public OrderedPropertiesBuilder suppressDateInComment(boolean suppressDate) { this.suppressDate = suppressDate; return this; } /** * Builds a new {@link OrderedProperties} instance. * * @return the new instance */ public OrderedProperties build() { Map<String, String> properties = (this.comparator != null) ? new TreeMap<String, String>(comparator) : new LinkedHashMap<String, String>(); return new OrderedProperties(properties, suppressDate); } } /** * Custom {@link Properties} that delegates reading, writing, and enumerating properties to the * backing {@link OrderedProperties} instance's properties. */ private static final class CustomProperties extends Properties { private final Map<String, String> targetProperties; private CustomProperties(Map<String, String> targetProperties) { this.targetProperties = targetProperties; } @Override public Object get(Object key) { return targetProperties.get(key); } @Override public Object put(Object key, Object value) { return targetProperties.put((String) key, (String) value); } @Override public String getProperty(String key) { return targetProperties.get(key); } @Override public Enumeration<Object> keys() { return new Vector<Object>(targetProperties.keySet()).elements(); } @SuppressWarnings("NullableProblems") @Override public Set<Object> keySet() { return new LinkedHashSet<Object>(targetProperties.keySet()); } } /** * Custom {@link BufferedWriter} for storing properties that will write all leading lines of comments except * the last comment line. Using the JDK Properties class to store properties, the last comment * line always contains the current date which is what we want to filter out. */ private static final class DateSuppressingPropertiesBufferedWriter extends BufferedWriter { private final String LINE_SEPARATOR = System.getProperty("line.separator"); private StringBuilder currentComment; private String previousComment; private DateSuppressingPropertiesBufferedWriter(Writer out) { super(out); } @SuppressWarnings("NullableProblems") @Override public void write(String string) throws IOException { if (currentComment != null) { currentComment.append(string); if (string.endsWith(LINE_SEPARATOR)) { if (previousComment != null) { super.write(previousComment); } previousComment = currentComment.toString(); currentComment = null; } } else if (string.startsWith(" currentComment = new StringBuilder(string); } else { super.write(string); } } } }
package org.exist.mongodb.test.bson; import org.exist.test.runner.XSuite; import org.junit.runner.RunWith; @RunWith(XSuite.class) @XSuite.XSuiteFiles({ "src/test/xquery" }) public class ParserTests { }
package org.apache.ibatis.session; import org.apache.ibatis.executor.BatchResult; import java.sql.Connection; import java.util.List; import java.util.Map; /** * The primary Java interface for working with MyBatis. * Through this interface you can execute commands, get mappers and manage transactions. * */ public interface SqlSession { /** * Retrieve a single row mapped from the statement key * @param <T> the returned object type * @param statement * @return Mapped object */ <T> T selectOne(String statement); /** * Retrieve a single row mapped from the statement key and parameter. * @param <T> the returned object type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @return Mapped object */ <T> T selectOne(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter. * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @return List of mapped object */ <E> List<E> selectList(String statement); /** * Retrieve a list of mapped objects from the statement key and parameter. * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @return List of mapped object */ <E> List<E> selectList(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter, * within the specified row bounds. * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param rowBounds Bounds to limit object retrieval * @return List of mapped object */ <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param mapKey The property to use as key for each value in the list. * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, String mapKey); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param mapKey The property to use as key for each value in the list. * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param mapKey The property to use as key for each value in the list. * @param rowBounds Bounds to limit object retrieval * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); /** * Retrieve a single row mapped from the statement key and parameter * using a {@code ResultHandler}. * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, Object parameter, ResultHandler handler); /** * Retrieve a single row mapped from the statement * using a {@code ResultHandler}. * @param statement Unique identifier matching the statement to use. * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, ResultHandler handler); /** * Retrieve a single row mapped from the statement key and parameter * using a {@code ResultHandler} and {@code RowBounds} * @param statement Unique identifier matching the statement to use. * @param rowBounds RowBound instance to limit the query results * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler); /** * Execute an insert statement. * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the insert. */ int insert(String statement); /** * Execute an insert statement with the given parameter object. Any generated * autoincrement values or selectKey entries will modify the given parameter * object properties. Only the number of rows affected will be returned. * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the insert. */ int insert(String statement, Object parameter); /** * Execute an update statement. The number of rows affected will be returned. * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the update. */ int update(String statement); /** * Execute an update statement. The number of rows affected will be returned. * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the update. */ int update(String statement, Object parameter); /** * Execute a delete statement. The number of rows affected will be returned. * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the delete. */ int delete(String statement); /** * Execute a delete statement. The number of rows affected will be returned. * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the delete. */ int delete(String statement, Object parameter); /** * Flushes batch statements and commits database connection. * Note that database connection will not be committed if no updates/deletes/inserts were called. * To force the commit call {@link SqlSession#commit(boolean)} */ void commit(); /** * Flushes batch statements and commits database connection. * @param force forces connection commit */ void commit(boolean force); /** * Discards pending batch statements and rolls database connection back. * Note that database connection will not be rolled back if no updates/deletes/inserts were called. * To force the rollback call {@link SqlSession#rollback(boolean)} */ void rollback(); /** * Discards pending batch statements and rolls database connection back. * Note that database connection will not be rolled back if no updates/deletes/inserts were called. * @param force forces connection rollback */ void rollback(boolean force); /** * Flushes batch statements. * @return BatchResult list of updated records */ public List<BatchResult> flushStatements(); /** * Closes the session */ void close(); /** * Clears local session cache */ void clearCache(); /** * Retrieves current configuration * @return Configuration */ Configuration getConfiguration(); /** * Retrieves a mapper. * @param <T> the mapper type * @param type Mapper interface class * @return a mapper bound to this SqlSession */ <T> T getMapper(Class<T> type); /** * Retrieves inner database connection * @return Connection */ Connection getConnection(); }
package de.pigeont.bowlinggame.render; import com.googlecode.lanterna.SGR; import com.googlecode.lanterna.TerminalPosition; import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.graphics.TextGraphics; import com.googlecode.lanterna.screen.Screen; import com.sun.istack.internal.NotNull; import de.pigeont.bowlinggame.controller.GameController; import java.io.IOException; import java.util.logging.Logger; public final class GameRender { private static final Integer OFFSET = 40; private static GameRender render; private final Logger logger; private GameController controller; private Screen screen; private Long gameControllerID = 0L; //range from 0 to 10 mean 0% to 100% private Integer progressbar = OFFSET; //indicate progressbar increase or decrease private Boolean increaseprogressbar = true; public GameRender(Logger _logger) { logger = _logger; } @NotNull public static GameRender createRender(@NotNull Logger logger) { render = null == render ? render = new GameRender(logger) : render; return render; } public void initGame() { try { //put it in stack for performance screen = controller.getScreen(); TextGraphics g = screen.newTextGraphics(); //draw ambient and information g.setForegroundColor(TextColor.ANSI.CYAN); g.drawLine(36, 0, 36, 24, '|'); g.putString(46, 1, "Information: ", SGR.BOLD); g.putString(46, 2, "use keyboard to play", SGR.BOLD); g.putString(46, 3, "'q' : quit", SGR.BOLD); g.putString(46, 4, "enter : throw", SGR.BOLD); //draw pins drawPins(g); //draw ball drawBall(g); //draw power drawPower(g); //draw hook if (controller.powerIsSet()) drawHook(g); screen.refresh(); } catch (IOException e) { throw new RuntimeException(e); } } public void update() { try { TextGraphics g = screen.newTextGraphics(); //draw power drawPower(g); //draw hook if (controller.powerIsSet()) drawHook(g); screen.refresh(); } catch (IOException e) { throw new RuntimeException(e); } } private void drawPower(TextGraphics g) throws IOException { g.putString(40, 7, "weak power", SGR.BOLD); g.putString(78, 7, "strong power", SGR.BOLD); if (controller.powerIsSet()) { g.drawRectangle(new TerminalPosition(40, 8), new TerminalSize(49, 3), ' g.setCharacter(43, 9, '+'); return; } g.drawRectangle(new TerminalPosition(40, 8), new TerminalSize(49, 3), ' drawProcessBar(g, 9); } private void drawHook(TextGraphics g) { g.putString(40, 11, "left", SGR.BOLD); g.putString(78, 11, "right", SGR.BOLD); if (controller.hookIsSet()) { g.drawRectangle(new TerminalPosition(40, 12), new TerminalSize(49, 3), ' g.setCharacter(43, 13, '+'); return; } g.drawRectangle(new TerminalPosition(40, 12), new TerminalSize(49, 3), ' drawProcessBar(g, 13); } private void drawPins(TextGraphics g) throws IOException { g.setForegroundColor(TextColor.ANSI.DEFAULT); controller.getOriginPins() .parallelStream() .forEach(p -> g.setCharacter(p[0], p[1], 'I')); } private void drawBall(TextGraphics g) throws IOException { g.setCharacter(15, 18, '@'); } private void drawProcessBar(TextGraphics g, Integer y) { if (increaseprogressbar) { if (87 > progressbar) { g.setCharacter(progressbar, y, '+'); progressbar++; return; } increaseprogressbar = false; return; } if (41 < progressbar) { g.setCharacter(progressbar, y, ' '); progressbar return; } increaseprogressbar = true; } public void setController(@NotNull GameController controller) { if (0L != gameControllerID) throw new RuntimeException("reassignment of render of game constrolelr"); this.controller = controller; gameControllerID = 1L; } public Integer getProgressbar() { return progressbar; } public void resetProgressbar() { this.progressbar = OFFSET; } }
package org.arachb.owlbuilder.lib; import java.sql.SQLException; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.arachb.arachadmin.AbstractConnection; import org.arachb.arachadmin.ParticipantBean; import org.arachb.owlbuilder.Owlbuilder; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; import org.semanticweb.owlapi.model.OWLClassAxiom; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLIndividual; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasoner; public class Participant implements AbstractNamedEntity{ final static int DBID = 1; final static int DBTAXON = 2; final static int DBSUBSTRATE = 3; final static int DBANATOMY = 4; final static int DBQUANTIFICATION = 5; final static int DBGENERATEDID = 6; final static int DBPUBLICATIONTAXON = 7; final static int DBLABEL = 8; final static int DBPUBLICATIONANATOMY = 9; final static int DBPUBLICATIONSUBSTRATE = 10; final static int DBTAXONSOURCEID = 11; final static int DBTAXONGENERATEDID = 12; final static int DBSUBSTRATESOURCEID = 13; final static int DBSUBSTRATEGENERATEDID = 14; final static int DBANATOMYSOURCEID = 15; final static int DBANATOMYGENERATEDID = 16; final static String BADTAXQuantifiedParticipant = "Term without IRI referenced as participant taxon: participant QuantifiedParticipantxon id = %s"; final static String BADANATOMYIRI = "Term without IRQuantifiedParticipantd as participant anatomy: participant id = %s; anatomy id = %s"; final static String BADSUBSTRATEIRI = "Term without IRI referenced as participant substrate; participant id = %s; substrate id = %s"; private final static String INDIVIDUALQUANTIFIER = "INDIVIDUAL"; private final static String SOMEQUANTIFIER = "SOME"; private static Logger log = Logger.getLogger(Participant.class); private final ParticipantBean bean; public Participant(ParticipantBean b){ bean = b; } /** * Utility for making Participant Sets from sets of beans */ public static Set<Participant> wrapSet(Set<ParticipantBean> bset){ final Set<Participant>result = new HashSet<Participant>(); for(ParticipantBean b : bset){ result.add(new Participant(b)); } return result; } @Override public OWLObject generateOWL(Owlbuilder builder) throws SQLException{ bean.traverseElements(); //start of something new if (INDIVIDUALQUANTIFIER.equalsIgnoreCase(bean.getQuantification())){ return generateOWLForIndividual(builder); } else if (SOMEQUANTIFIER.equalsIgnoreCase(bean.getQuantification())){ return generateOWLForClass(builder); } else{ final String msg = "Participant had bad quantification: " + bean.getQuantification(); log.error(msg); throw new IllegalArgumentException(msg); } } OWLObject generateOWLForClass(Owlbuilder builder) { final OWLDataFactory factory = builder.getDataFactory(); if (getSubstrate() != 0){ if (getAnatomyIri() != null){ processParticipantSubstrateForClass(builder,IRI.create(getSubstrateIri())); } else{ final String msg = String.format("No substrate IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } OWLClass taxonClass = null; if (getTaxon() != 0){ if (getTaxonIri() != null){ taxonClass = processParticipantTaxonForClass(builder,IRI.create(getTaxonIri())); } else { final String msg = String.format("No taxon IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } if (getAnatomy() != 0){ if (getAnatomyIri() != null){ OWLClass anatomyClass = processParticipantAnatomyForClass(builder,IRI.create(getAnatomyIri())); if (taxonClass != null){ OWLObjectProperty partOf = factory.getOWLObjectProperty(IRIManager.partOfProperty); OWLClassExpression partOfSomeTaxon = factory.getOWLObjectSomeValuesFrom(partOf, taxonClass); OWLClassExpression anatomyOfTaxon = factory.getOWLObjectIntersectionOf(anatomyClass,partOfSomeTaxon); return anatomyOfTaxon; } } else{ final String msg = String.format("No anatomy IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } return taxonClass; } /** * This adds assertions for a participant when the participant is an * individual. An individual is most likely an anatomical part of an * individual instance of a taxon, but it might be the entire individual * taxon instance or an instance of a substrate class. * */ OWLObject generateOWLForIndividual(Owlbuilder builder) throws SQLException { IRIManager iriManager = builder.getIRIManager(); iriManager.validateIRI(this); final OWLDataFactory factory = builder.getDataFactory(); final OWLIndividual ind = factory.getOWLNamedIndividual(IRI.create(getIriString())); log.info("individual is " + ind); //anatomy specified if (bean.getAnatomy() != 0) generateOWLforAnatomy(builder, ind); // No anatomy specified, just a taxon OWLOntology target = builder.getTarget(); OWLOntologyManager manager = builder.getOntologyManager(); if (bean.getTaxon() != 0){ if (bean.getTaxonIri() != null){ OWLClass taxon = processParticipantTaxonForIndividual(builder,IRI.create(bean.getTaxonIri())); OWLClassAssertionAxiom taxonAssertion = factory.getOWLClassAssertionAxiom(taxon,ind); manager.addAxiom(target, taxonAssertion); return ind; } else { final String msg = String.format("No taxon IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } if (bean.getSubstrate() != 0){ if (bean.getAnatomyIri() != null){ processParticipantSubstrateForIndividual(builder,IRI.create(bean.getSubstrateIri())); } else{ final String msg = String.format("No substrate IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } return ind; } /** * * @param builder * @param iri */ void processParticipantSubstrateForIndividual(Owlbuilder builder, IRI iri){ final OWLOntology target = builder.getTarget(); final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); boolean substrate_duplicate = target.containsClassInSignature(iri); if (!substrate_duplicate){ boolean substrate_exists = merged.containsClassInSignature(iri); if (substrate_exists){ log.info("Found class in signature of merged ontology for: " + iri); OWLClass substrateClass = factory.getOWLClass(iri); processSubstrate(builder,substrateClass); } } } /** * @param builder * @param factory * @param target * @param manager * @param partofProperty * @param ind */ private void generateOWLforAnatomy(Owlbuilder builder, final OWLIndividual ind) { final OWLDataFactory factory = builder.getDataFactory(); OWLOntology target = builder.getTarget(); OWLOntologyManager manager = builder.getOntologyManager(); final OWLObjectProperty partofProperty = factory.getOWLObjectProperty(IRIManager.partOfProperty); { if (bean.getAnatomyIri() != null){ final OWLClass anatomyClass =processParticipantAnatomy(builder,IRI.create(bean.getAnatomyIri())); log.info("anatomy is " + anatomyClass); // and the taxon (anatomy w/o taxon should be flagged as a curation error if (bean.getTaxon() != 0){ if (bean.getTaxonIri() != null){ // This will require some more attention - curation should be able to // label the organisms because different parts of the same organism or // the same part will be mentioned multiple times - this is why arachb // uses individuals in the first place log.info("taxon is " + bean.getTaxonIri()); OWLIndividual organism = factory.getOWLAnonymousIndividual(); OWLClass taxon = processParticipantTaxon(builder,IRI.create(bean.getTaxonIri())); OWLClassAssertionAxiom taxonAssertion = factory.getOWLClassAssertionAxiom(taxon,organism); log.warn("assert " + organism + " is " + taxon); manager.addAxiom(target, taxonAssertion); OWLObjectPropertyAssertionAxiom partofAssertion = factory.getOWLObjectPropertyAssertionAxiom(partofProperty, organism, ind); log.warn("assert " + organism + " part of " + ind); manager.addAxiom(target, partofAssertion); OWLClassAssertionAxiom anatomyAssertion = factory.getOWLClassAssertionAxiom(anatomyClass, ind); log.warn("assert " + ind + " is " + anatomyClass); manager.addAxiom(target, anatomyAssertion); } else { final String msg = String.format("No taxon IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } else { final String msg = String.format("No taxon specified; id = %s", getId()); throw new IllegalStateException(msg); } } else{ final String msg = String.format("No anatomy IRI available; id = %s",getId()); throw new IllegalStateException(msg); } } } /** * * @param builder * @param iri * @return */ OWLClass processParticipantTaxon(Owlbuilder builder,IRI iri){ final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); OWLOntology target = builder.getTarget(); boolean taxon_duplicate = target.containsClassInSignature(iri); if (!taxon_duplicate){ if (merged.containsClassInSignature(iri)) // taxon in merged (so from NCBI) return processNCBITaxon(builder, iri); else return processNonNCBITaxon(builder, iri); } else{ OWLClass taxonClass = factory.getOWLClass(iri); return taxonClass; // may not be right } } /** * * @param builder * @param iri * @return class for anatomy */ OWLClass processParticipantAnatomy(Owlbuilder builder, IRI iri){ final OWLOntology target = builder.getTarget(); final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); boolean anatomy_duplicate = target.containsClassInSignature(iri); if (!anatomy_duplicate){ boolean anatomy_exists = merged.containsClassInSignature(iri); if (anatomy_exists){ log.info("Found class in signature of merged ontology for: " + iri); OWLClass anatomyClass = factory.getOWLClass(iri); processAnatomyForIndividual(builder,anatomyClass); return anatomyClass; } else{ log.info("Did not find class in signature of merged ontology for: " + bean.getTaxonIri()); return null; } } else{ OWLClass anatomyClass = factory.getOWLClass(iri); return anatomyClass; // may not be right } } OWLClass processParticipantTaxonForClass(Owlbuilder builder,IRI iri){ final OWLOntology target = builder.getTarget(); final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); final OWLReasoner reasoner = builder.getPreReasoner(); boolean taxon_duplicate = target.containsClassInSignature(iri); if (!taxon_duplicate){ boolean taxon_exists = merged.containsClassInSignature(iri); if (taxon_exists){ log.info("Found class in signature of merged ontology for: " + getTaxonIri()); OWLClass taxonClass = factory.getOWLClass(iri); final NodeSet<OWLClass> taxonParents = reasoner.getSuperClasses(taxonClass, false); log.info("Node count = " + taxonParents.getNodes().size()); Set<OWLClass>parentList = taxonParents.getFlattened(); log.info("Flattened parent count = " + parentList.size()); parentList.add(taxonClass); for (OWLClass taxon : parentList){ participantProcessTaxon(builder,taxon); } return taxonClass; } else{ log.info("Did not find taxon class in signature of merged ontology for: " + getTaxonIri()); final IRI taxonIri = IRI.create(getTaxonIri()); final Map<IRI,Taxon> nonNCBITaxa = builder.getNonNCBITaxa(); final OWLOntologyManager manager = builder.getOntologyManager(); Taxon t = nonNCBITaxa.get(taxonIri); if (t == null){ log.info("Taxon IRI not found in declared non-NCBI taxa"); throw new IllegalStateException("Taxon IRI not found in declared non-NCBI taxa"); } final OWLClass taxonClass = factory.getOWLClass(iri); if (t.getParentSourceId() != null){ IRI parentIri = IRI.create(t.getParentSourceId()); OWLClass parentClass = factory.getOWLClass(parentIri); log.info("Parent IRI is " + parentIri.toString()); OWLAxiom sc_ax = factory.getOWLSubClassOfAxiom(taxonClass, parentClass); manager.addAxiom(target, sc_ax); } else{ log.info("failed to find IRI of parent of " + getTaxonIri()); } if (t.getName() != null){ OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(), factory.getOWLLiteral(t.getName())); OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(iri, labelAnno); // Add the axiom to the ontology manager.addAxiom(target,ax); } return taxonClass; } } else{ OWLClass taxonClass = factory.getOWLClass(iri); return taxonClass; // may not be right } } void participantProcessTaxon(Owlbuilder builder,OWLClass taxon){ final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ //add appropriate when figured out log.info("Need to add taxon: " + taxon.getIRI()); //log.info("Defining Axioms"); manager.addAxioms(extracted, merged.getAxioms(taxon)); //log.info("Annotations"); Set<OWLAnnotationAssertionAxiom> taxonAnnotations = merged.getAnnotationAssertionAxioms(taxon.getIRI()); for (OWLAnnotationAssertionAxiom a : taxonAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.info("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } } /** * * @param builder * @param iri * @return */ OWLClass processParticipantTaxonForIndividual(Owlbuilder builder,IRI iri){ final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); OWLOntology target = builder.getTarget(); boolean taxon_duplicate = target.containsClassInSignature(iri); if (!taxon_duplicate){ if (merged.containsClassInSignature(iri)) // taxon in merged (so from NCBI) return processNCBITaxon(builder, iri); else return processNonNCBITaxon(builder, iri); } else{ OWLClass taxonClass = factory.getOWLClass(iri); return taxonClass; // may not be right } } /** * * @param builder * @param iri * @return */ private OWLClass processNCBITaxon(Owlbuilder builder, IRI iri) { log.info("Found class in signature of merged ontology for: " + iri); final OWLDataFactory factory = builder.getDataFactory(); final OWLReasoner reasoner = builder.getPreReasoner(); OWLClass taxonClass = factory.getOWLClass(iri); final NodeSet<OWLClass> taxonParents = reasoner.getSuperClasses(taxonClass, false); log.info("Node count = " + taxonParents.getNodes().size()); Set<OWLClass>parentList = taxonParents.getFlattened(); log.info("Flattened parent count = " + parentList.size()); parentList.add(taxonClass); for (OWLClass taxon : parentList){ processTaxon(builder,taxon); } return taxonClass; } void processTaxon(Owlbuilder builder,OWLClass taxon){ final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ //add appropriate when figured out log.info("Need to add taxon: " + taxon.getIRI()); //log.info("Defining Axioms"); manager.addAxioms(extracted, merged.getAxioms(taxon)); //log.info("Annotations"); Set<OWLAnnotationAssertionAxiom> taxonAnnotations = merged.getAnnotationAssertionAxioms(taxon.getIRI()); for (OWLAnnotationAssertionAxiom a : taxonAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.info("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } } /** * @param builder * @param iri * @return */ private OWLClass processNonNCBITaxon(Owlbuilder builder, IRI iri) { final OWLDataFactory factory = builder.getDataFactory(); final OWLOntology target = builder.getTarget(); log.info("Did not find taxon class in signature of merged ontology for: " + bean.getTaxonIri()); final IRI taxonIri = IRI.create(bean.getTaxonIri()); final Map<IRI, Taxon> nonNCBITaxa = builder.getNonNCBITaxa(); final OWLOntologyManager manager = builder.getOntologyManager(); final Taxon t = nonNCBITaxa.get(taxonIri); if (t == null){ log.info("Taxon IRI not found in declared non-NCBI taxa"); throw new IllegalStateException("Taxon IRI not found in declared non-NCBI taxa"); } final OWLClass taxonClass = factory.getOWLClass(iri); if (t.getParentSourceId() != null){ IRI parentIri = IRI.create(t.getParentSourceId()); OWLClass parentClass = factory.getOWLClass(parentIri); log.info("Parent IRI is " + parentIri.toString()); OWLAxiom sc_ax = factory.getOWLSubClassOfAxiom(taxonClass, parentClass); manager.addAxiom(target, sc_ax); } else{ log.info("failed to find IRI of parent of " + bean.getTaxonIri()); } if (t.getName() != null){ OWLAnnotation labelAnno = factory.getOWLAnnotation(factory.getRDFSLabel(), factory.getOWLLiteral(t.getName())); OWLAxiom ax = factory.getOWLAnnotationAssertionAxiom(iri, labelAnno); // Add the axiom to the ontology manager.addAxiom(target,ax); } return taxonClass; } OWLClass processParticipantAnatomyForClass(Owlbuilder builder, IRI iri){ final OWLOntology target = builder.getTarget(); final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); boolean anatomy_duplicate = target.containsClassInSignature(iri); if (!anatomy_duplicate){ boolean anatomy_exists = merged.containsClassInSignature(iri); if (anatomy_exists){ log.info("Found class in signature of merged ontology for: " + iri); OWLClass anatomyClass = factory.getOWLClass(iri); participantProcessAnatomy(builder,anatomyClass); return anatomyClass; } else{ log.info("Did not find class in signature of merged ontology for: " + getAnatomyIri()); return null; } } else{ OWLClass taxonClass = factory.getOWLClass(iri); return taxonClass; // may not be right } } public void participantProcessAnatomy(Owlbuilder builder, OWLClass anatomyClass) { final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ log.info("Need to add anatomy: " + anatomyClass.getIRI()); Set<OWLClassAxiom> anatAxioms = merged.getAxioms(anatomyClass); manager.addAxioms(extracted, anatAxioms); Set<OWLAnnotationAssertionAxiom> anatAnnotations = merged.getAnnotationAssertionAxioms(anatomyClass.getIRI()); for (OWLAnnotationAssertionAxiom a : anatAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.info("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } builder.initializeMiscTermAndParents(anatomyClass); } public void processAnatomyForIndividual(Owlbuilder builder, OWLClass anatomyClass) { final OWLOntologyManager manager = builder.getOntologyManager(); final OWLOntology merged = builder.getMergedSources(); final OWLOntology extracted = builder.getTarget(); if (true){ log.info("Need to add anatomy: " + anatomyClass.getIRI()); Set<OWLClassAxiom> anatAxioms = merged.getAxioms(anatomyClass); manager.addAxioms(extracted, anatAxioms); Set<OWLAnnotationAssertionAxiom> anatAnnotations = merged.getAnnotationAssertionAxioms(anatomyClass.getIRI()); for (OWLAnnotationAssertionAxiom a : anatAnnotations){ //log.info(" Annotation Axiom: " + a.toString()); if (a.getAnnotation().getProperty().isLabel()){ log.info("Label is " + a.getAnnotation().getValue().toString()); manager.addAxiom(extracted, a); } } } builder.initializeMiscTermAndParents(anatomyClass); } void processParticipantSubstrateForClass(Owlbuilder builder, IRI iri){ final OWLOntology target = builder.getTarget(); final OWLOntology merged = builder.getMergedSources(); final OWLDataFactory factory = builder.getDataFactory(); boolean substrate_duplicate = target.containsClassInSignature(iri); if (!substrate_duplicate){ boolean substrate_exists = merged.containsClassInSignature(iri); if (substrate_exists){ log.info("Found class in signature of merged ontology for: " + iri); OWLClass substrateClass = factory.getOWLClass(iri); processSubstrate(builder,substrateClass); } } } public void processSubstrate(Owlbuilder builder, OWLClass substrateClass) { builder.initializeMiscTermAndParents(substrateClass); } public int getId(){ return bean.getId(); } public int getTaxon(){ return bean.getTaxon(); } public int getSubstrate(){ return bean.getSubstrate(); } public int getAnatomy(){ return bean.getAnatomy(); } public String getQuantification(){ return bean.getQuantification(); } public String getPublicationTaxon(){ return bean.getPublicationTaxon(); } public String getLabel(){ return bean.getLabel(); } public String getPublicationAnatomy(){ return bean.getPublicationAnatomy(); } public String getPublicationSubstrate(){ return bean.getPublicationSubstrate(); } public String getTaxonIri(){ return bean.getTaxonIri(); } public String getSubstrateIri(){ return bean.getSubstrateIri(); } public String getAnatomyIri(){ return bean.getAnatomyIri(); } public String getGeneratedId(){ return bean.getGeneratedId(); } public void setGeneratedId(String s){ bean.setGeneratedId(s); } public String getIriString(){ if (getGeneratedId() == null){ throw new IllegalStateException("Individual has neither assigned nor generated id"); } return getGeneratedId(); } @Override public Object checkIriString() { // TODO Auto-generated method stub return null; } @Override public void updateDB(AbstractConnection c) throws SQLException { // TODO Auto-generated method stub } }
package org.whattf.datatype; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashSet; import org.relaxng.datatype.DatatypeException; public class MetaName extends AbstractDatatype { private static final HashSet<String> registeredMetaNames = new HashSet<String>(); static { // Standard metadata names from the spec registeredMetaNames.add("application-name"); registeredMetaNames.add("author"); registeredMetaNames.add("description"); registeredMetaNames.add("generator"); registeredMetaNames.add("keywords"); BufferedReader br = new BufferedReader(new InputStreamReader( MetaName.class.getClassLoader().getResourceAsStream( "nu/validator/localentities/files/meta-extensions"))); // Read in registered metadata names from cached copy of the registry try { String read = br.readLine(); while (read != null) { registeredMetaNames.add(br.readLine()); read = br.readLine(); } } catch (IOException e) { throw new RuntimeException(e); } } /** * The singleton instance. */ public static final MetaName THE_INSTANCE = new MetaName(); /** * Package-private constructor */ private MetaName() { super(); } @Override public void checkValid(CharSequence literal) throws DatatypeException { String token = toAsciiLowerCase(literal); if (!registeredMetaNames.contains(token)) { throw newDatatypeException("Keyword ", token, " is not registered."); } } @Override public String getName() { return "metadata name"; } }
package org.minimalj.repository.sql; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.minimalj.model.Keys; import org.minimalj.model.annotation.Size; import org.minimalj.repository.DataSourceFactory; import org.minimalj.util.CloneHelper; import org.minimalj.util.EqualsHelper; import org.minimalj.util.IdUtils; public class SqlCrudTest { private static SqlRepository repository; @BeforeClass public static void setupRepository() { repository = new SqlRepository(DataSourceFactory.embeddedDataSource(), A.class, G.class, H.class, M.class, TestEntity.class, TestElement.class); } @AfterClass public static void shutdownRepository() { } @Test public void testInsertAndDelete() { G g = new G("testName1"); Object id = repository.insert(g); G g2 = repository.read(G.class, id); Assert.assertNotNull(g2); repository.delete(g2); G g3 = repository.read(G.class, id); Assert.assertNull(g3); } @Test @Ignore // TODO define if insert really may change input. If yes, BackendRepository should do it too. public void testInsertShouldNotChangeInput() { G g = new G("testName1"); G g_clone = CloneHelper.clone(g); repository.insert(g); boolean equals = EqualsHelper.equals(g, g_clone); Assert.assertTrue(equals); } @Test public void testInsertAndDeleteHistorized() { A a = new A("testName1"); Object id = repository.insert(a); A a2 = repository.read(A.class, id); Assert.assertNotNull(a2); repository.delete(a2); A a3 = repository.read(A.class, id); Assert.assertNull(a3); List<A> history = repository.loadHistory(A.class, id, 1); Assert.assertFalse(history.isEmpty()); Assert.assertTrue(history.get(0).historized); } @Test public void testCrudWithSubtable() { A a = new A("testName1"); a.b.add(new B("testNameB1")); a.b.add(new B("testNameB2")); a.c.add(new C("testNameC1")); a.c.add(new C("testNameC2")); a.c.add(new C("testNameC3")); Object id = repository.insert(a); A a2 = repository.read(A.class, id); Assert.assertEquals("The string in the first B of A should match the original String", "testNameB1", a2.b.get(0).bName); Assert.assertEquals("The string in the second C of A should match the original String", "testNameC2", a2.c.get(1).cName); Assert.assertEquals("The count of the B's attached to A should match", 2, a2.b.size()); Assert.assertEquals("The count of the C's attached to A should match", 3, a2.c.size()); } @Test public void testSubtableVersion() { Object id = writeSimpleA(); readTheAandAddBandE(id); A a = repository.read(A.class, id); int version = IdUtils.getVersion(a); Assert.assertEquals("A should now have 2 versions (0 and 1)", 1, version); A a3 = repository.readVersion(A.class, id, 0); Assert.assertEquals("The historized (first) version of A should not have any B attached", 0, a3.b.size()); Assert.assertTrue("The historized (first) version of A should not have a E attached", EmptyObjects.isEmpty(a3.e)); A a4 = repository.readVersion(A.class, id, 1); Assert.assertEquals("The actual version of A should have a B attached", 1, a4.b.size()); Assert.assertNotNull("The actual version of A should have a E attached", a4.e); addAnotherB(a4); removeFirstB(id); removeFirstB(id); a = repository.read(A.class, id); version = IdUtils.getVersion(a); Assert.assertEquals("A should now have 4 historized versions and the actual should be version 4", 4, version); Assert.assertEquals("Every B should be removed from the A now", 0, repository.read(A.class, id).b.size()); // now check for the right amount of B's attached to A in every version Assert.assertEquals(1, repository.readVersion(A.class, id, 3).b.size()); Assert.assertEquals(2, repository.readVersion(A.class, id, 2).b.size()); Assert.assertEquals(1, repository.readVersion(A.class, id, 1).b.size()); Assert.assertEquals(0, repository.readVersion(A.class, id, 0).b.size()); } @Test public void testDependable() throws Exception { H h = new H(); Object id = repository.insert(h); h = repository.read(H.class, id); h.k = new K("Test"); repository.update(h); h = repository.read(H.class, id); Assert.assertNotNull("Dependable should be available", h.k); Assert.assertEquals("Content of dependable should be stored", "Test", h.k.k); h.k = null; repository.update(h); h = repository.read(H.class, id); Assert.assertNull("Dependable should be removed", h.k); } @Test(expected = RuntimeException.class) public void testDeleteIdentifiableChild() { TestEntity entity = new TestEntity("testN"); TestElement e1 = new TestElement("testO1"); TestElement e2 = new TestElement("testO2"); entity.testElementList.add(e1); entity.testElementList.add(e2); Object entity_id = repository.insert(entity); entity = repository.read(TestEntity.class, entity_id); Assert.assertEquals(2, entity.testElementList.size()); e1 = entity.testElementList.get(0); e2 = entity.testElementList.get(1); Assert.assertNotNull(e1.id); Assert.assertNotNull(e2.id); TestElement elementToDelete = e1; executeWithoutLog(() -> repository.delete(elementToDelete)); } public static void executeWithoutLog(Runnable r) { Level logLevel = AbstractTable.sqlLogger.getLevel(); try { AbstractTable.sqlLogger.setLevel(Level.OFF); r.run(); } finally { AbstractTable.sqlLogger.setLevel(logLevel); } } @Test(expected = RuntimeException.class) public void testDeleteIdentifiableReference() { TestEntity entity = new TestEntity("testN"); TestElement e = new TestElement("testO"); entity.testElementReference = e; Object element_id = repository.insert(entity); entity = repository.read(TestEntity.class, element_id); Assert.assertNotNull(entity.testElementReference); e = entity.testElementReference; Assert.assertNotNull(e.id); TestElement elementToDelete = e; executeWithoutLog(() -> repository.delete(elementToDelete)); } @Test public void testByteArray() throws Exception { M m = new M(); Object id = repository.insert(m); m = repository.read(M.class, id); m.bytes = new byte[]{1,2,3}; repository.update(m); m = repository.read(M.class, id); Assert.assertNotNull("Byte array should be available", m.bytes); Assert.assertEquals("Content of byte array should be stored", 3, m.bytes.length); repository.delete(m); } private Object writeSimpleA() { A a = new A("testName1"); Object id = repository.insert(a); return id; } private void readTheAandAddBandE(Object id) { A a2 = repository.read(A.class, id); a2.b.add(new B("testNameB1")); a2.e = new E(); a2.e.e = "AddedE"; repository.update(a2); } private void addAnotherB(final A a4) { a4.b.add(new B("testNameB2")); repository.update(a4); } private void removeFirstB(final Object id) { A a5 = repository.read(A.class, id); a5.b.remove(0); repository.update(a5); } public static class TestElement { public static final TestElement $ = Keys.of(TestElement.class); public TestElement() { // needed for reflection constructor } public TestElement(String testElementName) { this.testElementName = testElementName; } public Object id; @Size(30) public String testElementName; } public static class TestEntity { public static final TestEntity $ = Keys.of(TestEntity.class); public TestEntity() { // needed for reflection constructor } public TestEntity(String testElement) { this.testElement = testElement; } public Object id; @Size(20) public String testElement; public List<TestElement> testElementList = new ArrayList<>(); public TestElement testElementReference; } }
/* * $Log: MessageSendingPipe.java,v $ * Revision 1.36 2007-12-10 10:11:39 europe\L190409 * added input/output validation * * Revision 1.35 2007/10/03 08:52:56 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed HashMap to Map * * Revision 1.34 2007/07/10 08:03:04 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * move String check to calling of sender * * Revision 1.33 2007/06/19 12:08:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * log when using stub * * Revision 1.32 2007/06/12 11:23:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added correlationIdXPath (...) * * Revision 1.30 2007/06/07 12:28:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * avoid messageid to be null * * Revision 1.29 2007/05/23 09:24:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added messageLog functionality * * Revision 1.28 2007/05/09 09:46:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected javadoc * optimized stubFile code * * Revision 1.27 2007/02/12 14:50:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added result checking facilities (by PL) * * Revision 1.26 2007/02/12 10:38:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added attribute stubFileName (by PL) * * Revision 1.25 2007/02/05 14:59:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * update javadoc * * Revision 1.24 2006/12/28 14:21:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.23 2006/12/13 16:29:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * catch null input * * Revision 1.22 2006/01/05 14:36:30 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.21 2005/10/24 09:20:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made namespaceAware an attribute of AbstractPipe * * Revision 1.20 2005/09/08 15:59:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * return something when asynchronous sender has no listener * * Revision 1.19 2005/08/24 15:53:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved error message for configuration exception * * Revision 1.18 2005/07/05 11:51:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging of receiving result * * Revision 1.17 2004/10/19 06:39:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified parameter handling, introduced IWithParameters * * Revision 1.16 2004/10/14 16:11:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed ParameterResolutionContext from Object,Hashtable to String, PipelineSession * * Revision 1.15 2004/10/05 10:53:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added support for parameterized senders * * Revision 1.14 2004/09/08 14:16:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * catch more throwables in doPipe() * * Revision 1.13 2004/09/01 11:28:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added exception-forward * * Revision 1.12 2004/08/23 13:10:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated JavaDoc * * Revision 1.11 2004/08/09 13:52:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of function propagateName() * catches more exceptions in start() * * Revision 1.10 2004/07/19 13:23:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging + no exception but only warning on timeout if no timeoutforward exists * * Revision 1.9 2004/07/07 13:49:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved handling of timeout when no timeout-forward exists * * Revision 1.8 2004/06/21 09:58:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Changed exception handling for starting pipe; Exception thrown now contains pipename * * Revision 1.7 2004/05/21 07:59:30 unknown <unknown@ibissource.org> * Add (modifications) due to the postbox sender implementation * * Revision 1.6 2004/04/15 15:07:57 Johan Verrips <johan.verrips@ibissource.org> * when a timeout occured, the receiver was not closed. Fixed it. * * Revision 1.5 2004/03/30 07:30:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * */ package nl.nn.adapterframework.pipes; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.xml.transform.TransformerConfigurationException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.HasSender; import nl.nn.adapterframework.core.ICorrelatedPullingListener; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.ISenderWithParameters; import nl.nn.adapterframework.core.ITransactionalStorage; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.ParameterException; import nl.nn.adapterframework.core.PipeForward; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.core.PipeStartException; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.TimeOutException; import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter; import nl.nn.adapterframework.parameters.Parameter; import nl.nn.adapterframework.parameters.ParameterList; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.Misc; import nl.nn.adapterframework.util.TransformerPool; import nl.nn.adapterframework.util.XmlUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; public class MessageSendingPipe extends FixedForwardPipe implements HasSender { public static final String version = "$RCSfile: MessageSendingPipe.java,v $ $Revision: 1.36 $ $Date: 2007-12-10 10:11:39 $"; private final static String TIMEOUTFORWARD = "timeout"; private final static String EXCEPTIONFORWARD = "exception"; private final static String ILLEGALRESULTFORWARD = "illegalResult"; private final static String STUBFILENAME = "stubFileName"; private String resultOnTimeOut = "receiver timed out"; private String linkMethod = "CORRELATIONID"; private String stubFileName; private boolean checkXmlWellFormed = false; private String checkRootTag; private String auditTrailXPath; private String correlationIDXPath; private ISender sender = null; private ICorrelatedPullingListener listener = null; private ITransactionalStorage messageLog=null; // private variables private String returnString; private TransformerPool auditTrailTp=null; private TransformerPool correlationIDTp=null; private IPipe inputValidator=null; private IPipe outputValidator=null; protected void propagateName() { ISender sender=getSender(); if (sender!=null && StringUtils.isEmpty(sender.getName())) { sender.setName(getName() + "-sender"); } ICorrelatedPullingListener listener=getListener(); if (listener!=null && StringUtils.isEmpty(listener.getName())) { listener.setName(getName() + "-replylistener"); } } public void setName(String name) { super.setName(name); propagateName(); } public void addParameter(Parameter p){ if (getSender() instanceof ISenderWithParameters && getParameterList()!=null) { if (p.getName().equals(STUBFILENAME)) { super.addParameter(p); } else { ((ISenderWithParameters)getSender()).addParameter(p); } } } /** * Checks whether a sender is defined for this pipe. */ public void configure() throws ConfigurationException { super.configure(); if (StringUtils.isNotEmpty(getStubFileName())) { try { returnString = Misc.resourceToString(ClassUtils.getResourceURL(this,getStubFileName()), SystemUtils.LINE_SEPARATOR); } catch (Throwable e) { throw new ConfigurationException("Pipe [" + getName() + "] got exception loading ["+getStubFileName()+"]", e); } } else { propagateName(); if (getSender() == null) { throw new ConfigurationException( getLogPrefix(null) + "no sender defined "); } try { getSender().configure(); } catch (ConfigurationException e) { throw new ConfigurationException(getLogPrefix(null)+"while configuring sender",e); } if (getSender() instanceof HasPhysicalDestination) { log.info(getLogPrefix(null)+"has sender on "+((HasPhysicalDestination)getSender()).getPhysicalDestinationName()); } if (getListener() != null) { if (getSender().isSynchronous()) { throw new ConfigurationException( getLogPrefix(null) + "cannot have listener with synchronous sender"); } try { getListener().configure(); } catch (ConfigurationException e) { throw new ConfigurationException(getLogPrefix(null)+"while configuring listener",e); } if (getListener() instanceof HasPhysicalDestination) { log.info(getLogPrefix(null)+"has listener on "+((HasPhysicalDestination)getListener()).getPhysicalDestinationName()); } } if (!(getLinkMethod().equalsIgnoreCase("MESSAGEID")) && (!(getLinkMethod().equalsIgnoreCase("CORRELATIONID")))) { throw new ConfigurationException( "Invalid argument for property LinkMethod [" + getLinkMethod() + "]. it should be either MESSAGEID or CORRELATIONID"); } if (isCheckXmlWellFormed() || StringUtils.isNotEmpty(getCheckRootTag())) { if (findForward(ILLEGALRESULTFORWARD) == null) throw new ConfigurationException(getLogPrefix(null) + "has no forward with name [illegalResult]"); } } ITransactionalStorage messageLog = getMessageLog(); if (messageLog!=null) { messageLog.configure(); if (StringUtils.isNotEmpty(getAuditTrailXPath())) { try { auditTrailTp = new TransformerPool(XmlUtils.createXPathEvaluatorSource(getAuditTrailXPath())); } catch (TransformerConfigurationException e) { throw new ConfigurationException(getLogPrefix(null) + "cannot create transformer for audittrail ["+getAuditTrailXPath()+"]",e); } } if (StringUtils.isNotEmpty(getCorrelationIDXPath())) { try { correlationIDTp = new TransformerPool(XmlUtils.createXPathEvaluatorSource(getCorrelationIDXPath())); } catch (TransformerConfigurationException e) { throw new ConfigurationException(getLogPrefix(null) + "cannot create transformer for correlationID ["+getCorrelationIDXPath()+"]",e); } } } if (getInputValidator()!=null) { getInputValidator().configure(); } if (getOutputValidator()!=null) { getOutputValidator().configure(); } } public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException { // if (input==null) { // throw new PipeRunException(this, "received null as input"); String result = null; if (getInputValidator()!=null) { log.debug(getLogPrefix(session)+"validating input"); PipeRunResult validationResult = getInputValidator().doPipe(input,session); if (validationResult!=null && !validationResult.getPipeForward().getName().equals("success")) { return validationResult; } } if (StringUtils.isNotEmpty(getStubFileName())) { ParameterList pl = getParameterList(); result=returnString; if (pl != null) { ParameterResolutionContext prc = new ParameterResolutionContext((String)input, session); Map params; try { params = prc.getValueMap(pl); } catch (ParameterException e1) { throw new PipeRunException(this,getLogPrefix(session)+"got exception evaluating parameters",e1); } String sfn = null; if (params != null && params.size() > 0) { sfn = (String)params.get(STUBFILENAME); } if (sfn != null) { try { result = Misc.resourceToString(ClassUtils.getResourceURL(this,sfn), SystemUtils.LINE_SEPARATOR); log.info(getLogPrefix(session)+"returning result from dynamic stub ["+sfn+"]"); } catch (Throwable e) { throw new PipeRunException(this,getLogPrefix(session)+"got exception loading result from stub [" + sfn + "]",e); } } else { log.info(getLogPrefix(session)+"returning result from static stub ["+getStubFileName()+"]"); } // // Use remaining params as outgoing UDZs // Map udzMap = new HashMap(); // udzMap.putAll(params); // udzMap.remove(STUBFILENAME); } else { log.info(getLogPrefix(session)+"returning result from static stub ["+getStubFileName()+"]"); } } else { ICorrelatedPullingListener replyListener = getListener(); Map threadContext=new HashMap(); try { String correlationID = session.getMessageId(); String messageID = null; // sendResult has a messageID for async senders, the result for sync senders String sendResult = sendMessage(input, session, correlationID, getSender(), threadContext); if (getSender().isSynchronous()) { if (log.isInfoEnabled()) { log.info(getLogPrefix(session)+ "sent message to ["+ getSender().getName()+ "] synchronously"); } result = sendResult; } else { messageID = sendResult; // if linkMethod is MESSAGEID overwrite correlationID with the messageID // as this will be used with the listener if (getLinkMethod().equalsIgnoreCase("MESSAGEID")) { correlationID = sendResult; } if (log.isInfoEnabled()) { log.info(getLogPrefix(session) + "sent message to [" + getSender().getName()+ "] messageID ["+ messageID+ "] correlationID ["+ correlationID+ "] linkMethod ["+ getLinkMethod() + "]"); } } ITransactionalStorage messageLog = getMessageLog(); if (messageLog!=null) { String messageTrail="no audit trail"; if (auditTrailTp!=null) { messageTrail=auditTrailTp.transform((String)input,null); } String storedMessageID=messageID; if (storedMessageID==null) { storedMessageID="-"; } if (correlationIDTp!=null) { correlationID=correlationIDTp.transform((String)input,null); if (StringUtils.isEmpty(correlationID)) { correlationID="-"; } } messageLog.storeMessage(storedMessageID,correlationID,new Date(),messageTrail,(String)input); } if (replyListener != null) { if (log.isDebugEnabled()) { log.debug(getLogPrefix(session) + "starts listening for return message with correlationID ["+ correlationID + "]"); } threadContext = replyListener.openThread(); Object msg = replyListener.getRawMessage(correlationID, threadContext); if (msg==null) { log.info(getLogPrefix(session)+"received null reply message"); } else { log.info(getLogPrefix(session)+"received reply message"); } result = replyListener.getStringFromRawMessage(msg, threadContext); } else { result = sendResult; } if (result == null) { result = ""; } } catch (TimeOutException toe) { PipeForward timeoutForward = findForward(TIMEOUTFORWARD); if (timeoutForward==null) { log.warn(getLogPrefix(session) + "timeout occured, but no timeout-forward defined", toe); timeoutForward=getForward(); } else { log.warn(getLogPrefix(session) + "timeout occured", toe); } return new PipeRunResult(timeoutForward,getResultOnTimeOut()); } catch (Throwable t) { PipeForward exceptionForward = findForward(EXCEPTIONFORWARD); if (exceptionForward!=null) { log.warn(getLogPrefix(session) + "exception occured, forwarding to exception-forward ["+exceptionForward.getPath()+"], exception:\n", t); String resultmsg; if (input instanceof String) { resultmsg=new ErrorMessageFormatter().format(getLogPrefix(session),t,this,(String)input,session.getMessageId(),0); } else { if (input==null) { input="null"; } resultmsg=new ErrorMessageFormatter().format(getLogPrefix(session),t,this,input.toString(),session.getMessageId(),0); } return new PipeRunResult(exceptionForward,resultmsg); } throw new PipeRunException(this, getLogPrefix(session) + "caught exception", t); } finally { if (getListener()!=null) try { log.debug(getLogPrefix(session)+"is closing listener"); replyListener.closeThread(threadContext); } catch (ListenerException le) { log.error(getLogPrefix(session)+"got error closing listener", le); } } } if (!validResult(result)) { PipeForward illegalResultForward = findForward(ILLEGALRESULTFORWARD); return new PipeRunResult(illegalResultForward, result); } if (getOutputValidator()!=null) { log.debug(getLogPrefix(session)+"validating response"); PipeRunResult validationResult = getOutputValidator().doPipe(result,session); if (validationResult!=null && !validationResult.getPipeForward().getName().equals("success")) { return validationResult; } } return new PipeRunResult(getForward(), result); } private boolean validResult(String result) { boolean validResult = true; if (isCheckXmlWellFormed() || StringUtils.isNotEmpty(getCheckRootTag())) { if (!XmlUtils.isWellFormed(result, getCheckRootTag())) { validResult = false; } } return validResult; } protected String sendMessage(Object input, PipeLineSession session, String correlationID, ISender sender, Map threadContext) throws SenderException, TimeOutException { if (!(input instanceof String)) { throw new SenderException("String expected, got a [" + input.getClass().getName() + "]"); } // sendResult has a messageID for async senders, the result for sync senders if (sender instanceof ISenderWithParameters && getParameterList()!=null) { ISenderWithParameters psender = (ISenderWithParameters) sender; ParameterResolutionContext prc = new ParameterResolutionContext((String)input, session, isNamespaceAware()); return psender.sendMessage(correlationID, (String) input, prc); } return sender.sendMessage(correlationID, (String) input); } public void start() throws PipeStartException { if (StringUtils.isEmpty(getStubFileName())) { try { getSender().open(); if (getListener() != null) { getListener().open(); } } catch (Throwable t) { PipeStartException pse = new PipeStartException(getLogPrefix(null)+"could not start", t); pse.setPipeNameInError(getName()); throw pse; } } ITransactionalStorage messageLog = getMessageLog(); if (messageLog!=null) { try { messageLog.open(); } catch (Exception e) { PipeStartException pse = new PipeStartException(getLogPrefix(null)+"could not open messagelog", e); pse.setPipeNameInError(getName()); throw pse; } } } public void stop() { if (StringUtils.isEmpty(getStubFileName())) { log.info(getLogPrefix(null) + "is closing"); try { getSender().close(); } catch (SenderException e) { log.warn(getLogPrefix(null) + "exception closing sender", e); } if (getListener() != null) { try { log.info(getLogPrefix(null) + "is closing; closing listener"); getListener().close(); } catch (ListenerException e) { log.warn(getLogPrefix(null) + "Exception closing listener", e); } } } ITransactionalStorage messageLog = getMessageLog(); if (messageLog!=null) { try { messageLog.close(); } catch (Exception e) { log.warn(getLogPrefix(null) + "Exception closing messageLog", e); } } } /** * Register a {@link ICorrelatedPullingListener} at this Pipe */ protected void setListener(ICorrelatedPullingListener listener) { this.listener = listener; log.debug( "pipe [" + getName() + " registered listener [" + listener.toString() + "]"); } public ICorrelatedPullingListener getListener() { return listener; } /** * Sets the messageLog. */ protected void setMessageLog(ITransactionalStorage messageLog) { if (messageLog.isActive()) { this.messageLog = messageLog; messageLog.setName("messageLog of ["+getName()+"]"); if (StringUtils.isEmpty(messageLog.getSlotId())) { messageLog.setSlotId(getName()); } messageLog.setType("L"); } } public ITransactionalStorage getMessageLog() { return messageLog; } /** * Register a ISender at this Pipe * @see ISender */ protected void setSender(ISender sender) { this.sender = sender; log.debug( "pipe [" + getName() + " registered sender [" + sender.getName() + "] with properties [" + sender.toString() + "]"); } public ISender getSender() { return sender; } /** * The message that is returned when the time listening for a reply message * exceeds the timeout, or in other situations no reply message is received. */ public void setResultOnTimeOut(String newResultOnTimeOut) { resultOnTimeOut = newResultOnTimeOut; } public String getResultOnTimeOut() { return resultOnTimeOut; } /** * For asynchronous communication, the server side may either use the messageID or the correlationID * in the correlationID field of the reply message. Use this property to set the behaviour of the reply-listener. * <ul> * <li>Use <code>MESSAGEID</code> to let the listener wait for a message with the messageID of the * sent message in the correlation ID field</li> * <li>Use <code>CORRELATIONID</code> to let the listener wait for a message with the correlationID of the * sent message in the correlation ID field</li> * </ul> * When you use the method CORRELATIONID you have the advantage that you can trace your request * as the messageID as it is known in the Adapter is used as the correlationID. In the logging you should be able * to follow the message more clearly. When you use the method MESSAGEID, the messageID (unique for every * message) will be expected in the correlationID field of the returned message. * * @param method either MESSAGEID or CORRELATIONID */ public void setLinkMethod(String method) { linkMethod = method; } public String getLinkMethod() { return linkMethod; } public void setStubFileName(String fileName) { stubFileName = fileName; } public String getStubFileName() { return stubFileName; } public void setCheckXmlWellFormed(boolean b) { checkXmlWellFormed = b; } public boolean isCheckXmlWellFormed() { return checkXmlWellFormed; } public void setCheckRootTag(String s) { checkRootTag = s; } public String getCheckRootTag() { return checkRootTag; } public void setAuditTrailXPath(String string) { auditTrailXPath = string; } public String getAuditTrailXPath() { return auditTrailXPath; } public void setCorrelationIDXPath(String string) { correlationIDXPath = string; } public String getCorrelationIDXPath() { return correlationIDXPath; } public void setInputValidator(IPipe inputValidator) { // if (inputValidator.isActive()) { this.inputValidator = inputValidator; } public IPipe getInputValidator() { return inputValidator; } public void setOutputValidator(IPipe outputValidator) { // if (outputValidator.isActive()) { this.outputValidator = outputValidator; } public IPipe getOutputValidator() { return outputValidator; } }
package drullkus.thermalsmeltery; import mantle.pulsar.config.ForgeCFG; import mantle.pulsar.control.PulseManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import drullkus.thermalsmeltery.config.TSmeltConfig; import drullkus.thermalsmeltery.plugins.EnderIOSmeltery; import drullkus.thermalsmeltery.plugins.ThermalExpansionSmeltery; import drullkus.thermalsmeltery.plugins.TinkersSmeltery; @Mod(modid = ThermalSmeltery.MODID, name = ThermalSmeltery.NAME, dependencies = ThermalSmeltery.DEPENDENCIES) public class ThermalSmeltery { public static final String MODID = "ThermalSmeltery"; public static final String NAME = "Thermal Smeltery"; public static final String DEPENDENCIES = "after:ExtraTiC;after:BigReactors;required-after:TConstruct;required-after:ThermalExpansion"; public static final Logger logger = LogManager.getLogger(MODID); @Instance(MODID) public static ThermalSmeltery instance = new ThermalSmeltery(); public static PulseManager pulsar = new PulseManager(MODID, new ForgeCFG("TSmeltModules", "Modules: Disabling these will disable a chunk of the mod")); @EventHandler public void preInit(FMLPreInitializationEvent event) { TSmeltConfig.initProps(event.getModConfigurationDirectory()); pulsar.registerPulse(new ThermalExpansionSmeltery()); pulsar.registerPulse(new TinkersSmeltery()); pulsar.registerPulse(new EnderIOSmeltery()); pulsar.preInit(event); } @EventHandler public void init(FMLInitializationEvent event) { pulsar.init(event); } @EventHandler public void postInit(FMLPostInitializationEvent event) { pulsar.postInit(event); } }
package org.binwang.bard.core; import org.binwang.bard.core.doc.Api; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * GenericHandler is a class that is the foundation of Adapter, Filter, Injector and Handler. * It could run its method with defined annotations. * * @param <AnnotationType> Which annotation is this GenericHandler bind to. No need on Handler. * @see org.binwang.bard.core.Adapter * @see org.binwang.bard.core.Filter * @see org.binwang.bard.core.Injector * @see org.binwang.bard.core.Handler */ public abstract class GenericHandler<AnnotationType extends Annotation> { /** * The context in this handler. */ protected Context context; // TODO: should variable and returnType more suitable in context? /** * Only used by {@link org.binwang.bard.core.Injector}, store the current variable that will be injected. */ protected Object variable; /** * Only used by {@link org.binwang.bard.core.Injector}, the type inject variable. */ protected Class returnType = Object.class; /** * Used by {@link org.binwang.bard.core.Filter}, {@link org.binwang.bard.core.Injector} and * {@link org.binwang.bard.core.Adapter}, the annotation instance that bind to it. */ protected AnnotationType annotation; /** * A mapper to find GenericHandler from annotation class. */ protected AnnotationMapper mapper; /** * API document, used except in {@link org.binwang.bard.core.Handler} */ protected Api api = new Api(); /** * APIs, used in {@link org.binwang.bard.core.Handler} */ protected List<Api> apis = new LinkedList<>(); public GenericHandler() { } public <HandlerType extends GenericHandler> HandlerType newFromThis( Class<? extends HandlerType> handlerClass, Class<?> returnType, Annotation annotation ) throws IllegalAccessException, InstantiationException { HandlerType handler = handlerClass.newInstance(); handler.context = context; handler.variable = variable; handler.returnType = returnType; handler.annotation = annotation; handler.mapper = mapper; handler.api = api; return handler; } protected void runMethods(Class<? extends Annotation> requiredAnnotation) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { Method[] methods = this.getClass().getMethods(); for (Method m : methods) { runMethod(m, requiredAnnotation); } } protected void generateApi() throws InstantiationException, IllegalAccessException { Method[] methods = this.getClass().getMethods(); Annotation[] classAnnotations = this.getClass().getAnnotations(); for (Method m : methods) { boolean isHandler = false; Annotation[] methodAnnotations = m.getAnnotations(); for (int i = 0; i < methodAnnotations.length + classAnnotations.length; i++) { Annotation annotation; if (i < classAnnotations.length) { annotation = classAnnotations[i]; } else { annotation = methodAnnotations[i - classAnnotations.length]; } Class<? extends Annotation> annotationClass = annotation.annotationType(); Class<? extends Filter> filterClass = mapper.filterMap.get(annotationClass); if (filterClass != null) { Filter filter = newFromThis(filterClass, Object.class, annotation); filter.generateApi(); filter.generateDoc(); api = filter.api; } Class<? extends Adapter> adapterClass = mapper.adapterMap.get(annotationClass); if (adapterClass != null) { if (i >= classAnnotations.length) { isHandler = true; } Adapter adapter = newFromThis(adapterClass, Object.class, annotation); adapter.generateApi(); adapter.generateDoc(); api = adapter.api; } } Parameter[] parameters = m.getParameters(); for (Parameter parameter : parameters) { Annotation[] pAnnotations = parameter.getAnnotations(); for (Annotation annotation : pAnnotations) { Class<? extends Annotation> annotationClass = annotation.annotationType(); Class<? extends Injector> injectorClass = mapper.injectorMap.get(annotationClass); if (injectorClass != null) { Injector injector = newFromThis(injectorClass, parameter.getType(), annotation); injector.generateApi(); injector.generateDoc(); api = injector.api; } } } if (isHandler && this instanceof Handler) { apis.add(api); api = new Api(); } } } /** * Run GenericHandler method with adapters, filters and injectors. * If the class is {@link Handler}, it will only run when there is at least one adapter on it. * * @param m The method to run * @param requiredAnnotation Method will run when has requiredAnnotation. If it is null, method will run. * @return The method's return. Or NO_ADAPTER if do not match the request. * @see org.binwang.bard.core.Filter * @see org.binwang.bard.core.Adapter * @see org.binwang.bard.core.Injector * @see org.binwang.bard.core.Handler */ protected Object runMethod(Method m, Class<? extends Annotation> requiredAnnotation) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { Boolean findRequiredAnnotation = false; Boolean findAdapterOnMethod = false; NoAdapter noAdapter = NoAdapter.NO_ADAPTER; // get method's annotation Annotation[] methodAnnotations = m.getAnnotations(); // get class's annotation Annotation[] classAnnotations = this.getClass().getAnnotations(); Map<Class<? extends Annotation>, List<Adapter>> adapterMap = new LinkedHashMap<>(); Filter[] filters = new Filter[methodAnnotations.length + classAnnotations.length]; int filterSize = 0; // check the annotations, to get adapters and filters for (int i = 0; i < methodAnnotations.length + classAnnotations.length; i++) { Annotation annotation; if (i < classAnnotations.length) { annotation = classAnnotations[i]; } else { annotation = methodAnnotations[i - classAnnotations.length]; } Class<? extends Annotation> annotationClass = annotation.annotationType(); if (annotationClass == requiredAnnotation) { findRequiredAnnotation = true; } Class<? extends Adapter> adapterClass = mapper.adapterMap.get(annotationClass); if (adapterClass != null) { Adapter adapter = newFromThis(adapterClass, Object.class, annotation); /* Add the adapters with the same annotation type to one list, in order to processing them together. Helpful while define adapters could be used both on class and method. */ List<Adapter> adapters = adapterMap.get(annotationClass); if (adapters == null) { adapters = new LinkedList<>(); } adapters.add(adapter); adapterMap.put(annotationClass, adapters); if (i >= classAnnotations.length) { findAdapterOnMethod = true; } } Class<? extends Filter> filterClass = mapper.filterMap.get(annotationClass); if (filterClass != null) { Filter filter = newFromThis(filterClass, Object.class, annotation); filters[filterSize++] = filter; } } // is the method has the specified annotation? if (!findRequiredAnnotation && requiredAnnotation != null) { return noAdapter; } // if no adapter specified on handler, return it if (this instanceof Handler && !findAdapterOnMethod) { return noAdapter; } /* Run adapter first, check if all the adapters return true. If some adapters has the same annotation type (this only happens both class and method has the same annotation), run all the chain, if one get true then it is successful. It is very helpful to define adapter annotations that could be used both on class and method: such as Path. */ for (Map.Entry<Class<? extends Annotation>, List<Adapter>> entry : adapterMap.entrySet()) { boolean matching = false; List<Adapter> adapters = entry.getValue(); LinkedList<Adapter> runAdapters = new LinkedList<>(); for (Adapter adapter : adapters) { adapter.context = context; runAdapters.addFirst(adapter); matching = adapter.match() || matching; context = adapter.context; } for (Adapter adapter : runAdapters) { adapter.after(); context = adapter.context; } if (!matching) { return NoAdapter.NO_ADAPTER; } } Object result = null; int filterI = 0; int injectorI; LinkedList<LinkedList<Injector>> injectors = new LinkedList<>(); LinkedList<Filter> runFilters = new LinkedList<>(); // try-catch, so that if error occurs, recovery to run filters' and injectors' after actions try { // run filters before for (; filterI < filterSize; filterI++) { filters[filterI].context = context; runFilters.addFirst(filters[filterI]); filters[filterI].before(); context = filters[filterI].context; if (context.exception != null) { throw context.exception; } } // run injectors before to get params Parameter[] parameters = m.getParameters(); Object args[] = new Object[parameters.length]; for (injectorI = 0; injectorI < parameters.length; injectorI++) { // run injectors on one param, to get what should it be Annotation[] annotations = parameters[injectorI].getAnnotations(); Class parameterClass = parameters[injectorI].getType(); LinkedList<Injector> paramInjectors = new LinkedList<>(); injectors.addFirst(paramInjectors); Object var = null; for (Annotation annotation : annotations) { Class<? extends Annotation> annotationClass = annotation.annotationType(); Class<? extends Injector> injectorClass = mapper.injectorMap.get(annotationClass); if (injectorClass == null) { continue; } Injector injector = newFromThis(injectorClass, parameterClass, annotation); injector.context = context; injector.variable = var; // add injector, in order to run after actions paramInjectors.addFirst(injector); injector.before(); var = injector.variable; context = injector.context; if (context.exception != null) { throw context.exception; } } args[injectorI] = var; } // run method result = m.invoke(this, args); // just put the result in context only if the class is Handler (or its extends) if (this instanceof Handler) { context.result = result; } } catch (final InvocationTargetException e) { // throw by m.invoke, the cause is the true exception context.exception = (Exception) e.getCause(); } catch (IllegalAccessException | InstantiationException | NoSuchMethodException e) { // these exceptions are caused by framework, so print them e.printStackTrace(); } catch (Exception e) { // it is the exception throw by filters or injectors context.exception = e; } finally { // first run injector after actions for (LinkedList<Injector> paramsInjectors : injectors) { for (Injector injector : paramsInjectors) { injector.context = context; injector.after(); context = injector.context; } } // then run filter after actions for (Filter filter : runFilters) { filter.context = context; filter.after(); context = filter.context; } } return result; } }
package org.mockito; import org.junit.Before; import org.junit.Test; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent; import org.mockito.invocation.Invocation; import org.mockito.invocation.MockHandler; import org.mockitoutil.TestBase; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.concurrent.Callable; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; /** * This test is an experimental use of Mockito API to simulate static mocking. * Other frameworks (like Powermock) can use it to build decent support for static mocking. */ public class StaticMockingExperimentTest extends TestBase { Foo mock = Mockito.mock(Foo.class); MockHandler handler = Mockito.mockingDetails(mock).getMockHandler(); Method staticMethod; Callable realMethod = new Callable() { @Override public Object call() throws Exception { return null; } }; @Before public void before() throws Throwable { staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class); } @Test public void verify_static_method() throws Throwable { //register staticMethod call on mock Invocation invocation = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "some arg"); handler.handle(invocation); //verify staticMethod on mock verify(mock); Invocation verification = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "some arg"); handler.handle(verification); //verify zero times, method with different argument verify(mock, times(0)); Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "different arg"); handler.handle(differentArg); } @Test public void verification_failure_static_method() throws Throwable { //register staticMethod call on mock Invocation invocation = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "foo"); handler.handle(invocation); //verify staticMethod on mock verify(mock); Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "different arg"); try { handler.handle(differentArg); fail(); } catch (ArgumentsAreDifferent e) {} } @Test public void stubbing_static_method() throws Throwable { //register staticMethod call on mock Invocation invocation = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "foo"); handler.handle(invocation); //register stubbing when(null).thenReturn("hey"); //validate stubbed return value assertEquals("hey", handler.handle(invocation)); assertEquals("hey", handler.handle(invocation)); //default null value is returned if invoked with different argument Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "different arg"); assertEquals(null, handler.handle(differentArg)); } @Test public void do_answer_stubbing_static_method() throws Throwable { //register stubbed return value doReturn("hey").when(mock); //complete stubbing by triggering an invocation that needs to be stubbed Invocation invocation = Mockito.framework() .createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "foo"); handler.handle(invocation); //validate stubbed return value assertEquals("hey", handler.handle(invocation)); assertEquals("hey", handler.handle(invocation)); //default null value is returned if invoked with different argument Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "different arg"); assertEquals(null, handler.handle(differentArg)); } @Test public void verify_no_more_interactions() throws Throwable { //works for now because there are not interactions verifyNoMoreInteractions(mock); //register staticMethod call on mock Invocation invocation = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "foo"); handler.handle(invocation); //fails now because we have one static invocation recorded try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} } /** * Adapts constructor to method calls needed to work with Mockito API. */ interface ConstructorMethodAdapter { Object construct(Constructor constructor, Object ... args); } @Test public void stubbing_new() throws Throwable { Constructor<Foo> ctr = Foo.class.getConstructor(String.class); Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0]; //stub constructor doReturn(new Foo("hey!")).when(mock); Invocation constructor = Mockito.framework().createInvocation( mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "foo"); handler.handle(constructor); //test stubbing Object result = handler.handle(constructor); assertEquals("foo:hey!", result.toString()); //stubbing miss Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "different arg"); Object result2 = handler.handle(differentArg); assertEquals(null, result2); } @Test public void verifying_new() throws Throwable { Constructor<Foo> ctr = Foo.class.getConstructor(String.class); Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0]; //invoke constructor Invocation constructor = Mockito.framework().createInvocation( mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "matching arg"); handler.handle(constructor); //verify successfully verify(mock); handler.handle(constructor); //verification failure verify(mock); Invocation differentArg = Mockito.framework().createInvocation(mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "different arg"); try { handler.handle(differentArg); fail(); } catch (WantedButNotInvoked e) { assertThat(e.getMessage()) .contains("matching arg") .contains("different arg"); } } static class Foo { private final String arg; public Foo(String arg) { this.arg = arg; } public static String staticMethod(String arg) { return ""; } @Override public String toString() { return "foo:" + arg; } } }
package org.javarosa.demo.shell; import java.util.Hashtable; import javax.microedition.lcdui.Displayable; import org.javarosa.core.Context; import org.javarosa.core.JavaRosaPlatform; import org.javarosa.core.api.Constants; import org.javarosa.core.api.IModule; import org.javarosa.core.api.IShell; import org.javarosa.core.model.FormData; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.storage.FormDataRMSUtility; import org.javarosa.core.model.storage.FormDefRMSUtility; import org.javarosa.core.util.WorkflowStack; import org.javarosa.demo.module.SplashScreenModule; import org.javarosa.formmanager.activity.FormListModule; import org.javarosa.formmanager.activity.FormTransportModule; import org.javarosa.formmanager.activity.ModelListModule; import org.javarosa.formmanager.utility.TransportContext; import org.javarosa.xform.util.XFormUtils; /** * This is the shell for the JavaRosa demo that handles switching all of the views * @author Brian DeRenzi * */ public class JavaRosaDemoShell implements IShell { // List of views that are used by this shell FormListModule formModule = null; SplashScreenModule splashScreen = null; FormTransportModule formTransport = null; ModelListModule modelModule = null; WorkflowStack stack; Context context; IModule currentModule; public JavaRosaDemoShell() { stack = new WorkflowStack(); context = new Context(); } public void exitShell() { } public void run() { init(); System.out.println("done init"); this.splashScreen = new SplashScreenModule(this, "/splash.gif"); System.out.println("done splash init"); this.formModule = new FormListModule(this,"Forms List"); System.out.println("Done formlist init"); this.formTransport = new FormTransportModule(this); this.modelModule = new ModelListModule(this); currentModule = splashScreen; this.splashScreen.start(context); System.out.println("Done with splashscreen start"); // switchView(ViewTypes.FORM_LIST); } private void init() { FormDataRMSUtility formData = new FormDataRMSUtility(FormDataRMSUtility.getUtilityName()); FormDefRMSUtility formDef = new FormDefRMSUtility(FormDefRMSUtility.getUtilityName()); System.out.println("Loading Forms"); // For now let's add the dummy form. if (formDef.getNumberOfRecords() == 0) { formDef.writeToRMS(XFormUtils .getFormFromResource("/hmis-a_draft.xhtml")); formDef.writeToRMS(XFormUtils .getFormFromResource("/hmis-b_draft.xhtml")); formDef.writeToRMS(XFormUtils .getFormFromResource("/shortform.xhtml")); } System.out.println("Done Loading Forms"); JavaRosaPlatform.instance().getStorageManager().getRMSStorageProvider() .registerRMSUtility(formData); JavaRosaPlatform.instance().getStorageManager().getRMSStorageProvider() .registerRMSUtility(formDef); System.out.println("Done registering"); } private void workflow(IModule lastModule, String returnCode, Hashtable returnVals) { //TODO: parse any returnvals into context if(stack.size() != 0) { stack.pop().resume(context); } // TODO Auto-generated method stub if( lastModule == this.splashScreen ) { currentModule = modelModule; this.modelModule.start(context); } if(lastModule == this.modelModule) { if(returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) { Object returnVal = returnVals.get(ModelListModule.returnKey); if(returnVal == ModelListModule.CMD_MSGS) { //Go to the FormTransport Module look at messages. TransportContext msgContext = new TransportContext(context); msgContext.setRequestedView(TransportContext.MESSAGE_VIEW); currentModule = formTransport; formTransport.start(msgContext); } } if(returnCode == Constants.ACTIVITY_COMPLETE) { //A Model was selected for some purpose Object returnVal = returnVals.get(ModelListModule.returnKey); if(returnVal == ModelListModule.CMD_EDIT) { //Load the Form Entry Module, and feed it the form data FormDef form = (FormDef)returnVals.get("form"); FormData data = (FormData)returnVals.get("data"); } if(returnVal == ModelListModule.CMD_SEND) { FormData data = (FormData)returnVals.get("data"); // Initialize the FormTransport Module, and feed it this form data. } } } if(lastModule == this.formTransport) { if(returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) { } if(returnCode == Constants.ACTIVITY_COMPLETE) { } } } /* (non-Javadoc) * @see org.javarosa.shell.IShell#moduleCompeleted(org.javarosa.module.IModule) */ public void returnFromModule(IModule module, String returnCode, Hashtable returnVals) { module.halt(); if(returnCode == Constants.ACTIVITY_SUSPEND || returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) { stack.push(module); } workflow(module, returnCode, returnVals); } public void setDisplay(IModule callingModule, Displayable display) { if(callingModule == currentModule) { JavaRosaPlatform.instance().getDisplay().setCurrent(display); } else { System.out.println("Module: " + callingModule + " attempted, but failed, to set the display"); } } }
package org.mvel.tests.main; import junit.framework.TestCase; import org.mvel.*; import static org.mvel.MVEL.*; import org.mvel.ast.WithNode; import org.mvel.debug.DebugTools; import org.mvel.debug.Debugger; import org.mvel.debug.Frame; import org.mvel.integration.Interceptor; import org.mvel.integration.ResolverTools; import org.mvel.integration.VariableResolverFactory; import org.mvel.integration.impl.ClassImportResolverFactory; import org.mvel.integration.impl.LocalVariableResolverFactory; import org.mvel.integration.impl.MapVariableResolverFactory; import org.mvel.integration.impl.StaticMethodImportResolverFactory; import org.mvel.optimizers.OptimizerFactory; import org.mvel.tests.main.res.*; import java.io.Serializable; import static java.lang.System.currentTimeMillis; import java.text.SimpleDateFormat; import java.util.*; public class CoreConfidenceTests extends TestCase { protected Foo foo = new Foo(); protected Map<String, Object> map = new HashMap<String, Object>(); protected Base base = new Base(); protected DerivedClass derived = new DerivedClass(); public CoreConfidenceTests() { foo.setBar(new Bar()); map.put("foo", foo); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("misc", new MiscTestClass()); map.put("pi", "3.14"); map.put("hour", "60"); map.put("zero", 0); map.put("testImpl", new TestInterface() { public String getName() { return "FOOBAR!"; } public boolean isFoo() { return true; } }); map.put("derived", derived); } public void testSingleProperty() { assertEquals(false, parseDirect("fun")); } public void testMethodOnValue() { assertEquals("DOG", parseDirect("foo.bar.name.toUpperCase()")); } public void testSimpleProperty() { assertEquals("dog", parseDirect("foo.bar.name")); } public void testSimpleProperty2() { assertEquals("cat", parseDirect("DATA")); } public void testPropertyViaDerivedClass() { assertEquals("cat", parseDirect("derived.data")); } public void testDeepAssignment() { assertEquals("crap", parseDirect("foo.bar.assignTest = 'crap'")); assertEquals("crap", parseDirect("foo.bar.assignTest")); } public void testThroughInterface() { assertEquals("FOOBAR!", parseDirect("testImpl.name")); } public void testThroughInterface2() { assertEquals(true, parseDirect("testImpl.foo")); } public void testMapAccessWithMethodCall() { assertEquals("happyBar", parseDirect("funMap['foo'].happy()")); } public void testBooleanOperator() { assertEquals(true, parseDirect("foo.bar.woof == true")); } public void testBooleanOperator2() { assertEquals(false, parseDirect("foo.bar.woof == false")); } public void testBooleanOperator3() { assertEquals(true, parseDirect("foo.bar.woof== true")); } public void testBooleanOperator4() { assertEquals(false, parseDirect("foo.bar.woof ==false")); } public void testBooleanOperator5() { assertEquals(true, parseDirect("foo.bar.woof == true")); } public void testBooleanOperator6() { assertEquals(false, parseDirect("foo.bar.woof==false")); } public void testTextComparison() { assertEquals(true, parseDirect("foo.bar.name == 'dog'")); } public void testNETextComparison() { assertEquals(true, parseDirect("foo.bar.name != 'foo'")); } public void testChor() { assertEquals("cat", parseDirect("a or b or c")); } public void testChorWithLiteral() { assertEquals("fubar", parseDirect("a or 'fubar'")); } public void testNullCompare() { assertEquals(true, parseDirect("c != null")); } public void testUninitializedInt() { assertEquals(0, parseDirect("sarahl")); } public void testAnd() { assertEquals(true, parseDirect("c != null && foo.bar.name == 'dog' && foo.bar.woof")); } public void testAnd2() { assertEquals(true, parseDirect("c!=null&&foo.bar.name=='dog'&&foo.bar.woof")); } public void testMath() { assertEquals(188.4f, parseDirect("pi * hour")); } public void testMath2() { assertEquals(3, parseDirect("foo.number-1")); } public void testComplexExpression() { assertEquals("bar", parseDirect("a = 'foo'; b = 'bar'; c = 'jim'; list = {a,b,c}; list[1]")); } public void testComplexAnd() { assertEquals(true, parseDirect("(pi * hour) > 0 && foo.happy() == 'happyBar'")); } public void testShortPathExpression() { assertEquals(null, parseDirect("3 > 4 && foo.toUC('test'); foo.register")); } public void testShortPathExpression2() { assertEquals(true, parseDirect("4 > 3 || foo.toUC('test')")); } public void testShortPathExpression4() { assertEquals(true, parseDirect("4>3||foo.toUC('test')")); } public void testOrOperator() { assertEquals(true, parseDirect("true||true")); } public void testOrOperator2() { assertEquals(true, parseDirect("2 > 3 || 3 > 2")); } public void testOrOperator3() { assertEquals(true, parseDirect("pi > 5 || pi > 6 || pi > 3")); } public void testShortPathExpression3() { assertEquals(false, parseDirect("defnull != null && defnull.length() > 0")); } public void testModulus() { assertEquals(38392 % 2, parseDirect("38392 % 2")); } public void testLessThan() { assertEquals(true, parseDirect("pi < 3.15")); assertEquals(true, parseDirect("pi <= 3.14")); assertEquals(false, parseDirect("pi > 3.14")); assertEquals(true, parseDirect("pi >= 3.14")); } public void testMethodAccess() { assertEquals("happyBar", parseDirect("foo.happy()")); } public void testMethodAccess2() { assertEquals("FUBAR", parseDirect("foo.toUC('fubar')")); } public void testMethodAccess3() { assertEquals(true, parseDirect("equalityCheck(c, 'cat')")); } public void testMethodAccess4() { assertEquals(null, parseDirect("readBack(null)")); } public void testMethodAccess5() { assertEquals("nulltest", parseDirect("appendTwoStrings(null, 'test')")); } public void testMethodAccess6() { assertEquals(true, parseDirect(" equalityCheck( c \n , \n 'cat' ) ")); } public void testNegation() { assertEquals(true, parseDirect("!fun && !fun")); } public void testNegation2() { assertEquals(false, parseDirect("fun && !fun")); } public void testNegation3() { assertEquals(true, parseDirect("!(fun && fun)")); } public void testNegation4() { assertEquals(false, parseDirect("(fun && fun)")); } public void testMultiStatement() { assertEquals(true, parseDirect("populate(); barfoo == 'sarah'")); } public void testAssignment() { assertEquals(true, parseDirect("populate(); blahfoo = 'sarah'; blahfoo == 'sarah'")); } public void testAssignment2() { assertEquals("sarah", parseDirect("populate(); blahfoo = barfoo")); } public void testAssignment3() { assertEquals(java.lang.Integer.class, parseDirect("blah = 5").getClass()); } public void testAssignment4() { assertEquals(102, parseDirect("a = 100 + 1 + 1")); } public void testOr() { assertEquals(true, parseDirect("fun || true")); } public void testLiteralPassThrough() { assertEquals(true, parseDirect("true")); } public void testLiteralPassThrough2() { assertEquals(false, parseDirect("false")); } public void testLiteralPassThrough3() { assertEquals(null, parseDirect("null")); } public void testRegEx() { assertEquals(true, parseDirect("foo.bar.name ~= '[a-z].+'")); } public void testRegExNegate() { assertEquals(false, parseDirect("!(foo.bar.name ~= '[a-z].+')")); } public void testRegEx2() { assertEquals(true, parseDirect("foo.bar.name ~= '[a-z].+' && foo.bar.name != null")); } public void testRegEx3() { assertEquals(true, parseDirect("foo.bar.name~='[a-z].+'&&foo.bar.name!=null")); } public void testBlank() { assertEquals(true, parseDirect("'' == empty")); } public void testBlank2() { assertEquals(true, parseDirect("BWAH == empty")); } public void testBooleanModeOnly2() { assertEquals(false, (Object) MVEL.evalToBoolean("BWAH", base, map)); } public void testBooleanModeOnly4() { assertEquals(true, (Object) MVEL.evalToBoolean("hour == (hour + 0)", base, map)); } public void testTernary() { assertEquals("foobie", parseDirect("zero==0?'foobie':zero")); } public void testTernary2() { assertEquals("blimpie", parseDirect("zero==1?'foobie':'blimpie'")); } public void testTernary3() { assertEquals("foobiebarbie", parseDirect("zero==1?'foobie':'foobie'+'barbie'")); } public void testStrAppend() { assertEquals("foobarcar", parseDirect("'foo' + 'bar' + 'car'")); } public void testStrAppend2() { assertEquals("foobarcar1", parseDirect("'foobar' + 'car' + 1")); } public void testInstanceCheck1() { assertEquals(true, parseDirect("c is java.lang.String")); } public void testInstanceCheck2() { assertEquals(false, parseDirect("pi is java.lang.Integer")); } public void testInstanceCheck3() { assertEquals(true, parseDirect("foo is org.mvel.tests.main.res.Foo")); } public void testBitwiseOr1() { assertEquals(6, parseDirect("2|4")); } public void testBitwiseOr2() { assertEquals(true, parseDirect("(2 | 1) > 0")); } public void testBitwiseOr3() { assertEquals(true, parseDirect("(2|1) == 3")); } public void testBitwiseAnd1() { assertEquals(2, parseDirect("2 & 3")); } public void testShiftLeft() { assertEquals(4, parseDirect("2 << 1")); } public void testUnsignedShiftLeft() { assertEquals(2, parseDirect("-2 <<< 0")); } public void testShiftRight() { assertEquals(128, parseDirect("256 >> 1")); } public void testXOR() { assertEquals(3, parseDirect("1 ^ 2")); } public void testContains1() { assertEquals(true, parseDirect("list contains 'Happy!'")); } public void testContains2() { assertEquals(false, parseDirect("list contains 'Foobie'")); } public void testContains3() { assertEquals(true, parseDirect("sentence contains 'fox'")); } public void testContains4() { assertEquals(false, parseDirect("sentence contains 'mike'")); } public void testContains5() { assertEquals(true, parseDirect("!(sentence contains 'mike')")); } public void testInvert() { assertEquals(~10, parseDirect("~10")); } public void testInvert2() { assertEquals(~(10 + 1), parseDirect("~(10 + 1)")); } public void testInvert3() { assertEquals(~10 + (1 + ~50), parseDirect("~10 + (1 + ~50)")); } public void testListCreation2() { assertTrue(parseDirect("[\"test\"]") instanceof List); } public void testListCreation3() { assertTrue(parseDirect("[66]") instanceof List); } public void testListCreation4() { List ar = (List) parseDirect("[ 66 , \"test\" ]"); assertEquals(2, ar.size()); assertEquals(66, ar.get(0)); assertEquals("test", ar.get(1)); } public void testListCreationWithCall() { assertEquals(1, parseDirect("[\"apple\"].size()")); } public void testArrayCreationWithLength() { assertEquals(2, parseDirect("Array.getLength({'foo', 'bar'})")); } public void testEmptyList() { assertTrue(parseDirect("[]") instanceof List); } public void testEmptyArray() { assertTrue(((Object[]) parseDirect("{}")).length == 0); } public void testEmptyArray2() { assertTrue(((Object[]) parseDirect("{ }")).length == 0); } public void testArrayCreation() { assertEquals(0, parseDirect("arrayTest = {{1, 2, 3}, {2, 1, 0}}; arrayTest[1][2]")); } public void testMapCreation() { assertEquals("sarah", parseDirect("map = ['mike':'sarah','tom':'jacquelin']; map['mike']")); } public void testMapCreation2() { assertEquals("sarah", parseDirect("map = ['mike' :'sarah' ,'tom' :'jacquelin' ]; map['mike']")); } public void testMapCreation3() { assertEquals("foo", parseDirect("map = [1 : 'foo']; map[1]")); } public void testProjectionSupport() { assertEquals(true, parseDirect("(name in things)contains'Bob'")); } public void testProjectionSupport1() { assertEquals(true, parseDirect("(name in things) contains 'Bob'")); } public void testProjectionSupport2() { assertEquals(3, parseDirect("(name in things).size()")); } public void testSizeOnInlineArray() { assertEquals(3, parseDirect("{1,2,3}.size()")); } public void testStaticMethodFromLiteral() { assertEquals(String.class.getName(), parseDirect("String.valueOf(Class.forName('java.lang.String').getName())")); } // public void testMethodCallsEtc() { // parseDirect("title = 1; " + // "frame = new javax.swing.JFrame; " + // "label = new javax.swing.JLabel; " + // "title = title + 1;" + // "frame.setTitle(title);" + // "label.setText('MVEL UNIT TEST PACKAGE -- IF YOU SEE THIS, THAT IS GOOD');" + // "frame.getContentPane().add(label);" + // "frame.pack();" + // "frame.setVisible(true);"); public void testObjectInstantiation() { parseDirect("new java.lang.String('foobie')"); } public void testObjectInstantiationWithMethodCall() { parseDirect("new String('foobie') . toString()"); } public void testObjectInstantiation2() { parseDirect("new String() is String"); } public void testObjectInstantiation3() { parseDirect("new java.text.SimpleDateFormat('yyyy').format(new java.util.Date(System.currentTimeMillis()))"); } public void testArrayCoercion() { assertEquals("gonk", parseDirect("funMethod( {'gonk', 'foo'} )")); } public void testArrayCoercion2() { assertEquals(10, parseDirect("sum({2,2,2,2,2})")); } public void testMapAccess() { assertEquals("dog", parseDirect("funMap['foo'].bar.name")); } public void testMapAccess2() { assertEquals("dog", parseDirect("funMap.foo.bar.name")); } public void testSoundex() { assertTrue((Boolean) parseDirect("'foobar' soundslike 'fubar'")); } public void testSoundex2() { assertFalse((Boolean) parseDirect("'flexbar' soundslike 'fubar'")); } public void testThisReference() { assertEquals(true, parseDirect("this") instanceof Base); } public void testThisReference2() { assertEquals(true, parseDirect("this.funMap") instanceof Map); } public void testThisReference3() { assertEquals(true, parseDirect("this is org.mvel.tests.main.res.Base")); } public void testStringEscaping() { assertEquals("\"Mike Brock\"", parseDirect("\"\\\"Mike Brock\\\"\"")); } public void testStringEscaping2() { assertEquals("MVEL's Parser is Fast", parseDirect("'MVEL\\'s Parser is Fast'")); } public void testEvalToBoolean() { assertEquals(true, (boolean) MVEL.evalToBoolean("true ", "true")); assertEquals(true, (boolean) MVEL.evalToBoolean("true ", "true")); } public void testCompiledMapStructures() { Serializable compiled = compileExpression("['foo':'bar'] contains 'foo'"); executeExpression(compiled, null, null, Boolean.class); } public void testSubListInMap() { assertEquals("pear", parseDirect("map = ['test' : 'poo', 'foo' : [c, 'pear']]; map['foo'][1]")); } public void testCompiledMethodCall() { Serializable compiled = compileExpression("c.getClass()"); assertEquals(String.class, executeExpression(compiled, base, map)); } public void testStaticNamespaceCall() { assertEquals(java.util.ArrayList.class, parseDirect("java.util.ArrayList")); } public void testStaticNamespaceClassWithMethod() { assertEquals("FooBar", parseDirect("java.lang.String.valueOf('FooBar')")); } public void testThisReferenceInMethodCall() { assertEquals(101, parseDirect("Integer.parseInt(this.number)")); } public void testThisReferenceInConstructor() { assertEquals("101", parseDirect("new String(this.number)")); } public void testConstructor() { assertEquals("foo", parseDirect("a = 'foobar'; new String(a.toCharArray(), 0, 3)")); } public void testStaticNamespaceClassWithField() { assertEquals(Integer.MAX_VALUE, parseDirect("java.lang.Integer.MAX_VALUE")); } public void testStaticNamespaceClassWithField2() { assertEquals(Integer.MAX_VALUE, parseDirect("Integer.MAX_VALUE")); } public void testStaticFieldAsMethodParm() { assertEquals(String.valueOf(Integer.MAX_VALUE), parseDirect("String.valueOf(Integer.MAX_VALUE)")); } public void testEmptyIf() { assertEquals(5, parseDirect("a = 5; if (a == 5) { }; return a;")); } public void testEmptyIf2() { assertEquals(5, parseDirect("a=5;if(a==5){};return a;")); } public void testIf() { assertEquals(10, parseDirect("if (5 > 4) { return 10; } else { return 5; }")); } public void testIf2() { assertEquals(10, parseDirect("if (5 < 4) { return 5; } else { return 10; }")); } public void testIf3() { assertEquals(10, parseDirect("if(5<4){return 5;}else{return 10;}")); } public void testIfAndElse() { assertEquals(true, parseDirect("if (false) { return false; } else { return true; }")); } public void testIfAndElseif() { assertEquals(true, parseDirect("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;")); } public void testIfAndElseIfCondensedGrammar() { assertEquals("Foo", parseDirect("if (false) return 'Bar'; else return 'Foo';")); } public void testForeEach2() { assertEquals(6, parseDirect("total = 0; a = {1,2,3}; foreach(item : a) { total += item }; total")); } public void testForEach3() { assertEquals(true, parseDirect("a = {1,2,3}; foreach (i : a) { if (i == 1) { return true; } }")); } public void testForEach4() { assertEquals("OneTwoThreeFour", parseDirect("a = {1,2,3,4}; builder = ''; foreach (i : a) {" + " if (i == 1) { builder += 'One' } else if (i == 2) { builder += 'Two' } " + "else if (i == 3) { builder += 'Three' } else { builder += 'Four' }" + "}; builder;")); } public void testWith() { assertEquals("OneTwo", parseDirect("with (foo) {aValue = 'One',bValue='Two'}; foo.aValue + foo.bValue;")); } public void testWith2() { assertEquals("OneTwo", parseDirect( "with (foo) { \n" + "aValue = 'One', \n" + "bValue='Two' \n" + "}; \n" + "foo.aValue + foo.bValue;")); } public void testAssertion() { try { parseDirect("assert false"); assertTrue(false); } catch (AssertionError error) { } } public void testAssertion2() { try { parseDirect("assert true;"); } catch (AssertionError error) { assertTrue(false); } } public void testMagicArraySize() { assertEquals(5, parseDirect("stringArray.size()")); } public void testMagicArraySize2() { assertEquals(5, parseDirect("intArray.size()")); } public void testStaticVarAssignment() { assertEquals("1", parseDirect("String mikeBrock = 1; mikeBrock")); } public void testIntentionalFailure() { try { parseDirect("int = 0"); // should fail because int is a reserved word. assertTrue(false); } catch (Exception e) { } } public void testImport() { assertEquals(HashMap.class, parseDirect("import java.util.HashMap; HashMap;")); } public void testStaticImport() { assertEquals(2.0, parseDirect("import_static java.lang.Math.sqrt; sqrt(4)")); } public void testFunctionPointer() { assertEquals(2.0, parseDirect("squareRoot = java.lang.Math.sqrt; squareRoot(4)")); } public void testFunctionPointerAsParam() { assertEquals("2.0", parseDirect("squareRoot = Math.sqrt; new String(String.valueOf(squareRoot(4)));")); } public void testIncrementOperator() { assertEquals(2, parseDirect("x = 1; x++; x")); } public void testPreIncrementOperator() { assertEquals(2, parseDirect("x = 1; ++x")); } public void testDecrementOperator() { assertEquals(1, parseDirect("x = 2; x } public void testPreDecrementOperator() { assertEquals(1, parseDirect("x = 2; --x")); } public void testQualifiedStaticTyping() { assertEquals(20, parseDirect("java.math.BigDecimal a = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal b = new java.math.BigDecimal( 10.0 ); java.math.BigDecimal c = a + b; return c; ")); } public void testUnQualifiedStaticTyping() { assertEquals(20, parseDirect("import java.math.BigDecimal; BigDecimal a = new BigDecimal( 10.0 ); BigDecimal b = new BigDecimal( 10.0 ); BigDecimal c = a + b; return c; ")); } public void testObjectCreation() { assertEquals(6, parseDirect("new Integer( 6 )")); } public void testTernary4() { assertEquals("<test>", parseDirect("true ? '<test>' : '<poo>'")); } public void testStringAsCollection() { assertEquals('o', parseDirect("abc = 'foo'; abc[1]")); } public void testSubExpressionIndexer() { assertEquals("bar", parseDirect("xx = new java.util.HashMap(); xx.put('foo', 'bar'); prop = 'foo'; xx[prop];")); } public void testCompileTimeLiteralReduction() { assertEquals(1000, parseDirect("10 * 100")); } public void testInterfaceResolution() { Serializable ex = MVEL.compileExpression("foo.collectionTest.size()"); foo.setCollectionTest(new HashSet()); Object result1 = MVEL.executeExpression(ex, map); foo.setCollectionTest(new ArrayList()); Object result2 = MVEL.executeExpression(ex, map); assertEquals(result1, result2); } /** * Start collections framework based compliance tests */ public void testCreationOfSet() { assertEquals("foo bar foo bar", parseDirect("set = new java.util.HashSet(); " + "set.add('foo');" + "set.add('bar');" + "output = '';" + "foreach (item : set) {" + "output = output + item + ' ';" + "} " + "foreach (item : set) {" + "output = output + item + ' ';" + "} " + "output = output.trim();" + "if (set.size() == 2) { return output; }")); } public void testCreationOfList() { assertEquals(5, parseDirect("l = new java.util.LinkedList();" + "l.add('fun');" + "l.add('happy');" + "l.add('fun');" + "l.add('slide');" + "l.add('crap');" + "poo = new java.util.ArrayList(l);" + "poo.size();")); } public void testMapOperations() { assertEquals("poo5", parseDirect( "l = new java.util.ArrayList();" + "l.add('plop');" + "l.add('poo');" + "m = new java.util.HashMap();" + "m.put('foo', l);" + "m.put('cah', 'mah');" + "m.put('bar', 'foo');" + "m.put('sarah', 'mike');" + "m.put('edgar', 'poe');" + "" + "if (m.edgar == 'poe') {" + "return m.foo[1] + m.size();" + "}")); } public void testStackOperations() { assertEquals(10, parseDirect( "stk = new java.util.Stack();" + "stk.push(5);" + "stk.push(5);" + "stk.pop() + stk.pop();" )); } public void testBreakpoints() { ExpressionCompiler compiler = new ExpressionCompiler("a = 5;\nb = 5;\n\nif (a == b) {\n\nSystem.out.println('Good');\nreturn a + b;\n}\n"); System.out.println(" compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); CompiledExpression compiled = compiler.compile(ctx); System.out.println(DebugTools.decompile(compiled)); MVELRuntime.registerBreakpoint("test.mv", 7); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(10, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(map))); } public void testBreakpoints2() { ExpressionCompiler compiler = new ExpressionCompiler("System.out.println('test the debugger');\n a = 0;"); compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test.mv"); CompiledExpression compiled = compiler.compile(ctx); System.out.println(DebugTools.decompile(compiled)); } public void testBreakpoints3() { String expr = "System.out.println( \"a1\" );\n" + "System.out.println( \"a2\" );\n" + "System.out.println( \"a3\" );\n" + "System.out.println( \"a4\" );\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); compiler.setDebugSymbols(true); ParserContext context = new ParserContext(); context.addImport("System", System.class); context.setStrictTypeEnforcement(true); context.setDebugSymbols(true); context.setSourceFile("mysource"); Serializable compiledExpression = compiler.compile(context); String s = org.mvel.debug.DebugTools.decompile(compiledExpression); System.out.println("output: " + s); int fromIndex = 0; int count = 0; while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) { count++; } assertEquals(4, count); } public void testBreakpointsAcrossComments() { ExpressionCompiler compiler = new ExpressionCompiler("/** This is a comment\nSecond comment line\nThird Comment Line\n*/\nSystem.out.println('4');\nSystem.out.println('5');\na = 0;\n b = 1;\n a + b"); compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test2.mv"); CompiledExpression compiled = compiler.compile(ctx); System.out.println(DebugTools.decompile(compiled)); MVELRuntime.registerBreakpoint("test2.mv", 5); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(map))); } public void testBreakpointsAcrossComments2() { ExpressionCompiler compiler = new ExpressionCompiler( "// This is a comment\n" + "//Second comment line\n" + "//Third Comment Line\n" + "\n" + "System.out.println('4');\n" + "System.out.println('5');\n" + "a = 0;\n" + "b = 1;\n" + " a + b"); compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(); ctx.setSourceFile("test2.mv"); CompiledExpression compiled = compiler.compile(ctx); System.out.println(DebugTools.decompile(compiled)); MVELRuntime.registerBreakpoint("test2.mv", 6); Debugger testDebugger = new Debugger() { public int onBreak(Frame frame) { System.out.println("Breakpoint [source:" + frame.getSourceName() + "; line:" + frame.getLineNumber() + "]"); return 0; } }; MVELRuntime.setThreadDebugger(testDebugger); assertEquals(1, MVEL.executeDebugger(compiled, null, new MapVariableResolverFactory(map))); } public void testDebugSymbolsWithWindowsLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\r\n" + " System.out.println( \"a2\" );\r\n" + " System.out.println( \"a3\" );\r\n" + " System.out.println( \"a4\" );\r\n"; ExpressionCompiler compiler = new ExpressionCompiler( expr ); compiler.setDebugSymbols( true ); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols( true ); ctx.setSourceFile( "mysource" ); Serializable compiledExpression = compiler.compile(ctx); String s = org.mvel.debug.DebugTools.decompile( compiledExpression ); int fromIndex=0; int count = 0; while ((fromIndex = s.indexOf( "DEBUG_SYMBOL", fromIndex+1 )) > -1) { count++; } assertEquals(4, count); } public void testDebugSymbolsWithUnixLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\n" + " System.out.println( \"a2\" );\n" + " System.out.println( \"a3\" );\n" + " System.out.println( \"a4\" );\n"; ExpressionCompiler compiler = new ExpressionCompiler( expr ); compiler.setDebugSymbols( true ); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols( true ); ctx.setSourceFile( "mysource" ); Serializable compiledExpression = compiler.compile(ctx); String s = org.mvel.debug.DebugTools.decompile( compiledExpression ); int fromIndex=0; int count = 0; while ((fromIndex = s.indexOf( "DEBUG_SYMBOL", fromIndex+1 )) > -1) { count++; } assertEquals(4, count); } public void testDebugSymbolsWithMixedLinedEndings() throws Exception { String expr = " System.out.println( \"a1\" );\n" + " System.out.println( \"a2\" );\r\n" + " System.out.println( \"a3\" );\n" + " System.out.println( \"a4\" );\r\n"; ExpressionCompiler compiler = new ExpressionCompiler( expr ); compiler.setDebugSymbols( true ); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.setDebugSymbols( true ); ctx.setSourceFile( "mysource" ); Serializable compiledExpression = compiler.compile(ctx); String s = org.mvel.debug.DebugTools.decompile( compiledExpression ); int fromIndex=0; int count = 0; while ((fromIndex = s.indexOf( "DEBUG_SYMBOL", fromIndex+1 )) > -1) { count++; } assertEquals(4, count); } public void testReflectionCache() { assertEquals("happyBar", parseDirect("foo.happy(); foo.bar.happy()")); } public void testVarInputs() { ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;"); compiler.compile(); ParserContext pCtx = compiler.getParserContextState(); assertEquals(4, pCtx.getInputs().size()); assertTrue(pCtx.getInputs().containsKey("test")); assertTrue(pCtx.getInputs().containsKey("foo")); assertTrue(pCtx.getInputs().containsKey("bo")); assertTrue(pCtx.getInputs().containsKey("trouble")); assertEquals(2, pCtx.getVariables().size()); assertTrue(pCtx.getVariables().containsKey("bleh")); assertTrue(pCtx.getVariables().containsKey("twa")); assertEquals(String.class, pCtx.getVarOrInputType("bleh")); } public void testVarInputs2() { ExpressionCompiler compiler = new ExpressionCompiler("test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;"); ParserContext ctx = new ParserContext(); ctx.setRetainParserState(true); compiler.compile(ctx); System.out.println(ctx.getVarOrInputType("bleh")); } public void testVarInputs3() { ExpressionCompiler compiler = new ExpressionCompiler("addresses['home'].street"); compiler.compile(); assertFalse(compiler.getParserContextState().getInputs().keySet().contains("home")); } public void testAnalyzer() { ExpressionCompiler compiler = new ExpressionCompiler("order.id == 10"); compiler.compile(); for (String input : compiler.getParserContextState().getInputs().keySet()) { System.out.println("input>" + input); } assertEquals(1, compiler.getParserContextState().getInputs().size()); assertTrue(compiler.getParserContextState().getInputs().containsKey("order")); } public void testClassImportViaFactory() { MapVariableResolverFactory mvf = new MapVariableResolverFactory(map); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(HashMap.class); ResolverTools.appendFactory(mvf, classes); Serializable compiled = compileExpression("HashMap map = new HashMap()", classes.getImportedClasses()); assertTrue(executeExpression(compiled, mvf) instanceof HashMap); } public void testCheeseConstructor() { MapVariableResolverFactory mvf = new MapVariableResolverFactory(map); ClassImportResolverFactory classes = new ClassImportResolverFactory(); classes.addClass(Cheese.class); ResolverTools.appendFactory(mvf, classes); Serializable compiled = compileExpression("cheese = new Cheese(\"cheddar\", 15);", classes.getImportedClasses()); assertTrue(executeExpression(compiled, mvf) instanceof Cheese); } public void testInterceptors() { Interceptor testInterceptor = new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { System.out.println("BEFORE Node: " + node.getName()); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { System.out.println("AFTER Node: " + node.getName()); return 0; } }; Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>(); interceptors.put("test", testInterceptor); Serializable compiled = compileExpression("@test System.out.println('MIDDLE');", null, interceptors); executeExpression(compiled); } public void testMacroSupport() { Map<String, Object> vars = new HashMap<String, Object>(); vars.put("foo", new Foo()); Map<String, Interceptor> interceptors = new HashMap<String, Interceptor>(); Map<String, Macro> macros = new HashMap<String, Macro>(); interceptors.put("Modify", new Interceptor() { public int doBefore(ASTNode node, VariableResolverFactory factory) { Object object = ((WithNode) node).getNestedStatement().getValue(null, factory); factory.createVariable("mod", "FOOBAR!"); return 0; } public int doAfter(Object val, ASTNode node, VariableResolverFactory factory) { return 0; } }); macros.put("modify", new Macro() { public String doMacro() { return "@Modify with"; } }); ExpressionCompiler compiler = new ExpressionCompiler(parseMacros("modify (foo) { aValue = 'poo' }; mod", macros)); compiler.setDebugSymbols(true); ParserContext ctx = new ParserContext(null, interceptors, null); ctx.setSourceFile("test.mv"); CompiledExpression compiled = compiler.compile(ctx); assertEquals("FOOBAR!", MVEL.executeExpression(compiled, null, vars)); } public void testComments() { assertEquals(10, parseDirect("// This is a comment\n5 + 5")); } public void testComments2() { assertEquals(20, parseDirect("10 + 10; // This is a comment")); } public void testComments3() { assertEquals(30, parseDirect("/* This is a test of\r\n" + "MVEL's support for\r\n" + "multi-line comments\r\n" + "*/\r\n 15 + 15")); } public void testComments4() { assertEquals(50, parseDirect("/** This is a fun test script **/\r\n" + "a = 10;\r\n" + "/**\r\n" + "* Here is a useful variable\r\n" + "*/\r\n" + "b = 20; // set b to '20'\r\n" + "return ((a + b) * 2) - 10;\r\n" + "// last comment\n")); } public void testSubtractNoSpace1() { assertEquals(59, parseDirect("hour-1")); } public void testStrictTypingCompilation() { ExpressionCompiler compiler = new ExpressionCompiler("a.foo;\nb.foo;\n x = 5"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); try { compiler.compile(ctx); } catch (CompileException e) { e.printStackTrace(); assertEquals(2, e.getErrors().size()); return; } assertTrue(false); } public void testStrictTypingCompilation2() throws NoSuchMethodException { ParserContext ctx = new ParserContext(); //noinspection RedundantArrayCreation ctx.addImport("getRuntime", Runtime.class.getMethod("getRuntime", new Class[]{})); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler("getRuntime()"); StaticMethodImportResolverFactory si = new StaticMethodImportResolverFactory(ctx); assertTrue(executeExpression(compiler.compile(ctx), si) instanceof Runtime); } public void testStrictTypingCompilation3() throws NoSuchMethodException { ParserContext ctx = new ParserContext(); // ctx.addImport("getRuntime", Runtime.class.getMethod("getRuntime", new Class[]{})); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler("message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n" + "System.out.println(message + ';' + b); b"); assertEquals(7, executeExpression(compiler.compile(ctx), new LocalVariableResolverFactory())); } public void testProvidedExternalTypes() { ExpressionCompiler compiler = new ExpressionCompiler("foo.bar"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); ctx.addInput("foo", Foo.class); compiler.compile(ctx); } public void testEqualityRegression() { ExpressionCompiler compiler = new ExpressionCompiler("price == (new Integer( 5 ) + 5 ) "); compiler.compile(); } public void testEvaluationRegression() { ExpressionCompiler compiler = new ExpressionCompiler("(p.age * 2)"); compiler.compile(); assertTrue(compiler.getParserContextState().getInputs().containsKey("p")); } public void testAssignmentRegression() { ExpressionCompiler compiler = new ExpressionCompiler("total = total + $cheese.price"); compiler.compile(); } public void testTypeRegression() { ExpressionCompiler compiler = new ExpressionCompiler("total = 0"); ParserContext ctx = new ParserContext(); ctx.setStrictTypeEnforcement(true); compiler.compile(ctx); assertEquals(Integer.class, compiler.getParserContextState().getVarOrInputType("total")); } public void testDateComparison() { map.put("dt1", new Date(currentTimeMillis() - 100000)); map.put("dt2", new Date(currentTimeMillis())); assertTrue((Boolean) parseDirect("dt1 < dt2")); } public void testDynamicDeop() { Serializable s = MVEL.compileExpression("name"); assertEquals("dog", MVEL.executeExpression(s, foo)); assertEquals("dog", MVEL.executeExpression(s, foo.getBar())); } public void testVirtProperty() { Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("test", "foo"); Map<String, Object> vars = new HashMap<String, Object>(); vars.put("mp", testMap); assertEquals("bar", MVEL.executeExpression(compileExpression("mp.test = 'bar'; mp.test"), vars)); } public void testMapPropertyCreateCondensed() { assertEquals("foo", parseDirect("map = new java.util.HashMap(); map['test'] = 'foo'; map['test'];")); } public void testClassLiteral() { assertEquals(String.class, parseDirect("java.lang.String")); } public void testDeepMethod() { assertEquals(false, parseDirect("foo.bar.testList.add(new String()); foo.bar.testList == empty")); } public void testArrayAccessorAssign() { assertEquals("foo", parseDirect("a = {'f00', 'bar'}; a[0] = 'foo'; a[0]")); } public void testListAccessorAssign() { assertEquals("bar", parseDirect("a = new java.util.ArrayList(); a.add('foo'); a.add('BAR'); a[1] = 'bar'; a[1]")); } public void testBracketInString() { parseDirect("System.out.println('1)your guess was:');"); } public void testNesting() { assertEquals("foo", parseDirect("new String(new String(new String(\"foo\")));")); } public void testDeepPropertyAdd() { assertEquals(10, parseDirect("foo.countTest+ 10")); } public void testDeepAssignmentIncrement() { assertEquals(true, parseDirect("foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }")); } public void testDeepAssignmentWithBlock() { assertEquals(true, parseDirect("with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; } else { foo.countTest = 0; return false; }")); } public Object parseDirect(String ex) { return compiledExecute(ex); } public Object compiledExecute(String ex) { OptimizerFactory.setDefaultOptimizer("ASM"); ExpressionCompiler compiler = new ExpressionCompiler(ex); Serializable compiled = compiler.compile(); // System.out.println(DebugTools.decompile(compiled)); Object first = executeExpression(compiled, base, map); Object second = executeExpression(compiled, base, map); Object third = MVEL.eval(ex, base, map); if (first != null && !first.getClass().isArray()) { assertEquals(first, second); if (!first.equals(second)) { throw new AssertionError("Different result from test 1 and 2 (Compiled Re-Run / JIT) [first: " + String.valueOf(first) + "; second: " + String.valueOf(second) + "]"); } if (!first.equals(third)) { throw new AssertionError("Different result from test 1 and 3 (Compiled to Interpreted) [first: " + String.valueOf(first) + " (" + (first != null ? first.getClass().getName() : "null") + "); third: " + String.valueOf(third) + " (" + (second != null ? first.getClass().getName() : "null") + ")]"); } } OptimizerFactory.setDefaultOptimizer("reflective"); compiled = compileExpression(ex); Object fourth = executeExpression(compiled, base, map); Object fifth = executeExpression(compiled, base, map); if (fourth != null && !fourth.getClass().isArray()) { assertEquals(fourth, fifth); if (!fourth.equals(fifth)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + String.valueOf(first) + "; second: " + String.valueOf(second) + "]"); } } return second; } public Object compiledExecute(String ex, Object base, Map map) { Serializable compiled = compileExpression(ex); Object first = executeExpression(compiled, base, map); Object second = executeExpression(compiled, base, map); if (first != null && !first.getClass().isArray()) assertSame(first, second); return second; } @SuppressWarnings({"unchecked"}) public void testDifferentImplSameCompile() { Serializable compiled = compileExpression("a.funMap.hello"); Map testMap = new HashMap(); for (int i = 0; i < 100; i++) { Base b = new Base(); b.funMap.put("hello", "dog"); testMap.put("a", b); assertEquals("dog", executeExpression(compiled, testMap)); b = new Base(); b.funMap.put("hello", "cat"); testMap.put("a", b); assertEquals("cat", executeExpression(compiled, testMap)); } } @SuppressWarnings({"unchecked"}) public void testInterfaceMethodCallWithSpace() { Serializable compiled = compileExpression("drools.retract (cheese)"); Map map = new HashMap(); DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper(); map.put("drools", helper); Cheese cheese = new Cheese("stilton", 15); map.put("cheese", cheese); executeExpression(compiled, map); assertSame(cheese, helper.retracted.get(0)); } @SuppressWarnings({"unchecked"}) public void testInterfaceMethodCallWithMacro() { Map macros = new HashMap(1); macros.put("retract", new Macro() { public String doMacro() { return "drools.retract"; } }); Serializable compiled = compileExpression(parseMacros("retract(cheese)", macros)); Map map = new HashMap(); DefaultKnowledgeHelper helper = new DefaultKnowledgeHelper(); map.put("drools", helper); Cheese cheese = new Cheese("stilton", 15); map.put("cheese", cheese); executeExpression(compiled, map); assertSame(cheese, helper.retracted.get(0)); } @SuppressWarnings({"UnnecessaryBoxing"}) public void testToList() { String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )"; List list = (List) parseDirect(text); assertSame("dog", list.get(0)); assertEquals("hello", list.get(1)); assertEquals(new Integer(42), list.get(2)); Map map = (Map) list.get(3); assertEquals("value1", map.get("key1")); List nestedList = (List) map.get("cat"); assertEquals(14, nestedList.get(0)); assertEquals("car", nestedList.get(1)); assertEquals(42, nestedList.get(2)); nestedList = (List) list.get(4); assertEquals(42, nestedList.get(0)); map = (Map) nestedList.get(1); assertEquals("value1", map.get("cat")); } @SuppressWarnings({"UnnecessaryBoxing"}) public void testToListStrictMode() { String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )"; ParserContext ctx = new ParserContext(); ctx.addInput("misc", MiscTestClass.class); ctx.addInput("foo", Foo.class); ctx.addInput("c", String.class); ctx.setStrictTypeEnforcement(true); ExpressionCompiler compiler = new ExpressionCompiler(text); Serializable expr = compiler.compile(ctx); List list = (List) MVEL.executeExpression(expr, map); assertSame("dog", list.get(0)); assertEquals("hello", list.get(1)); assertEquals(new Integer(42), list.get(2)); Map map = (Map) list.get(3); assertEquals("value1", map.get("key1")); List nestedList = (List) map.get("cat"); assertEquals(14, nestedList.get(0)); assertEquals("car", nestedList.get(1)); assertEquals(42, nestedList.get(2)); nestedList = (List) list.get(4); assertEquals(42, nestedList.get(0)); map = (Map) nestedList.get(1); assertEquals("value1", map.get("cat")); } public void testToList2() { for (int i = 0; i < 10; i++) { testToList(); } } public static class MiscTestClass { int exec = 0; @SuppressWarnings({"unchecked", "UnnecessaryBoxing"}) public List toList(Object object1, String string, int integer, Map map, List list) { exec++; List l = new ArrayList(); l.add(object1); l.add(string); l.add(new Integer(integer)); l.add(map); l.add(list); return l; } public int getExec() { return exec; } } /** * Community provided test cases */ @SuppressWarnings({"unchecked"}) public void testCalculateAge() { // System.out.println("Calculating the Age"); Calendar c1 = Calendar.getInstance(); c1.set(1999, 0, 10); // 1999 jan 20 Map objectMap = new HashMap(1); Map propertyMap = new HashMap(1); propertyMap.put("GEBDAT", c1.getTime()); objectMap.put("EV_VI_ANT1", propertyMap); assertEquals("N", compiledExecute("new org.mvel.tests.main.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'" , null, objectMap)); } /** * Provided by: Alex Roytman */ public void testMethodResolutionWithNullParameter() { Context ctx = new Context(); ctx.setBean(new Bean()); Map<String, Object> vars = new HashMap<String, Object>(); System.out.println("bean.today: " + MVEL.eval("bean.today", ctx, vars)); System.out.println("formatDate(bean.today): " + MVEL.eval("formatDate(bean.today)", ctx, vars)); //calling method with string param with null parameter works System.out.println("formatString(bean.nullString): " + MVEL.eval("formatString(bean.nullString)", ctx, vars)); System.out.println("bean.myDate = bean.nullDate: " + MVEL.eval("bean.myDate = bean.nullDate; return bean.nullDate;", ctx, vars)); //calling method with Date param with null parameter fails System.out.println("formatDate(bean.myDate): " + MVEL.eval("formatDate(bean.myDate)", ctx, vars)); //same here System.out.println(MVEL.eval("formatDate(bean.nullDate)", ctx, vars)); } public static class Bean { private Date myDate = new Date(); public Date getToday() { return new Date(); } public Date getNullDate() { return null; } public String getNullString() { return null; } public Date getMyDate() { return myDate; } public void setMyDate(Date myDate) { this.myDate = myDate; } } public static class Context { private final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); private Bean bean; public Bean getBean() { return bean; } public void setBean(Bean bean) { this.bean = bean; } public String formatDate(Date date) { return date == null ? null : dateFormat.format(date); } public String formatString(String str) { return str == null ? "<NULL>" : str; } } /** * Provided by: Phillipe Ombredanne */ public void testCompileParserContextShouldNotLoopIndefinitelyOnValidJavaExpression() { String expr = " System.out.println( message );\n" + "m.setMessage( \"Goodbye cruel world\" );\n" + "System.out.println(m.getStatus());\n" + "m.setStatus( Message.GOODBYE );\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Message", Message.class); context.addInput("System", void.class); context.addInput("message", Object.class); context.addInput("m", Object.class); compiler.compile(context); } public void testStaticNested() { assertEquals(1, MVEL.eval("org.mvel.tests.main.CoreConfidenceTests$Message.GOODBYE", new HashMap())); } public void testStaticNestedWithImport() { String expr = "Message.GOODBYE;\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Message", Message.class); Serializable compiledExpression = compiler.compile(context); assertEquals(1, MVEL.executeExpression(compiledExpression)); } /** * Provided by: Aadi Deshpande */ public void testPropertyVerfierShoudldNotLoopIndefinately() { String expr = "\t\tmodel.latestHeadlines = $list;\n" + "model.latestHeadlines.add( 0, (model.latestHeadlines[2]) );"; ExpressionCompiler compiler = new ExpressionCompiler(expr); compiler.setVerifying(true); ParserContext pCtx = new ParserContext(); pCtx.addInput("$list", List.class); pCtx.addInput("model", Model.class); compiler.compile(pCtx); } public void testCompileWithNewInsideMethodCall() { String expr = " p.name = \"goober\";\n" + " System.out.println(p.name);\n" + " drools.insert(new Address(\"Latona\"));\n"; ExpressionCompiler compiler = new ExpressionCompiler(expr); ParserContext context = new ParserContext(); context.setStrictTypeEnforcement(false); context.addImport("Person", Person.class); context.addImport("Address", Address.class); context.addInput("p", Person.class); context.addInput("drools", Drools.class); compiler.compile(context); } public static class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class Address { private String street; public Address(String street) { super(); this.street = street; } } public static class Drools { public void insert(Object obj) { } } public static class Model { private List latestHeadlines; public List getLatestHeadlines() { return latestHeadlines; } public void setLatestHeadlines(List latestHeadlines) { this.latestHeadlines = latestHeadlines; } } public static class Message { public static final int HELLO = 0; public static final int GOODBYE = 1; private String message; private int status; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } } }
package edu.ufl.cise.cnt5106c.messages; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.ProtocolException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; /** * * @author Giacomo Benincasa (giacomo@cise.ufl.edu) */ public class Handshake implements Serializable { private final static String _protocolId = "P2PFILESHARINGPROJ"; private final byte[] _zeroBits = new byte[10]; private final byte[] _peerId = new byte[4]; private Handshake() { } public Handshake (int peerId) { this (ByteBuffer.allocate(4).putInt(peerId).array()); } private Handshake (byte[] peerId) { if (peerId.length > 4) { throw new ArrayIndexOutOfBoundsException("peerId max length is 4, while " + Arrays.toString (peerId) + "'s length is "+ peerId.length); } int i = 0; for (byte b : peerId) { _peerId[i++] = b; } } private void writeObject(ObjectOutputStream oos) throws IOException { byte[] peerId = _protocolId.getBytes(Charset.forName("US-ASCII")); if (peerId.length > _protocolId.length()) { throw new IOException("protocol id length is " + peerId.length + " instead of " + _protocolId.length()); } oos.write(peerId, 0, peerId.length); oos.write(_zeroBits, 0, _zeroBits.length); oos.write(_peerId, 0, _peerId.length); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { // Read and check protocol Id byte[] protocolId = new byte[_protocolId.length()]; if (ois.read(protocolId, 0, _protocolId.length()) < _protocolId.length()) { throw new ProtocolException ("protocol id is " + Arrays.toString (protocolId) + " instead of " + _protocolId); } if (!_protocolId.equals (new String(protocolId, "US-ASCII"))) { throw new ProtocolException ("protocol id is " + Arrays.toString (protocolId) + " instead of " + _protocolId); } // Read and check zero bits if (ois.read(_zeroBits, 0, _zeroBits.length) < _zeroBits.length) { throw new ProtocolException ("zero bit bytes read are less than " + _zeroBits.length); } // Read and check peer id if (ois.read(_zeroBits, 0, _peerId.length) < _peerId.length) { throw new ProtocolException ("peer id bytes read are less than " + _peerId.length); } } public static Handshake readMessage (InputStream in) throws Exception { Handshake handshake = new Handshake(); handshake.readObject(new ObjectInputStream (in)); return handshake; } public int getPeerId() { return ByteBuffer.wrap(_peerId).getInt(); } }
package org.jasome.executive; import org.jasome.metrics.calculators.*; import org.jasome.input.Processor; class ProcessorFactory { static Processor getProcessor() { Processor processor = new Processor(); processor.registerTypeCalculator(new RawTotalLinesOfCodeCalculator()); processor.registerTypeCalculator(new NumberOfFieldsCalculator()); processor.registerProjectCalculator(new TotalLinesOfCodeCalculator.ProjectCalculator()); processor.registerPackageCalculator(new TotalLinesOfCodeCalculator.PackageCalculator()); processor.registerTypeCalculator(new TotalLinesOfCodeCalculator.TypeCalculator()); processor.registerMethodCalculator(new TotalLinesOfCodeCalculator.MethodCalculator()); processor.registerMethodCalculator(new CyclomaticComplexityCalculator()); processor.registerTypeCalculator(new WeightedMethodsCalculator()); processor.registerMethodCalculator(new NumberOfParametersCalculator()); processor.registerPackageCalculator(new NumberOfClassesCalculator()); processor.registerTypeCalculator(new SpecializationIndexCalculator()); processor.registerPackageCalculator(new RobertMartinCouplingCalculator()); processor.registerMethodCalculator(new NestedBlockDepthCalculator()); processor.registerTypeCalculator(new LackOfCohesionMethodsCalculator()); processor.registerTypeCalculator(new ClassInheritanceCalculator()); processor.registerTypeCalculator(new MethodAndAttributeInheritanceCalculator()); processor.registerMethodCalculator(new FanCalculator()); processor.registerTypeCalculator(new LinkCalculator()); processor.registerMethodCalculator(new McclureCalculator()); processor.registerTypeCalculator(new TypeAggregatorCalculator()); processor.registerPackageCalculator(new PackageAggregatorCalculator()); return processor; } }
package org.owasp.esapi.reference; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.owasp.esapi.*; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.filters.SecurityWrapperRequest; import org.owasp.esapi.http.MockHttpServletRequest; import org.owasp.esapi.http.MockHttpServletResponse; import org.owasp.esapi.reference.validation.HTMLValidationRule; import org.owasp.esapi.reference.validation.StringValidationRule; import javax.servlet.http.Cookie; /** * The Class ValidatorTest. * * @author Mike Fauzy (mike.fauzy@aspectsecurity.com) * @author Jeff Williams (jeff.williams@aspectsecurity.com) */ public class ValidatorTest extends TestCase { private static final String PREFERRED_ENCODING = "UTF-8"; public static Test suite() { return new TestSuite(ValidatorTest.class); } /** * Instantiates a new HTTP utilities test. * * @param testName the test name */ public ValidatorTest(String testName) { super(testName); } /** * {@inheritDoc} * * @throws Exception */ protected void setUp() throws Exception { // none } /** * {@inheritDoc} * * @throws Exception */ protected void tearDown() throws Exception { // none } public void testAddRule() { Validator validator = ESAPI.validator(); ValidationRule rule = new StringValidationRule("ridiculous"); validator.addRule(rule); assertEquals(rule, validator.getRule("ridiculous")); } public void testAssertValidFileUpload() { // assertValidFileUpload(String, String, String, byte[], int, boolean, ValidationErrorList) } public void testGetPrintable1() { // getValidPrintable(String, char[], int, boolean, ValidationErrorList) } public void testGetPrintable2() { // getValidPrintable(String, String, int, boolean, ValidationErrorList) } public void testGetRule() { Validator validator = ESAPI.validator(); ValidationRule rule = new StringValidationRule("rule"); validator.addRule(rule); assertEquals(rule, validator.getRule("rule")); assertFalse(rule == validator.getRule("ridiculous")); } public void testGetValidCreditCard() { System.out.println("getValidCreditCard"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); assertTrue(instance.isValidCreditCard("cctest1", "1234 9876 0000 0008", false)); assertTrue(instance.isValidCreditCard("cctest2", "1234987600000008", false)); assertFalse(instance.isValidCreditCard("cctest3", "12349876000000081", false)); assertFalse(instance.isValidCreditCard("cctest4", "4417 1234 5678 9112", false)); instance.getValidCreditCard("cctest5", "1234 9876 0000 0008", false, errors); assertEquals(0, errors.size()); instance.getValidCreditCard("cctest6", "1234987600000008", false, errors); assertEquals(0, errors.size()); instance.getValidCreditCard("cctest7", "12349876000000081", false, errors); assertEquals(1, errors.size()); instance.getValidCreditCard("cctest8", "4417 1234 5678 9112", false, errors); assertEquals(2, errors.size()); } public void testGetValidDate() throws Exception { System.out.println("getValidDate"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); assertTrue(instance.getValidDate("datetest1", "June 23, 1967", DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US), false) != null); instance.getValidDate("datetest2", "freakshow", DateFormat.getDateInstance(), false, errors); assertEquals(1, errors.size()); // TODO: This test case fails due to an apparent bug in SimpleDateFormat instance.getValidDate("test", "June 32, 2008", DateFormat.getDateInstance(), false, errors); // assertEquals( 2, errors.size() ); } public void testGetValidDirectoryPath() throws Exception { System.out.println("getValidDirectoryPath"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // find a directory that exists File parent = new File("/"); String path = ESAPI.securityConfiguration().getResourceFile("ESAPI.properties").getParentFile().getCanonicalPath(); instance.getValidDirectoryPath("dirtest1", path, parent, true, errors); assertEquals(0, errors.size()); instance.getValidDirectoryPath("dirtest2", null, parent, false, errors); assertEquals(1, errors.size()); instance.getValidDirectoryPath("dirtest3", "ridicul%00ous", parent, false, errors); assertEquals(2, errors.size()); } public void testGetValidDouble() { System.out.println("getValidDouble"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); instance.getValidDouble("dtest1", "1.0", 0, 20, true, errors); assertEquals(0, errors.size()); instance.getValidDouble("dtest2", null, 0, 20, true, errors); assertEquals(0, errors.size()); instance.getValidDouble("dtest3", null, 0, 20, false, errors); assertEquals(1, errors.size()); instance.getValidDouble("dtest4", "ridiculous", 0, 20, true, errors); assertEquals(2, errors.size()); instance.getValidDouble("dtest5", "" + (Double.MAX_VALUE), 0, 20, true, errors); assertEquals(3, errors.size()); instance.getValidDouble("dtest6", "" + (Double.MAX_VALUE + .00001), 0, 20, true, errors); assertEquals(4, errors.size()); } public void testGetValidFileContent() { System.out.println("getValidFileContent"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); byte[] bytes = null; try { bytes = "12345".getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { fail(PREFERRED_ENCODING + " not a supported encoding?!?!!"); } instance.getValidFileContent("test", bytes, 5, true, errors); assertEquals(0, errors.size()); instance.getValidFileContent("test", bytes, 4, true, errors); assertEquals(1, errors.size()); } public void testGetValidFileName() throws Exception { System.out.println("getValidFileName"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); String testName = "aspe%20ct.jar"; assertEquals("Percent encoding is not changed", testName, instance.getValidFileName("test", testName, ESAPI.securityConfiguration().getAllowedFileExtensions(), false, errors)); } public void testGetValidInput() { System.out.println("getValidInput"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // instance.getValidInput(String, String, String, int, boolean, ValidationErrorList) } public void testGetValidInteger() { System.out.println("getValidInteger"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // instance.getValidInteger(String, String, int, int, boolean, ValidationErrorList) } public void testGetValidListItem() { System.out.println("getValidListItem"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // instance.getValidListItem(String, String, List, ValidationErrorList) } public void testGetValidNumber() { System.out.println("getValidNumber"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // instance.getValidNumber(String, String, long, long, boolean, ValidationErrorList) } public void testGetValidRedirectLocation() { System.out.println("getValidRedirectLocation"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // instance.getValidRedirectLocation(String, String, boolean, ValidationErrorList) } public void testGetValidSafeHTML() throws Exception { System.out.println("getValidSafeHTML"); Validator instance = ESAPI.validator(); ValidationErrorList errors = new ValidationErrorList(); // new school test case setup HTMLValidationRule rule = new HTMLValidationRule("test"); ESAPI.validator().addRule(rule); assertEquals("Test.", ESAPI.validator().getRule("test").getValid("test", "Test. <script>alert(document.cookie)</script>")); String test1 = "<b>Jeff</b>"; String result1 = instance.getValidSafeHTML("test", test1, 100, false, errors); assertEquals(test1, result1); String test2 = "<a href=\"http: String result2 = instance.getValidSafeHTML("test", test2, 100, false, errors); assertEquals(test2, result2); String test3 = "Test. <script>alert(document.cookie)</script>"; assertEquals("Test.", rule.getSafe("test", test3)); assertEquals("Test. &lt;<div>load=alert()</div>", rule.getSafe("test", "Test. <<div on<script></script>load=alert()")); assertEquals("Test. <div>b</div>", rule.getSafe("test", "Test. <div style={xss:expression(xss)}>b</div>")); assertEquals("Test.", rule.getSafe("test", "Test. <s%00cript>alert(document.cookie)</script>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); assertEquals("Test. alert(document.cookie)", rule.getSafe("test", "Test. <s\tcript>alert(document.cookie)</script>")); // TODO: ENHANCE waiting for a way to validate text headed for an attribute for scripts // This would be nice to catch, but just looks like text to AntiSamy // assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" ")); // String result4 = instance.getValidSafeHTML("test", test4); // assertEquals("", result4); } public void testIsInvalidFilename() { System.out.println("testIsInvalidFilename"); Validator instance = ESAPI.validator(); char invalidChars[] = "/\\:*?\"<>|".toCharArray(); for (int i = 0; i < invalidChars.length; i++) { assertFalse(invalidChars[i] + " is an invalid character for a filename", instance.isValidFileName("test", "as" + invalidChars[i] + "pect.jar", false)); } assertFalse("Files must have an extension", instance.isValidFileName("test", "", false)); assertFalse("Files must have a valid extension", instance.isValidFileName("test.invalidExtension", "", false)); assertFalse("Filennames cannot be the empty string", instance.isValidFileName("test", "", false)); } public void testIsValidDate() { System.out.println("isValidDate"); Validator instance = ESAPI.validator(); DateFormat format = SimpleDateFormat.getDateInstance(); assertTrue(instance.isValidDate("datetest1", "September 11, 2001", format, true)); assertFalse(instance.isValidDate("datetest2", null, format, false)); assertFalse(instance.isValidDate("datetest3", "", format, false)); } public void testIsValidDirectoryPath() throws IOException { System.out.println("isValidDirectoryPath"); // get an encoder with a special list of codecs and make a validator out of it List list = new ArrayList(); list.add("HTMLEntityCodec"); Encoder encoder = new DefaultEncoder(list); Validator instance = new DefaultValidator(encoder); boolean isWindows = (System.getProperty("os.name").indexOf("Windows") != -1) ? true : false; File parent = new File("/"); if (isWindows) { String sysRoot = new File(System.getenv("SystemRoot")).getCanonicalPath(); // Windows paths that don't exist and thus should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\ridiculous", parent, false)); assertFalse(instance.isValidDirectoryPath("test", "c:\\jeff", parent, false)); assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", parent, false)); // Windows paths assertTrue(instance.isValidDirectoryPath("test", "C:\\", parent, false)); // Windows root directory assertTrue(instance.isValidDirectoryPath("test", sysRoot, parent, false)); // Windows always exist directory assertFalse(instance.isValidDirectoryPath("test", sysRoot + "\\System32\\cmd.exe", parent, false)); // Windows command shell // Unix specific paths should not pass assertFalse(instance.isValidDirectoryPath("test", "/tmp", parent, false)); // Unix Temporary directory assertFalse(instance.isValidDirectoryPath("test", "/bin/sh", parent, false)); // Unix Standard shell assertFalse(instance.isValidDirectoryPath("test", "/etc/config", parent, false)); // Unix specific paths that should not exist or work assertFalse(instance.isValidDirectoryPath("test", "/etc/ridiculous", parent, false)); assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", parent, false)); } else { // Windows paths should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\ridiculous", parent, false)); assertFalse(instance.isValidDirectoryPath("test", "c:\\temp\\..\\etc", parent, false)); // Standard Windows locations should fail assertFalse(instance.isValidDirectoryPath("test", "c:\\", parent, false)); // Windows root directory assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\temp", parent, false)); // Windows temporary directory assertFalse(instance.isValidDirectoryPath("test", "c:\\Windows\\System32\\cmd.exe", parent, false)); // Windows command shell // Unix specific paths should pass assertTrue(instance.isValidDirectoryPath("test", "/", parent, false)); // Root directory assertTrue(instance.isValidDirectoryPath("test", "/bin", parent, false)); // Always exist directory // Unix specific paths that should not exist or work assertFalse(instance.isValidDirectoryPath("test", "/bin/sh", parent, false)); // Standard shell, not dir assertFalse(instance.isValidDirectoryPath("test", "/etc/ridiculous", parent, false)); assertFalse(instance.isValidDirectoryPath("test", "/tmp/../etc", parent, false)); } } public void TestIsValidDirectoryPath() { // isValidDirectoryPath(String, String, boolean) } public void testIsValidDouble() { // isValidDouble(String, String, double, double, boolean) } public void testIsValidFileContent() { System.out.println("isValidFileContent"); byte[] content = null; try { content = "This is some file content".getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!"); } Validator instance = ESAPI.validator(); assertTrue(instance.isValidFileContent("test", content, 100, false)); } public void testIsValidFileName() { System.out.println("isValidFileName"); Validator instance = ESAPI.validator(); assertTrue("Simple valid filename with a valid extension", instance.isValidFileName("test", "aspect.jar", false)); assertTrue("All valid filename characters are accepted", instance.isValidFileName("test", "!@#$%^&{}[]()_+-=,.~'` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.jar", false)); assertTrue("Legal filenames that decode to legal filenames are accepted", instance.isValidFileName("test", "aspe%20ct.jar", false)); } public void testIsValidFileUpload() throws IOException { System.out.println("isValidFileUpload"); String filepath = new File(System.getProperty("user.dir")).getCanonicalPath(); String filename = "aspect.jar"; File parent = new File("/").getCanonicalFile(); byte[] content = null; try { content = "This is some file content".getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!"); } Validator instance = ESAPI.validator(); assertTrue(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false)); filepath = "/ridiculous"; filename = "aspect.jar"; try { content = "This is some file content".getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!"); } assertFalse(instance.isValidFileUpload("test", filepath, filename, parent, content, 100, false)); } public void testIsValidHTTPRequestParameterSet() { // isValidHTTPRequestParameterSet(String, Set, Set) } public void testisValidInput() { System.out.println("isValidInput"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidInput("test", "jeff.williams@aspectsecurity.com", "Email", 100, false)); assertFalse(instance.isValidInput("test", "jeff.williams@@aspectsecurity.com", "Email", 100, false)); assertFalse(instance.isValidInput("test", "jeff.williams@aspectsecurity", "Email", 100, false)); assertTrue(instance.isValidInput("test", "jeff.wil'liams@aspectsecurity.com", "Email", 100, false)); assertTrue(instance.isValidInput("test", "jeff.wil''liams@aspectsecurity.com", "Email", 100, false)); assertTrue(instance.isValidInput("test", "123.168.100.234", "IPAddress", 100, false)); assertTrue(instance.isValidInput("test", "192.168.1.234", "IPAddress", 100, false)); assertFalse(instance.isValidInput("test", "..168.1.234", "IPAddress", 100, false)); assertFalse(instance.isValidInput("test", "10.x.1.234", "IPAddress", 100, false)); assertTrue(instance.isValidInput("test", "http: assertFalse(instance.isValidInput("test", "http: assertFalse(instance.isValidInput("test", "http: assertTrue(instance.isValidInput("test", "078-05-1120", "SSN", 100, false)); assertTrue(instance.isValidInput("test", "078 05 1120", "SSN", 100, false)); assertTrue(instance.isValidInput("test", "078051120", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "987-65-4320", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "000-00-0000", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "(555) 555-5555", "SSN", 100, false)); assertFalse(instance.isValidInput("test", "test", "SSN", 100, false)); assertTrue(instance.isValidInput("test", "jeffWILLIAMS123", "HTTPParameterValue", 100, false)); assertTrue(instance.isValidInput("test", "jeff .-/+=@_ WILLIAMS", "HTTPParameterValue", 100, false)); // Removed per Issue 116 - The '*' character is valid as a parameter character // assertFalse(instance.isValidInput("test", "jeff*WILLIAMS", "HTTPParameterValue", 100, false)); assertFalse(instance.isValidInput("test", "jeff^WILLIAMS", "HTTPParameterValue", 100, false)); assertFalse(instance.isValidInput("test", "jeff\\WILLIAMS", "HTTPParameterValue", 100, false)); assertTrue(instance.isValidInput("test", null, "Email", 100, true)); assertFalse(instance.isValidInput("test", null, "Email", 100, false)); } public void testIsValidInteger() { System.out.println("isValidInteger"); Validator instance = ESAPI.validator(); //testing negative range assertFalse(instance.isValidInteger("test", "-4", 1, 10, false)); assertTrue(instance.isValidInteger("test", "-4", -10, 10, false)); //testing null value assertTrue(instance.isValidInteger("test", null, -10, 10, true)); assertFalse(instance.isValidInteger("test", null, -10, 10, false)); //testing empty string assertTrue(instance.isValidInteger("test", "", -10, 10, true)); assertFalse(instance.isValidInteger("test", "", -10, 10, false)); //testing improper range assertFalse(instance.isValidInteger("test", "50", 10, -10, false)); //testing non-integers assertFalse(instance.isValidInteger("test", "4.3214", -10, 10, true)); assertFalse(instance.isValidInteger("test", "-1.65", -10, 10, true)); //other testing assertTrue(instance.isValidInteger("test", "4", 1, 10, false)); assertTrue(instance.isValidInteger("test", "400", 1, 10000, false)); assertTrue(instance.isValidInteger("test", "400000000", 1, 400000000, false)); assertFalse(instance.isValidInteger("test", "4000000000000", 1, 10000, false)); assertFalse(instance.isValidInteger("test", "alsdkf", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "--10", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "14.1414234x", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "Infinity", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "-Infinity", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "-NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "+NaN", 10, 10000, false)); assertFalse(instance.isValidInteger("test", "1e-6", -999999999, 999999999, false)); assertFalse(instance.isValidInteger("test", "-1e-6", -999999999, 999999999, false)); } public void testIsValidListItem() { System.out.println("isValidListItem"); Validator instance = ESAPI.validator(); List list = new ArrayList(); list.add("one"); list.add("two"); assertTrue(instance.isValidListItem("test", "one", list)); assertFalse(instance.isValidListItem("test", "three", list)); } public void testIsValidNumber() { System.out.println("isValidNumber"); Validator instance = ESAPI.validator(); //testing negative range assertFalse(instance.isValidNumber("test", "-4", 1, 10, false)); assertTrue(instance.isValidNumber("test", "-4", -10, 10, false)); //testing null value assertTrue(instance.isValidNumber("test", null, -10, 10, true)); assertFalse(instance.isValidNumber("test", null, -10, 10, false)); //testing empty string assertTrue(instance.isValidNumber("test", "", -10, 10, true)); assertFalse(instance.isValidNumber("test", "", -10, 10, false)); //testing improper range assertFalse(instance.isValidNumber("test", "5", 10, -10, false)); //testing non-integers assertTrue(instance.isValidNumber("test", "4.3214", -10, 10, true)); assertTrue(instance.isValidNumber("test", "-1.65", -10, 10, true)); //other testing assertTrue(instance.isValidNumber("test", "4", 1, 10, false)); assertTrue(instance.isValidNumber("test", "400", 1, 10000, false)); assertTrue(instance.isValidNumber("test", "400000000", 1, 400000000, false)); assertFalse(instance.isValidNumber("test", "4000000000000", 1, 10000, false)); assertFalse(instance.isValidNumber("test", "alsdkf", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "--10", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "14.1414234x", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "Infinity", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "-Infinity", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "NaN", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "-NaN", 10, 10000, false)); assertFalse(instance.isValidNumber("test", "+NaN", 10, 10000, false)); assertTrue(instance.isValidNumber("test", "1e-6", -999999999, 999999999, false)); assertTrue(instance.isValidNumber("test", "-1e-6", -999999999, 999999999, false)); } public void testIsValidParameterSet() { System.out.println("isValidParameterSet"); Set requiredNames = new HashSet(); requiredNames.add("p1"); requiredNames.add("p2"); requiredNames.add("p3"); Set optionalNames = new HashSet(); optionalNames.add("p4"); optionalNames.add("p5"); optionalNames.add("p6"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.addParameter("p1", "value"); request.addParameter("p2", "value"); request.addParameter("p3", "value"); ESAPI.httpUtilities().setCurrentHTTP(request, response); Validator instance = ESAPI.validator(); assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames)); request.addParameter("p4", "value"); request.addParameter("p5", "value"); request.addParameter("p6", "value"); assertTrue(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames)); request.removeParameter("p1"); assertFalse(instance.isValidHTTPRequestParameterSet("HTTPParameters", request, requiredNames, optionalNames)); } public void testIsValidPrintable() { System.out.println("isValidPrintable"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidPrintable("name", "abcDEF", 100, false)); assertTrue(instance.isValidPrintable("name", "!@#R()*$;><()", 100, false)); char[] chars = {0x60, (char) 0xFF, 0x10, 0x25}; assertFalse(instance.isValidPrintable("name", chars, 100, false)); assertFalse(instance.isValidPrintable("name", "%08", 100, false)); } public void testIsValidRedirectLocation() { // isValidRedirectLocation(String, String, boolean) } public void testIsValidSafeHTML() { System.out.println("isValidSafeHTML"); Validator instance = ESAPI.validator(); assertTrue(instance.isValidSafeHTML("test", "<b>Jeff</b>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "<a href=\"http: assertTrue(instance.isValidSafeHTML("test", "Test. <script>alert(document.cookie)</script>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "Test. <div style={xss:expression(xss)}>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "Test. <s%00cript>alert(document.cookie)</script>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "Test. <s\tcript>alert(document.cookie)</script>", 100, false)); assertTrue(instance.isValidSafeHTML("test", "Test. <s\r\n\0cript>alert(document.cookie)</script>", 100, false)); // TODO: waiting for a way to validate text headed for an attribute for scripts // This would be nice to catch, but just looks like text to AntiSamy // assertFalse(instance.isValidSafeHTML("test", "\" onload=\"alert(document.cookie)\" ")); } public void testSafeReadLine() { System.out.println("safeReadLine"); byte[] bytes = null; try { bytes = "testString".getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e1) { fail(PREFERRED_ENCODING + " not a supported encoding?!?!!!"); } ByteArrayInputStream s = new ByteArrayInputStream(bytes); Validator instance = ESAPI.validator(); try { instance.safeReadLine(s, -1); fail(); } catch (ValidationException e) { // Expected } s.reset(); try { instance.safeReadLine(s, 4); fail(); } catch (ValidationException e) { // Expected } s.reset(); try { String u = instance.safeReadLine(s, 20); assertEquals("testString", u); } catch (ValidationException e) { fail(); } // This sub-test attempts to validate that BufferedReader.readLine() and safeReadLine() are similar in operation // for the nominal case try { s.reset(); InputStreamReader isr = new InputStreamReader(s); BufferedReader br = new BufferedReader(isr); String u = br.readLine(); s.reset(); String v = instance.safeReadLine(s, 20); assertEquals(u, v); } catch (IOException e) { fail(); } catch (ValidationException e) { fail(); } } public void testIssue82_SafeString_Bad_Regex() { Validator instance = ESAPI.validator(); try { instance.getValidInput("address", "55 main st. pasadena ak", "SafeString", 512, false); } catch (ValidationException e) { fail(e.getLogMessage()); } } public void testGetParameterMap() { //testing Validator.HTTPParameterName and Validator.HTTPParameterValue MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); //an example of a parameter from displaytag, should pass request.addParameter("d-49653-p", "pass"); request.addParameter("<img ", "fail"); request.addParameter(generateStringOfLength(32), "pass"); request.addParameter(generateStringOfLength(33), "fail"); assertEquals(safeRequest.getParameterMap().size(), 2); assertNull(safeRequest.getParameterMap().get("<img")); assertNull(safeRequest.getParameterMap().get(generateStringOfLength(33))); } public void testGetParameterNames() { //testing Validator.HTTPParameterName MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); //an example of a parameter from displaytag, should pass request.addParameter("d-49653-p", "pass"); request.addParameter("<img ", "fail"); request.addParameter(generateStringOfLength(32), "pass"); request.addParameter(generateStringOfLength(33), "fail"); assertEquals(Collections.list(safeRequest.getParameterNames()).size(), 2); } public void testGetParameter() { //testing Validator.HTTPParameterValue MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); request.addParameter("p1", "Alice"); request.addParameter("p2", "bob@alice.com");//mail-address from a submit-form request.addParameter("p3", ESAPI.authenticator().generateStrongPassword()); request.addParameter("p4", new String(EncoderConstants.CHAR_PASSWORD_SPECIALS)); //TODO - I think this should fair request.addParameter("p5", "?"); //some special characters from european languages; request.addParameter("f1", "<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>"); request.addParameter("f2", "<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>"); request.addParameter("f3", "<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>"); for (int i = 1; i <= 4; i++) { assertTrue(safeRequest.getParameter("p" + i).equals(request.getParameter("p" + i))); } for (int i = 1; i <= 2; i++) { boolean testResult = false; try { testResult = safeRequest.getParameter("f" + i).equals(request.getParameter("f" + i)); } catch (NullPointerException npe) { //the test is this block SHOULD fail. a NPE is an acceptable failure state testResult = false; //redundant, just being descriptive here } assertFalse(testResult); } assertNull(safeRequest.getParameter("e1")); //This is revealing problems with Jeff's original SafeRequest //mishandling of the AllowNull parameter. I'm adding a new Google code //bug to track this. //assertNotNull(safeRequest.getParameter("e1", false)); } public void testGetCookies() { //testing Validator.HTTPCookieName and Validator.HTTPCookieValue MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); //should support a base64-encode value request.setCookie("p1", "34=VJhjv7jiDu7tsdLrQQ2KcUwpfWUM2_mBae6UA8ttk4wBHdxxQ-1IBxyCOn3LWE08SDhpnBcJ7N5Vze48F2t8a1R_hXt7PX1BvgTM0pn-T4JkqGTm_tlmV4RmU3GT-dgn"); request.setCookie("f1", "<A HREF=\"http://66.102.7.147/\">XSS</A>"); request.setCookie("load-balancing", "pass"); request.setCookie("'bypass", "fail"); Cookie[] cookies = safeRequest.getCookies(); assertEquals(cookies[0].getValue(), request.getCookies()[0].getValue()); assertEquals(cookies[1].getName(), request.getCookies()[2].getName()); assertTrue(cookies.length == 2); } public void testGetHeader() { //testing Validator.HTTPHeaderValue MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); request.addHeader("p1", "login"); request.addHeader("f1", "<A HREF=\"http://0x42.0x0000066.0x7.0x93/\">XSS</A>"); request.addHeader("p2", generateStringOfLength(150)); request.addHeader("f2", generateStringOfLength(151)); assertEquals(safeRequest.getHeader("p1"), request.getHeader("p1")); assertEquals(safeRequest.getHeader("p2"), request.getHeader("p2")); assertFalse(safeRequest.getHeader("f1").equals(request.getHeader("f1"))); assertFalse(safeRequest.getHeader("f2").equals(request.getHeader("f2"))); assertNull(safeRequest.getHeader("p3")); } public void testGetHeaderNames() { //testing Validator.HTTPHeaderName MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); request.addHeader("d-49653-p", "pass"); request.addHeader("<img ", "fail"); request.addHeader(generateStringOfLength(32), "pass"); request.addHeader(generateStringOfLength(33), "fail"); assertEquals(Collections.list(safeRequest.getHeaderNames()).size(), 2); } public void testGetQueryString() { //testing Validator.HTTPQueryString MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); request.setQueryString("mail=bob@alice.com&passwd=" + new String(EncoderConstants.CHAR_PASSWORD_SPECIALS));// TODO, fix this + "&special="); assertEquals(safeRequest.getQueryString(), request.getQueryString()); request.setQueryString("mail=<IMG SRC=\"jav\tascript:alert('XSS');\">"); assertFalse(safeRequest.getQueryString().equals(request.getQueryString())); request.setQueryString("mail=bob@alice.com-passwd=johny"); assertTrue(safeRequest.getQueryString().equals(request.getQueryString())); request.setQueryString("mail=bob@alice.com-passwd=johny&special"); //= is missing! assertFalse(safeRequest.getQueryString().equals(request.getQueryString())); } public void testGetRequestURI() { //testing Validator.HTTPURI MockHttpServletRequest request = new MockHttpServletRequest(); SecurityWrapperRequest safeRequest = new SecurityWrapperRequest(request); try { request.setRequestURI("/app/page.jsp"); } catch (UnsupportedEncodingException ignored) { } assertEquals(safeRequest.getRequestURI(), request.getRequestURI()); } private String generateStringOfLength(int length) { StringBuilder longString = new StringBuilder(); for (int i = 0; i < length; i++) { longString.append("a"); } return longString.toString(); } }
package eu.rekawek.coffeegb.cpu; import eu.rekawek.coffeegb.AddressSpace; public class InterruptManager implements AddressSpace { public enum InterruptType { VBlank(0x0040), LCDC(0x0048), Timer(0x0050), Serial(0x0058), P10_13(0x0060); private final int handler; InterruptType(int handler) { this.handler = handler; } public int getHandler() { return handler; } } private final boolean gbc; private boolean ime; private int interruptFlag = 0xe1; private int interruptEnabled; private int pendingEnableInterrupts = -1; private int pendingDisableInterrupts = -1; public InterruptManager(boolean gbc) { this.gbc = gbc; } public void enableInterrupts(boolean withDelay) { pendingDisableInterrupts = -1; if (withDelay) { if (pendingEnableInterrupts == -1) { pendingEnableInterrupts = 1; } } else { pendingEnableInterrupts = -1; ime = true; } } public void disableInterrupts(boolean withDelay) { pendingEnableInterrupts = -1; if (withDelay && gbc) { if (pendingDisableInterrupts == -1) { pendingDisableInterrupts = 1; } } else { pendingDisableInterrupts = -1; ime = false; } } public void requestInterrupt(InterruptType type) { interruptFlag = interruptFlag | (1 << type.ordinal()); } public void clearInterrupt(InterruptType type) { interruptFlag = interruptFlag & ~(1 << type.ordinal()); } public void onInstructionFinished() { if (pendingEnableInterrupts != -1) { if (pendingEnableInterrupts enableInterrupts(false); } } if (pendingDisableInterrupts != -1) { if (pendingDisableInterrupts disableInterrupts(false); } } } public boolean isIme() { return ime; } public boolean isInterruptRequested() { return (interruptFlag & interruptEnabled) != 0; } public boolean isHaltBug() { return (interruptFlag & interruptEnabled & 0x1f) != 0 && !ime; } @Override public boolean accepts(int address) { return address == 0xff0f || address == 0xffff; } @Override public void setByte(int address, int value) { switch (address) { case 0xff0f: interruptFlag = value | 0xe0; break; case 0xffff: interruptEnabled = value; break; } } @Override public int getByte(int address) { switch (address) { case 0xff0f: return interruptFlag; case 0xffff: return interruptEnabled; default: return 0xff; } } }
package org.concord.energy3d.gui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyBoundsAdapter; import java.awt.event.HierarchyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.embed.swing.JFXPanel; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.StackedBarChart; import javafx.scene.chart.XYChart; import javafx.scene.layout.GridPane; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.scene.SceneManager; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.util.Config; import org.concord.energy3d.util.Util; import org.poly2tri.geometry.primitives.Point; import org.poly2tri.transform.coordinate.AnyToXYTransform; import org.poly2tri.transform.coordinate.XYToAnyTransform; import org.poly2tri.triangulation.point.TPoint; import com.ardor3d.image.Image; import com.ardor3d.image.ImageDataFormat; import com.ardor3d.image.PixelDataType; import com.ardor3d.image.Texture.MinificationFilter; import com.ardor3d.image.Texture2D; import com.ardor3d.intersection.PickResults; import com.ardor3d.intersection.PickingUtil; import com.ardor3d.intersection.PrimitivePickResults; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Ray3; import com.ardor3d.math.Vector2; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector2; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.scenegraph.Spatial; import com.ardor3d.util.TextureKey; import com.ardor3d.util.geom.BufferUtils; public class EnergyPanel extends JPanel { public static final ReadOnlyColorRGBA[] solarColors = { ColorRGBA.BLUE, ColorRGBA.GREEN, ColorRGBA.YELLOW, ColorRGBA.RED }; public static final double SOLAR_STEP = 2.0; private static final int SOLAR_MINUTE_STEP = 15; private static final double COST_PER_KWH = 0.13; private static final long serialVersionUID = 1L; private static final Map<String, Integer> cityLatitute = new HashMap<String, Integer>(); private static final Map<String, int[]> avgMonthlyLowTemperatures = new HashMap<String, int[]>(); private static final Map<String, int[]> avgMonthlyHighTemperatures = new HashMap<String, int[]>(); private static final EnergyPanel instance = new EnergyPanel(); private static final DecimalFormat twoDecimals = new DecimalFormat(); private static final DecimalFormat noDecimals = new DecimalFormat(); private static final DecimalFormat moneyDecimals = new DecimalFormat(); private static final RuntimeException cancelException = new RuntimeException("CANCEL"); private static boolean keepHeatmapOn = false; public enum UpdateRadiation { ALWAYS, NEVER, ONLY_IF_SLECTED_IN_GUI }; static { twoDecimals.setMaximumFractionDigits(2); noDecimals.setMaximumFractionDigits(0); moneyDecimals.setMaximumFractionDigits(0); cityLatitute.put("Moscow", 55); cityLatitute.put("Ottawa", 45); cityLatitute.put("Boston", 42); cityLatitute.put("Beijing", 39); cityLatitute.put("Washington DC", 38); cityLatitute.put("Tehran", 35); cityLatitute.put("Los Angeles", 34); cityLatitute.put("Miami", 25); cityLatitute.put("Mexico City", 19); cityLatitute.put("Singapore", 1); cityLatitute.put("Sydney", -33); cityLatitute.put("Buenos Aires", -34); avgMonthlyLowTemperatures.put("Boston", new int[] { -6, -4, -1, 5, 10, 16, 18, 18, 14, 8, 3, -2 }); avgMonthlyHighTemperatures.put("Boston", new int[] { 2, 4, 7, 13, 19, 24, 28, 27, 22, 16, 11, 5 }); avgMonthlyLowTemperatures.put("Moscow", new int[] { -14, -14, -9, 0, 6, 10, 13, 11, 6, 1, -5, -10 }); avgMonthlyHighTemperatures.put("Moscow", new int[] { -7, -6, 0, 9, 17, 22, 24, 22, 16, 8, 0, -5 }); avgMonthlyLowTemperatures.put("Ottawa", new int[] { -16, -14, -7, 1, 7, 12, 15, 14, 9, 3, -2, -11 }); avgMonthlyHighTemperatures.put("Ottawa", new int[] { -7, -5, 2, 11, 18, 23, 26, 24, 19, 13, 4, -4 }); avgMonthlyLowTemperatures.put("Beijing", new int[] { -9, -7, -1, 7, 13, 18, 21, 20, 14, 7, -1, -7 }); avgMonthlyHighTemperatures.put("Beijing", new int[] { 1, 4, 11, 19, 26, 30, 31, 29, 26, 19, 10, 3 }); avgMonthlyLowTemperatures.put("Washington DC", new int[] { -2, -1, 3, 8, 13, 19, 22, 21, 17, 11, 5, 1 }); avgMonthlyHighTemperatures.put("Washington DC", new int[] { 6, 8, 13, 19, 24, 29, 32, 31, 27, 30, 14, 8 }); avgMonthlyLowTemperatures.put("Tehran", new int[] { 1, 3, 7, 13, 17, 22, 25, 25, 21, 15, 8, 3 }); avgMonthlyHighTemperatures.put("Tehran", new int[] { 8, 11, 16, 23, 28, 34, 37, 36, 32, 25, 16, 10 }); avgMonthlyLowTemperatures.put("Los Angeles", new int[] { 9, 9, 11, 12, 14, 16, 18, 18, 17, 15, 11, 8 }); avgMonthlyHighTemperatures.put("Los Angeles", new int[] { 20, 21, 21, 23, 23, 26, 28, 29, 28, 26, 23, 20 }); avgMonthlyLowTemperatures.put("Miami", new int[] { 16, 17, 18, 21, 23, 25, 26, 26, 26, 24, 21, 18 }); avgMonthlyHighTemperatures.put("Miami", new int[] { 23, 24, 24, 26, 28, 31, 31, 32, 31, 29, 26, 24 }); avgMonthlyLowTemperatures.put("Mexico City", new int[] { 6, 7, 9, 11, 12, 12, 12, 12, 12, 10, 8, 7 }); avgMonthlyHighTemperatures.put("Mexico City", new int[] { 21, 23, 25, 26, 26, 24, 23, 23, 23, 22, 22, 21 }); avgMonthlyLowTemperatures.put("Singapore", new int[] { 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 23, 23 }); avgMonthlyHighTemperatures.put("Singapore", new int[] { 29, 31, 31, 32, 31, 31, 31, 31, 31, 31, 30, 29 }); avgMonthlyLowTemperatures.put("Sydney", new int[] { 19, 19, 18, 15, 12, 9, 8, 8, 11, 14, 16, 18 }); avgMonthlyHighTemperatures.put("Sydney", new int[] { 26, 26, 25, 23, 20, 17, 17, 18, 20, 22, 23, 25 }); avgMonthlyLowTemperatures.put("Buenos Aires", new int[] { 20, 19, 18, 14, 11, 8, 8, 9, 11, 13, 16, 18 }); avgMonthlyHighTemperatures.put("Buenos Aires", new int[] { 28, 27, 25, 22, 18, 15, 14, 16, 18, 21, 24, 27 }); } private JFXPanel fxPanel; private final XYChart.Data<String, Number> wallsAreaChartData = new XYChart.Data<String, Number>("Area", 0); private final XYChart.Data<String, Number> windowsAreaChartData = new XYChart.Data<String, Number>("Area", 0); private final XYChart.Data<String, Number> doorsAreaChartData = new XYChart.Data<String, Number>("Area", 0); private final XYChart.Data<String, Number> roofsAreaChartData = new XYChart.Data<String, Number>("Area", 0); private final XYChart.Data<String, Number> wallsEnergyChartData = new XYChart.Data<String, Number>("Energy Loss", 0); private final XYChart.Data<String, Number> windowsEnergyChartData = new XYChart.Data<String, Number>("Energy Loss", 0); private final XYChart.Data<String, Number> doorsEnergyChartData = new XYChart.Data<String, Number>("Energy Loss", 0); private final XYChart.Data<String, Number> roofsEnergyChartData = new XYChart.Data<String, Number>("Energy Loss", 0); private final JTextField heatingRateTextField; private final JComboBox wallsComboBox; private final JComboBox doorsComboBox; private final JComboBox windowsComboBox; private final JComboBox roofsComboBox; private final JCheckBox autoCheckBox; private final JTextField heatingYearlyTextField; private final JTextField sunRateTextField; private final JTextField sunTodayTextField; private final JTextField sunYearlyTextField; private final JTextField heatingTodayTextField; private final JTextField coolingRateTextField; private final JTextField coolingTodayTextField; private final JTextField coolingYearlyTextField; private final JTextField totalRateTextField; private final JTextField totalTodayTextField; private final JTextField totalYearlyTextField; private final JTextField heatingCostTextField; private final JTextField coolingCostTextField; private final JTextField totalCostTextField; private final JSpinner insideTemperatureSpinner; private final JSpinner outsideTemperatureSpinner; private final JLabel dateLabel; private final JLabel timeLabel; private final JSpinner dateSpinner; private final JSpinner timeSpinner; private final JComboBox cityComboBox; private final JLabel latitudeLabel; private final JSpinner latitudeSpinner; private final JPanel panel_4; private final JSlider colorMapSlider; private final JPanel colormapPanel; private final JLabel legendLabel; private final JLabel contrastLabel; private final JProgressBar progressBar; private JTextField solarRateTextField; private JTextField solarTodayTextField; private JTextField solarYearlyTextField; private final Map<Mesh, double[][]> solarOnMesh = new HashMap<Mesh, double[][]>(); private final Map<HousePart, Double> solarTotal = new HashMap<HousePart, Double>(); private final Map<Mesh, Boolean> textureCoordsAlreadyComputed = new HashMap<Mesh, Boolean>(); private final List<Spatial> solarCollidables = new ArrayList<Spatial>(); private double[][] solarOnLand; private Thread thread; private double wallsArea; private double doorsArea; private double windowsArea; private double roofsArea; private double wallUFactor; private double doorUFactor; private double windowUFactor; private double roofUFactor; private long maxSolarValue; private boolean computeRequest; private boolean initJavaFxAlreadyCalled = false; private boolean alreadyRenderedHeatmap = false; private UpdateRadiation updateRadiation; private boolean computeEnabled = true; private final ArrayList<PropertyChangeListener> propertyChangeListeners = new ArrayList<PropertyChangeListener>(); private JPanel partPanel; private JLabel partEnergyLabel; private JTextField partEnergyTextField; private JPanel housePanel; private JLabel solarPotentialKWhLabel; private JLabel lblSolarPotentialEnergy; private JTextField houseSolarPotentialTextField; private JLabel lblNewLabel; private JPanel panel; private JPanel panel_2; private JLabel lblPosition; private JTextField positionTextField; private JLabel lblArea; private JTextField areaTextField; private JLabel lblHeight; private JTextField heightTextField; private JPanel panel_5; private JLabel lblVolume; private JTextField volumnTextField; private static class EnergyAmount { double solar; double solarPanel; double heating; double cooling; } public static EnergyPanel getInstance() { return instance; } private EnergyPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.repaint(); this.paint(null); progressBar = new JProgressBar(); add(progressBar); final JPanel panel_3 = new JPanel(); panel_3.setBorder(new TitledBorder(null, "Time & Location", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(panel_3); final GridBagLayout gbl_panel_3 = new GridBagLayout(); panel_3.setLayout(gbl_panel_3); dateLabel = new JLabel("Date: "); final GridBagConstraints gbc_dateLabel = new GridBagConstraints(); gbc_dateLabel.gridx = 0; gbc_dateLabel.gridy = 0; panel_3.add(dateLabel, gbc_dateLabel); dateSpinner = new JSpinner(); dateSpinner.setModel(new SpinnerDateModel(new Date(1380427200000L), null, null, Calendar.MONTH)); dateSpinner.setEditor(new JSpinner.DateEditor(dateSpinner, "MMMM dd")); dateSpinner.addHierarchyBoundsListener(new HierarchyBoundsAdapter() { @Override public void ancestorResized(final HierarchyEvent e) { dateSpinner.setMinimumSize(dateSpinner.getPreferredSize()); dateSpinner.setPreferredSize(dateSpinner.getPreferredSize()); dateSpinner.removeHierarchyBoundsListener(this); } }); dateSpinner.addChangeListener(new javax.swing.event.ChangeListener() { boolean firstCall = true; @Override public void stateChanged(final javax.swing.event.ChangeEvent e) { if (firstCall) { firstCall = false; return; } final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setDate((Date) dateSpinner.getValue()); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_dateSpinner = new GridBagConstraints(); gbc_dateSpinner.insets = new Insets(0, 0, 1, 1); gbc_dateSpinner.gridx = 1; gbc_dateSpinner.gridy = 0; panel_3.add(dateSpinner, gbc_dateSpinner); cityComboBox = new JComboBox(); cityComboBox.setModel(new DefaultComboBoxModel(new String[] { "", "Moscow", "Ottawa", "Boston", "Beijing", "Washington DC", "Tehran", "Los Angeles", "Miami", "Mexico City", "Singapore", "Sydney", "Buenos Aires" })); cityComboBox.setSelectedItem("Boston"); cityComboBox.setMaximumRowCount(15); cityComboBox.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent e) { if (cityComboBox.getSelectedItem().equals("")) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else { final Integer newLatitude = cityLatitute.get(cityComboBox.getSelectedItem()); if (newLatitude.equals(latitudeSpinner.getValue())) compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); else latitudeSpinner.setValue(newLatitude); } } }); final GridBagConstraints gbc_cityComboBox = new GridBagConstraints(); gbc_cityComboBox.gridwidth = 2; gbc_cityComboBox.fill = GridBagConstraints.HORIZONTAL; gbc_cityComboBox.gridx = 2; gbc_cityComboBox.gridy = 0; panel_3.add(cityComboBox, gbc_cityComboBox); timeLabel = new JLabel("Time: "); final GridBagConstraints gbc_timeLabel = new GridBagConstraints(); gbc_timeLabel.gridx = 0; gbc_timeLabel.gridy = 1; panel_3.add(timeLabel, gbc_timeLabel); timeSpinner = new JSpinner(new SpinnerDateModel()); timeSpinner.setEditor(new JSpinner.DateEditor(timeSpinner, "H:mm")); timeSpinner.addChangeListener(new javax.swing.event.ChangeListener() { private boolean firstCall = true; @Override public void stateChanged(final javax.swing.event.ChangeEvent e) { // ignore the first event if (firstCall) { firstCall = false; return; } final Heliodon heliodon = Heliodon.getInstance(); if (heliodon != null) heliodon.setTime((Date) timeSpinner.getValue()); compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_timeSpinner = new GridBagConstraints(); gbc_timeSpinner.insets = new Insets(0, 0, 0, 1); gbc_timeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_timeSpinner.gridx = 1; gbc_timeSpinner.gridy = 1; panel_3.add(timeSpinner, gbc_timeSpinner); latitudeLabel = new JLabel("Latitude: "); final GridBagConstraints gbc_altitudeLabel = new GridBagConstraints(); gbc_altitudeLabel.insets = new Insets(0, 1, 0, 0); gbc_altitudeLabel.gridx = 2; gbc_altitudeLabel.gridy = 1; panel_3.add(latitudeLabel, gbc_altitudeLabel); latitudeSpinner = new JSpinner(); latitudeSpinner.setModel(new SpinnerNumberModel(Heliodon.DEFAULT_LATITUDE, -90, 90, 1)); latitudeSpinner.addChangeListener(new javax.swing.event.ChangeListener() { @Override public void stateChanged(final javax.swing.event.ChangeEvent e) { if (!cityComboBox.getSelectedItem().equals("") && !cityLatitute.values().contains(latitudeSpinner.getValue())) cityComboBox.setSelectedItem(""); Heliodon.getInstance().setLatitude(((Integer) latitudeSpinner.getValue()) / 180.0 * Math.PI); compute(UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); final GridBagConstraints gbc_latitudeSpinner = new GridBagConstraints(); gbc_latitudeSpinner.fill = GridBagConstraints.HORIZONTAL; gbc_latitudeSpinner.gridx = 3; gbc_latitudeSpinner.gridy = 1; panel_3.add(latitudeSpinner, gbc_latitudeSpinner); panel_3.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel_3.getPreferredSize().height)); panel_4 = new JPanel(); panel_4.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Solar Irradiation Heat Map", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(panel_4); final GridBagLayout gbl_panel_4 = new GridBagLayout(); panel_4.setLayout(gbl_panel_4); legendLabel = new JLabel("Color Scale: "); final GridBagConstraints gbc_legendLabel = new GridBagConstraints(); gbc_legendLabel.insets = new Insets(5, 0, 0, 0); gbc_legendLabel.anchor = GridBagConstraints.WEST; gbc_legendLabel.gridx = 0; gbc_legendLabel.gridy = 0; panel_4.add(legendLabel, gbc_legendLabel); colorMapSlider = new JSlider(); colorMapSlider.setMinimum(10); colorMapSlider.setMaximum(90); colorMapSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (!colorMapSlider.getValueIsAdjusting()) compute(SceneManager.getInstance().isSolarColorMap() ? UpdateRadiation.ALWAYS : UpdateRadiation.ONLY_IF_SLECTED_IN_GUI); } }); colormapPanel = new JPanel() { private static final long serialVersionUID = 1L; @Override public void paint(final Graphics g) { final int STEP = 5; final Dimension size = getSize(); for (int x = 0; x < size.width - STEP; x += STEP) { final ColorRGBA color = computeSolarColor(x, size.width); g.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue())); g.fillRect(x, 0, x + STEP, size.height); } } }; final GridBagConstraints gbc_colormapPanel = new GridBagConstraints(); gbc_colormapPanel.fill = GridBagConstraints.HORIZONTAL; gbc_colormapPanel.gridy = 0; gbc_colormapPanel.gridx = 1; panel_4.add(colormapPanel, gbc_colormapPanel); contrastLabel = new JLabel("Contrast: "); final GridBagConstraints gbc_contrastLabel = new GridBagConstraints(); gbc_contrastLabel.anchor = GridBagConstraints.WEST; gbc_contrastLabel.gridx = 0; gbc_contrastLabel.gridy = 1; panel_4.add(contrastLabel, gbc_contrastLabel); colorMapSlider.setSnapToTicks(true); colorMapSlider.setMinorTickSpacing(10); colorMapSlider.setMajorTickSpacing(10); colorMapSlider.setPaintTicks(true); final GridBagConstraints gbc_colorMapSlider = new GridBagConstraints(); gbc_colorMapSlider.gridy = 1; gbc_colorMapSlider.gridx = 1; panel_4.add(colorMapSlider, gbc_colorMapSlider); panel_4.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel_4.getPreferredSize().height)); final JPanel temperaturePanel = new JPanel(); temperaturePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Temperature \u00B0C", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(temperaturePanel); final GridBagLayout gbl_temperaturePanel = new GridBagLayout(); temperaturePanel.setLayout(gbl_temperaturePanel); final JLabel insideTemperatureLabel = new JLabel("Inside: "); insideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_insideTemperatureLabel = new GridBagConstraints(); gbc_insideTemperatureLabel.gridx = 1; gbc_insideTemperatureLabel.gridy = 0; temperaturePanel.add(insideTemperatureLabel, gbc_insideTemperatureLabel); insideTemperatureSpinner = new JSpinner(); insideTemperatureSpinner.setToolTipText("Thermostat temperature setting for the inside of the house"); insideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { compute(UpdateRadiation.NEVER); } }); insideTemperatureSpinner.setModel(new SpinnerNumberModel(20, -70, 60, 1)); final GridBagConstraints gbc_insideTemperatureSpinner = new GridBagConstraints(); gbc_insideTemperatureSpinner.gridx = 2; gbc_insideTemperatureSpinner.gridy = 0; temperaturePanel.add(insideTemperatureSpinner, gbc_insideTemperatureSpinner); final JLabel outsideTemperatureLabel = new JLabel(" Outside: "); outsideTemperatureLabel.setToolTipText(""); final GridBagConstraints gbc_outsideTemperatureLabel = new GridBagConstraints(); gbc_outsideTemperatureLabel.gridx = 3; gbc_outsideTemperatureLabel.gridy = 0; temperaturePanel.add(outsideTemperatureLabel, gbc_outsideTemperatureLabel); temperaturePanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, temperaturePanel.getPreferredSize().height)); outsideTemperatureSpinner = new JSpinner(); outsideTemperatureSpinner.setToolTipText("Outside temperature at this time and day"); outsideTemperatureSpinner.setEnabled(false); outsideTemperatureSpinner.setModel(new SpinnerNumberModel(10, -70, 60, 1)); outsideTemperatureSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if (thread == null) compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_outsideTemperatureSpinner = new GridBagConstraints(); gbc_outsideTemperatureSpinner.gridx = 4; gbc_outsideTemperatureSpinner.gridy = 0; temperaturePanel.add(outsideTemperatureSpinner, gbc_outsideTemperatureSpinner); autoCheckBox = new JCheckBox("Auto"); autoCheckBox.setToolTipText("Automatically set the outside temperature based on historic average of the selected city"); autoCheckBox.setSelected(true); autoCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final boolean selected = autoCheckBox.isSelected(); outsideTemperatureSpinner.setEnabled(!selected); if (selected) updateOutsideTemperature(); compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_autoCheckBox = new GridBagConstraints(); gbc_autoCheckBox.gridx = 5; gbc_autoCheckBox.gridy = 0; temperaturePanel.add(autoCheckBox, gbc_autoCheckBox); partPanel = new JPanel(); partPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Part", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(partPanel); partEnergyLabel = new JLabel("Solar Energy Potential:"); partPanel.add(partEnergyLabel); partEnergyTextField = new JTextField(); partPanel.add(partEnergyTextField); partEnergyTextField.setColumns(10); solarPotentialKWhLabel = new JLabel("kWh"); partPanel.add(solarPotentialKWhLabel); housePanel = new JPanel(); housePanel.setBorder(new TitledBorder(null, "House", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(housePanel); housePanel.setLayout(new BoxLayout(housePanel, BoxLayout.Y_AXIS)); panel = new JPanel(); housePanel.add(panel); lblSolarPotentialEnergy = new JLabel("Solar Energy Potential:"); panel.add(lblSolarPotentialEnergy); houseSolarPotentialTextField = new JTextField(); panel.add(houseSolarPotentialTextField); houseSolarPotentialTextField.setColumns(10); lblNewLabel = new JLabel("kWh"); panel.add(lblNewLabel); panel_2 = new JPanel(); housePanel.add(panel_2); lblPosition = new JLabel("Position:"); panel_2.add(lblPosition); positionTextField = new JTextField(); panel_2.add(positionTextField); positionTextField.setColumns(10); lblHeight = new JLabel("Height:"); panel_2.add(lblHeight); heightTextField = new JTextField(); panel_2.add(heightTextField); heightTextField.setColumns(10); panel_5 = new JPanel(); housePanel.add(panel_5); lblArea = new JLabel("Area:"); panel_5.add(lblArea); areaTextField = new JTextField(); panel_5.add(areaTextField); areaTextField.setColumns(10); lblVolume = new JLabel("Volume:"); panel_5.add(lblVolume); volumnTextField = new JTextField(); panel_5.add(volumnTextField); volumnTextField.setColumns(10); final JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Energy", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(panel_1); final GridBagLayout gbl_panel_1 = new GridBagLayout(); gbl_panel_1.columnWeights = new double[] { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }; panel_1.setLayout(gbl_panel_1); final JLabel sunLabel = new JLabel("Passive Solar"); final GridBagConstraints gbc_sunLabel = new GridBagConstraints(); gbc_sunLabel.insets = new Insets(0, 0, 5, 5); gbc_sunLabel.gridx = 1; gbc_sunLabel.gridy = 0; panel_1.add(sunLabel, gbc_sunLabel); final JLabel solarLabel = new JLabel("Photovoltaic"); solarLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_solarLabel = new GridBagConstraints(); gbc_solarLabel.insets = new Insets(0, 0, 5, 5); gbc_solarLabel.gridx = 2; gbc_solarLabel.gridy = 0; panel_1.add(solarLabel, gbc_solarLabel); final JLabel heatingLabel = new JLabel("Heating"); heatingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_heatingLabel = new GridBagConstraints(); gbc_heatingLabel.insets = new Insets(0, 0, 5, 5); gbc_heatingLabel.gridx = 3; gbc_heatingLabel.gridy = 0; panel_1.add(heatingLabel, gbc_heatingLabel); final JLabel coolingLabel = new JLabel("Cooling"); coolingLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_coolingLabel = new GridBagConstraints(); gbc_coolingLabel.insets = new Insets(0, 0, 5, 5); gbc_coolingLabel.gridx = 4; gbc_coolingLabel.gridy = 0; panel_1.add(coolingLabel, gbc_coolingLabel); final JLabel totalLabel = new JLabel("Total"); totalLabel.setHorizontalAlignment(SwingConstants.CENTER); final GridBagConstraints gbc_totalLabel = new GridBagConstraints(); gbc_totalLabel.insets = new Insets(0, 0, 5, 0); gbc_totalLabel.gridx = 5; gbc_totalLabel.gridy = 0; panel_1.add(totalLabel, gbc_totalLabel); final JLabel nowLabel = new JLabel("Now (watts):"); final GridBagConstraints gbc_nowLabel = new GridBagConstraints(); gbc_nowLabel.insets = new Insets(0, 0, 5, 5); gbc_nowLabel.anchor = GridBagConstraints.WEST; gbc_nowLabel.gridx = 0; gbc_nowLabel.gridy = 1; panel_1.add(nowLabel, gbc_nowLabel); sunRateTextField = new JTextField(); sunRateTextField.setEditable(false); final GridBagConstraints gbc_sunRateTextField = new GridBagConstraints(); gbc_sunRateTextField.insets = new Insets(0, 0, 5, 5); gbc_sunRateTextField.weightx = 1.0; gbc_sunRateTextField.fill = GridBagConstraints.HORIZONTAL; gbc_sunRateTextField.gridx = 1; gbc_sunRateTextField.gridy = 1; sunRateTextField.setColumns(5); panel_1.add(sunRateTextField, gbc_sunRateTextField); solarRateTextField = new JTextField(); solarRateTextField.setEditable(false); final GridBagConstraints gbc_solarRateTextField = new GridBagConstraints(); gbc_solarRateTextField.weightx = 1.0; gbc_solarRateTextField.insets = new Insets(0, 0, 5, 5); gbc_solarRateTextField.fill = GridBagConstraints.HORIZONTAL; gbc_solarRateTextField.gridx = 2; gbc_solarRateTextField.gridy = 1; panel_1.add(solarRateTextField, gbc_solarRateTextField); solarRateTextField.setColumns(5); heatingRateTextField = new JTextField(); final GridBagConstraints gbc_heatingRateTextField = new GridBagConstraints(); gbc_heatingRateTextField.insets = new Insets(0, 0, 5, 5); gbc_heatingRateTextField.weightx = 1.0; gbc_heatingRateTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingRateTextField.gridx = 3; gbc_heatingRateTextField.gridy = 1; panel_1.add(heatingRateTextField, gbc_heatingRateTextField); heatingRateTextField.setEditable(false); heatingRateTextField.setColumns(5); coolingRateTextField = new JTextField(); coolingRateTextField.setEditable(false); final GridBagConstraints gbc_coolingRateTextField = new GridBagConstraints(); gbc_coolingRateTextField.insets = new Insets(0, 0, 5, 5); gbc_coolingRateTextField.weightx = 1.0; gbc_coolingRateTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingRateTextField.gridx = 4; gbc_coolingRateTextField.gridy = 1; panel_1.add(coolingRateTextField, gbc_coolingRateTextField); coolingRateTextField.setColumns(5); totalRateTextField = new JTextField(); totalRateTextField.setEditable(false); final GridBagConstraints gbc_totalRateTextField = new GridBagConstraints(); gbc_totalRateTextField.insets = new Insets(0, 0, 5, 0); gbc_totalRateTextField.weightx = 1.0; gbc_totalRateTextField.fill = GridBagConstraints.HORIZONTAL; gbc_totalRateTextField.gridx = 5; gbc_totalRateTextField.gridy = 1; panel_1.add(totalRateTextField, gbc_totalRateTextField); totalRateTextField.setColumns(5); final JLabel todayLabel = new JLabel("Today (kWh): "); final GridBagConstraints gbc_todayLabel = new GridBagConstraints(); gbc_todayLabel.insets = new Insets(0, 0, 5, 5); gbc_todayLabel.anchor = GridBagConstraints.WEST; gbc_todayLabel.gridx = 0; gbc_todayLabel.gridy = 2; panel_1.add(todayLabel, gbc_todayLabel); sunTodayTextField = new JTextField(); sunTodayTextField.setEditable(false); final GridBagConstraints gbc_sunTodayTextField = new GridBagConstraints(); gbc_sunTodayTextField.insets = new Insets(0, 0, 5, 5); gbc_sunTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_sunTodayTextField.gridx = 1; gbc_sunTodayTextField.gridy = 2; panel_1.add(sunTodayTextField, gbc_sunTodayTextField); sunTodayTextField.setColumns(5); solarTodayTextField = new JTextField(); solarTodayTextField.setEditable(false); final GridBagConstraints gbc_solarTodayTextField = new GridBagConstraints(); gbc_solarTodayTextField.insets = new Insets(0, 0, 5, 5); gbc_solarTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_solarTodayTextField.gridx = 2; gbc_solarTodayTextField.gridy = 2; panel_1.add(solarTodayTextField, gbc_solarTodayTextField); solarTodayTextField.setColumns(5); heatingTodayTextField = new JTextField(); heatingTodayTextField.setEditable(false); final GridBagConstraints gbc_heatingTodayTextField = new GridBagConstraints(); gbc_heatingTodayTextField.insets = new Insets(0, 0, 5, 5); gbc_heatingTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingTodayTextField.gridx = 3; gbc_heatingTodayTextField.gridy = 2; panel_1.add(heatingTodayTextField, gbc_heatingTodayTextField); heatingTodayTextField.setColumns(5); coolingTodayTextField = new JTextField(); coolingTodayTextField.setEditable(false); final GridBagConstraints gbc_coolingTodayTextField = new GridBagConstraints(); gbc_coolingTodayTextField.insets = new Insets(0, 0, 5, 5); gbc_coolingTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingTodayTextField.gridx = 4; gbc_coolingTodayTextField.gridy = 2; panel_1.add(coolingTodayTextField, gbc_coolingTodayTextField); coolingTodayTextField.setColumns(5); totalTodayTextField = new JTextField(); totalTodayTextField.setEditable(false); final GridBagConstraints gbc_totalTodayTextField = new GridBagConstraints(); gbc_totalTodayTextField.insets = new Insets(0, 0, 5, 0); gbc_totalTodayTextField.fill = GridBagConstraints.HORIZONTAL; gbc_totalTodayTextField.gridx = 5; gbc_totalTodayTextField.gridy = 2; panel_1.add(totalTodayTextField, gbc_totalTodayTextField); totalTodayTextField.setColumns(5); final JLabel yearlyLabel = new JLabel("Yearly (kWh): "); final GridBagConstraints gbc_yearlyLabel = new GridBagConstraints(); gbc_yearlyLabel.insets = new Insets(0, 0, 5, 5); gbc_yearlyLabel.anchor = GridBagConstraints.WEST; gbc_yearlyLabel.gridx = 0; gbc_yearlyLabel.gridy = 3; panel_1.add(yearlyLabel, gbc_yearlyLabel); panel_1.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel_1.getPreferredSize().height)); sunYearlyTextField = new JTextField(); sunYearlyTextField.setEditable(false); final GridBagConstraints gbc_sunYearlyTextField = new GridBagConstraints(); gbc_sunYearlyTextField.insets = new Insets(0, 0, 5, 5); gbc_sunYearlyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_sunYearlyTextField.gridx = 1; gbc_sunYearlyTextField.gridy = 3; panel_1.add(sunYearlyTextField, gbc_sunYearlyTextField); sunYearlyTextField.setColumns(5); solarYearlyTextField = new JTextField(); solarYearlyTextField.setEditable(false); final GridBagConstraints gbc_solarYearlyTextField = new GridBagConstraints(); gbc_solarYearlyTextField.insets = new Insets(0, 0, 5, 5); gbc_solarYearlyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_solarYearlyTextField.gridx = 2; gbc_solarYearlyTextField.gridy = 3; panel_1.add(solarYearlyTextField, gbc_solarYearlyTextField); solarYearlyTextField.setColumns(5); heatingYearlyTextField = new JTextField(); heatingYearlyTextField.setEditable(false); final GridBagConstraints gbc_heatingYearlyTextField = new GridBagConstraints(); gbc_heatingYearlyTextField.insets = new Insets(0, 0, 5, 5); gbc_heatingYearlyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingYearlyTextField.gridx = 3; gbc_heatingYearlyTextField.gridy = 3; panel_1.add(heatingYearlyTextField, gbc_heatingYearlyTextField); heatingYearlyTextField.setColumns(5); coolingYearlyTextField = new JTextField(); coolingYearlyTextField.setEditable(false); final GridBagConstraints gbc_coolingYearlyTextField = new GridBagConstraints(); gbc_coolingYearlyTextField.insets = new Insets(0, 0, 5, 5); gbc_coolingYearlyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingYearlyTextField.gridx = 4; gbc_coolingYearlyTextField.gridy = 3; panel_1.add(coolingYearlyTextField, gbc_coolingYearlyTextField); coolingYearlyTextField.setColumns(5); totalYearlyTextField = new JTextField(); totalYearlyTextField.setEditable(false); final GridBagConstraints gbc_totalYearlyTextField = new GridBagConstraints(); gbc_totalYearlyTextField.insets = new Insets(0, 0, 5, 0); // gbc_totalYearlyTextField.insets = new Insets(0, 0, 5, 0); gbc_totalYearlyTextField.fill = GridBagConstraints.HORIZONTAL; gbc_totalYearlyTextField.gridx = 5; gbc_totalYearlyTextField.gridy = 3; panel_1.add(totalYearlyTextField, gbc_totalYearlyTextField); totalYearlyTextField.setColumns(5); final JLabel yearlyCostLabel = new JLabel("Yearly Cost:"); final GridBagConstraints gbc_yearlyCostLabel = new GridBagConstraints(); gbc_yearlyCostLabel.insets = new Insets(0, 0, 0, 5); gbc_yearlyCostLabel.anchor = GridBagConstraints.WEST; gbc_yearlyCostLabel.gridx = 0; gbc_yearlyCostLabel.gridy = 4; panel_1.add(yearlyCostLabel, gbc_yearlyCostLabel); heatingCostTextField = new JTextField(); heatingCostTextField.setEditable(false); final GridBagConstraints gbc_heatingCostTextField = new GridBagConstraints(); gbc_heatingCostTextField.insets = new Insets(0, 0, 0, 5); gbc_heatingCostTextField.fill = GridBagConstraints.HORIZONTAL; gbc_heatingCostTextField.gridx = 3; gbc_heatingCostTextField.gridy = 4; panel_1.add(heatingCostTextField, gbc_heatingCostTextField); heatingCostTextField.setColumns(5); coolingCostTextField = new JTextField(); coolingCostTextField.setEditable(false); final GridBagConstraints gbc_coolingCostTextField = new GridBagConstraints(); gbc_coolingCostTextField.insets = new Insets(0, 0, 0, 5); gbc_coolingCostTextField.fill = GridBagConstraints.HORIZONTAL; gbc_coolingCostTextField.gridx = 4; gbc_coolingCostTextField.gridy = 4; panel_1.add(coolingCostTextField, gbc_coolingCostTextField); coolingCostTextField.setColumns(5); totalCostTextField = new JTextField(); totalCostTextField.setEditable(false); final GridBagConstraints gbc_totalCostTextField = new GridBagConstraints(); gbc_totalCostTextField.fill = GridBagConstraints.HORIZONTAL; gbc_totalCostTextField.gridx = 5; gbc_totalCostTextField.gridy = 4; panel_1.add(totalCostTextField, gbc_totalCostTextField); totalCostTextField.setColumns(5); final Dimension size = heatingLabel.getMinimumSize(); sunLabel.setMinimumSize(size); solarLabel.setMinimumSize(size); coolingLabel.setMinimumSize(size); totalLabel.setMinimumSize(size); final JPanel uFactorPanel = new JPanel(); uFactorPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "U-Factor W/(m\u00B2.\u00B0C)", TitledBorder.LEADING, TitledBorder.TOP, null, null)); add(uFactorPanel); final GridBagLayout gbl_uFactorPanel = new GridBagLayout(); uFactorPanel.setLayout(gbl_uFactorPanel); final JLabel wallsLabel = new JLabel("Walls:"); final GridBagConstraints gbc_wallsLabel = new GridBagConstraints(); gbc_wallsLabel.anchor = GridBagConstraints.EAST; gbc_wallsLabel.insets = new Insets(0, 0, 5, 5); gbc_wallsLabel.gridx = 0; gbc_wallsLabel.gridy = 0; uFactorPanel.add(wallsLabel, gbc_wallsLabel); wallsComboBox = new WideComboBox(); wallsComboBox.setEditable(true); wallsComboBox.setModel(new DefaultComboBoxModel(new String[] { "0.28 ", "0.67 (Concrete 8\")", "0.41 (Masonary Brick 8\")", "0.04 (Flat Metal 8\" Fiberglass Insulation)" })); wallsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_wallsComboBox = new GridBagConstraints(); gbc_wallsComboBox.insets = new Insets(0, 0, 5, 5); gbc_wallsComboBox.gridx = 1; gbc_wallsComboBox.gridy = 0; uFactorPanel.add(wallsComboBox, gbc_wallsComboBox); final JLabel doorsLabel = new JLabel("Doors:"); final GridBagConstraints gbc_doorsLabel = new GridBagConstraints(); gbc_doorsLabel.anchor = GridBagConstraints.EAST; gbc_doorsLabel.insets = new Insets(0, 0, 5, 5); gbc_doorsLabel.gridx = 2; gbc_doorsLabel.gridy = 0; uFactorPanel.add(doorsLabel, gbc_doorsLabel); doorsComboBox = new WideComboBox(); doorsComboBox.setEditable(true); doorsComboBox.setModel(new DefaultComboBoxModel(new String[] { "0.00 " })); doorsComboBox.setModel(new DefaultComboBoxModel(new String[] { "1.14 ", "1.20 (Steel)", "0.64 (Wood)" })); doorsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_doorsComboBox = new GridBagConstraints(); gbc_doorsComboBox.insets = new Insets(0, 0, 5, 0); gbc_doorsComboBox.gridx = 3; gbc_doorsComboBox.gridy = 0; uFactorPanel.add(doorsComboBox, gbc_doorsComboBox); final JLabel windowsLabel = new JLabel("Windows:"); final GridBagConstraints gbc_windowsLabel = new GridBagConstraints(); gbc_windowsLabel.anchor = GridBagConstraints.EAST; gbc_windowsLabel.insets = new Insets(0, 0, 0, 5); gbc_windowsLabel.gridx = 0; gbc_windowsLabel.gridy = 1; uFactorPanel.add(windowsLabel, gbc_windowsLabel); windowsComboBox = new WideComboBox(); windowsComboBox.setEditable(true); windowsComboBox.setModel(new DefaultComboBoxModel(new String[] { "1.89 ", "1.22 (Single Pane)", "0.70 (Double Pane)" })); windowsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_windowsComboBox = new GridBagConstraints(); gbc_windowsComboBox.insets = new Insets(0, 0, 0, 5); gbc_windowsComboBox.gridx = 1; gbc_windowsComboBox.gridy = 1; uFactorPanel.add(windowsComboBox, gbc_windowsComboBox); final JLabel roofsLabel = new JLabel("Roofs:"); final GridBagConstraints gbc_roofsLabel = new GridBagConstraints(); gbc_roofsLabel.anchor = GridBagConstraints.EAST; gbc_roofsLabel.insets = new Insets(0, 0, 0, 5); gbc_roofsLabel.gridx = 2; gbc_roofsLabel.gridy = 1; uFactorPanel.add(roofsLabel, gbc_roofsLabel); roofsComboBox = new WideComboBox(); roofsComboBox.setEditable(true); roofsComboBox.setModel(new DefaultComboBoxModel(new String[] { "0.14 ", "0.23 (Concrete 3\")", "0.11 (Flat Metal 3\" Fiberglass Insulation)", "0.10 (Wood 3\" Fiberglass Insulation)" })); roofsComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { compute(UpdateRadiation.NEVER); } }); final GridBagConstraints gbc_roofsComboBox = new GridBagConstraints(); gbc_roofsComboBox.gridx = 3; gbc_roofsComboBox.gridy = 1; uFactorPanel.add(roofsComboBox, gbc_roofsComboBox); uFactorPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, uFactorPanel.getPreferredSize().height)); final Component verticalGlue = Box.createVerticalGlue(); add(verticalGlue); if (Config.isRestrictMode()) { coolingLabel.setVisible(false); coolingCostTextField.setVisible(false); coolingRateTextField.setVisible(false); coolingTodayTextField.setVisible(false); coolingYearlyTextField.setVisible(false); heatingLabel.setVisible(false); heatingCostTextField.setVisible(false); heatingRateTextField.setVisible(false); heatingTodayTextField.setVisible(false); heatingYearlyTextField.setVisible(false); totalLabel.setVisible(false); totalCostTextField.setVisible(false); totalRateTextField.setVisible(false); totalTodayTextField.setVisible(false); totalYearlyTextField.setVisible(false); yearlyCostLabel.setVisible(false); temperaturePanel.setVisible(false); uFactorPanel.setVisible(false); } } public void initJavaFXGUI() { if (fxPanel == null && !initJavaFxAlreadyCalled) { initJavaFxAlreadyCalled = true; try { System.out.println("initJavaFXGUI()"); fxPanel = new JFXPanel(); final GridBagConstraints gbc_fxPanel = new GridBagConstraints(); fxPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 400)); gbc_fxPanel.gridwidth = 3; gbc_fxPanel.fill = GridBagConstraints.BOTH; gbc_fxPanel.insets = new Insets(0, 0, 5, 0); gbc_fxPanel.gridx = 0; gbc_fxPanel.gridy = 1; add(fxPanel, gbc_fxPanel); initFxComponents(); } catch (final Throwable e) { System.out.println("Error occured when initializing JavaFX: JavaFX is probably not supported!"); e.printStackTrace(); } } } private void initFxComponents() { Platform.runLater(new Runnable() { @Override public void run() { final GridPane grid = new GridPane(); final javafx.scene.Scene scene = new javafx.scene.Scene(grid, 800, 400); scene.getStylesheets().add("org/concord/energy3d/gui/css/fx.css"); final NumberAxis yAxis = new NumberAxis(0, 100, 10); final CategoryAxis xAxis = new CategoryAxis(); xAxis.setCategories(FXCollections.<String> observableArrayList(Arrays.asList("Area", "Energy Loss"))); final StackedBarChart<String, Number> chart = new StackedBarChart<String, Number>(xAxis, yAxis); chart.setStyle("-fx-background-color: #" + Integer.toHexString(UIManager.getColor("Panel.background").getRGB() & 0x00FFFFFF) + ";"); XYChart.Series<String, Number> series = new XYChart.Series<String, Number>(); series.setName("Walls"); series.getData().add(wallsAreaChartData); series.getData().add(wallsEnergyChartData); chart.getData().add(series); series = new XYChart.Series<String, Number>(); series.setName("Doors"); series.getData().add(doorsAreaChartData); series.getData().add(doorsEnergyChartData); chart.getData().add(series); series = new XYChart.Series<String, Number>(); series.setName("Windows"); series.getData().add(windowsAreaChartData); series.getData().add(windowsEnergyChartData); chart.getData().add(series); series = new XYChart.Series<String, Number>(); series.setName("Roof"); series.getData().add(roofsAreaChartData); series.getData().add(roofsEnergyChartData); chart.getData().add(series); grid.add(chart, 0, 0); fxPanel.setScene(scene); } }); } public void updateAreaChart() { final double total = wallsArea + doorsArea + windowsArea + roofsArea; final boolean isZero = (total == 0.0); wallsAreaChartData.setYValue(isZero ? 0 : wallsArea / total * 100.0); doorsAreaChartData.setYValue(isZero ? 0 : doorsArea / total * 100.0); windowsAreaChartData.setYValue(isZero ? 0 : windowsArea / total * 100.0); roofsAreaChartData.setYValue(isZero ? 0 : roofsArea / total * 100.0); } public void updateEnergyLossChart() { final double walls = wallsArea * wallUFactor; final double doors = doorsArea * doorUFactor; final double windows = windowsArea * windowUFactor; final double roofs = roofsArea * roofUFactor; final double total = walls + windows + doors + roofs; final boolean isZero = (total == 0.0); wallsEnergyChartData.setYValue(isZero ? 0 : walls / total * 100.0); doorsEnergyChartData.setYValue(isZero ? 0 : doors / total * 100.0); windowsEnergyChartData.setYValue(isZero ? 0 : windows / total * 100.0); roofsEnergyChartData.setYValue(isZero ? 0 : roofs / total * 100.0); } public void compute(final UpdateRadiation updateRadiation) { if (!computeEnabled) return; this.updateRadiation = updateRadiation; if (thread != null && thread.isAlive()) computeRequest = true; else { thread = new Thread("Energy Computer") { @Override public void run() { do { computeRequest = false; /* since this thread can accept multiple computeRequest, cannot use updateRadiationColorMap parameter directly */ try { computeNow(EnergyPanel.this.updateRadiation); } catch (final Throwable e) { e.printStackTrace(); Util.reportError(e); } try { Thread.sleep(500); } catch (final InterruptedException e) { e.printStackTrace(); } progressBar.setValue(0); } while (computeRequest); thread = null; } }; thread.start(); } } public void computeNow(final UpdateRadiation updateRadiation) { try { System.out.println("EnergyPanel.computeNow()"); progressBar.setValue(0); if (updateRadiation != UpdateRadiation.NEVER) { if (updateRadiation == UpdateRadiation.ALWAYS || (SceneManager.getInstance().isSolarColorMap() && (!alreadyRenderedHeatmap || keepHeatmapOn))) { alreadyRenderedHeatmap = true; computeRadiation(); notifyPropertyChangeListeners(new PropertyChangeEvent(EnergyPanel.this, "Solar energy calculation completed", 0, 1)); } else { if (SceneManager.getInstance().isSolarColorMap()) MainPanel.getInstance().getSolarButton().setSelected(false); int numberOfHouses = 0; for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation && !part.getChildren().isEmpty() && !part.isFrozen()) numberOfHouses++; if (numberOfHouses >= 2) break; } for (final HousePart part : Scene.getInstance().getParts()) if (part instanceof Foundation) ((Foundation) part).setSolarValue(numberOfHouses >= 2 && !part.getChildren().isEmpty() && !part.isFrozen() ? -1 : -2); SceneManager.getInstance().refresh(); } } computeEnergy(); } catch (final RuntimeException e) { if (e != cancelException) e.printStackTrace(); } } private void computeEnergy() { if (autoCheckBox.isSelected()) updateOutsideTemperature(); try { wallUFactor = parseUFactor(wallsComboBox); doorUFactor = parseUFactor(doorsComboBox); windowUFactor = parseUFactor(windowsComboBox); roofUFactor = parseUFactor(roofsComboBox); } catch (final Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(MainPanel.getInstance(), "Invalid U-Factor value: " + e.getMessage(), "Invalid U-Factor", JOptionPane.WARNING_MESSAGE); return; } wallsArea = 0; doorsArea = 0; windowsArea = 0; roofsArea = 0; /* compute area */ for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Wall) wallsArea += part.computeArea(); else if (part instanceof Window) windowsArea += part.computeArea(); else if (part instanceof Door) doorsArea += part.computeArea(); else if (part instanceof Roof) roofsArea += part.computeArea(); } updateAreaChart(); updateEnergyLossChart(); final int insideTemperature = (Integer) insideTemperatureSpinner.getValue(); final int outsideTemperature = (Integer) outsideTemperatureSpinner.getValue(); computeEnergyLossRate(insideTemperature - outsideTemperature); final EnergyAmount energyRate = computeEnergyRate(Heliodon.getInstance().getSunLocation(), insideTemperature, outsideTemperature); sunRateTextField.setText(noDecimals.format(energyRate.solar)); solarRateTextField.setText(noDecimals.format(energyRate.solarPanel)); heatingRateTextField.setText(noDecimals.format(energyRate.heating)); coolingRateTextField.setText(noDecimals.format(energyRate.cooling)); totalRateTextField.setText(noDecimals.format(energyRate.heating + energyRate.cooling)); final EnergyAmount energyToday = computeEnergyToday((Calendar) Heliodon.getInstance().getCalander().clone(), (Integer) insideTemperatureSpinner.getValue()); sunTodayTextField.setText(twoDecimals.format(energyToday.solar)); solarTodayTextField.setText(twoDecimals.format(energyToday.solarPanel)); heatingTodayTextField.setText(twoDecimals.format(energyToday.heating)); coolingTodayTextField.setText(twoDecimals.format(energyToday.cooling)); totalTodayTextField.setText(twoDecimals.format(energyToday.heating + energyToday.cooling)); final EnergyAmount energyYearly = computeEnergyYearly((Integer) insideTemperatureSpinner.getValue()); sunYearlyTextField.setText(noDecimals.format(energyYearly.solar)); solarYearlyTextField.setText(noDecimals.format(energyYearly.solarPanel)); heatingYearlyTextField.setText(noDecimals.format(energyYearly.heating)); coolingYearlyTextField.setText(noDecimals.format(energyYearly.cooling)); totalYearlyTextField.setText(noDecimals.format(energyYearly.heating + energyYearly.cooling)); heatingCostTextField.setText("$" + moneyDecimals.format(COST_PER_KWH * energyYearly.heating)); coolingCostTextField.setText("$" + moneyDecimals.format(COST_PER_KWH * energyYearly.cooling)); totalCostTextField.setText("$" + moneyDecimals.format(COST_PER_KWH * (energyYearly.heating + energyYearly.cooling))); progressBar.setValue(100); } private double parseUFactor(final JComboBox comboBox) { final String valueStr = comboBox.getSelectedItem().toString(); final int indexOfSpace = valueStr.indexOf(' '); return Double.parseDouble(valueStr.substring(0, indexOfSpace != -1 ? indexOfSpace : valueStr.length())); } private EnergyAmount computeEnergyYearly(final double insideTemperature) { final EnergyAmount energyYearly = new EnergyAmount(); final Calendar date = Calendar.getInstance(); date.set(Calendar.DAY_OF_MONTH, 15); date.set(Calendar.MONTH, 0); for (int month = 0; month < 11; month++) { final EnergyAmount energyToday = computeEnergyToday(date, insideTemperature); final int daysInMonth = date.getActualMaximum(Calendar.DAY_OF_MONTH); energyYearly.solar += energyToday.solar * daysInMonth; energyYearly.solarPanel += energyToday.solarPanel * daysInMonth; energyYearly.heating += energyToday.heating * daysInMonth; energyYearly.cooling += energyToday.cooling * daysInMonth; date.add(Calendar.MONTH, 1); } return energyYearly; } private EnergyAmount computeEnergyToday(final Calendar today, final double insideTemperature) { final EnergyAmount energyToday = new EnergyAmount(); final Heliodon heliodon = Heliodon.getInstance(); today.set(Calendar.SECOND, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.HOUR_OF_DAY, 0); final double[] outsideTemperature; if (getCity().isEmpty()) { /* * if there are no temperatures available for the selected city compute zero for cooling and heating */ outsideTemperature = new double[] { insideTemperature, insideTemperature }; energyToday.heating = Double.NaN; energyToday.cooling = Double.NaN; } else outsideTemperature = computeOutsideTemperature(today); for (int hour = 0; hour < 24; hour++) { final EnergyAmount energyThisHour = computeEnergyRate(heliodon.computeSunLocation(today), insideTemperature, outsideTemperature[0] + (outsideTemperature[1] - outsideTemperature[0]) / 24 * hour); energyToday.solar += energyThisHour.solar / 1000.0; energyToday.solarPanel += energyThisHour.solarPanel / 1000.0; energyToday.heating += energyThisHour.heating / 1000.0; energyToday.cooling += energyThisHour.cooling / 1000.0; today.add(Calendar.HOUR_OF_DAY, 1); } final double coolingWithSolarPanel = Math.max(0.0, energyToday.cooling - energyToday.solarPanel); final double heatingWithSolarPanel = energyToday.heating - energyToday.solarPanel - (energyToday.cooling - coolingWithSolarPanel); energyToday.cooling = coolingWithSolarPanel; energyToday.heating = heatingWithSolarPanel; return energyToday; } private double[] computeOutsideTemperature(final Calendar today) { final int day = today.get(Calendar.DAY_OF_MONTH); final int daysInMonth = today.getActualMaximum(Calendar.DAY_OF_MONTH); final double[] outsideTemperature = new double[2]; final Calendar monthFrom, monthTo; final int halfMonth = daysInMonth / 2; final double portion; final int totalDaysOfMonth; if (day < halfMonth) { monthFrom = (Calendar) today.clone(); monthFrom.add(Calendar.MONTH, -1); monthTo = today; final int prevHalfMonth = monthFrom.getActualMaximum(Calendar.DAY_OF_MONTH) - monthFrom.getActualMaximum(Calendar.DAY_OF_MONTH) / 2; totalDaysOfMonth = prevHalfMonth + daysInMonth / 2; portion = (double) (day + prevHalfMonth) / totalDaysOfMonth; } else { monthFrom = today; monthTo = (Calendar) today.clone(); monthTo.add(Calendar.MONTH, 1); final int nextHalfMonth = monthTo.getActualMaximum(Calendar.DAY_OF_MONTH) / 2; totalDaysOfMonth = halfMonth + nextHalfMonth; portion = (double) (day - halfMonth) / totalDaysOfMonth; } final int[] monthlyLowTemperatures = avgMonthlyLowTemperatures.get(getCity()); final int[] monthlyHighTemperatures = avgMonthlyHighTemperatures.get(getCity()); final int monthFromIndex = monthFrom.get(Calendar.MONTH); final int monthToIndex = monthTo.get(Calendar.MONTH); outsideTemperature[0] = monthlyLowTemperatures[monthFromIndex] + (monthlyLowTemperatures[monthToIndex] - monthlyLowTemperatures[monthFromIndex]) * portion; outsideTemperature[1] = monthlyHighTemperatures[monthFromIndex] + (monthlyHighTemperatures[monthToIndex] - monthlyHighTemperatures[monthFromIndex]) * portion; return outsideTemperature; } public String getCity() { return (String) cityComboBox.getSelectedItem(); } public void setCity(final String city) { cityComboBox.setSelectedItem(city); } private EnergyAmount computeEnergyRate(final ReadOnlyVector3 sunLocation, final double insideTemperature, final double outsideTemperature) { if (computeRequest) throw cancelException; final EnergyAmount energyRate = new EnergyAmount(); // if (Heliodon.getInstance().isVisible() && sunLocation.getZ() > 0.0) { if (sunLocation.getZ() > 0.0) { energyRate.solar = computeEnergySolarRate(sunLocation.normalize(null)); energyRate.solarPanel = computeEnergySolarPanelRate(sunLocation.normalize(null)); } final double energyLossRate = computeEnergyLossRate(insideTemperature - outsideTemperature); if (energyLossRate >= 0.0) { energyRate.heating = energyLossRate; energyRate.cooling = 0.0; } else { energyRate.cooling = -energyLossRate; energyRate.heating = 0.0; } if (Heliodon.getInstance().isVisible()) { final double heatingWithSolar = Math.max(0.0, energyRate.heating - energyRate.solar); final double coolingWithSolar = energyRate.cooling + energyRate.solar - (energyRate.heating - heatingWithSolar); energyRate.heating = heatingWithSolar; energyRate.cooling = coolingWithSolar; if (outsideTemperature < insideTemperature) energyRate.cooling = 0; } return energyRate; } private double computeEnergyLossRate(final double deltaT) { final double wallsEnergyLoss = wallsArea * wallUFactor * deltaT; final double doorsEnergyLoss = doorsArea * doorUFactor * deltaT; final double windowsEnergyLoss = windowsArea * windowUFactor * deltaT; final double roofsEnergyLoss = roofsArea * roofUFactor * deltaT; return wallsEnergyLoss + doorsEnergyLoss + windowsEnergyLoss + roofsEnergyLoss; } private double computeEnergySolarRate(final ReadOnlyVector3 sunVector) { double totalRate = 0.0; final boolean computeSunEnergyOfWalls = Scene.getInstance().isComputeSunEnergyOfWalls(); for (final HousePart part : Scene.getInstance().getParts()) if ((part instanceof Window && !computeSunEnergyOfWalls) || (part instanceof Wall && computeSunEnergyOfWalls)) { final double dot = part.getContainer().getFaceDirection().dot(sunVector); if (dot > 0.0) totalRate += 100.0 * part.computeArea() * dot; } return totalRate; } private double computeEnergySolarPanelRate(final ReadOnlyVector3 sunVector) { double totalRate = 0.0; for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof SolarPanel) { final double dot = part.getContainer().getFaceDirection().dot(sunVector); if (dot > 0.0) totalRate += 70.0 * part.computeArea() * dot; } } return totalRate; } private void updateOutsideTemperature() { if (getCity().isEmpty()) outsideTemperatureSpinner.setValue(15); else { final double[] temperature = computeOutsideTemperature(Heliodon.getInstance().getCalander()); final double avgTemperature = (temperature[0] + temperature[1]) / 2.0; outsideTemperatureSpinner.setValue((int) Math.round(avgTemperature)); } } public JSpinner getDateSpinner() { return dateSpinner; } public JSpinner getTimeSpinner() { return timeSpinner; } private void computeRadiation() { System.out.println("computeRadiation()"); initSolarCollidables(); solarOnMesh.clear(); solarTotal.clear(); textureCoordsAlreadyComputed.clear(); for (final HousePart part : Scene.getInstance().getParts()) part.setSolarPotentialEnergy(0.0); solarOnLand = null; maxSolarValue = 1; // computeSolarOnLand(Heliodon.getInstance().getSunLocation()); // computeRadiationOnWalls(Heliodon.getInstance().getSunLocation()); // computeRadiationOnRoofs(Heliodon.getInstance().getSunLocation()); // computeRadiationOnSolarPanels(Heliodon.getInstance().getSunLocation()); computeRadiationToday((Calendar) Heliodon.getInstance().getCalander().clone()); updateSolarValueOnAllHouses(); } private void initSolarCollidables() { solarCollidables.clear(); for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) solarCollidables.add(part.getMesh()); else if (part instanceof Wall) solarCollidables.add(((Wall) part).getInvisibleMesh()); else if (part instanceof SolarPanel) solarCollidables.add(((SolarPanel) part).getSurroundMesh()); else if (part instanceof Roof) for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) solarCollidables.add(((Node) roofPart).getChild(0)); } } private void computeRadiationOnRoofs(final HousePart part, final ReadOnlyVector3 directionTowardSun) { for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { final ReadOnlyVector3 faceDirection = (ReadOnlyVector3) roofPart.getUserData(); if (faceDirection.dot(directionTowardSun) > 0) { final Mesh mesh = (Mesh) ((Node) roofPart).getChild(0); computeRadiationOnMesh(directionTowardSun, part, mesh, mesh, faceDirection, false); } } } private void computeRadiationOnWalls(final Wall wall, final ReadOnlyVector3 directionTowardSun) { final ReadOnlyVector3 faceDirection = wall.getFaceDirection(); if (wall.isDrawCompleted() && faceDirection.dot(directionTowardSun) > 0) computeRadiationOnMesh(directionTowardSun, wall, wall.getMesh(), wall.getInvisibleMesh(), faceDirection, true); } private void computeRadiationOnSolarPanels(final ReadOnlyVector3 sunLocation) { if (sunLocation.getZ() <= 0) return; final ReadOnlyVector3 directionTowardSun = sunLocation.normalize(null); for (final HousePart part : Scene.getInstance().getParts()) { final ReadOnlyVector3 faceDirection = part.getFaceDirection(); if (part instanceof SolarPanel && part.isDrawCompleted() && faceDirection.dot(directionTowardSun) > 0) { final SolarPanel solarPanel = (SolarPanel) part; // computeRadiationOnMesh(directionTowardSun, null, solarPanel.getMesh(), solarPanel.getMesh(), faceDirection, false); final Mesh drawMesh = solarPanel.getMesh(); double[][] solar = solarOnMesh.get(drawMesh); if (solar == null) { solar = new double[1][1]; solarOnMesh.put(drawMesh, solar); } final double OFFSET = 0.1; final ReadOnlyVector3 offset = directionTowardSun.multiply(OFFSET, null); final ReadOnlyVector3 center = drawMesh.getTranslation(); final double dot = solarPanel.getFaceDirection().dot(directionTowardSun); final Ray3 pickRay = new Ray3(center.add(offset, null), directionTowardSun); final PickResults pickResults = new PrimitivePickResults(); for (final Spatial spatial : solarCollidables) if (spatial != drawMesh) { PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() != 0) break; } if (pickResults.getNumber() == 0) solar[0][0] += dot; } } } private void computeRadiationOnMesh(final ReadOnlyVector3 directionTowardSun, final HousePart housePart, final Mesh drawMesh, final Mesh collisionMesh, final ReadOnlyVector3 normal, final boolean addToTotal) { /* needed in order to prevent picking collision with neighboring wall at wall edge */ final double OFFSET = 0.1; final ReadOnlyVector3 offset = directionTowardSun.multiply(OFFSET, null); final AnyToXYTransform toXY = new AnyToXYTransform(normal.getX(), normal.getY(), normal.getZ()); final XYToAnyTransform fromXY = new XYToAnyTransform(normal.getX(), normal.getY(), normal.getZ()); final FloatBuffer vertexBuffer = collisionMesh.getMeshData().getVertexBuffer(); vertexBuffer.rewind(); double minX, minY, maxX, maxY; minX = minY = Double.POSITIVE_INFINITY; maxX = maxY = Double.NEGATIVE_INFINITY; double z = Double.NaN; final List<ReadOnlyVector2> points = new ArrayList<ReadOnlyVector2>(vertexBuffer.limit() / 3); while (vertexBuffer.hasRemaining()) { final Vector3 pWorld = drawMesh.localToWorld(new Vector3(vertexBuffer.get(), vertexBuffer.get(), vertexBuffer.get()), null); final Point p = new TPoint(pWorld.getX(), pWorld.getY(), pWorld.getZ()); toXY.transform(p); if (p.getX() < minX) minX = p.getX(); if (p.getX() > maxX) maxX = p.getX(); if (p.getY() < minY) minY = p.getY(); if (p.getY() > maxY) maxY = p.getY(); if (Double.isNaN(z)) z = p.getZ(); points.add(new Vector2(p.getX(), p.getY())); } final Point tmp = new TPoint(minX, minY, z); fromXY.transform(tmp); final ReadOnlyVector3 origin = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); tmp.set(minX, maxY, z); fromXY.transform(tmp); final ReadOnlyVector3 p1 = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); tmp.set(maxX, minY, z); fromXY.transform(tmp); final ReadOnlyVector3 p2 = new Vector3(tmp.getX(), tmp.getY(), tmp.getZ()); final double height = p1.subtract(origin, null).length(); final int rows = (int) Math.ceil(height / SOLAR_STEP); final int cols = (int) Math.ceil(p2.subtract(origin, null).length() / SOLAR_STEP); double[][] solar = solarOnMesh.get(drawMesh); if (solar == null) { solar = new double[roundToPowerOfTwo(rows)][roundToPowerOfTwo(cols)]; solarOnMesh.put(drawMesh, solar); } if (textureCoordsAlreadyComputed.get(drawMesh) == null) { final ReadOnlyVector2 originXY = new Vector2(minX, minY); final ReadOnlyVector2 uXY = new Vector2(maxX - minX, 0).normalizeLocal(); final ReadOnlyVector2 vXY = new Vector2(0, maxY - minY).normalizeLocal(); for (int row = 0; row < solar.length; row++) for (int col = 0; col < solar[0].length; col++) { if (row >= rows || col >= cols) solar[row][col] = -1; else { final ReadOnlyVector2 p = originXY.add(uXY.multiply(col * SOLAR_STEP, null), null).add(vXY.multiply(row * SOLAR_STEP, null), null); boolean isInside = false; for (int i = 0; i < points.size(); i += 3) { if (Util.isPointInsideTriangle(p, points.get(i), points.get(i + 1), points.get(i + 2))) { isInside = true; break; } } if (!isInside) solar[row][col] = -1; } } } final ReadOnlyVector3 u = p2.subtract(origin, null).normalizeLocal(); final ReadOnlyVector3 v = p1.subtract(origin, null).normalizeLocal(); final double dot = normal.dot(directionTowardSun); for (int col = 0; col < cols; col++) { final ReadOnlyVector3 pU = u.multiply(SOLAR_STEP / 2.0 + col * SOLAR_STEP, null).addLocal(origin); final double w = (col == cols - 1) ? p2.distance(pU) : SOLAR_STEP; for (int row = 0; row < rows; row++) { if (computeRequest) throw cancelException; if (solar[row][col] == -1) continue; final ReadOnlyVector3 p = v.multiply(SOLAR_STEP / 2.0 + row * SOLAR_STEP, null).addLocal(pU); final double h; if (row == rows - 1) h = height - (row * SOLAR_STEP); else h = SOLAR_STEP; final Ray3 pickRay = new Ray3(p.add(offset, null), directionTowardSun); final PickResults pickResults = new PrimitivePickResults(); for (final Spatial spatial : solarCollidables) if (spatial != collisionMesh) { PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() != 0) break; } if (pickResults.getNumber() == 0) { solar[row][col] += dot; final double annotationScale = Scene.getInstance().getAnnotationScale(); // final int repeat = 1; // if (addToTotal) { // final Double val = solarTotal.get(house); // final double solarValue = repeat * dot * w * h * annotationScale; // solarTotal.put(house, val == null ? 0 : val + solarValue); housePart.setSolarPotentialEnergy(housePart.getSolarPotentialEnergy() + dot * w * h * annotationScale * annotationScale); } } } if (textureCoordsAlreadyComputed.get(drawMesh) == null && !(housePart instanceof Window)) { updateRadiationMeshTextureCoords(drawMesh, origin, u, v, rows, cols); textureCoordsAlreadyComputed.put(drawMesh, Boolean.TRUE); } } private void updateRadiationMeshTextureCoords(final Mesh drawMesh, final ReadOnlyVector3 origin, final ReadOnlyVector3 uDir, final ReadOnlyVector3 vDir, final int rows, final int cols) { final ReadOnlyVector3 o = origin; final ReadOnlyVector3 u = uDir.multiply(roundToPowerOfTwo(cols) * EnergyPanel.SOLAR_STEP, null); final ReadOnlyVector3 v = vDir.multiply(roundToPowerOfTwo(rows) * EnergyPanel.SOLAR_STEP, null); final FloatBuffer vertexBuffer = drawMesh.getMeshData().getVertexBuffer(); final FloatBuffer textureBuffer = drawMesh.getMeshData().getTextureBuffer(0); vertexBuffer.rewind(); textureBuffer.rewind(); while (vertexBuffer.hasRemaining()) { final ReadOnlyVector3 p = drawMesh.localToWorld(new Vector3(vertexBuffer.get(), vertexBuffer.get(), vertexBuffer.get()), null); final Vector3 uP = Util.closestPoint(o, u, p, v.negate(null)); final float uScale = (float) (uP.distance(o) / u.length()); final Vector3 vP = Util.closestPoint(o, v, p, u.negate(null)); final float vScale = (float) (vP.distance(o) / v.length()); textureBuffer.put(uScale).put(vScale); } } private void computeRadiationOnLand(final ReadOnlyVector3 sunLocation) { if (sunLocation.getZ() <= 0) return; final ReadOnlyVector3 directionTowardSun = sunLocation.normalize(null); /* * needed in order to prevent picking collision with neighboring wall at wall edge */ // final double OFFSET = 0.1; // final ReadOnlyVector3 offset = directionTowardSun.multiply(OFFSET, null); final double SOLAR_STEP = EnergyPanel.SOLAR_STEP * 4; final int rows = (int) (256 / SOLAR_STEP); final int cols = rows; if (solarOnLand == null) solarOnLand = new double[rows][cols]; final Vector3 p = new Vector3(); for (int col = 0; col < cols; col++) { p.setX((col - cols / 2) * SOLAR_STEP + SOLAR_STEP / 2.0); for (int row = 0; row < rows; row++) { if (computeRequest) throw cancelException; p.setY((row - rows / 2) * SOLAR_STEP + SOLAR_STEP / 2.0); // final Ray3 pickRay = new Ray3(p.add(offset, null), directionTowardSun); final Ray3 pickRay = new Ray3(p, directionTowardSun); final PickResults pickResults = new PrimitivePickResults(); for (final Spatial spatial : solarCollidables) PickingUtil.findPick(spatial, pickRay, pickResults, false); if (pickResults.getNumber() == 0) solarOnLand[row][col] += directionTowardSun.dot(Vector3.UNIT_Z); } } } private void computeRadiationToday(final Calendar today) { final Heliodon heliodon = Heliodon.getInstance(); today.set(Calendar.SECOND, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.HOUR_OF_DAY, 0); for (int minute = 0; minute < 1440; minute += SOLAR_MINUTE_STEP) { final ReadOnlyVector3 sunLocation = heliodon.computeSunLocation(today).normalize(null); // final ReadOnlyVector3 sunLocation = heliodon.getSunLocation(); if (sunLocation.getZ() > 0) { final ReadOnlyVector3 directionTowardSun = sunLocation.normalize(null); for (final HousePart part : Scene.getInstance().getParts()) { if (part.isDrawCompleted()) if (part instanceof Wall || part instanceof Window || part instanceof SolarPanel) { // computeRadiationOnWalls(part, sunLocation); final ReadOnlyVector3 faceDirection = part.getFaceDirection(); if (faceDirection.dot(directionTowardSun) > 0) computeRadiationOnMesh(directionTowardSun, part, part.getMesh(), part instanceof Wall ? ((Wall) part).getInvisibleMesh() : part.getMesh(), faceDirection, true); } else if (part instanceof Roof) { // computeRadiationOnRoofs(part, sunLocation); for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { final ReadOnlyVector3 faceDirection = (ReadOnlyVector3) roofPart.getUserData(); if (faceDirection.dot(directionTowardSun) > 0) { final Mesh mesh = (Mesh) ((Node) roofPart).getChild(0); computeRadiationOnMesh(directionTowardSun, part, mesh, mesh, faceDirection, false); } } } // computeRadiationOnSolarPanels(sunLocation); computeRadiationOnLand(sunLocation); } } maxSolarValue++; today.add(Calendar.MINUTE, SOLAR_MINUTE_STEP); progress(); } maxSolarValue *= (100 - colorMapSlider.getValue()) / 100.0; } // private void updateSolarValueOnAllHouses() { // applySolarTexture(SceneManager.getInstance().getSolarLand(), solarOnLand, maxSolarValue); // for (final HousePart part : Scene.getInstance().getParts()) { // if (part instanceof Foundation) { // final List<Roof> roofs = new ArrayList<Roof>(); // final Foundation foundation = (Foundation) part; // for (final HousePart houseChild : foundation.getChildren()) { // if (houseChild instanceof Wall) { // final Wall wall = (Wall) houseChild; // applySolarTexture(houseChild.getMesh(), solarOnMesh.get(wall.getMesh()), maxSolarValue); // final Roof roof = (Roof) wall.getRoof(); // if (roof != null && !roofs.contains(roof)) // roofs.add(roof); // for (final Roof roof : roofs) // for (final Spatial roofPart : roof.getRoofPartsRoot().getChildren()) { // final Mesh mesh = (Mesh) ((Node) roofPart).getChild(0); // applySolarTexture(mesh, solarOnMesh.get(mesh), maxSolarValue); // final Double val = solarTotal.get(foundation); // foundation.setSolarValue(convertSolarValue(val)); // } else if (part instanceof SolarPanel) { // final Mesh mesh = part.getMesh(); // applySolarTexture(mesh, solarOnMesh.get(mesh), maxSolarValue); // SceneManager.getInstance().refresh(); private void updateSolarValueOnAllHouses() { applySolarTexture(SceneManager.getInstance().getSolarLand(), solarOnLand, maxSolarValue); for (final HousePart part : Scene.getInstance().getParts()) if (part instanceof Wall || part instanceof Window || part instanceof SolarPanel) applySolarTexture(part.getMesh(), solarOnMesh.get(part.getMesh()), maxSolarValue); else if (part instanceof Roof) for (final Spatial roofPart : ((Roof) part).getRoofPartsRoot().getChildren()) { final Mesh mesh = (Mesh) ((Node) roofPart).getChild(0); applySolarTexture(mesh, solarOnMesh.get(mesh), maxSolarValue); } for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) { final Foundation foundation = (Foundation) part; double totalSolar = 0.0; for (final HousePart houseChild : Scene.getInstance().getParts()) if (houseChild.getTopContainer() == foundation) totalSolar += houseChild.getSolarPotentialEnergy(); foundation.setSolarValue(convertSolarValue(totalSolar)); } } SceneManager.getInstance().refresh(); } public long convertSolarValue(final Double val) { return val == null ? 0 : val.longValue() / (60 / SOLAR_MINUTE_STEP); } // private void print(final HousePart part, final double[][] solar) { // System.out.println(part); // if (solar == null) // System.out.println("null"); // else // for (int i = 0; i < solar.length; i++) { // for (int j = 0; j < solar[0].length; j++) // System.out.print((int) Math.round(solar[i][j]) + " "); // System.out.println(); private void progress() { progressBar.setValue(progressBar.getValue() + 1); } public void setLatitude(final int latitude) { latitudeSpinner.setValue(latitude); } public int getLatitude() { return (Integer) latitudeSpinner.getValue(); } public int roundToPowerOfTwo(final int n) { return (int) Math.pow(2.0, Math.ceil(Math.log(n) / Math.log(2))); } public JSlider getColorMapSlider() { return colorMapSlider; } private void applySolarTexture(final Mesh mesh, final double[][] solarData, final long maxValue) { if (solarData != null) fillBlanksWithNeighboringValues(solarData); final int rows; final int cols; if (solarData == null) { rows = cols = 1; } else { rows = solarData.length; cols = solarData[0].length; } final ByteBuffer data = BufferUtils.createByteBuffer(cols * rows * 3); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { final double value = solarData == null ? 0 : solarData[row][col]; final ColorRGBA color = computeSolarColor(value, maxValue); data.put((byte) (color.getRed() * 255)).put((byte) (color.getGreen() * 255)).put((byte) (color.getBlue() * 255)); } } final Image image = new Image(ImageDataFormat.RGB, PixelDataType.UnsignedByte, cols, rows, data, null); final Texture2D texture = new Texture2D(); texture.setTextureKey(TextureKey.getRTTKey(MinificationFilter.NearestNeighborNoMipMaps)); texture.setImage(image); final TextureState textureState = new TextureState(); textureState.setTexture(texture); mesh.setRenderState(textureState); } private void fillBlanksWithNeighboringValues(final double[][] solarData) { final int rows = solarData.length; final int cols = solarData[0].length; for (int repeat = 0; repeat < 2; repeat++) for (int row = 0; row < rows; row++) for (int col = 0; col < cols; col++) if (solarData[row][col] == -1) if (solarData[row][(col + 1) % cols] != -1) solarData[row][col] = solarData[row][(col + 1) % cols]; else if (col != 0 && solarData[row][col - 1] != -1) solarData[row][col] = solarData[row][col - 1]; else if (col == 0 && solarData[row][cols - 1] != -1) solarData[row][col] = solarData[row][cols - 1]; else if (solarData[(row + 1) % rows][col] != -1) solarData[row][col] = solarData[(row + 1) % rows][col]; else if (row != 0 && solarData[row - 1][col] != -1) solarData[row][col] = solarData[row - 1][col]; else if (row == 0 && solarData[rows - 1][col] != -1) solarData[row][col] = solarData[rows - 1][col]; } private ColorRGBA computeSolarColor(final double value, final long maxValue) { final ReadOnlyColorRGBA[] colors = EnergyPanel.solarColors; long valuePerColorRange = maxValue / (colors.length - 1); final int colorIndex; if (valuePerColorRange == 0) { valuePerColorRange = 1; colorIndex = 0; } else colorIndex = (int) Math.min(value / valuePerColorRange, colors.length - 2); final float scalar = Math.min(1.0f, (float) (value - valuePerColorRange * colorIndex) / valuePerColorRange); final ColorRGBA color = new ColorRGBA().lerpLocal(colors[colorIndex], colors[colorIndex + 1], scalar); return color; } public void clearAlreadyRendered() { alreadyRenderedHeatmap = false; } public static void setKeepHeatmapOn(final boolean on) { keepHeatmapOn = on; } public void setComputeEnabled(final boolean computeEnabled) { this.computeEnabled = computeEnabled; } public Map<HousePart, Double> getSolarTotal() { return solarTotal; } @Override public void addPropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.add(pcl); } @Override public void removePropertyChangeListener(final PropertyChangeListener pcl) { propertyChangeListeners.remove(pcl); } private void notifyPropertyChangeListeners(final PropertyChangeEvent evt) { if (!propertyChangeListeners.isEmpty()) { for (final PropertyChangeListener x : propertyChangeListeners) { x.propertyChange(evt); } } } public void updatePartEnergy() { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); final TitledBorder titledBorder = (TitledBorder) partPanel.getBorder(); if (selectedPart == null) titledBorder.setTitle("Part"); else titledBorder.setTitle("Part - " + selectedPart.toString().substring(0, selectedPart.toString().indexOf(')') + 1)); partPanel.repaint(); if (selectedPart == null || selectedPart instanceof Foundation || selectedPart instanceof Door) partEnergyTextField.setText(""); else if (MainPanel.getInstance().getSolarButton().isSelected()) partEnergyTextField.setText(noDecimals.format(convertSolarValue(selectedPart.getSolarPotentialEnergy()))); else partEnergyTextField.setText("n/a"); final Foundation foundation = selectedPart == null ? null : (Foundation) selectedPart.getTopContainer(); if (foundation != null) { houseSolarPotentialTextField.setText("" + foundation.getSolarValue()); final double[] buildingGeometry = foundation.getBuildingGeometry(); positionTextField.setText("(" + buildingGeometry[3] + ", " + buildingGeometry[4] + ")"); heightTextField.setText("" + buildingGeometry[0]); areaTextField.setText("" + buildingGeometry[1]); volumnTextField.setText("" + buildingGeometry[2]); } else { heightTextField.setText("n/a"); areaTextField.setText("n/a"); volumnTextField.setText("n/a"); } } }
package org.tendiwa.lexeme; import com.google.common.base.Joiner; import java.util.Collections; import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.tendiwa.lexeme.implementations.English; /** * @since 0.1 */ public final class ParsedVocabularyTest { @Test public void findsWords() throws Exception { final ParsedVocabulary bundle = new ParsedVocabulary( new English().grammar(), Collections.singletonList( IOUtils.toInputStream( Joiner.on('\n').join( "\"dragon\" {", " dragon [Sing]", " dragons [Plur]", "}", "\"bee\" [Жен] {", " bee [Sing]", " bees [Plur]", "}" ) ) ) ); MatcherAssert.assertThat( bundle.lexemes().size(), CoreMatchers.equalTo(2) ); MatcherAssert.assertThat( bundle.lexemes().containsKey("dragon"), CoreMatchers.equalTo(true) ); MatcherAssert.assertThat( bundle.lexemes().get("dragon").baseForm(), CoreMatchers.equalTo("dragon") ); MatcherAssert.assertThat( bundle.lexemes().get("dragon").form( new BasicGrammaticalMeaning( English.Grammemes.Plur ) ), CoreMatchers.equalTo("dragons") ); } }
package gvs.business.logic; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; import gvs.access.Persistor; import gvs.business.logic.graph.Session; import gvs.business.logic.graph.SessionFactory; import gvs.business.logic.tree.TreeSessionController; import gvs.business.model.SessionHolder; import gvs.business.model.graph.Graph; import gvs.business.model.tree.Tree; import gvs.interfaces.ISession; import gvs.interfaces.ITreeSessionController; /** * The Application Controller reacts on events from the user or newly received * data. The requested operations will be executed. * * @author aegli * */ @Singleton public class ApplicationController { private final SessionFactory sessionFactory; private final Persistor persistor; private final SessionHolder sessionHolder; private static final Logger logger = LoggerFactory .getLogger(ApplicationController.class); /** * Constructor. * * @param sessionHolder * wrapper for the current session * @param persistor * persistor * @param graphSessionFactory * factory for new sessions */ @Inject public ApplicationController(SessionHolder sessionHolder, Persistor persistor, SessionFactory graphSessionFactory) { this.sessionHolder = sessionHolder; this.persistor = persistor; this.sessionFactory = graphSessionFactory; } /** * Sets session chosen from drop down, informs model and updates view. * * @param session * new current session */ public synchronized void changeCurrentSession(ISession session) { sessionHolder.setCurrentSession(session); } /** * Loads a session from a specific file. * * @param fileName * fileName */ public synchronized void loadStoredSession(String fileName) { logger.info("Load session from filesystem"); ISession loadedSession = persistor.loadFile(fileName); sessionHolder.addSession(loadedSession); sessionHolder.setCurrentSession(loadedSession); } /** * Deletes a chosen session. * * @param pSessionController * SessionController */ public synchronized void deleteSession(ISession pSessionController) { logger.info("Delete session"); sessionHolder.removeSession(pSessionController); if (sessionHolder.getSessions().size() > 0) { logger.debug("Session controller deleted. Set former graph session"); ISession formerSession = sessionHolder.getSessions().iterator().next(); sessionHolder.setCurrentSession(formerSession); } else { // when the last session is deleted, create empty dummy controller // otherwise session-bindings for UI would have to be unbound etc. logger.debug("Set empty graph session"); sessionHolder.setCurrentSession(sessionFactory.create(-1, "")); } } /** * Adds a new tree model, if an associated session exists, adds model to * session. Otherwise, creates a new tree session * * @param pTreeModel * TreeModel * @param pId * Id * @param pSessionName * SessionName */ public synchronized void addTreeToSession(Tree pTreeModel, long pId, String pSessionName) { logger.info("New Tree arrived"); // TODO merge with addGraphToSession Iterator<ISession> sessionIt = sessionHolder.getSessions().iterator(); boolean isSessionExisting = false; while (sessionIt.hasNext()) { ISession sc = (ISession) (sessionIt.next()); if (sc.getId() == pId) { logger.debug("Add tree to exsting session"); ((ITreeSessionController) sc).addTreeModel(pTreeModel); isSessionExisting = true; } } if (!isSessionExisting) { logger.debug("Build new tree session"); ITreeSessionController newSession = new TreeSessionController(pId, pSessionName, pTreeModel); sessionHolder.addSession(newSession); logger.debug("Set session as actual model"); sessionHolder.setCurrentSession(newSession); } } /** * Adds a new graph model, if an associated session exists, adds model to * session. Otherwise, creates a new graph session * * @param graph * graphModel * @param sessionId * Id * @param sessionName * sessionName */ public synchronized void addGraphToSession(Graph graph, long sessionId, String sessionName) { logger.info("Received new graph"); boolean isSessionExisting = false; for (ISession session : sessionHolder.getSessions()) { if (session.getId() == sessionId) { logger.info("Add graph to exsting session"); Session existingSession = (Session) session; existingSession.addGraph(graph); existingSession.changeCurrentGraphToLast(); existingSession.layoutCurrentGraph(null); isSessionExisting = true; } } if (!isSessionExisting) { logger.info("Create new session"); Session newSession = sessionFactory.create(sessionId, sessionName); newSession.addGraph(graph); newSession.getGraphHolder().setCurrentGraph(graph); newSession.layoutCurrentGraph(null); sessionHolder.addSession(newSession); sessionHolder.setCurrentSession(newSession); } } }
package com.namelessdev.mpdroid.helpers; import java.net.UnknownHostException; import java.util.Collection; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.MPDStatusMonitor; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.event.TrackPositionListener; import org.a0z.mpd.exception.MPDServerException; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import com.namelessdev.mpdroid.MPDApplication; import com.namelessdev.mpdroid.tools.Tools; import com.namelessdev.mpdroid.tools.WeakLinkedList; /** * This Class implements the whole MPD Communication as a thread. It also "translates" the monitor event of the JMPDComm Library back to the * GUI-Thread, and allows to execute custom commands asynchronously. * * @author sag * */ public class MPDAsyncHelper extends Handler { // Event-ID's for PMix internal events... private static final int EVENT_CONNECT = 0; private static final int EVENT_DISCONNECT = 1; private static final int EVENT_CONNECTFAILED = 2; private static final int EVENT_CONNECTSUCCEEDED = 3; private static final int EVENT_STARTMONITOR = 4; private static final int EVENT_STOPMONITOR = 5; private static final int EVENT_EXECASYNC = 6; private static final int EVENT_EXECASYNCFINISHED = 7; // Event-ID's for JMPDComm events (from the listener)... private static final int EVENT_CONNECTIONSTATE = 11; private static final int EVENT_PLAYLIST = 12; private static final int EVENT_RANDOM = 13; private static final int EVENT_REPEAT = 14; private static final int EVENT_STATE = 15; private static final int EVENT_TRACK = 16; private static final int EVENT_UPDATESTATE = 17; private static final int EVENT_VOLUME = 18; private static final int EVENT_TRACKPOSITION = 19; private MPDAsyncWorker oMPDAsyncWorker; private HandlerThread oMPDAsyncWorkerThread; private MPDStatusMonitor oMonitor; public MPD oMPD; private static int iJobID = 0; // PMix internal ConnectionListener interface public interface ConnectionListener { public void connectionFailed(String message); public void connectionSucceeded(String message); } // Interface for callback when Asynchronous operations are finished public interface AsyncExecListener { public void asyncExecSucceeded(int jobID); } // Listener Collections private Collection<ConnectionListener> connectionListners; private Collection<StatusChangeListener> statusChangedListeners; private Collection<TrackPositionListener> trackPositionListeners; private Collection<AsyncExecListener> asyncExecListeners; // Current connection Information private MPDConnectionInfo conInfo; /** * Private constructor for static class */ public MPDAsyncHelper() { oMPD = new MPD(); oMPDAsyncWorkerThread = new HandlerThread("MPDAsyncWorker"); oMPDAsyncWorkerThread.start(); oMPDAsyncWorker = new MPDAsyncWorker(oMPDAsyncWorkerThread.getLooper()); connectionListners = new WeakLinkedList<ConnectionListener>("ConnectionListener"); statusChangedListeners = new WeakLinkedList<StatusChangeListener>("StatusChangeListener"); trackPositionListeners = new WeakLinkedList<TrackPositionListener>("TrackPositionListener"); asyncExecListeners = new WeakLinkedList<AsyncExecListener>("AsyncExecListener"); conInfo = new MPDConnectionInfo(); } /** * This method handles Messages, which comes from the AsyncWorker. This Message handler runs in the UI-Thread, and can therefore send * the information back to the listeners of the matching events... */ public void handleMessage(Message msg) { try { Object[] args = (Object[]) msg.obj; switch (msg.what) { case EVENT_CONNECTIONSTATE: for (StatusChangeListener listener : statusChangedListeners) listener.connectionStateChanged((Boolean)args[0], (Boolean)args[1]); // Also notify Connection Listener... if((Boolean)args[0]) for (ConnectionListener listener : connectionListners) listener.connectionSucceeded(""); if((Boolean)args[1]) for (ConnectionListener listener : connectionListners) listener.connectionFailed("Connection Lost"); break; case EVENT_PLAYLIST: for (StatusChangeListener listener : statusChangedListeners) listener.playlistChanged((MPDStatus)args[0], (Integer)args[1]); break; case EVENT_RANDOM: for (StatusChangeListener listener : statusChangedListeners) listener.randomChanged((Boolean)args[0]); break; case EVENT_REPEAT: for (StatusChangeListener listener : statusChangedListeners) listener.repeatChanged((Boolean)args[0]); break; case EVENT_STATE: for (StatusChangeListener listener : statusChangedListeners) listener.stateChanged((MPDStatus)args[0], (String)args[1]); break; case EVENT_TRACK: for (StatusChangeListener listener : statusChangedListeners) listener.trackChanged((MPDStatus) args[0], (Integer)args[1]); break; case EVENT_UPDATESTATE: for (StatusChangeListener listener : statusChangedListeners) listener.libraryStateChanged((Boolean)args[0]); break; case EVENT_VOLUME: for (StatusChangeListener listener : statusChangedListeners) listener.volumeChanged((MPDStatus) args[0], ((Integer) args[1])); break; case EVENT_TRACKPOSITION: for (TrackPositionListener listener : trackPositionListeners) listener.trackPositionChanged((MPDStatus) args[0]); break; case EVENT_CONNECTFAILED: for (ConnectionListener listener : connectionListners) listener.connectionFailed((String) args[0]); break; case EVENT_CONNECTSUCCEEDED: for (ConnectionListener listener : connectionListners) listener.connectionSucceeded(null); break; case EVENT_EXECASYNCFINISHED: // Asynchronous operation finished, call the listeners and supply the JobID... for (AsyncExecListener listener : asyncExecListeners) if (listener != null) listener.asyncExecSucceeded(msg.arg1); break; } } catch(ClassCastException e) { // happens when unknown message type is received } } public MPDConnectionInfo getConnectionSettings() { return conInfo; } public void connect() { oMPDAsyncWorker.obtainMessage(EVENT_CONNECT, conInfo).sendToTarget(); } public void disconnect() { oMPDAsyncWorker.obtainMessage(EVENT_DISCONNECT).sendToTarget(); } public void startMonitor() { oMPDAsyncWorker.obtainMessage(EVENT_STARTMONITOR).sendToTarget(); } public void stopMonitor() { oMPDAsyncWorker.obtainMessage(EVENT_STOPMONITOR).sendToTarget(); } public boolean isMonitorAlive() { if (oMonitor == null) return false; else return oMonitor.isAlive() & !oMonitor.isGivingUp(); } /** * Executes a Runnable Asynchronous. Meant to use for individual long during operations on JMPDComm. Use this method only, when the code * to execute is only used once in the project. If its use more than once, implement individual events and listener in this class. * * @param run * Runnable to execute async * @return JobID, which is brought back with the AsyncExecListener interface... */ public int execAsync(Runnable run) { int actjobid = iJobID++; oMPDAsyncWorker.obtainMessage(EVENT_EXECASYNC, actjobid, 0, run).sendToTarget(); return actjobid; } public void addStatusChangeListener(StatusChangeListener listener) { statusChangedListeners.add(listener); } public void addTrackPositionListener(TrackPositionListener listener) { trackPositionListeners.add(listener); } public void addConnectionListener(ConnectionListener listener) { connectionListners.add(listener); } public void addAsyncExecListener(AsyncExecListener listener) { asyncExecListeners.add(listener); } public void removeAsyncExecListener(AsyncExecListener listener) { asyncExecListeners.remove(listener); } public void removeStatusChangeListener(StatusChangeListener listener) { statusChangedListeners.remove(listener); } public void removeTrackPositionListener(TrackPositionListener listener) { trackPositionListeners.remove(listener); } public void removeConnectionListener(ConnectionListener listener) { connectionListners.remove(listener); } /** * Asynchronous worker thread-class for long during operations on JMPDComm * */ public class MPDAsyncWorker extends Handler implements StatusChangeListener, TrackPositionListener { public MPDAsyncWorker(Looper looper) { super(looper); } public void handleMessage(Message msg) { switch (msg.what) { case EVENT_CONNECT: try { MPDConnectionInfo conInfo = (MPDConnectionInfo) msg.obj; if (oMPD != null) { oMPD.connect(conInfo.sServer, conInfo.iPort); if (conInfo.sPassword != null) oMPD.password(conInfo.sPassword); MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTSUCCEEDED).sendToTarget(); } } catch (MPDServerException e) { MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTFAILED, Tools.toObjectArray(e.getMessage())).sendToTarget(); } catch (UnknownHostException e) { MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTFAILED, Tools.toObjectArray(e.getMessage())).sendToTarget(); } break; case EVENT_STARTMONITOR: if (oMonitor != null) { oMonitor = new MPDStatusMonitor(oMPD, 500); oMonitor.addStatusChangeListener(this); oMonitor.addTrackPositionListener(this); oMonitor.start(); } break; case EVENT_STOPMONITOR: if (oMonitor != null) oMonitor.giveup(); break; case EVENT_DISCONNECT: try { if (oMPD != null) oMPD.disconnect(); Log.d(MPDApplication.TAG, "Disconnected"); } catch (MPDServerException e) { Log.e(MPDApplication.TAG, "Error on disconnect", e);//Silent exception are dangerous } //Should not happen anymore //catch (NullPointerException ex) { break; case EVENT_EXECASYNC: Runnable run = (Runnable) msg.obj; run.run(); MPDAsyncHelper.this.obtainMessage(EVENT_EXECASYNCFINISHED, msg.arg1, 0).sendToTarget(); default: break; } } // Send all events as Messages back to the GUI-Thread @Override public void trackPositionChanged(MPDStatus status) { MPDAsyncHelper.this.obtainMessage(EVENT_TRACKPOSITION, Tools.toObjectArray(status)).sendToTarget(); } @Override public void volumeChanged(MPDStatus mpdStatus, int oldVolume) { MPDAsyncHelper.this.obtainMessage(EVENT_VOLUME, Tools.toObjectArray(mpdStatus, oldVolume)).sendToTarget(); } @Override public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) { MPDAsyncHelper.this.obtainMessage(EVENT_PLAYLIST, Tools.toObjectArray(mpdStatus, oldPlaylistVersion)).sendToTarget(); } @Override public void trackChanged(MPDStatus mpdStatus, int oldTrack) { MPDAsyncHelper.this.obtainMessage(EVENT_TRACK, Tools.toObjectArray(mpdStatus, oldTrack)).sendToTarget(); } @Override public void stateChanged(MPDStatus mpdStatus, String oldState) { MPDAsyncHelper.this.obtainMessage(EVENT_STATE, Tools.toObjectArray(mpdStatus, oldState)).sendToTarget(); } @Override public void repeatChanged(boolean repeating) { MPDAsyncHelper.this.obtainMessage(EVENT_REPEAT, Tools.toObjectArray(repeating)).sendToTarget(); } @Override public void randomChanged(boolean random) { MPDAsyncHelper.this.obtainMessage(EVENT_RANDOM, Tools.toObjectArray(random)).sendToTarget(); } @Override public void connectionStateChanged(boolean connected, boolean connectionLost) { MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTIONSTATE, Tools.toObjectArray(connected, connectionLost)).sendToTarget(); } @Override public void libraryStateChanged(boolean updating) { MPDAsyncHelper.this.obtainMessage(EVENT_UPDATESTATE, Tools.toObjectArray(updating)).sendToTarget(); } } public class MPDConnectionInfo { public String sServer; public int iPort; public String sPassword; public String sServerStreaming; public int iPortStreaming; public String sSuffixStreaming = ""; public String getConnectionStreamingServer() { return conInfo.sServerStreaming == null ? sServer : sServerStreaming; } } }
package org.lightmare.jpa.jta; /** * Properties to use for hibernate * * @author levan * */ public enum HibernateConfig { PLATFORM, FACTORY; public static final String PLATFORM_KEY = "hibernate.transaction.jta.platform"; public static final String PLATFORM_VALUE = "org.hibernate.service.jta.platform.internal.BitronixJtaPlatform"; public static final String FACTORY_KEY = "hibernate.transaction.factory_class"; public static final String FACTORY_VALUE = "org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory"; }
package org.elixirian.kommonlee.util; import static org.elixirian.kommonlee.util.Objects.toStringOf; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Strings { private Strings() throws IllegalAccessException { throw new IllegalAccessException(getClass().getName() + CommonConstants.CANNOT_BE_INSTANTIATED); } /** * Returns a copy of the given string, with leading and trailing whitespace omitted. If the given String contains * <code>null</code> reference it returns an "" (empty String). * * @param value * the given String value * @return the result of value.trim(). If the value is null, return "" (empty String). */ public static String nullSafeTrim(final String value) { return (null == value ? "" : value.trim()); } /** * Returns an empty String ({@code ""}) if the given value is {@code null}. If it is not {@code null}, returns the * given value itself. * * @param value * the given String value to check for nullity. * @return an empty String ({@code ""}) if the given value is {@code null}. If it is not {@code null}, returns the * given value itself */ public static String nullThenEmpty(final String value) { return null == value ? "" : value; } /** * Returns {@code null} if the given String variable is empty (its length is 0, {@code ""}) or it is null. If it is * not empty, returns the given value itself. * * @param value * the given String value to check for emptiness. * @return {@code null} if the given String variable is empty (its length is 0, {@code ""}) or it is null. If it is * not empty, returns the given value itself. */ public static String emptyThenNull(final String value) { return isNullOrEmpty(value) ? null : value; } /** * Checks if the given String value is empty. It means the given String parameter contains the null reference or no * String value which means its length is 0. * * @param value * the given String value. * @return true if the given String parameter contains the null reference or it has no String value (null == value || * 0 == value.length()). false if the given String parameter contains a reference pointing to any String value * having the length of which is greater than 0. */ public static boolean isNullOrEmpty(final String value) { return (null == value || 0 == value.length()); } /** * Checks if the given String value is not empty. It means the given String parameter contains neither the null * reference nor any String with 0 length. * * @param value * the given String value. * @return true if the given String parameter contains a reference pointing to any String object the length of which * is greater than 0 (null != value && 0 < value.length()). false if it contains null or a String value with 0 * length. */ public static boolean isNeitherNullNorEmpty(final String value) { return !isNullOrEmpty(value); } public static String repeat(final String value, final int times) throws IllegalArgumentException { if (0 > times) { throw new IllegalArgumentException( "The value of the times parameter cannot be a negative number. It must be a non-negative number."); } final String valueToUse = toStringOf(value); final StringBuilder stringBuilder = new StringBuilder(valueToUse.length() * times); for (int i = 0; i < times; i++) { stringBuilder.append(valueToUse); } return stringBuilder.toString(); } public static String[] findMatched(final String regex, final String value) { final Pattern pattern = Pattern.compile(regex); return findMatched(pattern, value); } public static String[] findMatched(final Pattern pattern, final String value) { final Matcher matcher = pattern.matcher(value); if (matcher.find()) { final int length = matcher.groupCount() + 1; final String[] textFound = new String[length]; for (int i = 0; i < length; i++) { textFound[i] = matcher.group(i); } return textFound; } return NeoArrays.EMPTY_STRING_ARRAY; } public static String[] matchEntirely(final String regex, final String value) { final Pattern pattern = Pattern.compile(regex); return matchEntirely(pattern, value); } public static String[] matchEntirely(final Pattern pattern, final String value) { final Matcher matcher = pattern.matcher(value); if (matcher.matches()) { final int length = matcher.groupCount() + 1; final String[] textMatched = new String[length]; for (int i = 0; i < length; i++) { textMatched[i] = matcher.group(i); } return textMatched; } return NeoArrays.EMPTY_STRING_ARRAY; } }
package seedu.tasklist.commons.util; import static org.junit.Assert.assertNotNull; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class AppUtilTest { @Rule public ExpectedException thrown = ExpectedException.none(); //author A0141993X @Test public void getImage_existingImage() { assertNotNull(AppUtil.getImage("/images/flexiTaskAppIcon.png")); } @Test public void getImage_nonExistingImage() { thrown.expect(NullPointerException.class); AppUtil.getImage("/images/flexiTaskAppIcon2.png"); } //@@author @Test public void getImage_nullGiven_assertionError() { thrown.expect(AssertionError.class); AppUtil.getImage(null); } }
package hudson.plugins.copyartifact; import com.thoughtworks.xstream.converters.UnmarshallingContext; import hudson.DescriptorExtensionList; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.console.HyperlinkNote; import hudson.diagnosis.OldDataMonitor; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.matrix.MatrixRun; import hudson.maven.MavenModuleSet; import hudson.maven.MavenModuleSetBuild; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.model.EnvironmentContributingAction; import hudson.model.Fingerprint; import hudson.model.FingerprintMap; import hudson.model.Hudson; import hudson.model.Job; import hudson.model.Item; import hudson.model.Project; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.listeners.ItemListener; import hudson.model.listeners.RunListener; import hudson.security.AccessControlled; import hudson.security.SecurityRealm; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.tasks.Fingerprinter.FingerprintAction; import hudson.util.DescribableList; import hudson.util.FormValidation; import hudson.util.XStream2; import java.io.IOException; import java.io.PrintStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.providers.UsernamePasswordAuthenticationToken; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; /** * Build step to copy artifacts from another project. * @author Alan Harder */ public class CopyArtifact extends Builder { private String projectName; private final String filter, target; private /*almost final*/ BuildSelector selector; @Deprecated private transient Boolean stable; private final Boolean flatten, optional; @DataBoundConstructor public CopyArtifact(String projectName, BuildSelector selector, String filter, String target, boolean flatten, boolean optional) { // Prevents both invalid values and access to artifacts of projects which this user cannot see. // If value is parameterized, it will be checked when build runs. if (projectName.indexOf('$') < 0 && new JobResolver(projectName).job == null) projectName = ""; // Ignore/clear bad value to avoid ugly 500 page this.projectName = projectName; this.selector = selector; this.filter = Util.fixNull(filter).trim(); this.target = Util.fixNull(target).trim(); this.flatten = flatten ? Boolean.TRUE : null; this.optional = optional ? Boolean.TRUE : null; } // Upgrade data from old format public static class ConverterImpl extends XStream2.PassthruConverter<CopyArtifact> { public ConverterImpl(XStream2 xstream) { super(xstream); } @Override protected void callback(CopyArtifact obj, UnmarshallingContext context) { if (obj.selector == null) { obj.selector = new StatusBuildSelector(obj.stable != null && obj.stable.booleanValue()); OldDataMonitor.report(context, "1.355"); // Core version# when CopyArtifact 1.2 released } } } public String getProjectName() { return projectName; } public BuildSelector getBuildSelector() { return selector; } public String getFilter() { return filter; } public String getTarget() { return target; } public boolean isFlatten() { return flatten != null && flatten.booleanValue(); } public boolean isOptional() { return optional != null && optional.booleanValue(); } @Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException { PrintStream console = listener.getLogger(); String expandedProject = projectName, expandedFilter = filter; try { EnvVars env = build.getEnvironment(listener); env.overrideAll(build.getBuildVariables()); // Add in matrix axes.. expandedProject = env.expand(projectName); JobResolver job = new JobResolver(expandedProject); if (job.job != null && !expandedProject.equals(projectName) // Authentication object for arbitrary user.. instead, only allow use of parameters // to select jobs which are accessible to all authenticated users. && !job.job.getACL().hasPermission( new UsernamePasswordAuthenticationToken("authenticated", "", new GrantedAuthority[]{ SecurityRealm.AUTHENTICATED_AUTHORITY }), Item.READ)) { job.job = null; // Disallow access } if (job.job == null) { console.println(Messages.CopyArtifact_MissingProject(expandedProject)); return false; } Run src = selector.getBuild(job.job, env, job.filter, build); if (src == null) { console.println(Messages.CopyArtifact_MissingBuild(expandedProject)); return isOptional(); // Fail build unless copy is optional } FilePath targetDir = build.getWorkspace(), baseTargetDir = targetDir; if (targetDir == null || !targetDir.exists()) { console.println(Messages.CopyArtifact_MissingWorkspace()); // (see JENKINS-3330) return isOptional(); // Fail build unless copy is optional } // Add info about the selected build into the environment EnvAction envData = build.getAction(EnvAction.class); if (envData != null) { envData.add(expandedProject, src.getNumber()); } if (target.length() > 0) targetDir = new FilePath(targetDir, env.expand(target)); expandedFilter = env.expand(filter); if (expandedFilter.trim().length() == 0) expandedFilter = "**"; CopyMethod copier = Hudson.getInstance().getExtensionList(CopyMethod.class).get(0); if (src instanceof MavenModuleSetBuild) { // Copy artifacts from the build (ArchiveArtifacts build step) boolean ok = perform(src, build, expandedFilter, targetDir, baseTargetDir, copier, console); // Copy artifacts from all modules of this Maven build (automatic archiving) for (Run r : ((MavenModuleSetBuild)src).getModuleLastBuilds().values()) ok |= perform(r, build, expandedFilter, targetDir, baseTargetDir, copier, console); return ok; } else if (src instanceof MatrixBuild) { boolean ok = false; // Copy artifacts from all configurations of this matrix build for (Run r : getMatrixRuns((MatrixBuild)src)) // Use subdir of targetDir with configuration name (like "jdk=java6u20") ok |= perform(r, build, expandedFilter, targetDir.child(r.getParent().getName()), baseTargetDir, copier, console); return ok; } else { return perform(src, build, expandedFilter, targetDir, baseTargetDir, copier, console); } } catch (IOException ex) { Util.displayIOException(ex, listener); ex.printStackTrace(listener.error( Messages.CopyArtifact_FailedToCopy(expandedProject, expandedFilter))); return false; } } private boolean perform(Run src, AbstractBuild<?,?> dst, String expandedFilter, FilePath targetDir, FilePath baseTargetDir, CopyMethod copier, PrintStream console) throws IOException, InterruptedException { // Check special case for copying from workspace instead of artifacts: boolean useWs = (selector instanceof WorkspaceSelector && src instanceof AbstractBuild); FilePath srcDir = useWs ? ((AbstractBuild)src).getWorkspace() : new FilePath(src.getArtifactsDir()); if (srcDir == null || !srcDir.exists()) { console.println(useWs ? Messages.CopyArtifact_MissingSrcWorkspace() // (see JENKINS-3330) : Messages.CopyArtifact_MissingSrcArtifacts()); return isOptional(); // Fail build unless copy is optional } copier.init(srcDir, baseTargetDir); int cnt; if (!isFlatten()) cnt = copier.copyAll(srcDir, expandedFilter, targetDir); else { targetDir.mkdirs(); // Create target if needed FilePath[] list = srcDir.list(expandedFilter); for (FilePath file : list) copier.copyOne(file, new FilePath(targetDir, file.getName())); cnt = list.length; } if (src instanceof AbstractBuild) { FingerprintMap map = Hudson.getInstance().getFingerprintMap(); Map<String,String> fingerprints = new HashMap<String, String>(); FilePath[] list = srcDir.list(expandedFilter); for (FilePath file : list) { String digest = file.digest(); Fingerprint f = map.getOrCreate(src, file.getName(), digest); f.add((AbstractBuild)src); f.add(dst); fingerprints.put(file.getName(), digest); } // add action FingerprintAction fa = dst.getAction(FingerprintAction.class); if (fa != null) fa.add(fingerprints); else dst.getActions().add(new FingerprintAction(dst, fingerprints)); } console.println(Messages.CopyArtifact_Copied(cnt, HyperlinkNote.encodeTo('/'+ src.getParent().getUrl(), src.getParent().getFullDisplayName()), HyperlinkNote.encodeTo('/'+src.getUrl(), Integer.toString(src.getNumber())))); // Fail build if 0 files copied unless copy is optional return cnt > 0 || isOptional(); } // TODO: remove this method and use getExactRuns directly once minimum core is 1.413+ private static List<MatrixRun> getMatrixRuns(MatrixBuild build) { // Use MatrixBuild.getExactRuns if available try { return (List<MatrixRun>)build.getClass().getMethod("getExactRuns").invoke(build); } catch (Exception ignore) {} return build.getRuns(); } // Find the job from the given name; usually just a Hudson.getItemByFullName lookup, // but this class encapsulates additional logic like filtering on parameters. private static class JobResolver { Job<?,?> job; BuildFilter filter = new BuildFilter(); JobResolver(String projectName) { Hudson hudson = Hudson.getInstance(); job = hudson.getItemByFullName(projectName, Job.class); if (job == null) { // Check for parameterized job with filter (see help file) int i = projectName.indexOf('/'); if (i > 0) { Job<?,?> candidate = hudson.getItemByFullName(projectName.substring(0, i), Job.class); if (candidate != null) { ParametersBuildFilter pFilter = new ParametersBuildFilter(projectName.substring(i + 1)); if (pFilter.isValid(candidate)) { job = candidate; filter = pFilter; } } } } } } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public FormValidation doCheckProjectName( @AncestorInPath AccessControlled anc, @QueryParameter String value) { if (!anc.hasPermission(Item.CONFIGURE)) return FormValidation.ok(); FormValidation result; Item item = new JobResolver(value).job; if (item != null) result = item instanceof MavenModuleSet ? FormValidation.warning(Messages.CopyArtifact_MavenProject()) : (item instanceof MatrixProject ? FormValidation.warning(Messages.CopyArtifact_MatrixProject()) : FormValidation.ok()); else if (value.indexOf('$') >= 0) result = FormValidation.warning(Messages.CopyArtifact_ParameterizedName()); else result = FormValidation.error( hudson.tasks.Messages.BuildTrigger_NoSuchProject( value, AbstractProject.findNearest(value).getName())); return result; } public boolean isApplicable(Class<? extends AbstractProject> clazz) { return true; } public String getDisplayName() { return Messages.CopyArtifact_DisplayName(); } public DescriptorExtensionList<BuildSelector,Descriptor<BuildSelector>> getBuildSelectors() { return Hudson.getInstance().<BuildSelector,Descriptor<BuildSelector>>getDescriptorList(BuildSelector.class); } } // Listen for project renames and update property here if needed. @Extension public static final class ListenerImpl extends ItemListener { @Override public void onRenamed(Item item, String oldName, String newName) { for (AbstractProject<?,?> project : Hudson.getInstance().getAllItems(AbstractProject.class)) { for (CopyArtifact ca : getCopiers(project)) try { if (ca.getProjectName().equals(oldName)) ca.projectName = newName; else if (ca.getProjectName().startsWith(oldName + '/')) // Support rename for "MatrixJobName/AxisName=value" type of name ca.projectName = newName + ca.projectName.substring(oldName.length()); else continue; project.save(); } catch (IOException ex) { Logger.getLogger(ListenerImpl.class.getName()).log(Level.WARNING, "Failed to resave project " + project.getName() + " for project rename in CopyArtifact build step (" + oldName + " =>" + newName + ")", ex); } } } private static List<CopyArtifact> getCopiers(AbstractProject project) { DescribableList<Builder,Descriptor<Builder>> list = project instanceof Project ? ((Project<?,?>)project).getBuildersList() : (project instanceof MatrixProject ? ((MatrixProject)project).getBuildersList() : null); if (list == null) return Collections.emptyList(); return (List<CopyArtifact>)list.getAll(CopyArtifact.class); } } // Listen for new builds and add EnvAction in any that use CopyArtifact build step @Extension public static final class CopyArtifactRunListener extends RunListener<Build> { public CopyArtifactRunListener() { super(Build.class); } @Override public void onStarted(Build r, TaskListener listener) { if (((Build<?,?>)r).getProject().getBuildersList().get(CopyArtifact.class) != null) r.addAction(new EnvAction()); } } private static class EnvAction implements EnvironmentContributingAction { // Decided not to record this data in build.xml, so marked transient: private transient Map<String,String> data = new HashMap<String,String>(); private void add(String projectName, int buildNumber) { if (data==null) return; int i = projectName.indexOf('/'); // Omit any detail after a / if (i > 0) projectName = projectName.substring(0, i); data.put("COPYARTIFACT_BUILD_NUMBER_" + projectName.toUpperCase().replaceAll("[^A-Z]+", "_"), // Only use letters and _ Integer.toString(buildNumber)); } public void buildEnvVars(AbstractBuild<?,?> build, EnvVars env) { if (data!=null) env.putAll(data); } public String getIconFileName() { return null; } public String getDisplayName() { return null; } public String getUrlName() { return null; } } }
package org.lightmare.libraries; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.lightmare.libraries.loaders.EjbClassLoader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Class for load jar or class files from specified path * * @author levan * */ public class LibraryLoader { private static final String ADD_URL_METHOD_NAME = "addURL"; private static final String CLOSE_METHOD_NAME = "close"; private static final String LOADER_THREAD_NAME = "library-class-loader-thread"; private static Method addURLMethod; private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(LibraryLoader.class); /** * implementation of {@link Callable}<ClassLoader> interface to initialize * {@link ClassLoader} in separate thread * * @author levan * */ private static class LibraryLoaderInit implements Callable<ClassLoader> { private URL[] urls; private ClassLoader parent; public LibraryLoaderInit(final URL[] urls, final ClassLoader parent) { this.urls = urls; this.parent = parent; } @Override public ClassLoader call() throws Exception { ClassLoader loader = cloneContextClassLoader(urls, parent); return loader; } } /** * Gets {@link URLClassLoader} class addURL method * * @return Method * @throws IOException */ private static Method getURLMethod() throws IOException { if (addURLMethod == null) { LOCK.lock(); try { if (addURLMethod == null && MetaUtils.hasMethod(URLClassLoader.class, ADD_URL_METHOD_NAME)) { addURLMethod = MetaUtils.getDeclaredMethod( URLClassLoader.class, ADD_URL_METHOD_NAME, URL.class); } } finally { LOCK.unlock(); } } return addURLMethod; } /** * If passed {@link ClassLoader} is instance of {@link URLClassLoader} then * gets {@link URL}[] of this {@link ClassLoader} calling * {@link URLClassLoader#getURLs()} method * * @param loader * @return {@link URL}[] */ private static URL[] getURLs(ClassLoader loader) { URL[] urls; if (loader instanceof URLClassLoader) { urls = ((URLClassLoader) loader).getURLs(); } else { urls = CollectionUtils.emptyArray(URL.class); } return urls; } /** * Initializes and returns enriched {@link ClassLoader} in separated * {@link Thread} to load bean and library classes * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader initializeLoader(final URL[] urls) throws IOException { ClassLoader parent = getContextClassLoader(); LibraryLoaderInit initializer = new LibraryLoaderInit(urls, parent); FutureTask<ClassLoader> task = new FutureTask<ClassLoader>(initializer); Thread thread = new Thread(task); thread.setName(LOADER_THREAD_NAME); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); ClassLoader ejbLoader; try { ejbLoader = task.get(); } catch (InterruptedException ex) { throw new IOException(ex); } catch (ExecutionException ex) { throw new IOException(ex); } return ejbLoader; } /** * Gets current {@link Thread}'s context {@link ClassLoader} object * * @return {@link ClassLoader} */ public static ClassLoader getContextClassLoader() { PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() { public ClassLoader run() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); return classLoader; } }; ClassLoader loader = AccessController.doPrivileged(action); return loader; } /** * Gets new {@link ClassLoader} enriched with passed {@link URL} array and * parent {@link ClassLoader} classes * * @param urls * @param parent * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(URL[] urls, ClassLoader parent) { ClassLoader enrichedLoader; if (CollectionUtils.available(urls)) { if (parent == null) { parent = getContextClassLoader(); } enrichedLoader = EjbClassLoader.newInstance(urls, parent); } else { enrichedLoader = null; } return enrichedLoader; } /** * Gets new {@link ClassLoader} enriched with passed {@link File} and it's * sub files {@link URL}s and parent {@link ClassLoader} classes * * @param file * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(File file, Set<URL> urls) throws IOException { FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader parent = getContextClassLoader(); ClassLoader enrichedLoader = getEnrichedLoader(paths, parent); return enrichedLoader; } /** * Initializes new {@link ClassLoader} from loaded {@link URL}'s from * enriched {@link ClassLoader} for beans and libraries * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader cloneContextClassLoader(final URL[] urls, ClassLoader parent) throws IOException { URLClassLoader loader = (URLClassLoader) getEnrichedLoader(urls, parent); try { // get all resources for cloning URL[] urlArray = loader.getURLs(); URL[] urlClone = urlArray.clone(); if (parent == null) { parent = getContextClassLoader(); } ClassLoader clone = EjbClassLoader.newInstance(urlClone, parent); return clone; } finally { closeClassLoader(loader); // dereference cloned class loader instance loader = null; } } /** * Merges two {@link ClassLoader}s in one * * @param newLoader * @param oldLoader * @return {@link ClassLoader} */ public static ClassLoader createCommon(ClassLoader newLoader, ClassLoader oldLoader) { URL[] urls = getURLs(oldLoader); ClassLoader commonLoader = URLClassLoader.newInstance(urls, oldLoader); urls = getURLs(newLoader); commonLoader = getEnrichedLoader(urls, newLoader); return commonLoader; } /** * Sets passed {@link Thread}'s context class loader appropriated * {@link ClassLoader} instance * * @param thread * @param loader */ public static void loadCurrentLibraries(Thread thread, ClassLoader loader) { if (ObjectUtils.notNull(loader)) { thread.setContextClassLoader(loader); } } /** * Sets passed {@link ClassLoader} instance as current {@link Thread}'s * context class loader * * @param loader */ public static void loadCurrentLibraries(ClassLoader loader) { Thread thread = Thread.currentThread(); loadCurrentLibraries(thread, loader); } /** * Adds {@link URL} array to system {@link ClassLoader} instance * * @param urls * @param method * @param urlLoader * @throws IOException */ public static void loadURLToSystem(URL[] urls, Method method, URLClassLoader urlLoader) throws IOException { for (URL url : urls) { MetaUtils.invokePrivate(method, urlLoader, url); } } /** * Loads all files and sub files {@link URL}s to system class loader * * @param libraryPath * @throws IOException */ private static void loadLibraryFromPath(String libraryPath) throws IOException { File file = new File(libraryPath); if (file.exists()) { Set<URL> urls = new HashSet<URL>(); FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); if (systemLoader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) systemLoader; Method method = getURLMethod(); if (ObjectUtils.notNull(method)) { loadURLToSystem(paths, method, urlLoader); } } } } /** * Loads jar or <code>.class</code> files to the current thread from * libraryPaths recursively * * @param libraryPaths * @throws IOException */ public static void loadLibraries(String... libraryPaths) throws IOException { if (ObjectUtils.available(libraryPaths)) { for (String libraryPath : libraryPaths) { loadLibraryFromPath(libraryPath); } } } /** * Loads passed classes to specified {@link ClassLoader} instance * * @param classes * @param loader */ public static void loadClasses(Collection<String> classes, ClassLoader loader) throws IOException { if (ObjectUtils.available(classes) && ObjectUtils.notNull(loader)) { for (String className : classes) { try { loader.loadClass(className); } catch (ClassNotFoundException ex) { throw new IOException(ex); } } } } /** * Loads passed classes to specified current {@link Thread}'s context class * loader * * @param classes */ public static void loadClasses(Collection<String> classes) throws IOException { ClassLoader loader = getContextClassLoader(); loadClasses(classes, loader); } /** * Closes passed {@link ClassLoader} if it is instance of * {@link URLClassLoader} class * * @param loader * @throws IOException */ public static void closeClassLoader(ClassLoader loader) throws IOException { if (ObjectUtils.notNull(loader) && loader instanceof URLClassLoader) { try { loader.clearAssertionStatus(); // Finds if loader associated class or superclass has "close" // method Class<?> loaderClass = loader.getClass(); boolean hasMethod = MetaUtils.hasPublicMethod(loaderClass, CLOSE_METHOD_NAME); if (hasMethod) { ((URLClassLoader) loader).close(); } } catch (Throwable th) { LOG.error(th.getMessage(), th); } } } }
package trinity.tests; import com.google.common.io.CharStreams; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import trinity.Trinity; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static java.nio.file.Files.delete; import static org.junit.Assert.assertEquals; public class CodeGenerationVisitorTest { private static final Path testFile = Paths.get("./test.c"); private static final Path binFile = Paths.get("./a.bin"); private static String getOutput(String input) throws Exception { String out = Trinity.compile(input); Files.write(testFile, out.getBytes()); Process process = new ProcessBuilder("gcc", testFile.toString(), "-lm", "-o", binFile.toString()).start(); if (process.waitFor() != 0) { throw new Exception("Error compiling c code"); } Process prog = new ProcessBuilder(binFile.toString()).start(); if (prog.waitFor() != 0) { throw new Exception("program exited with non zero exit code"); } InputStreamReader inr = new InputStreamReader(prog.getInputStream()); // Remove CR line-endings for Windows return CharStreams.toString(inr).replace("\r", ""); } @AfterClass public static void removeFiles() throws Exception { delete(binFile); delete(testFile); } @Test public void parseReturn() throws Exception { assertEquals("1.000000\n", getOutput("print 1;")); } @Test public void stdlib() throws Exception { assertEquals("1.000000\n", getOutput("print abs(-1);")); assertEquals("1.000000\n", getOutput("print abs(1);")); assertEquals("1.000000\n", getOutput("print round(1.23);")); assertEquals("1.000000\n", getOutput("print floor(1.23);")); assertEquals("2.000000\n", getOutput("print ceil(1.23);")); assertEquals("0.841471\n", getOutput("print sin(1);")); assertEquals("0.540302\n", getOutput("print cos(1);")); assertEquals("1.557408\n", getOutput("print tan(1);")); assertEquals("0.523599\n", getOutput("print asin(0.5);")); assertEquals("1.047198\n", getOutput("print acos(0.5);")); assertEquals("0.785398\n", getOutput("print atan(1);")); assertEquals("2.302585\n", getOutput("print log(10);")); assertEquals("2.000000\n", getOutput("print log10(100);")); assertEquals("10.000000\n", getOutput("print sqrt(100);")); assertEquals("1.414214\n", getOutput("print sqrt(2);")); } @Test public void forLoop() throws Exception { assertEquals("1.000000\n2.000000\n3.000000\n4.000000\n", getOutput("for Scalar s in [1,2,3,4] do print s; end")); assertEquals("[1.000000, 2.000000]\n[3.000000, 4.000000]\n", getOutput("for Vector[2] v in [1,2][3,4] do print v; end")); assertEquals("1.000000\n2.000000\n3.000000\n4.000000\n", getOutput("for Vector[2] v in [1,2][3,4] do for Scalar s in v do print s; end end")); assertEquals("4.000000\n6.000000\n", getOutput("Vector[2] v = [4,6]; for Scalar s in v do print s; end")); } @Test public void ifStatements() throws Exception { assertEquals("1.000000\n", getOutput("if true then print 1; else print 2; end")); assertEquals("3.000000\n", getOutput("if 3 < 2 then print 2; else print 3; end")); assertEquals("12.000000\n", getOutput("if [1,2] == [1,3] then print 21; elseif 1 == 1 then print 12; else print 3; end")); assertEquals("13.000000\n", getOutput("if [1,2] == [1,3] then print 21; elseif 1 != 1 then print 12; else print 13; end")); assertEquals("1.000000\n", getOutput("Scalar s = 2; Scalar d = 2; Scalar a = 33; Boolean i = (s == d); Boolean y = (d < a); if i and y then print 1; else print 2; end")); assertEquals("3.000000\n", getOutput("Boolean b = false; Boolean c = true; if b and c then print 2; else print 3; end")); assertEquals("2.000000\n", getOutput("if true or false then print 2; else print 3; end")); assertEquals("3.000000\n", getOutput("if false or false then print 2; else print 3; end")); } @Test public void testRange() throws Exception { assertEquals("[1.000000, 2.000000, 3.000000, 4.000000]\n", getOutput("Vector[4] v = [1..4]; print v;")); assertEquals("[8.000000, 7.000000, 6.000000]\n", getOutput("Vector[3] v = [8..6]; print v;")); assertEquals("true\n", getOutput("print [1,2,3][3,4,5] == [1..3][3..5];")); assertEquals("[1.000000, 2.000000, 3.000000]\n[3.000000, 4.000000, 5.000000]\n", getOutput("Matrix[2,3] v = [1..3][3..5]; print v;")); assertEquals("[1.000000, 2.000000, 3.000000]\n[3.000000, 4.000000, 5.000000]\n", getOutput("Matrix[2,3] v = [1,2,3][3..5]; print v;")); assertEquals("[1.000000, 2.000000, 3.000000]\n[3.000000, 4.000000, 5.000000]\n", getOutput("Matrix[2,3] v = [1..3][3,4,5]; print v;")); } @Test public void matrixDependency() throws Exception { assertEquals("[7.000000, 8.000000, 9.000000]\n[3.000000, 4.000000, 6.000000]\n[187.000000, 24.000000, 5.000000]\n", getOutput("Scalar x(Vector[2] v) do return v[2]; end Vector[2] w = [3,4]; Matrix[3,3] nest = [7..9][3,x(w),6][[1,[3,4]*[6,7]]*[3,4],24,5]; print nest;")); } @Test public void declarations() throws Exception { assertEquals("4.000000\n", getOutput("Scalar s = 4; print s;")); assertEquals("[4.000000, 6.000000]\n", getOutput("Vector[2] v = [4,6]; print v;")); assertEquals("[1.000000, 2.000000, 3.000000]\n[4.000000, 5.000000, 6.000000]\n", getOutput("Matrix[2,3] m = [1,2,3][4,5,6]; print m;")); assertEquals("true\n", getOutput("Boolean b = true; print b;")); } @Test public void functions() throws Exception { assertEquals("18.000000\n", getOutput("Scalar mulle(Scalar a, Scalar b) do return a*b; end print mulle(3,6);")); assertEquals("32.000000\n", getOutput("Scalar dotp(Vector[3] a, Vector[3] b) do Scalar x = 0; return a*b; end Vector[3] v1 = [1,2,3]; print dotp(v1,[4,5,6]);")); assertEquals("[28.000000]\n", getOutput("Matrix[1,1] crazy(Vector[2] a, Vector[2] b) do return a*b'; end Vector[2] dave = [2,3]; print crazy(dave,[5,6]);")); assertEquals("[4.000000, 5.000000, 6.000000]\n", getOutput("Vector[3] vectosaurus(Scalar a, Scalar b, Scalar c) do return [a,b,c]; end print vectosaurus(4,5,6);")); } @Test public void indexing() throws Exception { assertEquals("2.000000\n3.000000\n", getOutput("Vector[3] a = [2,3,4]; print a[1]; print a[2];")); assertEquals("15.000000\n", getOutput("Vector[10] a = [11..20]; print a[5];")); assertEquals("12.000000\n2.000000\n4.000000\n", getOutput("Matrix[3,5] a = [11..15][4,6,8,2,1][3..7]; print a[1,2]; print a[2,4]; print a[3,2];")); assertEquals("7.000000\n", getOutput("Matrix[3,10] m = [1..10][3..12][64..55]; Vector[10] a = m[2]; print a[5];")); } @Ignore public void indexingBounds() throws Exception { // TODO: bounds checking assertEquals("error\n", getOutput("Vector[3] a = [2,3,4]; print a[0];")); assertEquals("error\n", getOutput("Vector[3] a = [2,3,4]; print a[4];")); assertEquals("error\n", getOutput("Matrix[2,3] a = [2,3,4][1..3]; print a[2,0];")); assertEquals("error\n", getOutput("Matrix[2,3] a = [2,3,4][1..3]; print a[2,4];")); assertEquals("error\n", getOutput("Matrix[2,3] a = [2,3,4][1..3]; print a[0,2];")); assertEquals("error\n", getOutput("Matrix[2,3] a = [2,3,4][1..3]; print a[3,2];")); } @Test public void negation() throws Exception { assertEquals("-1.000000\n", getOutput("Scalar m = 1; Scalar n = -m; print n;")); assertEquals("3.000000\n", getOutput("Scalar m= -3; print -m;")); assertEquals("[-1.000000, -2.000000, -3.000000, -4.000000]\n", getOutput("Vector[4] v = [1, 2, 3, 4]; Vector[4] o = -v; print o;")); assertEquals("[-1.000000, -2.000000]\n[-3.000000, -4.000000]\n[-5.000000, -1.000000]\n[-6.000000, -2.000000]\n", getOutput("Matrix[4,2] M = [1, 2][3, 4][5, 1][6, 2]; print -M;")); } @Test public void multiplication() throws Exception { assertEquals("125.000000\n", getOutput("Scalar a = 5; Scalar b = 25; Scalar r = a * b; print r;")); assertEquals("-125.000000\n", getOutput("Scalar a = 5; Scalar b = -25; Scalar r = a * b; print r;")); assertEquals("125.000000\n", getOutput("Scalar a = -5; Scalar b = -25; Scalar r = a * b; print r;")); assertEquals("8.000000\n", getOutput("Scalar a = 2; Scalar b = 2; Scalar r = a * b * b; print r;")); assertEquals("[2.000000, 4.000000, 6.000000, 8.000000, 10.000000]\n", getOutput("Vector[5] v = [1, 2, 3, 4, 5]; Scalar j = 2; Vector[5] k = v*j; print k;")); assertEquals("[2.000000, 4.000000]\n[6.000000, 8.000000]\n[10.000000, 12.000000]\n", getOutput("Matrix[3,2] m = [1, 2][ 3, 4][5, 6]; Scalar j = 2; Matrix[3,2] k = m*j; print k;")); assertEquals("[2.000000, 4.000000]\n[6.000000, 8.000000]\n[10.000000, 12.000000]\n", getOutput("Matrix[3,2] m = [1, 2][ 3, 4][5, 6]; Scalar j = 2; Matrix[3,2] k = j*m; print k;")); assertEquals("[5.000000, -10.000000]\n[15.000000, -10.000000]\n[23.000000, -14.000000]\n", getOutput("Matrix[3,2] a = [-1, 2][3, 4][5, 6]; Matrix[2,2] b = [1, 2][3, -4]; Matrix[3,2] c = a * b; print c;")); assertEquals("[7.000000, 10.000000]\n[15.000000, 22.000000]\n", getOutput("Matrix[2,2] m = [1, 2][3, 4]; Matrix[2,2] n = [1, 2][3, 4]; print m * n;")); assertEquals("221.000000\n", getOutput("Vector[4] v = [50, 2, 3, 4]; Vector[4] d = [4, 5, 1, 2]; print v * d;")); } @Test public void division() throws Exception { assertEquals("4.000000\n", getOutput("Scalar a = 100; Scalar t = 25; print a / t;")); assertEquals("[1.000000, 2.000000, 4.000000, 8.000000]\n", getOutput("Vector[4] v = [2, 4, 8, 16]; Scalar n = 2; print v / n;")); assertEquals("[8.000000, 7.000000]\n[6.000000, 5.000000]\n[4.000000, 3.000000]\n[2.000000, 1.000000]\n", getOutput("Matrix[4,2] m = [16, 14][12, 10][8, 6][4, 2]; Scalar i = 2; print m / i;")); assertEquals("[-8.000000, -7.000000, -6.000000, -5.000000]\n", getOutput("Vector[4] v = [16, 14, 12, 10]; Scalar i = -2; print v / i;")); } @Test public void not() throws Exception { assertEquals("true\n", getOutput("Boolean b = 4 == 3; print !b;")); assertEquals("false\n", getOutput("Boolean b = 4 != 3; print !b;")); } @Test public void transpose() throws Exception { assertEquals("[1.000000, 7.000000]\n[5.000000, -5.000000]\n[6.000000, -1.000000]\n", getOutput("Matrix[2,3] m = [1, 5, 6][7, -5, -1]; Matrix[3,2] t = m'; print t;")); assertEquals("[1.000000, 4.000000, 7.000000]\n[2.000000, -5.000000, 8.000000]\n[3.000000, -6.000000, 9.000000]\n", getOutput("Matrix[3,3] m = [1, 2, 3][4, -5, -6][7, 8, 9]; print m';")); assertEquals("[1.000000]\n[2.000000]\n[3.000000]\n[4.000000]\n[5.000000]\n", getOutput("Vector[5] v = [1, 2, 3, 4, 5]; Matrix[5,1] m = v'; print m;")); assertEquals("[1.000000, 2.000000, 3.000000, 4.000000, 5.000000]\n", getOutput("Matrix[5,1] m = [1][2][3][4][5]; Vector[5] v = m'; print v;")); } @Test public void addition() throws Exception { assertEquals("7.000000\n", getOutput("Scalar a = 5; Scalar b = 2; print a + b;")); assertEquals("-5.000000\n", getOutput("Scalar a = -35; Scalar b = 30; print a + b;")); assertEquals("[-11.000000, -9.000000, -7.000000, 13.000000]\n[13.000000, 13.000000, 13.000000, 3.000000]\n[5.000000, 13.000000, 13.000000, 13.000000]\n", getOutput("Matrix[3,4] m = [1, 2, 3, 4][5, 6, 7, 8][9, 10, 11, 12]; Matrix[3,4] n = [-12, -11, -10, 9][8, 7, 6, -5][-4, 3, 2, 1]; print m + n;")); assertEquals("[5.000000, 7.000000, 9.000000]\n", getOutput("Vector[3] v = [4, 5, 6]; Vector[3] l = [1, 2, 3]; print v + l;")); } @Test public void subtraction() throws Exception { assertEquals("3.000000\n", getOutput("Scalar a = 5; Scalar b = 2; print a - b;")); assertEquals("-5.000000\n", getOutput("Scalar a = -35; Scalar b = -30; print a - b;")); assertEquals("[3.000000, 3.000000, 9.000000]\n", getOutput("Vector[3] v = [4, 5, 6]; Vector[3] l = [1, 2, -3]; print v - l;")); assertEquals("[-3.000000, -13.000000]\n[3.000000, 8.000000]\n[4.000000, -3.000000]\n", getOutput("Matrix[3,2] m = [4, -5][-6, 3][-2, 1]; Matrix[3,2] n = [7, 8][-9, -5][-6, 4]; print m - n;")); } @Test public void equality() throws Exception { assertEquals("true\n", getOutput("Boolean t = true; Boolean o = true; print t == o;")); assertEquals("true\n", getOutput("Boolean t = false; Boolean o = false; print t == o;")); assertEquals("false\n", getOutput("Boolean t = true; Boolean o = false; print t == o;")); assertEquals("false\n", getOutput("Boolean t = true; Boolean o = true; print t != o;")); assertEquals("false\n", getOutput("Boolean t = false; Boolean o = false; print t != o;")); assertEquals("true\n", getOutput("Boolean t = true; Boolean o = false; print t != o;")); assertEquals("true\n", getOutput("Scalar s = 12; Scalar c = 12; print s == c;")); assertEquals("false\n", getOutput("Scalar s = -12; Scalar c = 12; print s == c;")); assertEquals("false\n", getOutput("Scalar s = 12; Scalar c = 12; print s != c;")); assertEquals("true\n", getOutput("Scalar s = -12; Scalar c = 12; print s != c;")); assertEquals("true\n", getOutput("Vector[5] d = [1, 2, 3, 4, 5]; Vector[5] q = [1, 2, 3, 4, 5]; print d == q;")); assertEquals("false\n", getOutput("Vector[5] d = [1, 2, 3, 4, 5]; Vector[5] q = [100, 2, 3, 4, 5]; print d == q;")); assertEquals("false\n", getOutput("Vector[5] d = [1, 2, 3, 4, 5]; Vector[5] q = [1, 2, 3, 4, 5]; print d != q;")); assertEquals("true\n", getOutput("Vector[5] d = [1, 2, 3, 4, 5]; Vector[5] q = [100, 2, 3, 4, 5]; print d != q;")); assertEquals("true\n", getOutput("Matrix[2,2] m = [1, 2][3, 4]; Matrix[2,2] n = [1, 2][3, 4]; print m == n;")); assertEquals("false\n", getOutput("Matrix[2,3] m = [1, 2, 3][4, 5, 6]; Matrix[2,3] n = [6, 5, 4][3, 2, 1]; print m == n;")); assertEquals("false\n", getOutput("Matrix[2,2] m = [1, 2][3, 4]; Matrix[2,2] n = [1, 2][3, 4]; print m != n;")); assertEquals("true\n", getOutput("Matrix[2,3] m = [1, 2, 3][4, 5, 6]; Matrix[2,3] n = [6, 5, 4][3, 2, 1]; print m != n;")); } @Test public void relation() throws Exception { assertEquals("true\n", getOutput("Scalar a = 22.5; Scalar t = 22; Boolean b = a > t; print b;")); assertEquals("false\n", getOutput("Scalar a = 22.5; Scalar t = 22; Boolean b = a < t; print b;")); assertEquals("false\n", getOutput("Scalar a = 22; Scalar t = 22; Boolean b = a < t; print b;")); assertEquals("true\n", getOutput("Scalar e = 45; Scalar r = 45; print e <= r;")); assertEquals("false\n", getOutput("Scalar e = 93; Scalar r = 45; print e <= r;")); assertEquals("true\n", getOutput("Scalar s = 93; Scalar d = 45; print s >= d;")); assertEquals("false\n", getOutput("Scalar s = 2; Scalar d = 45; print s >= d;")); } @Test public void parens() throws Exception { assertEquals("30.000000\n", getOutput("Scalar a = 3; Scalar b = 7; print (a + b) * a;")); assertEquals("[24.000000, 24.000000]\n[48.000000, 48.000000]\n", getOutput("Matrix[2,2] m = [2, 2][4, 4]; Matrix[2,2] n = m / 2; print (m + m) * m;")); assertEquals("[-24.000000, -24.000000]\n[-48.000000, -48.000000]\n", getOutput("Matrix[2,2] m = [2, 2][4, 4]; Matrix[2,2] n = m / 2; print -((m + m) * m) ;")); } @Test public void exponential() throws Exception { assertEquals("262144.000000\n", getOutput("Scalar a = 8; Scalar b = 6; print a ^ b;")); assertEquals("0.015625\n", getOutput("Scalar a = 8; Scalar b = -2; print a ^ b;")); assertEquals("[121824.000000, 149688.000000, 177552.000000]\n[275886.000000, 338985.000000, 402084.000000]\n[429948.000000, 528282.000000, 626616.000000]\n", getOutput("Matrix[3,3] m = [1, 2, 3][4, 5, 6][7, 8, 9]; Scalar e = 5; print m ^ e;")); assertEquals("[9.000000, 8.000000, 7.000000]\n[6.000000, 5.000000, 4.000000]\n[3.000000, 2.000000, 1.000000]\n", getOutput("Matrix[3,3] l = [9, 8, 7][6, 5, 4][3, 2, 1]; Matrix[3,3] x = l ^ 1; print x;")); assertEquals("[1.000000, 0.000000, 0.000000, 0.000000]\n[0.000000, 1.000000, 0.000000, 0.000000]\n[0.000000, 0.000000, 1.000000, 0.000000]\n[0.000000, 0.000000, 0.000000, 1.000000]\n", getOutput("Matrix[4,4] y = [5, -9, -8, -7][5, -6, -5, -4][5, 4, 5, 6][5, 7, 8, 9]; print y ^ 0;")); } }
package io.domisum.lib.auxiliumlib.util; import io.domisum.lib.auxiliumlib.annotations.API; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.time.Duration; import java.time.Instant; import java.time.temporal.Temporal; @API @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class TimeUtil { // MATH @API public static Duration getDeltaAbs(Duration duration1, Duration duration2) { return duration1.minus(duration2).abs(); } @API public static Duration min(Duration a, Duration b) { return (a.compareTo(b) < 0) ? a : b; } @API public static Duration max(Duration a, Duration b) { return (a.compareTo(b) > 0) ? a : b; } // FLOATING COMMA CONVERSION @API public static double getDaysDecimal(Duration duration) { return duration.getSeconds()/(double) Duration.ofDays(1).getSeconds(); } @API public static double getHoursDecimal(Duration duration) { return duration.getSeconds()/(double) Duration.ofHours(1).getSeconds(); } @API public static double getMinutesDecimal(Duration duration) { return duration.getSeconds()/(double) Duration.ofMinutes(1).getSeconds(); } @API public static double getSecondsDecimal(Duration duration) { return duration.toMillis()/(double) Duration.ofSeconds(1).toMillis(); } @API public static double getMillisecondsDecimal(Duration duration) { return duration.getSeconds()*1000+(duration.toNanosPart()/(double) (1000*1000)); } @API public static Duration fromSecondsDecimal(double seconds) { return Duration.ofMillis(Math.round(seconds*1000)); } // DISPLAY @API public static String displayMinutesSeconds(Duration duration) { final int secondsInMinute = 60; long totalSeconds = (int) Math.ceil(duration.toMillis()/(double) 1000); long displayMinutes = totalSeconds/secondsInMinute; long displaySeconds = totalSeconds%secondsInMinute; String secondsString = displaySeconds+""; if(secondsString.length() == 1) secondsString = "0"+secondsString; return displayMinutes+":"+secondsString; } // NOW @API public static Instant ago(Duration duration) { return Instant.now().minus(duration); } @API public static Duration toNow(Temporal from) { return Duration.between(from, Instant.now()); } @API public static Duration until(Temporal until) { return Duration.between(Instant.now(), until); } @API public static boolean isOlderThan(Instant instant, Duration duration) { var age = toNow(instant); return Compare.greaterThan(age, duration); } @API public static boolean isYoungerThan(Instant instant, Duration duration) { var age = toNow(instant); return Compare.lessThan(age, duration); } @API public static boolean hasPassed(Instant instant) { return instant.isBefore(Instant.now()); } @API public static boolean isInFuture(Instant instant) { return instant.isAfter(Instant.now()); } }
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static byte byteDef; private static boolean booleanDef; private static char charDef; private static short shortDef; private static int intDef; private static long longDef; private static float floatDef; private static double doubleDef; // default value for modifier private static final int DEFAULT_MODIFIER = 0; /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { constructor.setAccessible(Boolean.TRUE); } instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { constructor.setAccessible(accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { Constructor<T> constructor = getConstructor(type, parameterTypes); T instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, Boolean.TRUE, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; try { ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = Class.forName(className, Boolean.TRUE, loader); } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { Method[] methods = getDeclaredMethods(clazz); boolean found = Boolean.FALSE; int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { method.setAccessible(Boolean.TRUE); } value = invoke(method, data, arguments); } finally { method.setAccessible(accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { method.setAccessible(Boolean.TRUE); } value = invokeStatic(method, arguments); } finally { method.setAccessible(accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { field.setAccessible(Boolean.TRUE); } field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { field.setAccessible(accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { if (ObjectUtils.notTrue(accessible)) { field.setAccessible(Boolean.TRUE); } value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { field.setAccessible(accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = byteDef; } else if (clazz.equals(boolean.class)) { value = booleanDef; } else if (clazz.equals(char.class)) { value = charDef; } else if (clazz.equals(short.class)) { value = shortDef; } else if (clazz.equals(int.class)) { value = intDef; } else if (clazz.equals(long.class)) { value = longDef; } else if (clazz.equals(float.class)) { value = floatDef; } else if (clazz.equals(double.class)) { value = doubleDef; } else { value = null; } } else { value = null; } return value; } }
package org.grouplens.grapht.util; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; @Immutable public final class ClassProxy implements Serializable { private static final long serialVersionUID = 1; private static final Logger logger = LoggerFactory.getLogger(ClassProxy.class); private final String className; private final long checksum; @Nullable private transient volatile WeakReference<Class<?>> theClass; private transient ClassLoader classLoader; private ClassProxy(String name, long check) { className = name; checksum = check; classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = ClassProxy.class.getClassLoader(); } } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = ClassProxy.class.getClassLoader(); } } /** * Get the class name. This name does not include any array information. * @return The class name. */ public String getClassName() { return className; } @Override public String toString() { return "proxy of " + className; } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof ClassProxy) { ClassProxy op = (ClassProxy) o; return className.equals(op.className); } else { return false; } } @Override public int hashCode() { return className.hashCode(); } /** * Resolve a class proxy to a class. * @return The class represented by this proxy. * @throws ClassNotFoundException if the class represented by this proxy cannot be found. */ public Class<?> resolve() throws ClassNotFoundException { WeakReference<Class<?>> ref = theClass; Class<?> cls = ref == null ? null : ref.get(); if (cls == null) { if(className.equals("void")) { // special case cls = Void.TYPE; } else { cls = ClassUtils.getClass(classLoader, className); } long check = checksumClass(cls); if (!isSerializationPermissive() && checksum != check) { throw new ClassNotFoundException("checksum mismatch for " + cls.getName()); } else { if (checksum != check) { logger.warn("checksum mismatch for {}", cls); } theClass = new WeakReference<Class<?>>(cls); } } return cls; } private static final Map<Class<?>, ClassProxy> proxyCache = new WeakHashMap<Class<?>, ClassProxy>(); /** * Construct a class proxy for a class. * * @param cls The class. * @return The class proxy. */ public static synchronized ClassProxy of(Class<?> cls) { ClassProxy proxy = proxyCache.get(cls); if (proxy == null) { proxy = new ClassProxy(cls.getName(), checksumClass(cls)); proxy.theClass = new WeakReference<Class<?>>(cls); proxyCache.put(cls, proxy); } return proxy; } private static final Charset UTF8 = Charset.forName("UTF-8"); public static boolean isSerializationPermissive() { return Boolean.getBoolean("grapht.deserialization.permissive"); } /** * Compute a checksum for a class. These checksums are used to see if a class has changed * its definition since being serialized. * <p> * The checksum used here is not cryptographically strong. It is intended only as a sanity * check to detect incompatible serialization, not to robustly prevent tampering. The * checksum algorithm currently is to compute an MD5 checksum over class member signatures * and XOR the lower and upper halves of the checksum. * </p> * * @param type The class to checksum. * @return The */ private static long checksumClass(Class<?> type) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("JVM does not support MD5"); } checksumClass(type, digest); ByteBuffer buf = ByteBuffer.wrap(digest.digest()); return buf.getLong() ^ buf.getLong(); } private static void checksumClass(Class<?> type, MessageDigest digest) { // we compute a big hash of all the members of the class, and its superclasses. List<String> members = new ArrayList<String>(); for (Constructor<?> c: type.getDeclaredConstructors()) { members.add(String.format("%s(%s)", c.getName(), StringUtils.join(c.getParameterTypes(), ", "))); } for (Method m: type.getDeclaredMethods()) { members.add(String.format("%s(%s): %s", m.getName(), StringUtils.join(m.getParameterTypes(), ", "), m.getReturnType())); } for (Field f: type.getDeclaredFields()) { members.add(f.getName() + ":" + f.getType().getName()); } Collections.sort(members); Class<?> sup = type.getSuperclass(); if (sup != null) { checksumClass(sup, digest); } for (String mem: members) { digest.update(mem.getBytes(UTF8)); } } }
package io.github.classgraph; import java.lang.reflect.Modifier; import io.github.classgraph.utils.TypeUtils; /** * Information on the parameters of a method. * * @author lukehutch */ public class MethodParameterInfo { final AnnotationInfo[] annotationInfo; private final int modifiers; private final TypeSignature typeDescriptor; private final TypeSignature typeSignature; private final String name; private ScanResult scanResult; /** * @param annotationInfo * {@link AnnotationInfo} for any annotations on this method parameter. * @param modifiers * The method parameter modifiers. * @param typeDescriptor * The method parameter type descriptor. * @param typeSignature * The method parameter type signature. * @param name * The method parameter name. */ MethodParameterInfo(final AnnotationInfo[] annotationInfo, final int modifiers, final TypeSignature typeDescriptor, final TypeSignature typeSignature, final String name) { this.name = name; this.modifiers = modifiers; this.typeDescriptor = typeDescriptor; this.typeSignature = typeSignature; this.annotationInfo = annotationInfo; } /** * Method parameter name. May be null, for unnamed parameters (e.g. synthetic parameters), or if compiled for * JDK version lower than 8, or if compiled for JDK version 8+ but without the commandline switch `-parameters`. * * @return The method parameter name. */ public String getName() { return name; } /** * Method parameter modifiers. May be zero, if no modifier bits set, or if compiled for JDK version lower than * 8, or if compiled for JDK version 8+ but without the commandline switch `-parameters`. * * @return The method parameter modifiers. */ public int getModifiers() { return modifiers; } /** * Get the method parameter modifiers as a String, e.g. "final". For the modifier bits, call * {@link #getModifiers()}. * * @return The modifiers for the method parameter, as a String. */ public String getModifiersStr() { return TypeUtils.modifiersToString(getModifiers(), /* isMethod = */ true); } /** * Method parameter type signature, possibly including generic type information (or null if no type signature * information available for this parameter). * * @return The method type signature, if available, else null. */ public TypeSignature getTypeSignature() { return typeSignature; } /** * Method parameter type descriptor. * * @return The method type descriptor. */ public TypeSignature getTypeDescriptor() { return typeDescriptor; } /** * Method parameter type signature, or if not available, method type descriptor. * * @return The method type signature, if present, otherwise the method type descriptor. */ public TypeSignature getTypeSignatureOrTypeDescriptor() { return typeSignature != null ? typeSignature : typeDescriptor; } /** * Method parameter annotation info (or null if no annotations). * * @return {@link AnnotationInfo} for any annotations on this method parameter. */ // TODO: change this to AnnotationInfoList public AnnotationInfo[] getAnnotationInfo() { if (!scanResult.scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()"); } return annotationInfo; } protected void setScanResult(final ScanResult scanResult) { this.scanResult = scanResult; if (this.annotationInfo != null) { for (final AnnotationInfo ai : annotationInfo) { ai.setScanResult(scanResult); } } if (this.typeDescriptor != null) { this.typeDescriptor.setScanResult(scanResult); } if (this.typeSignature != null) { this.typeSignature.setScanResult(scanResult); } } @Override public String toString() { final StringBuilder buf = new StringBuilder(); final AnnotationInfo[] annInfo = getAnnotationInfo(); if (annInfo != null) { for (int j = 0; j < annInfo.length; j++) { annInfo[j].toString(buf); buf.append(' '); } } final int flag = getModifiers(); if ((flag & Modifier.FINAL) != 0) { buf.append("final "); } if ((flag & TypeUtils.MODIFIER_SYNTHETIC) != 0) { buf.append("synthetic "); } if ((flag & TypeUtils.MODIFIER_MANDATED) != 0) { buf.append("mandated "); } buf.append(getTypeSignatureOrTypeDescriptor().toString()); buf.append(' '); buf.append(name == null ? "_unnamed_param" : name); return buf.toString(); } }
package org.lightmare.utils.reflect; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Class to use reflection {@link Method} calls and {@link Field} information * sets * * @author levan * */ public class MetaUtils { // default values for primitives private static final byte BYTE_DEF = 0; private static final boolean BOOLEAN_DEF = Boolean.FALSE; private static final char CHAR_DEF = '\u0000'; private static final short SHORT_DEF = 0; private static final int INT_DEF = 0; private static final long LONG_DEF = 0L; private static final float FLOAT_DEF = 0F; private static final double DOUBLE_DEF = 0D; // default value for modifier private static final int DEFAULT_MODIFIER = 0; // Lock to modify accessible mode of AccessibleObject instances private static final Lock ACCESSOR_LOCK = new ReentrantLock(); private static boolean notAccessible(AccessibleObject accessibleObject) { return ObjectUtils.notTrue(accessibleObject.isAccessible()); } /** * Modifies passed {@link AccessibleObject} as accessible * * @param accessibleObject * @return <code>boolean</code> */ private static boolean makeAccessible(AccessibleObject accessibleObject) { boolean locked = ObjectUtils.tryLock(ACCESSOR_LOCK); if (locked) { try { if (notAccessible(accessibleObject)) { accessibleObject.setAccessible(Boolean.TRUE); } } finally { ObjectUtils.unlock(ACCESSOR_LOCK); } } return locked; } /** * Sets object accessible flag as true if it is not * * @param accessibleObject * @param accessible */ private static void setAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked) && accessibleObject.isAccessible()) { locked = makeAccessible(accessibleObject); } } } /** * Modifies passed {@link AccessibleObject} as not accessible * * @param accessibleObject * @return <code>boolean</code> */ private static boolean makeInaccessible(AccessibleObject accessibleObject) { boolean locked = ObjectUtils.tryLock(ACCESSOR_LOCK); if (locked) { try { if (accessibleObject.isAccessible()) { accessibleObject.setAccessible(Boolean.FALSE); } } finally { ObjectUtils.unlock(ACCESSOR_LOCK); } } return locked; } /** * Sets passed {@link AccessibleObject}'s accessible flag as passed * accessible boolean value if the last one is false * * @param accessibleObject * @param accessible */ private static void resetAccessible(AccessibleObject accessibleObject, boolean accessible) { if (ObjectUtils.notTrue(accessible)) { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked) && accessibleObject.isAccessible()) { locked = makeInaccessible(accessibleObject); } } } /** * Makes accessible passed {@link Constructor}'s and invokes * {@link Constructor#newInstance(Object...)} method * * @param constructor * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T newInstance(Constructor<T> constructor, Object... parameters) throws IOException { T instance; boolean accessible = constructor.isAccessible(); try { setAccessible(constructor, accessible); instance = constructor.newInstance(parameters); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } finally { resetAccessible(constructor, accessible); } return instance; } /** * Gets declared constructor for given {@link Class} and given parameters * * @param type * @param parameterTypes * @return {@link Constructor} * @throws IOException */ public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) throws IOException { Constructor<T> constructor; try { constructor = type.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return constructor; } /** * Instantiates class by {@link Constructor} (MetaUtils * {@link #newInstance(Constructor, Object...)}) after * {@link MetaUtils#getConstructor(Class, Class...)} method call * * @param type * @param parameterTypes * @param parameters * @return <code>T</code> * @throws IOException */ public static <T> T callConstructor(Class<T> type, Class<?>[] parameterTypes, Object... parameters) throws IOException { T instance; Constructor<T> constructor = getConstructor(type, parameterTypes); instance = newInstance(constructor, parameters); return instance; } /** * Loads class by name * * @param className * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className) throws IOException { Class<?> clazz = classForName(className, null); return clazz; } /** * Loads class by name with specific {@link ClassLoader} if it is not * <code>null</code> * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, ClassLoader loader) throws IOException { Class<?> clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Loads and if initialize parameter is true initializes class by name with * specific {@link ClassLoader} if it is not <code>null</code> * * @param className * @param initialize * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> classForName(String className, boolean initialize, ClassLoader loader) throws IOException { Class<?> clazz; try { if (loader == null) { clazz = Class.forName(className); } else { clazz = Class.forName(className, initialize, loader); } } catch (ClassNotFoundException ex) { throw new IOException(ex); } return clazz; } /** * Loads class by name with current {@link Thread}'s {@link ClassLoader} and * initializes it * * @param className * @param loader * @return {@link Class} * @throws IOException */ public static Class<?> initClassForName(String className) throws IOException { Class<?> clazz; ClassLoader loader = LibraryLoader.getContextClassLoader(); clazz = classForName(className, Boolean.TRUE, loader); return clazz; } /** * Creates {@link Class} instance by {@link Class#newInstance()} method call * * @param clazz * @return */ public static <T> T instantiate(Class<T> clazz) throws IOException { T instance; try { instance = clazz.newInstance(); } catch (InstantiationException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } return instance; } /** * Gets declared method from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws IOException { Method method; try { method = clazz.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return method; } /** * Gets all declared methods from class * * @param clazz * @param methodName * @param parameterTypes * @return {@link Method} * @throws IOException */ public static Method[] getDeclaredMethods(Class<?> clazz) throws IOException { Method[] methods; try { methods = clazz.getDeclaredMethods(); } catch (SecurityException ex) { throw new IOException(ex); } return methods; } /** * Gets one modifier <code>int</code> value for passed collection * * @param modifiers * @return <code>int</code> */ private static int calculateModifier(int[] modifiers) { int modifier = DEFAULT_MODIFIER; if (ObjectUtils.notNull(modifiers)) { int length = modifiers.length; int modifierValue; for (int i = 0; i < length; i++) { modifierValue = modifiers[i]; modifier = modifier | modifierValue; } } return modifier; } /** * Finds if passed {@link Class} has declared public {@link Method} with * appropriated name * * @param clazz * @param modifiers * @param methodName * @return <code>boolean</code> * @throws IOException */ private static boolean classHasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Method[] methods = getDeclaredMethods(clazz); int length = methods.length; int modifier = calculateModifier(modifiers); Method method; for (int i = 0; i < length && ObjectUtils.notTrue(found); i++) { method = methods[i]; found = method.getName().equals(methodName); if (found && ObjectUtils.notEquals(modifier, DEFAULT_MODIFIER)) { found = ((method.getModifiers() & modifier) > DEFAULT_MODIFIER); } } return found; } /** * Finds if passed {@link Class} has {@link Method} with appropriated name * and modifiers * * @param clazz * @param methodName * @param modifiers * @return <code>boolean</code> * @throws IOException */ public static boolean hasMethod(Class<?> clazz, String methodName, int... modifiers) throws IOException { boolean found = Boolean.FALSE; Class<?> superClass = clazz; while (ObjectUtils.notNull(superClass) && ObjectUtils.notTrue(found)) { found = MetaUtils.classHasMethod(superClass, methodName, modifiers); if (ObjectUtils.notTrue(found)) { superClass = superClass.getSuperclass(); } } return found; } /** * Finds if passed {@link Class} has public {@link Method} with appropriated * name * * @param clazz * @param methodName * @return <code>boolean</code> * @throws IOException */ public static boolean hasPublicMethod(Class<?> clazz, String methodName) throws IOException { boolean found = MetaUtils.hasMethod(clazz, methodName, Modifier.PUBLIC); return found; } /** * Gets declared field from passed class with specified name * * @param clazz * @param name * @return {@link Field} * @throws IOException */ public static Field getDeclaredField(Class<?> clazz, String name) throws IOException { Field field; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } return field; } /** * Returns passed {@link Field}'s modifier * * @param field * @return <code>int</code> */ public static int getModifiers(Field field) { return field.getModifiers(); } /** * Returns passed {@link Method}'s modifier * * @param method * @return <code>int</code> */ public static int getModifiers(Method method) { return method.getModifiers(); } /** * Returns type of passed {@link Field} invoking {@link Field#getType()} * method * * @param field * @return {@link Class}<?> */ public static Class<?> getType(Field field) { return field.getType(); } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invoke(Method method, Object data, Object... arguments) throws IOException { Object value; try { value = method.invoke(data, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke {@link Method} with reflection * * @param method * @param data * @param arguments * @return {@link Object} * @throws IOException */ public static Object invokePrivate(Method method, Object data, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invoke(method, data, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Common method to invoke static {@link Method} with reflection * * @param method * @param arguments * @return * @throws IOException */ public static Object invokeStatic(Method method, Object... arguments) throws IOException { Object value; try { value = method.invoke(null, arguments); } catch (IllegalAccessException ex) { throw new IOException(ex); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (InvocationTargetException ex) { throw new IOException(ex); } return value; } /** * Common method to invoke private static {@link Method} * * @param method * @param arguments * @return * @throws IOException */ public static Object invokePrivateStatic(Method method, Object... arguments) throws IOException { Object value; boolean accessible = method.isAccessible(); try { setAccessible(method, accessible); value = invokeStatic(method, arguments); } finally { resetAccessible(method, accessible); } return value; } /** * Sets value to {@link Field} sets accessible Boolean.TRUE remporary if * needed * * @param field * @param value * @throws IOException */ public static void setFieldValue(Field field, Object data, Object value) throws IOException { boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); field.set(data, value); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } } /** * Gets value of specific field in specific {@link Object} * * @param field * @param data * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field, Object data) throws IOException { Object value; boolean accessible = field.isAccessible(); try { setAccessible(field, accessible); value = field.get(data); } catch (IllegalArgumentException ex) { throw new IOException(ex); } catch (IllegalAccessException ex) { throw new IOException(ex); } finally { resetAccessible(field, accessible); } return value; } /** * Gets value of specific static field * * @param field * @return {@link Object} * @throws IOException */ public static Object getFieldValue(Field field) throws IOException { Object value = getFieldValue(field, null); return value; } /** * Gets {@link List} of all {@link Method}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Method> * @throws IOException */ public static List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Method> methods = new ArrayList<Method>(); Method[] allMethods = getDeclaredMethods(clazz); for (Method method : allMethods) { if (method.isAnnotationPresent(annotationClass)) { methods.add(method); } } return methods; } /** * Gets {@link List} of all {@link Field}s from passed class annotated with * specified annotation * * @param clazz * @param annotationClass * @return {@link List}<Field> * @throws IOException */ public static List<Field> getAnnotatedFields(Class<?> clazz, Class<? extends Annotation> annotationClass) throws IOException { List<Field> fields = new ArrayList<Field>(); Field[] allFields = clazz.getDeclaredFields(); for (Field field : allFields) { if (field.isAnnotationPresent(annotationClass)) { fields.add(field); } } return fields; } /** * Gets wrapper class if passed class is primitive type * * @param type * @return {@link Class}<T> */ public static <T> Class<T> getWrapper(Class<?> type) { Class<T> wrapper; if (type.isPrimitive()) { if (type.equals(byte.class)) { wrapper = ObjectUtils.cast(Byte.class); } else if (type.equals(boolean.class)) { wrapper = ObjectUtils.cast(Boolean.class); } else if (type.equals(char.class)) { wrapper = ObjectUtils.cast(Character.class); } else if (type.equals(short.class)) { wrapper = ObjectUtils.cast(Short.class); } else if (type.equals(int.class)) { wrapper = ObjectUtils.cast(Integer.class); } else if (type.equals(long.class)) { wrapper = ObjectUtils.cast(Long.class); } else if (type.equals(float.class)) { wrapper = ObjectUtils.cast(Float.class); } else if (type.equals(double.class)) { wrapper = ObjectUtils.cast(Double.class); } else { wrapper = ObjectUtils.cast(type); } } else { wrapper = ObjectUtils.cast(type); } return wrapper; } /** * Returns default values if passed class is primitive else returns null * * @param clazz * @return Object */ public static Object getDefault(Class<?> clazz) { Object value; if (clazz.isPrimitive()) { if (clazz.equals(byte.class)) { value = BYTE_DEF; } else if (clazz.equals(boolean.class)) { value = BOOLEAN_DEF; } else if (clazz.equals(char.class)) { value = CHAR_DEF; } else if (clazz.equals(short.class)) { value = SHORT_DEF; } else if (clazz.equals(int.class)) { value = INT_DEF; } else if (clazz.equals(long.class)) { value = LONG_DEF; } else if (clazz.equals(float.class)) { value = FLOAT_DEF; } else if (clazz.equals(double.class)) { value = DOUBLE_DEF; } else { value = null; } } else { value = null; } return value; } }
package uk.ac.brighton.ci360.bigarrow; import java.util.ArrayList; import java.util.LinkedHashMap; import uk.ac.brighton.ci360.bigarrow.places.Place; import uk.ac.brighton.ci360.bigarrow.places.PlaceDetails; import uk.ac.brighton.ci360.bigarrow.places.PlacesList; import uk.ac.brighton.ci360.bigarrow.adapter.*; import uk.ac.brighton.ci360.bigarrow.classes.*; import android.app.ProgressDialog; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.ExpandableListView; public class PlaceDetailActivity extends PlaceSearchActivity { private static final String TAG = "PlaceDetailActivity"; PlaceDetails placeDetails; ProgressDialog pDialog; private ExpandListAdapter ExpAdapter; private ExpandableListView ExpandList; @Override public void onCreate(Bundle savedInstanceState) { firstSearchType = SearchType.DETAIL; Intent i = getIntent(); placeReference = i.getStringExtra(PlaceDetails.KEY_REFERENCE); super.onCreate(savedInstanceState); setContentView(R.layout.place_detail); pDialog = new ProgressDialog(PlaceDetailActivity.this); pDialog.setMessage("Loading details ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } @Override public void updatePlaceDetails(PlaceDetails details) { Log.d(TAG, "displaying details for " + details.result.name); pDialog.dismiss(); placeDetails = details; // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { if (placeDetails != null) { String status = placeDetails.status; Place place = placeDetails.result; if (status.equals("OK") && place != null) { ExpandList = (ExpandableListView) findViewById(R.id.ExpList); ExpAdapter = new ExpandListAdapter(PlaceDetailActivity.this, getExpListItems(place)); ExpandList.setAdapter(ExpAdapter); } } } /** * @param place - the place, details of which are asked * @return - list of groups used for showing the expandable view to the user */ private ArrayList<ExpandListGroup> getExpListItems(Place place) { ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>(); ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>(); final LinkedHashMap<String, String> details = place.getDetails(); //loop through all details available in the hashmap for (String key : details.keySet()) { ExpandListGroup group = new ExpandListGroup(); group.setName(key); ExpandListChild child = new ExpandListChild(); child.setName(details.get(key)); child.setTag(null); list2.add(child); group.setItems(list2); list2 = new ArrayList<ExpandListChild>(); list.add(group); } return list; } }); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void updateNearestPlaces(PlacesList places) { // TODO Auto-generated method stub } @Override public void updateNearestPlace(Place place, Location location, float distance) { // TODO Auto-generated method stub } }
package io.mycat.route.function; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import io.mycat.config.model.rule.RuleAlgorithm; import org.apache.log4j.Logger; /** * between * * @author wzh * */ public class PartitionByMonth extends AbstractPartitionAlgorithm implements RuleAlgorithm { private static final Logger LOGGER = Logger.getLogger(PartitionByDate.class); private String sBeginDate; private String dateFormat; private String sEndDate; private Calendar beginDate; private Calendar endDate; private int nPartition; private ThreadLocal<SimpleDateFormat> formatter; @Override public void init() { try { beginDate = Calendar.getInstance(); beginDate.setTime(new SimpleDateFormat(dateFormat) .parse(sBeginDate)); formatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(dateFormat); } }; if(sEndDate!=null&&!sEndDate.equals("")) { endDate = Calendar.getInstance(); endDate.setTime(new SimpleDateFormat(dateFormat).parse(sEndDate)); nPartition = ((endDate.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR)) * 12 + endDate.get(Calendar.MONTH) - beginDate.get(Calendar.MONTH)) + 1; if (nPartition <= 0) { throw new java.lang.IllegalArgumentException("Incorrect time range for month partitioning!"); } } else { nPartition = -1; } } catch (ParseException e) { throw new java.lang.IllegalArgumentException(e); } } /** * For circulatory partition, calculated value of target partition needs to be * rotated to fit the partition range */ private int reCalculatePartition(int targetPartition) { /** * If target date is previous of start time of partition setting, shift * the delta range between target and start date to be positive value */ if (targetPartition < 0) { targetPartition = nPartition - (-targetPartition) % nPartition; } if (targetPartition >= nPartition) { targetPartition = targetPartition % nPartition; } return targetPartition; } @Override public Integer calculate(String columnValue) { try { int targetPartition; Calendar curTime = Calendar.getInstance(); curTime.setTime(formatter.get().parse(columnValue)); targetPartition = ((curTime.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR)) * 12 + curTime.get(Calendar.MONTH) - beginDate.get(Calendar.MONTH)); /** * For circulatory partition, calculated value of target partition needs to be * rotated to fit the partition range */ if (nPartition > 0) { targetPartition = reCalculatePartition(targetPartition); } return targetPartition; } catch (ParseException e) { throw new IllegalArgumentException(new StringBuilder().append("columnValue:").append(columnValue).append(" Please check if the format satisfied.").toString(),e); } } @Override public Integer[] calculateRange(String beginValue, String endValue) { try { int startPartition, endPartition; Calendar partitionTime = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat(dateFormat); partitionTime.setTime(format.parse(beginValue)); startPartition = ((partitionTime.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR)) * 12 + partitionTime.get(Calendar.MONTH) - beginDate.get(Calendar.MONTH)); partitionTime.setTime(format.parse(endValue)); endPartition = ((partitionTime.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR)) * 12 + partitionTime.get(Calendar.MONTH) - beginDate.get(Calendar.MONTH)); List<Integer> list = new ArrayList<>(); while (startPartition <= endPartition) { Integer nodeValue = reCalculatePartition(startPartition); if (Collections.frequency(list, nodeValue) < 1) list.add(nodeValue); startPartition++; } int size = list.size(); return (list.toArray(new Integer[size])); } catch (ParseException e) { LOGGER.error(e); return new Integer[0]; } } public void setsBeginDate(String sBeginDate) { this.sBeginDate = sBeginDate; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } public void setsEndDate(String sEndDate) { this.sEndDate = sEndDate; } }
package org.minimalj.frontend.page; import org.minimalj.backend.Backend; import org.minimalj.frontend.Frontend.IContent; import org.minimalj.frontend.editor.Editor; import org.minimalj.frontend.form.Form; import org.minimalj.util.CloneHelper; import org.minimalj.util.GenericUtils; import org.minimalj.util.IdUtils; import org.minimalj.util.resources.Resources; /** * This page requires the object to be persistet. Meaning the object has to have * its id. If you want to display an object without involving a backend use a * normal page with this pattern: * * <pre> * public class TeaCup extends Page { * * private final TaxStatement teaCup; * * public TeaCup(TaxStatement teaCup) { * this.teaCup = teaCup; * } * * public IContent getContent() { * TaxStatementForm form = new TaxStatementForm(Form.READ_ONLY); * form.setObject(teaCup); * return form.getContent(); * } * } * </pre> * * But be carefull as this pattern keeps the complete object in the memory. */ public abstract class ObjectPage<T> extends Page { private final Class<T> objectClass; private Object objectId; private transient T object; private transient Form<T> form; @SuppressWarnings("unchecked") public ObjectPage(T object) { this((Class<T>) object.getClass(), IdUtils.getId(object, !IdUtils.PLAIN)); } public ObjectPage(Class<T> objectClass, Object objectId) { this.objectClass = objectClass; this.objectId = objectId; } public void setObject(T object) { if (object == null) { throw new NullPointerException(); } else if (object.getClass() != objectClass) { throw new IllegalArgumentException("Object is " + object.getClass() + " instead of " + objectClass); } else { objectId = IdUtils.getId(object, !IdUtils.PLAIN); this.object = object; if (form != null) { form.setObject(object); } } } @Override public String getTitle() { String title = Resources.getStringOrNull(getClass()); if (title != null) { return title; } else { Class<?> clazz = GenericUtils.getGenericClass(getClass()); return Resources.getString(clazz); } } protected abstract Form<T> createForm(); public Class<T> getObjectClass() { return objectClass; } public Object getObjectId() { return objectId; } public T getObject() { if (object == null) { object = load(); } return object; } @Override public IContent getContent() { if (form == null) { form = createForm(); } unload(); // TODO try catch around getObject to catch load problems and display stack trace form.setObject(getObject()); return form.getContent(); } public T load() { return Backend.read(objectClass, objectId); } public void unload() { object = null; } public void refresh() { setObject(load()); } public abstract class ObjectEditor extends Editor<T, T> { @Override protected T createObject() { return CloneHelper.clone(ObjectPage.this.getObject()); } @Override protected Object[] getNameArguments() { Class<?> editedClass = GenericUtils.getGenericClass(ObjectPage.this.getClass()); if (editedClass != null) { String resourceName = Resources.getResourceName(editedClass); return new Object[] { Resources.getString(resourceName) }; } else { return null; } } @Override protected void finished(T result) { setObject(result); } } }
package voogasalad_GucciGames.gameData.wrapper; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.thoughtworks.xstream.annotations.XStreamOmitField; import voogasalad_GucciGames.gameEngine.GameEngineClient; import voogasalad_GucciGames.gameEngine.GameEnginePlayer; import voogasalad_GucciGames.gameEngine.GameEngineServer; import voogasalad_GucciGames.gameEngine.GameEngineToGamePlayerInterface; import voogasalad_GucciGames.gameEngine.GameLevelEngine; import voogasalad_GucciGames.gameEngine.PlayerMapObjectInterface; import voogasalad_GucciGames.gameEngine.CommunicationParameters.ChangedParameters; import voogasalad_GucciGames.gameEngine.CommunicationParameters.GridCoordinateParameters; import voogasalad_GucciGames.gameEngine.gamePlayer.AllPlayers; import voogasalad_GucciGames.gameEngine.gamePlayer.GamePlayerPerson; import voogasalad_GucciGames.gameEngine.gamePlayer.chars.APlayerChars; import voogasalad_GucciGames.gameEngine.gamePlayer.chars.PlayerScore; import voogasalad_GucciGames.gameEngine.targetCoordinate.ATargetCoordinate; import voogasalad_GucciGames.gameplayer.controller.GameController; import voogasalad_GucciGames.gameplayer.controller.GameParametersInterface; /** * * This class will be a wrapper for the game engine and the information to * configure the game player gui * */ public class GameEngine implements IGameInfoToGAE, GameEngineToGamePlayerInterface { private static final int MAINMENU = -1; private Map<String, GameLevelEngine> myLevelsMap; private String myGameName; private String myCurrentLevel; private GameStats myGameStats; private List<String> played; private String myInitialLevel; private boolean isChangingLevel; private List<String> transferablePlayerCharacteristics; private volatile GameEnginePlayer iAmAPlayer; private volatile Thread t; @XStreamOmitField private GameController myController; public GameEngine(String initialLevel) { myLevelsMap = new HashMap<String, GameLevelEngine>(); this.myInitialLevel = initialLevel; this.myCurrentLevel = initialLevel; this.myGameStats = new GameStats(); myGameName = "RandomName"; this.transferablePlayerCharacteristics = new ArrayList<String>(); this.transferablePlayerCharacteristics.add("PlayerScore"); isChangingLevel = false; this.played = new ArrayList<>(); } public void setCurrentLevel(String level) { myCurrentLevel = level; } public GameEngine(String initialLevel, String gameName) { this(initialLevel); myGameName = gameName; } public void beHost() { iAmAPlayer = new GameEngineServer(this); t = new Thread(iAmAPlayer); t.start(); } public void beClient(String ipAddr) { iAmAPlayer = new GameEngineClient(this, ipAddr); t = new Thread(iAmAPlayer); t.start(); } public void resetGame() { // then here too myCurrentLevel = myInitialLevel; } @Override public void changeCurrentLevel(String newGameLevel) { if (this == null) { return; } myCurrentLevel = newGameLevel; if (iAmAPlayer != null) { iAmAPlayer.setLevelEngine(getCurrentLevel()); } isChangingLevel = true; // Have to have same number of players between levels myCurrentLevel = newGameLevel; // System.out.println("Tina " + newGameLevel); // if (!played.contains(newGameLevel)){ setUpGameStats(); // System.out.println("here "+newGameLevel); // played.add(newGameLevel); } private boolean setUpGameStats() { this.getCurrentLevel().setGameStats(myGameStats); AllPlayers players = this.getCurrentLevel().getPlayers(); for (Integer id : players.getAllIds()) { GamePlayerPerson player = players.getPlayerById(id); for (String ch : transferablePlayerCharacteristics) { if (player.hasCharacteristic(ch)) { this.myGameStats.addTransferableCharacteristic(id, player.getCharacteristics(ch), ch); } } } return true; } @Override public String getGameName() { return this.myGameName; } public void addLevel(String levelName, GameLevelEngine myEngine) { myEngine.setName(levelName); myLevelsMap.put(levelName, myEngine); } // I'm sorry for the code below // Java wouldn't let me modify the return type in the interface, don't know // why @Override public Map<String, IGameLevelToGamePlayer> getLevelsMap() { return Collections.unmodifiableMap(myLevelsMap); } @Override public List<String> getChoosableLevels() { List<String> levelNames = new ArrayList<String>(); for (GameLevelEngine engine : myLevelsMap.values()) { if (engine.isMyChoosability()) { levelNames.add(engine.getLevelName()); } } return levelNames; } @Override public void setLevel(String gameName, GameLevelEngine engine) { engine.setName(gameName); myLevelsMap.put(gameName, engine); } public GameLevelEngine getCurrentLevel() { // TODO Auto-generated method stub if (isChangingLevel) { updateTransfer(); isChangingLevel = false; } return myLevelsMap.get(myCurrentLevel); } private boolean updateTransfer() { AllPlayers players = this.myLevelsMap.get(myCurrentLevel).getPlayers(); for (Integer id : players.getAllIds()) { if (this.myGameStats.contains(id)) { GamePlayerPerson player = players.getPlayerById(id); Map<String, APlayerChars> map = this.myGameStats.getCharacteristics(id); for (String ch : map.keySet()) { player.addCharacterstic(ch, map.get(ch)); } } } return true; } @Override public String getName() { return getCurrentLevel().getLevelName(); } @Override public List<PlayerMapObjectInterface> getInitialState() { return getCurrentLevel().getInitialState(); } @Override public GameParametersInterface endTurn() { GameParametersInterface myParams = getCurrentLevel().endTurn(); if (iAmAPlayer != null) { iAmAPlayer.endTurn(); } return myParams; } @Override public int getTurnPlayerID() { return getCurrentLevel().getTurnPlayerID(); } @Override public GridCoordinateParameters getPossibleCoordinates(String action, PlayerMapObjectInterface mapObject) { return null; } @Override public ChangedParameters performAction(String action, PlayerMapObjectInterface mapObject, ATargetCoordinate target) { return null; } @Override public int getMapWidth() { // TODO Auto-generated method stub return getCurrentLevel().getMapWidth(); } @Override public int getMapHeight() { return getCurrentLevel().getMapHeight(); } @Override public GameParametersInterface getGameParameters() { return getCurrentLevel().getGameParameters(); } @Override public boolean hasLevelEnded() { return getCurrentLevel().hasLevelEnded(); } @Override public APlayerChars getPlayerCharacteristic(String name, int id) { // TODO Auto-generated method stub return this.myLevelsMap.get(myCurrentLevel).getPlayers().getPlayerById(id).getCharacteristics(name); } @Override public void addTransferableCharacteristic(String name) { this.transferablePlayerCharacteristics.add(name); } public void refreshGUI() { // TODO Auto-generated method stub System.out.println("NOW I AM ASKING GUI TO REFRESH"); myController.refreshGUI(); } public GameController getController() { return myController; } @Override public void setController(GameController myController) { this.myController = myController; } @Override public void setEngine(String gameName, GameLevelEngine engine) { myLevelsMap.put(gameName, engine); } }
package org.mac.sim.controller; import org.mac.sim.domain.SimulationBuilder; import org.mac.sim.thread.QueueManager; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping() public class SimController { @RequestMapping(path = "/run") public void runIt() { SimulationBuilder sb = new SimulationBuilder(); sb.setMonthsToPeakProductivity(12); sb.setTotalEmployees(100); sb.setPercentYearlyTurnOver(.06); sb.setYearsToSimulate(2); sb.build(); } @RequestMapping("/thread") public void runThreads(){ System.out.println("does this work?"); QueueManager qm = new QueueManager(null, 0, 0); qm.run(); } }
package dynamake.transcription; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import dynamake.commands.CommandStateWithOutput; import dynamake.commands.ContextualCommand; import dynamake.commands.CommandState; import dynamake.commands.ExecutionScope; import dynamake.commands.ReversibleCommand; import dynamake.delegates.Func0; import dynamake.models.Location; import dynamake.models.Model; import dynamake.models.ModelRootLocation; import dynamake.models.PropogationContext; public class SnapshottingTranscriber<T> implements Transcriber<T> { private Func0<T> prevalentSystemFunc; private T prevalentSystem; private int transactionEnlistingCount = 0; private int snapshotThreshold = 100; private ExecutorService transactionExecutor; private String prevalanceDirectory; private static String journalFileName = "log"; private static String journalFile = journalFileName + ".jnl"; private static String snapshotFile = "snap.shot"; private ExecutorService journalLogger; public SnapshottingTranscriber(Func0<T> prevalentSystemFunc) throws Exception { this.prevalentSystemFunc = prevalentSystemFunc; transactionExecutor = Executors.newSingleThreadExecutor(); journalLogger = Executors.newSingleThreadExecutor(); prevalanceDirectory = "jnl"; // One current journal with a predictive name and multiple old journals with predictive naming // One latest snapshot with a predictive name and multiple old snapshot with predictive naming // Each snapshot has a reference to its relative journal // When a snapshot is enqueue, then the current journal is closed and referenced to from the snapshot made followingly // such that it is known which journal to start from after the snapshot has been read. boolean journalExisted = true; boolean snapshotExisted = true; Path prevalanceDirectoryPath = Paths.get(prevalanceDirectory); if(!java.nio.file.Files.exists(prevalanceDirectoryPath)) { java.nio.file.Files.createDirectory(prevalanceDirectoryPath); journalExisted = false; } Path journalFilePath = Paths.get(prevalanceDirectory + "/" + journalFile); if(!java.nio.file.Files.exists(journalFilePath)) { java.nio.file.Files.createFile(journalFilePath); journalExisted = false; } Path snapshotFilePath = Paths.get(prevalanceDirectory + "/" + snapshotFile); if(!java.nio.file.Files.exists(snapshotFilePath)) { snapshotExisted = false; } if(snapshotExisted) { Snapshot<T> snapshot = loadSnapshot(prevalanceDirectory + "/" + snapshotFile); prevalentSystem = snapshot.prevalentSystem; } else prevalentSystem = prevalentSystemFunc.call(); if(journalExisted) { ArrayList<ContextualCommand<T>> transactions = readJournal(prevalanceDirectory + "/" + journalFile); replay(transactions, prevalentSystem); // Update the number of enlisted transactions which is used in the snapshotting logic transactionEnlistingCount += transactions.size(); } } private static <T> Snapshot<T> loadAndReplay(Func0<T> prevalantSystemFunc, String journalPath, String snapshotPath) throws ClassNotFoundException, IOException { Snapshot<T> snapshot; Path snapshotFilePath = Paths.get(snapshotPath); if(java.nio.file.Files.exists(snapshotFilePath)) snapshot = loadSnapshot(snapshotPath); else { T prevalantSystem = prevalantSystemFunc.call(); snapshot = new Snapshot<T>(prevalantSystem); } replay(snapshot.prevalentSystem, journalPath); return snapshot; } private static <T> ArrayList<ContextualCommand<T>> readJournal(String journalPath) throws ClassNotFoundException, IOException { ArrayList<ContextualCommand<T>> transactions = new ArrayList<ContextualCommand<T>>(); FileInputStream fileOutput = new FileInputStream(journalPath); BufferedInputStream bufferedOutput = new BufferedInputStream(fileOutput); try { while(bufferedOutput.available() != 0) { // Should be read in chunks ObjectInputStream objectOutput = new ObjectInputStream(bufferedOutput); @SuppressWarnings("unchecked") ContextualCommand<T> transaction = (ContextualCommand<T>)objectOutput.readObject(); transactions.add(transaction); } } finally { bufferedOutput.close(); } return transactions; } @SuppressWarnings("unchecked") private static <T> void replay(TransactionHandler<T> parentTransactionHandler, ContextualCommand<T> ctxTransaction, T prevalentSystem, PropogationContext propCtx, Collector<T> isolatedCollector) { Location locationFromReference = new ModelRootLocation(); T reference = (T)ctxTransaction.locationFromRootToReference.getChild(prevalentSystem); TransactionHandler<T> transactionHandler = ctxTransaction.transactionHandlerFactory.createTransactionHandler(reference); transactionHandler.startLogFor(parentTransactionHandler, reference); ExecutionScope scope = transactionHandler.getScope(); for(Object transactionFromRoot: ctxTransaction.transactionsFromRoot) { if(transactionFromRoot instanceof ReversibleCommand) { ReversibleCommand<T> entry = (ReversibleCommand<T>)transactionFromRoot; entry.executeForward(propCtx, reference, isolatedCollector, locationFromReference, scope); transactionHandler.logFor((T)reference, entry, propCtx, 0, isolatedCollector); } else if(transactionFromRoot instanceof ContextualCommand) { replay(transactionHandler, (ContextualCommand<T>)transactionFromRoot, prevalentSystem, propCtx, isolatedCollector); } } transactionHandler.commitLogFor(reference); } private static <T> void replay(ArrayList<ContextualCommand<T>> transactions, T prevalentSystem) { PropogationContext propCtx = new PropogationContext(); Collector<T> isolatedCollector = new NullCollector<T>(); for(ContextualCommand<T> ctxTransaction: transactions) replay(null, ctxTransaction, prevalentSystem, propCtx, isolatedCollector); } private static <T> void replay(T prevalentSystem, String journalPath) throws ClassNotFoundException, IOException { ArrayList<ContextualCommand<T>> transactions = readJournal(journalPath); replay(transactions, prevalentSystem); } private static class Snapshot<T> implements Serializable { private static final long serialVersionUID = 1L; public final T prevalentSystem; public Snapshot(T prevalentSystem) { this.prevalentSystem = prevalentSystem; } } private static <T> Snapshot<T> loadSnapshot(String snapshotPath) throws IOException, ClassNotFoundException { FileInputStream fileOutput = new FileInputStream(snapshotPath); BufferedInputStream bufferedOutput = new BufferedInputStream(fileOutput); ObjectInputStream objectOutput = new ObjectInputStream(bufferedOutput); @SuppressWarnings("unchecked") Snapshot<T> snapshot = (Snapshot<T>)objectOutput.readObject(); bufferedOutput.close(); return snapshot; } private static <T> void saveSnapshot(Func0<T> prevalantSystemFunc, String journalPath, String snapshotPath) throws ClassNotFoundException, IOException, ParseException { // Close journal Path currentJournalFilePath = Paths.get(journalPath); String nowFormatted = "" + System.nanoTime(); Path closedJournalFilePath = Paths.get(currentJournalFilePath.getParent() + "/" + nowFormatted + currentJournalFilePath.getFileName()); java.nio.file.Files.move(currentJournalFilePath, closedJournalFilePath); // Start new journal java.nio.file.Files.createFile(currentJournalFilePath); // Close snapshot Path currentSnapshotFilePath = Paths.get(snapshotPath); Path closedSnapshotFilePath = Paths.get(currentSnapshotFilePath.getParent() + "/" + nowFormatted + currentSnapshotFilePath.getFileName()); if(java.nio.file.Files.exists(currentSnapshotFilePath)) java.nio.file.Files.move(currentSnapshotFilePath, closedSnapshotFilePath); // Load copy of last snapshot (if any) and replay missing transactions; Snapshot<T> snapshot = loadAndReplay(prevalantSystemFunc, closedJournalFilePath.toString(), closedSnapshotFilePath.toString()); // Save modified snapshot FileOutputStream fileOutput = new FileOutputStream(snapshotPath, true); BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput); ObjectOutputStream objectOutput = new ObjectOutputStream(bufferedOutput); objectOutput.writeObject(snapshot); objectOutput.close(); } private void saveSnapshot() throws ClassNotFoundException, IOException, ParseException { saveSnapshot(prevalentSystemFunc, prevalanceDirectory + "/" + journalFile, prevalanceDirectory + "/" + snapshotFile); } public void executeTransient(Runnable runnable) { transactionExecutor.execute(runnable); } public void persistTransaction(final ContextualCommand<T> transaction) { journalLogger.execute(new Runnable() { @Override public void run() { try { // Should be written in chunks FileOutputStream fileOutput = new FileOutputStream(prevalanceDirectory + "/" + "log.jnl", true); BufferedOutputStream bufferedOutput = new BufferedOutputStream(fileOutput); ObjectOutputStream objectOutput = new ObjectOutputStream(bufferedOutput); objectOutput.writeObject(transaction); objectOutput.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // System.out.println("Persisted transaction."); transactionEnlistingCount++; if(transactionEnlistingCount >= snapshotThreshold) { System.out.println("Enlisted snapshot on thread " + Thread.currentThread().getId()); // TODO: Consider: Should an isolated propogation context created here? I.e., a snapshot propogation context? try { // Could be separated into the following: // Close latest journal and snapshot // With other execution service: Save snapshot based on closed journal and snapshot saveSnapshot(); } catch (ClassNotFoundException | IOException | ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } transactionEnlistingCount = 0; } } }); } @Override public void close() { try { transactionExecutor.shutdown(); journalLogger.shutdown(); } catch (Exception e) { e.printStackTrace(); } } @Override public T prevalentSystem() { return prevalentSystem; } private static class Instruction implements Serializable { private static final long serialVersionUID = 1L; public static final int OPCODE_START = 0; public static final int OPCODE_COMMIT = 1; public static final int OPCODE_REJECT = 2; public static final int OPCODE_FLUSH_NEXT_TRIGGER = 3; public static final int OPCODE_SEND_PROPOGATION_FINISHED = 4; public static final int OPCODE_PRODUCE = 5; public static final int OPCODE_CONSUME = 6; public final int type; public final Object operand1; public final Object operand2; public Instruction(int type) { this.type = type; this.operand1 = null; this.operand2 = null; } public Instruction(int type, Object operand1) { this.type = type; this.operand1 = operand1; this.operand2 = null; } public Instruction(int type, Object operand1, Object operand2) { this.type = type; this.operand1 = operand1; this.operand2 = operand2; } } public static class Connection<T> implements dynamake.transcription.Connection<T> { private TriggerHandler<T> triggerHandler; private SnapshottingTranscriber<T> transcriber; private TransactionFrame<T> currentFrame; public Connection(SnapshottingTranscriber<T> transcriber, TriggerHandler<T> triggerHandler) { this.transcriber = transcriber; this.triggerHandler = triggerHandler; } private static class TransactionFrame<T> { public final TransactionFrame<T> parent; public final T reference; public final Location locationFromRootToReference; public final TransactionHandlerFactory<T> handlerFactory; public final TransactionHandler<T> handler; // Somehow, flushed transaction should both be able to consist of atomic commands and committed transactions // This is needed in order to keep the order of the flushed commands/transaction correct // - and this is important during replay and reject public ArrayList<Object> flushedTransactionsFromRoot = new ArrayList<Object>(); // List of either atomic commands or transactions public TransactionFrame(TransactionFrame<T> parent, T reference, Location locationFromRootToReference, TransactionHandlerFactory<T> transactionHandlerFactory, TransactionHandler<T> handler) { this.parent = parent; this.reference = reference; this.locationFromRootToReference = locationFromRootToReference; this.handlerFactory = transactionHandlerFactory; this.handler = handler; } } private static class ReversibleInstructionPair<T> implements ReversibleCommand<T> { private static final long serialVersionUID = 1L; private final Instruction instruction; private final Object operand1; public ReversibleInstructionPair(Instruction instruction, Object operand1) { this.instruction = instruction; this.operand1 = operand1; } @Override public void executeForward(PropogationContext propCtx, T prevalentSystem, Collector<T> collector, Location location, ExecutionScope scope) { switch(instruction.type) { case Instruction.OPCODE_PRODUCE: Object valueToProduce = instruction.operand1; scope.produce(valueToProduce); break; case Instruction.OPCODE_CONSUME: scope.consume(); break; } } @Override public void executeBackward(PropogationContext propCtx, T prevalentSystem, Collector<T> collector, Location location, ExecutionScope scope) { switch(instruction.type) { case Instruction.OPCODE_PRODUCE: scope.unproduce(); break; case Instruction.OPCODE_CONSUME: Object consumedValue = operand1; scope.unconsume(consumedValue); break; } } } @Override public void trigger(final Trigger<T> trigger) { this.transcriber.transactionExecutor.execute(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { final PropogationContext propCtx = new PropogationContext(); final LinkedList<Object> commands = new LinkedList<Object>(); commands.add(trigger); Stack<List<Execution<T>>> propogationStack = new Stack<List<Execution<T>>>(); final ArrayList<Runnable> onAfterNextTrigger = new ArrayList<Runnable>(); while(!commands.isEmpty()) { Object command = commands.pop(); final ArrayList<Object> collectedCommands = new ArrayList<Object>(); Collector<T> collector = new Collector<T>() { @Override public void startTransaction(T reference, Object transactionHandlerClass) { TransactionHandlerFactory<T> transactionHandlerFactory; if(transactionHandlerClass instanceof Class) transactionHandlerFactory = new ReflectedTransactionHandlerFactory<T>((Class<? extends TransactionHandler<T>>)transactionHandlerClass); else transactionHandlerFactory = (TransactionHandlerFactory<T>)transactionHandlerClass; collectedCommands.add(new Instruction(Instruction.OPCODE_START, reference, transactionHandlerFactory)); } @Override public Object createProduceCommand(Object value) { return new Instruction(Instruction.OPCODE_PRODUCE, value); } @Override public Object createConsumeCommand() { return new Instruction(Instruction.OPCODE_CONSUME); } @Override public void execute(Object command) { if(command instanceof List) { // Assumed to be a list of reversible commands List<ReversibleCommand<T>> reversiblesCommands = (List<ReversibleCommand<T>>)command; collectedCommands.addAll(reversiblesCommands); } else if(command instanceof PendingCommandFactory) { collectedCommands.add(command); collectedCommands.add(new Instruction(Instruction.OPCODE_SEND_PROPOGATION_FINISHED, command)); } else { collectedCommands.add(command); } } @Override public void commitTransaction() { collectedCommands.add(Instruction.OPCODE_COMMIT); } @Override public void rejectTransaction() { collectedCommands.add(Instruction.OPCODE_REJECT); } @Override public void afterNextTrigger(Runnable runnable) { onAfterNextTrigger.add(runnable); } @Override public void flushNextTrigger() { collectedCommands.add(Instruction.OPCODE_FLUSH_NEXT_TRIGGER); } }; if(command instanceof Integer) { int i = (int)command; switch(i) { case Instruction.OPCODE_COMMIT: doCommit(); break; case Instruction.OPCODE_REJECT: doReject(); break; case Instruction.OPCODE_FLUSH_NEXT_TRIGGER: if(onAfterNextTrigger.size() > 0) { triggerHandler.handleAfterTrigger(new ArrayList<Runnable>(onAfterNextTrigger)); onAfterNextTrigger.clear(); } break; } } else if(command instanceof Instruction) { Instruction instruction = (Instruction)command; switch(instruction.type) { case Instruction.OPCODE_START: T reference = (T)instruction.operand1; TransactionHandlerFactory<T> transactionHandlerFactory = (TransactionHandlerFactory<T>)instruction.operand2; TransactionHandler<T> transactionHandler = transactionHandlerFactory.createTransactionHandler(reference); transactionHandler.startLogFor(currentFrame != null ? currentFrame.handler : null, reference); Location locationFromRoot = ((Model)reference).getLocator().locate(); currentFrame = new TransactionFrame<T>(currentFrame, reference, locationFromRoot, transactionHandlerFactory, transactionHandler); break; case Instruction.OPCODE_SEND_PROPOGATION_FINISHED: List<Execution<T>> pendingUndoablePairs = propogationStack.pop(); if(pendingUndoablePairs.size() != 1) { new String(); } Execution<T> execution = pendingUndoablePairs.get(0); ((PendingCommandFactory<T>)instruction.operand1).afterPropogationFinished(execution, propCtx, 0, collector); break; case Instruction.OPCODE_PRODUCE: logBeforeExecution(command, propCtx, collector); Object valueToProduce = instruction.operand1; currentFrame.handler.getScope().produce(valueToProduce); logExecution(new ReversibleInstructionPair<T>(instruction, new Instruction(Instruction.OPCODE_CONSUME)), propCtx, collector); break; case Instruction.OPCODE_CONSUME: logBeforeExecution(command, propCtx, collector); Object consumedValue = currentFrame.handler.getScope().consume(); logExecution(new ReversibleInstructionPair<T>(instruction, consumedValue), propCtx, collector); break; } } else if(command instanceof PendingCommandFactory) { TransactionFrame<T> frame = currentFrame; PendingCommandFactory<T> transactionFactory = (PendingCommandFactory<T>)command; T reference = frame.reference; TransactionHandler<T> transactionHandler = frame.handler; Location locationFromReference = new ModelRootLocation(); // If location was part of the executeOn invocation, location is probably no // necessary for creating dual commands. Further, then, it is probably not necessary // to create two sequences of pendingCommands. CommandState<T> pendingCommand = transactionFactory.createPendingCommand(); // Assumed that exactly one command is created consistenly // Should be in pending state ArrayList<CommandState<T>> undoables = new ArrayList<CommandState<T>>(); ExecutionScope scope = transactionHandler.getScope(); // The command in pending state should return a command in undoable state CommandState<T> undoableCommand = pendingCommand.executeOn(propCtx, reference, collector, locationFromReference, scope); undoables.add(undoableCommand); // frame.flushedUndoableTransactionsFromReferences.add(new UndoableCommandFromReference<T>(reference, undoables)); ArrayList<Execution<T>> pendingUndoablePairs = new ArrayList<Execution<T>>(); CommandStateWithOutput<T> undoable = (CommandStateWithOutput<T>)undoables.get(0); Execution<T> pendingUndoablePair = new Execution<T>(pendingCommand, undoable); pendingUndoablePairs.add(pendingUndoablePair); ArrayList<CommandState<T>> pendingCommands = new ArrayList<CommandState<T>>(); pendingCommands.add(pendingCommand); propogationStack.push(pendingUndoablePairs); } else if(command instanceof ReversibleCommand) { ReversibleCommand<T> rCommand = (ReversibleCommand<T>)command; Location locationFromReference = new ModelRootLocation(); ExecutionScope scope = currentFrame.handler.getScope(); logBeforeExecution(rCommand, propCtx, collector); rCommand.executeForward(propCtx, currentFrame.reference, collector, locationFromReference, scope); logExecution(rCommand, propCtx, collector); } else if(command instanceof Trigger) { // TODO: Consider: Should it be possible to hint which model to base the trigger on? ((Trigger<T>)command).run(collector); } if(collectedCommands.size() > 0) { commands.addAll(0, collectedCommands); } } if(onAfterNextTrigger.size() > 0) { triggerHandler.handleAfterTrigger(onAfterNextTrigger); } // System.out.println("Finished trigger"); } }); } private void logBeforeExecution(Object rCommand, PropogationContext propCtx, Collector<T> collector) { currentFrame.handler.logBeforeFor(currentFrame.reference, rCommand, propCtx, 0, collector); } private void logExecution(ReversibleCommand<T> rCommand, PropogationContext propCtx, Collector<T> collector) { currentFrame.handler.logFor(currentFrame.reference, rCommand, propCtx, 0, collector); currentFrame.flushedTransactionsFromRoot.add(rCommand); } private void doCommit() { if(currentFrame.flushedTransactionsFromRoot.size() > 0) { final ArrayList<Runnable> onAfterNextTrigger = new ArrayList<Runnable>(); currentFrame.handler.commitLogFor(currentFrame.reference); ArrayList<Object> transactionsFromRoot = new ArrayList<Object>(); buildTransactionToPersist(transactionsFromRoot, currentFrame); ContextualCommand<T> transactionToPersist = new ContextualCommand<T>(currentFrame.locationFromRootToReference, currentFrame.handlerFactory, transactionsFromRoot); if(currentFrame.parent == null) { // System.out.println("Committed connection"); transcriber.persistTransaction(transactionToPersist); if(onAfterNextTrigger.size() > 0) { triggerHandler.handleAfterTrigger(onAfterNextTrigger); } } else { currentFrame.parent.flushedTransactionsFromRoot.add(currentFrame); } } currentFrame = currentFrame.parent; } @SuppressWarnings("unchecked") private void buildTransactionToPersist(ArrayList<Object> transactionsFromRoot, TransactionFrame<T> frame) { for(Object committedExecution: frame.flushedTransactionsFromRoot) { if(committedExecution instanceof ReversibleCommand) { transactionsFromRoot.add(committedExecution); } else if(committedExecution instanceof TransactionFrame) { TransactionFrame<T> innerFrame = (TransactionFrame<T>)committedExecution; ArrayList<Object> innerTransactionsFromRoot = new ArrayList<Object>(); buildTransactionToPersist(innerTransactionsFromRoot, innerFrame); transactionsFromRoot.add(new ContextualCommand<T>(innerFrame.locationFromRootToReference, innerFrame.handlerFactory, innerTransactionsFromRoot)); } } } private void doReject() { PropogationContext propCtx = new PropogationContext(); final ArrayList<Runnable> onAfterNextTrigger = new ArrayList<Runnable>(); Collector<T> isolatedCollector = new NullCollector<T>() { @Override public void afterNextTrigger(Runnable runnable) { onAfterNextTrigger.add(runnable); } }; currentFrame.handler.rejectLogFor(currentFrame.reference); while(currentFrame != null) { rejectTransaction(propCtx, isolatedCollector, currentFrame); currentFrame = currentFrame.parent; } System.out.println("Rejected connection"); if(onAfterNextTrigger.size() > 0) { triggerHandler.handleAfterTrigger(onAfterNextTrigger); } } private static <T> void rejectTransaction(PropogationContext propCtx, Collector<T> isolatedCollector, TransactionFrame<T> frame) { ExecutionScope scope = frame.handler.getScope(); for(int i = frame.flushedTransactionsFromRoot.size() - 1; i >= 0; i Object committedExecution = frame.flushedTransactionsFromRoot.get(i); if(committedExecution instanceof ReversibleCommand) { @SuppressWarnings("unchecked") ReversibleCommand<T> undoableTransaction = (ReversibleCommand<T>)committedExecution; Location locationFromReference = new ModelRootLocation(); undoableTransaction.executeBackward(propCtx, frame.reference, isolatedCollector, locationFromReference, scope); } else if(committedExecution instanceof TransactionFrame) { @SuppressWarnings("unchecked") TransactionFrame<T> innerFrame = (TransactionFrame<T>)committedExecution; rejectTransaction(propCtx, isolatedCollector, innerFrame); } } } } @Override public Connection<T> createConnection(TriggerHandler<T> flushHandler) { return new Connection<T>(this, flushHandler); } }
package kr.jm.utils.exception; import kr.jm.utils.AutoStringBuilder; import kr.jm.utils.helper.JMLog; import kr.jm.utils.helper.JMResources; import org.slf4j.Logger; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.function.Supplier; public class JMExceptionManager { private static final String ERROR_HISTORY_SIZE = "error.history.size"; static { JMResources.setSystemPropertyIfIsNull(ERROR_HISTORY_SIZE, 500); } private static final String LINE_SEPARATOR = System .getProperty("line.separator"); private static final int maxQueueSize = new Integer( JMResources.getSystemProperty(ERROR_HISTORY_SIZE)); private static List<ErrorMessageHistory> errorMessageHistoryList = new LinkedList<ErrorMessageHistory>(); private static long errorCount = 0; public static void logException(Logger log, Exception e, String methodName, Object... params) { if (params.length > 0) JMLog.logException(log, e, methodName, params); else JMLog.logException(log, e, methodName); increaseErrorCount(); recordErrorMessageHistory(e); } private static void recordErrorMessageHistory(Exception e) { if (errorMessageHistoryList.size() >= maxQueueSize) errorMessageHistoryList.remove(0); errorMessageHistoryList.add(new ErrorMessageHistory(System .currentTimeMillis(), getStackTraceString(e))); } private static String getStackTraceString(Throwable throwable) { AutoStringBuilder stackTraceStringBuilder = new AutoStringBuilder( LINE_SEPARATOR); stackTraceStringBuilder.append(throwable.toString()); for (StackTraceElement stackTraceElement : throwable.getStackTrace()) stackTraceStringBuilder.append(stackTraceElement.toString()); return stackTraceStringBuilder.autoToString(); } public static List<ErrorMessageHistory> getErrorMessageHistoryList() { return errorMessageHistoryList; } public static void clearAll() { removeErrorMessgeHistoryList(); resetErrorCount(); } public static void removeErrorMessgeHistoryList() { errorMessageHistoryList.clear(); } public static long getErrorCount() { return errorCount; } public static void resetErrorCount() { errorCount = 0; } public static void increaseErrorCount() { errorCount++; } public static <T> T handleExceptionAndReturnNull(Logger log, Exception e, String method, Object... params) { logException(log, e, method, params); return null; } public static boolean handleExceptionAndReturnFalse(Logger log, Exception e, String method, Object... params) { logException(log, e, method, params); return false; } public static <T> T handleExceptionAndReturn(Logger log, Exception e, String method, Supplier<T> returnSupplier, Object... params) { logException(log, e, method, params); return returnSupplier.get(); } public static Object handleExceptionAndThrowRuntimeEx(Logger log, Exception e, String method, Object... params) { logException(log, e, method, params); throw new RuntimeException(e); } public static <T> Optional<T> handleExceptionAndReturnEmptyOptioal( Logger log, Exception e, String method, Object... params) { return Optional.empty(); } }
package org.nwapw.abacus.config; import com.moandjiezana.toml.Toml; import com.moandjiezana.toml.TomlWriter; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * The configuration object that stores * options that the user can change. */ public class Configuration { /** * The defaults TOML string. */ private static final String DEFAULT_CONFIG = "numberImplementation = \"naive\"\n" + "disabledPlugins = []"; /** * The defaults TOML object, parsed from the string. */ private static final Toml DEFAULT_TOML = new Toml().read(DEFAULT_CONFIG); /** * The TOML writer used to write this configuration to a file. */ private static final TomlWriter TOML_WRITER = new TomlWriter(); /** * The implementation of the number that should be used. */ private String numberImplementation = "<default>"; /** * The list of disabled plugins in this Configuration. */ private Set<String> disabledPlugins = new HashSet<>(); /** * Creates a new configuration with the given values. * @param numberImplementation the number implementation, like "naive" or "precise" * @param disabledPlugins the list of disabled plugins. */ public Configuration(String numberImplementation, String[] disabledPlugins){ this.numberImplementation = numberImplementation; this.disabledPlugins.addAll(Arrays.asList(disabledPlugins)); } /** * Loads a configuration from a given file, keeping non-specified fields default. * @param fromFile the file to load from. */ public Configuration(File fromFile){ if(!fromFile.exists()) return; copyFrom(new Toml(DEFAULT_TOML).read(fromFile).to(Configuration.class)); } /** * Copies the values from the given configuration into this one. * @param otherConfiguration the configuration to copy from. */ public void copyFrom(Configuration otherConfiguration){ this.numberImplementation = otherConfiguration.numberImplementation; this.disabledPlugins.addAll(otherConfiguration.disabledPlugins); } /** * Saves this configuration to the given file, creating * any directories that do not exist. * @param file the file to save to. */ public void saveTo(File file){ if(file.getParentFile() != null) file.getParentFile().mkdirs(); try { TOML_WRITER.write(this, file); } catch (IOException e) { e.printStackTrace(); } } /** * Gets the number implementation from this configuration. * @return the number implementation. */ public String getNumberImplementation() { return numberImplementation; } /** * Sets the number implementation for the configuration * @param numberImplementation the number implementation. */ public void setNumberImplementation(String numberImplementation) { this.numberImplementation = numberImplementation; } /** * Gets the list of disabled plugins. * @return the list of disabled plugins. */ public Set<String> getDisabledPlugins() { return disabledPlugins; } }
package crazypants.enderio.base; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.tuple.Triple; import com.enderio.core.common.Lang; import com.enderio.core.common.util.NNList; import com.enderio.core.common.util.NullHelper; import com.google.common.collect.ImmutableList; import crazypants.enderio.api.IMC; import crazypants.enderio.api.addon.IEnderIOAddon; import crazypants.enderio.base.capacitor.CapacitorKeyRegistry; import crazypants.enderio.base.conduit.redstone.ConnectivityTool; import crazypants.enderio.base.config.Config; import crazypants.enderio.base.config.config.DiagnosticsConfig; import crazypants.enderio.base.config.recipes.RecipeFactory; import crazypants.enderio.base.config.recipes.RecipeLoader; import crazypants.enderio.base.diagnostics.ProfilerAntiReactor; import crazypants.enderio.base.diagnostics.ProfilerDebugger; import crazypants.enderio.base.events.EnderIOLifecycleEvent; import crazypants.enderio.base.fluid.FluidFuelRegister; import crazypants.enderio.base.fluid.Fluids; import crazypants.enderio.base.gui.handler.GuiHelper; import crazypants.enderio.base.handler.ServerTickHandler; import crazypants.enderio.base.init.CommonProxy; import crazypants.enderio.base.init.ModObject; import crazypants.enderio.base.init.ModObjectRegistry; import crazypants.enderio.base.integration.bigreactors.BRProxy; import crazypants.enderio.base.integration.buildcraft.BuildcraftIntegration; import crazypants.enderio.base.integration.chiselsandbits.CABIMC; import crazypants.enderio.base.integration.te.TEUtil; import crazypants.enderio.base.loot.LootManager; import crazypants.enderio.base.material.recipes.MaterialOredicts; import crazypants.enderio.base.network.PacketHandler; import crazypants.enderio.base.paint.PaintSourceValidator; import crazypants.enderio.base.power.CapInjectHandler; import crazypants.enderio.base.recipe.alloysmelter.AlloyRecipeManager; import crazypants.enderio.base.recipe.sagmill.SagMillRecipeManager; import crazypants.enderio.base.recipe.slicensplice.SliceAndSpliceRecipeManager; import crazypants.enderio.base.recipe.soul.SoulBinderRecipeManager; import crazypants.enderio.base.recipe.vat.VatRecipeManager; import crazypants.enderio.base.transceiver.ServerChannelRegister; import crazypants.enderio.util.CapturedMob; import info.loenwind.scheduler.Celeb; import info.loenwind.scheduler.Scheduler; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.crash.ICrashReportDetail; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCEvent; import net.minecraftforge.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; @Mod(modid = EnderIO.MODID, name = EnderIO.MOD_NAME, version = EnderIO.VERSION, dependencies = EnderIO.DEPENDENCIES, guiFactory = "crazypants.enderio.base.config.ConfigFactoryEIO") public class EnderIO implements IEnderIOAddon { public static final @Nonnull String MODID = "enderio"; public static final @Nonnull String DOMAIN = "enderio"; public static final @Nonnull String MOD_NAME = "Ender IO"; public static final @Nonnull String VERSION = "@VERSION@"; private static final @Nonnull String DEFAULT_DEPENDENCIES = "after:endercore;after:hwyla;after:jei"; public static final @Nonnull String DEPENDENCIES = DEFAULT_DEPENDENCIES; @Instance(MODID) public static EnderIO instance; @SidedProxy(clientSide = "crazypants.enderio.base.init.ClientProxy", serverSide = "crazypants.enderio.base.init.CommonProxy") public static CommonProxy proxy; public static final @Nonnull Lang lang = new Lang(MODID); // prePreInit static { FluidRegistry.enableUniversalBucket(); CapInjectHandler.loadClass(); } @EventHandler public void preInit(@Nonnull FMLPreInitializationEvent event) { Log.debug("PHASE PRE-INIT START"); MinecraftForge.EVENT_BUS.post(new EnderIOLifecycleEvent.Config.Pre()); Config.init(event); MinecraftForge.EVENT_BUS.post(new EnderIOLifecycleEvent.Config.Post()); MinecraftForge.EVENT_BUS.post(new EnderIOLifecycleEvent.PreInit()); proxy.init(event); Log.debug("PHASE PRE-INIT END"); } @EventHandler public void load(@Nonnull FMLInitializationEvent event) { Log.debug("PHASE INIT START"); initCrashData(); // after blocks have been created Fluids.registerFuels(); ModObjectRegistry.init(event); BRProxy.init(event); CABIMC.init(event); PacketHandler.init(event); GuiHelper.init(event); proxy.init(event); Log.debug("PHASE INIT END"); } @EventHandler public void onImc(@Nonnull IMCEvent event) { Log.debug("PHASE IMC START"); processImc(event.getMessages()); /* * This is a mess. * * Items are registered in the registry event between preInit and Init. OreDicts are registered in Init (because Lex says so). MaterialRecipes.init() must * run after all oreDict registrations. RecipeLoader.addRecipes() should run in the registry event. * * At the moment we can delay RecipeLoader.addRecipes(), but still PostInit is too late as there's code that depends on it being done for all submods. */ MaterialOredicts.init(event); // handles oredict registration for dependent entries RecipeLoader.addRecipes(); CapacitorKeyRegistry.validate(); // END mess Log.debug("PHASE IMC END"); } @EventHandler public void postInit(@Nonnull FMLPostInitializationEvent event) { Log.debug("PHASE POST-INIT START"); Config.init(event); ModObjectRegistry.init(event); LootManager.init(event); SagMillRecipeManager.getInstance().create(); AlloyRecipeManager.getInstance().create(); SliceAndSpliceRecipeManager.getInstance().create(); VatRecipeManager.getInstance().create(); SoulBinderRecipeManager.getInstance().addDefaultRecipes(); PaintSourceValidator.instance.loadConfig(); BuildcraftIntegration.init(event); // TEUtil.init(event); proxy.init(event); Celeb.init(event); Scheduler.instance.start(); Log.debug("PHASE POST-INIT END"); } @EventHandler public void loadComplete(@Nonnull FMLLoadCompleteEvent event) { Log.debug("PHASE LOAD COMPLETE START"); // Some mods send IMCs during PostInit, so we catch them here. processImc(FMLInterModComms.fetchRuntimeMessages(this)); Log.debug("PHASE LOAD COMPLETE END"); } @EventHandler public void serverStopped(@Nonnull FMLServerStoppedEvent event) { ServerTickHandler.flush(); ServerChannelRegister.instance.reset(); } @EventHandler public static void onServerStart(FMLServerAboutToStartEvent event) { ServerChannelRegister.instance.reset(); } void processImc(ImmutableList<IMCMessage> messages) { for (IMCMessage msg : messages) { String key = msg.key; Log.info("Processing IMC message " + key + " from " + msg.getSender()); try { if (msg.isStringMessage()) { String value = msg.getStringValue(); if (value == null) { return; } if (IMC.XML_RECIPE.equals(key)) { RecipeLoader.addIMCRecipe(value); } else if (IMC.TELEPORT_BLACKLIST_ADD.equals(key)) { Config.TRAVEL_BLACKLIST.add(value); } else if (IMC.REDSTONE_CONNECTABLE_ADD.equals(key)) { ConnectivityTool.registerRedstoneAware(value); } } else if (msg.isResourceLocationMessage()) { ResourceLocation value = msg.getResourceLocationValue(); if (IMC.SOUL_VIAL_BLACKLIST.equals(key)) { CapturedMob.addToBlackList(value); } else if (IMC.SOUL_VIAL_UNSPAWNABLELIST.equals(key)) { CapturedMob.addToUnspawnableList(value); } } else if (msg.isNBTMessage()) { final NBTTagCompound nbtValue = msg.getNBTValue(); if (nbtValue == null) { return; } if (IMC.SOUL_BINDER_RECIPE.equals(key)) { SoulBinderRecipeManager.getInstance().addRecipeFromNBT(nbtValue); } else if (IMC.FLUID_FUEL_ADD.equals(key)) { FluidFuelRegister.instance.addFuel(nbtValue); } else if (IMC.FLUID_COOLANT_ADD.equals(key)) { FluidFuelRegister.instance.addCoolant(nbtValue); } } else if (msg.isItemStackMessage()) { if (IMC.PAINTER_WHITELIST_ADD.equals(key)) { PaintSourceValidator.instance.addToWhitelist(msg.getItemStackValue()); } else if (IMC.PAINTER_BLACKLIST_ADD.equals(key)) { PaintSourceValidator.instance.addToBlacklist(msg.getItemStackValue()); } } } catch (Exception e) { e.printStackTrace(); Log.error("Error occurred handling IMC message " + key + " from " + msg.getSender()); } } } public static @Nonnull EnderIO getInstance() { return NullHelper.notnullF(instance, "instance is missing"); } @Override @Nullable public Configuration getConfiguration() { return Config.config; } @EventHandler public void onServerAboutToStart(FMLServerAboutToStartEvent event) { if (DiagnosticsConfig.debugProfilerTracer.get()) { ProfilerDebugger.init(event); } else if (DiagnosticsConfig.debugProfilerAntiNuclearActivist.get()) { ProfilerAntiReactor.init(event); } } @Override @Nonnull public NNList<Triple<Integer, RecipeFactory, String>> getRecipeFiles() { return new NNList<>(Triple.of(0, null, "aliases"), Triple.of(1, null, "materials"), Triple.of(1, null, "items"), Triple.of(1, null, "base"), Triple.of(1, null, "balls"), Triple.of(9, null, "misc"), Triple.of(9, null, "capacitor")); } @Override @Nonnull public NNList<String> getExampleFiles() { return new NNList<>("peaceful", "easy_recipes", "hard_recipes", "broken_spawner", "cheap_materials"); } static void initCrashData() { // this is an ugly hack to make sure all anon subclasses of CrashReportCategory that are needed for a crash report are actually loaded CrashReport crashreport = CrashReport.makeCrashReport(new RuntimeException(), "Exception while updating neighbours"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); crashreportcategory.addDetail("Source block type", new ICrashReportDetail<String>() { @Override public String call() throws Exception { return "foo"; } }); CrashReportCategory.addBlockInfo(crashreportcategory, new BlockPos(0, 0, 0), ModObject.block_machine_base.getBlockNN().getDefaultState()); } }
package mcjty.deepresonance.blocks.tank; import com.google.common.collect.Maps; import elec332.core.main.ElecCore; import elec332.core.multiblock.dynamic.IDynamicMultiBlockTile; import elec332.core.network.IElecCoreNetworkTile; import elec332.core.server.ServerHelper; import elec332.core.world.WorldHelper; import mcjty.deepresonance.DeepResonance; import mcjty.deepresonance.api.fluid.IDeepResonanceFluidAcceptor; import mcjty.deepresonance.api.fluid.IDeepResonanceFluidProvider; import mcjty.deepresonance.grid.tank.DRTankMultiBlock; import mcjty.lib.entity.GenericTileEntity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.util.math.BlockPos; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.*; import java.util.Map; public class TileTank extends GenericTileEntity implements IDynamicMultiBlockTile<DRTankMultiBlock>, IFluidHandler, IDeepResonanceFluidAcceptor, IDeepResonanceFluidProvider, IElecCoreNetworkTile { public TileTank(){ super(); this.settings = Maps.newHashMap(); for (EnumFacing direction : EnumFacing.VALUES){ settings.put(direction, Mode.SETTING_NONE); } this.multiBlockSaveData = new NBTTagCompound(); this.tankHooks = Maps.newHashMap(); } // Client only private Fluid clientRenderFluid; private float renderHeight; //Value from 0.0f to 1.0f private NBTTagCompound multiBlockSaveData; protected Map<EnumFacing, Mode> settings; private Map<EnumFacing, ITankHook> tankHooks; public static enum Mode implements IStringSerializable { SETTING_NONE("none"), SETTING_ACCEPT("accept"), // Blue SETTING_PROVIDE("provide"); // Yellow private final String name; Mode(String name) { this.name = name; } @Override public String getName() { return name; } } @Override public void onPacketReceivedFromClient(EntityPlayerMP sender, int ID, NBTTagCompound data) { } public void sendPacket(int ID, NBTTagCompound data) { for (EntityPlayerMP player : ServerHelper.instance.getAllPlayersWatchingBlock(this.worldObj, this.pos)) { player.connection.sendPacket(new SPacketUpdateTileEntity(this.pos, ID, data)); } } @Override public void validate() { super.validate(); ElecCore.tickHandler.registerCall(() -> { if (WorldHelper.chunkLoaded(worldObj, pos)) { onTileLoaded(); } }, worldObj); } @Override public void invalidate() { if (!isInvalid()){ super.invalidate(); onTileUnloaded(); } } @Override public void onChunkUnload() { super.onChunkUnload(); onTileUnloaded(); } public void onTileLoaded() { if (!worldObj.isRemote) { DeepResonance.worldGridRegistry.getTankRegistry().get(worldObj).addTile(this); //MinecraftForge.EVENT_BUS.post(new FluidTileEvent.Load(this)); initHooks(); } } public void onTileUnloaded() { if (!worldObj.isRemote) { DeepResonance.worldGridRegistry.getTankRegistry().get(worldObj).removeTile(this); //MinecraftForge.EVENT_BUS.post(new FluidTileEvent.Unload(this)); for (Map.Entry<EnumFacing, ITankHook> entry : getConnectedHooks().entrySet()){ entry.getValue().unHook(this, entry.getKey().getOpposite()); } getConnectedHooks().clear(); } } public void onNeighborChange(){ Map<EnumFacing, ITankHook> hookMap = getConnectedHooks(); for (EnumFacing facing : EnumFacing.VALUES){ ITankHook tankHook = hookMap.get(facing); BlockPos pos = getPos().offset(facing); TileEntity tile = WorldHelper.chunkLoaded(worldObj, pos) ? WorldHelper.getTileAt(worldObj, pos) : null; if ((tile == null && tankHook != null) || (tile != null && tankHook == null) || (tile != tankHook)){ hookMap.remove(facing); if (tile instanceof ITankHook){ ((ITankHook) tile).hook(this, facing.getOpposite()); hookMap.put(facing, (ITankHook) tile); } } else if (tankHook != null){ tankHook.onContentChanged(this, facing.getOpposite()); } } } private void initHooks(){ tankHooks.clear(); for (EnumFacing facing : EnumFacing.VALUES){ BlockPos pos = getPos().offset(facing); TileEntity tile = WorldHelper.chunkLoaded(worldObj, pos) ? WorldHelper.getTileAt(worldObj, pos) : null; if (tile instanceof ITankHook){ tankHooks.put(facing, (ITankHook) tile); ((ITankHook) tile).hook(this, facing.getOpposite()); } } } private DRTankMultiBlock multiBlock; public FluidStack myTank; public Fluid lastSeenFluid; public Map<EnumFacing, Mode> getSettings() { return settings; } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); NBTTagList tagList = tagCompound.getTagList("settings", Constants.NBT.TAG_COMPOUND); if (tagList != null){ for (int i = 0; i < tagList.tagCount(); i++) { NBTTagCompound tag = tagList.getCompoundTagAt(i); EnumFacing side = EnumFacing.values()[tag.getInteger("dir")]; Mode mode = Mode.values()[tag.getInteger("n")]; settings.put(side, mode); } } } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); NBTTagList tagList = new NBTTagList(); for (Map.Entry<EnumFacing, Mode> entry : settings.entrySet()){ NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("dir", entry.getKey().ordinal()); tag.setInteger("n", entry.getValue().ordinal()); tagList.appendTag(tag); } tagCompound.setTag("settings", tagList); return tagCompound; } @Override public void readRestorableFromNBT(NBTTagCompound tagCompound) { super.readRestorableFromNBT(tagCompound); this.myTank = getFluidStackFromNBT(tagCompound); multiBlockSaveData = tagCompound.getCompoundTag("multiBlockData"); if (tagCompound.hasKey("lastSeenFluid")) { /* legacy compat */ this.lastSeenFluid = FluidRegistry.getFluid(tagCompound.getString("lastSeenFluid")); } else if (multiBlockSaveData.hasKey("lastSeenFluid")){ this.lastSeenFluid = FluidRegistry.getFluid(multiBlockSaveData.getString("lastSeenFluid")); } } public static FluidStack getFluidStackFromNBT(NBTTagCompound tagCompound) { NBTTagCompound mbTag = tagCompound.getCompoundTag("multiBlockData"); FluidStack s; if (tagCompound.hasKey("fluid")) { /* legacy compat */ s = FluidStack.loadFluidStackFromNBT(tagCompound.getCompoundTag("fluid")); } else if (mbTag.hasKey("fluid")){ s = FluidStack.loadFluidStackFromNBT(mbTag.getCompoundTag("fluid")); } else { s = null; } return s; } @Override public void writeRestorableToNBT(NBTTagCompound tagCompound) { super.writeRestorableToNBT(tagCompound); if (multiBlock != null) { getMultiBlock().setDataToTile(this); } ElecCore.systemPrintDebug("Writing restorable NBT @ " + pos); tagCompound.setTag("multiBlockData", multiBlockSaveData); } @Override public void setMultiBlock(DRTankMultiBlock multiBlock) { this.multiBlock = multiBlock; } @Override public DRTankMultiBlock getMultiBlock() { return multiBlock; } @Override public void setSaveData(NBTTagCompound nbtTagCompound) { ElecCore.systemPrintDebug("Setting MB save data @ " + pos); this.multiBlockSaveData = nbtTagCompound; } @Override public NBTTagCompound getSaveData() { return this.multiBlockSaveData; } @Override public int fill(EnumFacing from, FluidStack resource, boolean doFill) { if (!isInput(from)) return 0; notifyChanges(doFill); return multiBlock == null ? 0 : multiBlock.fill(from, resource, doFill); } @Override public FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain) { if (!isOutput(from)) return null; notifyChanges(doDrain); return multiBlock == null ? null : multiBlock.drain(from, resource, doDrain); } @Override public FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain) { if (!isOutput(from)) return null; notifyChanges(doDrain); return multiBlock == null ? null : multiBlock.drain(from, maxDrain, doDrain); } @Override public boolean canFill(EnumFacing from, Fluid fluid) { return isInput(from) && multiBlock != null && multiBlock.canFill(from, fluid); } @Override public boolean canDrain(EnumFacing from, Fluid fluid) { return isOutput(from) && multiBlock != null && multiBlock.canDrain(from, fluid); } @Override public FluidTankInfo[] getTankInfo(EnumFacing from) { return multiBlock == null ? new FluidTankInfo[0] : multiBlock.getTankInfo(from); } @Override public boolean canAcceptFrom(EnumFacing direction) { return isInput(direction); } @Override public boolean canProvideTo(EnumFacing direction) { return isOutput(direction); } @Override public FluidStack getProvidedFluid(int maxProvided, EnumFacing from) { if (!isOutput(from)) return null; return getMultiBlock() == null ? null : getMultiBlock().drain(maxProvided, true); } @Override public int getRequestedAmount(EnumFacing from) { if (!isInput(from)) return 0; return multiBlock == null ? 0 : Math.min(multiBlock.getFreeSpace(), 1000); } @Override public FluidStack acceptFluid(FluidStack fluidStack, EnumFacing from) { if (!isInput(from)) { fill(from, fluidStack, true); notifyChanges(true); return null; } else { return fluidStack; } } public Fluid getClientRenderFluid() { return clientRenderFluid; } // Client only public float getRenderHeight() { return renderHeight; } public FluidStack getFluid() { return multiBlock == null ? null : multiBlock.getFluid(); } public NBTTagCompound getFluidTag() { return getFluid() == null ? null : getFluid().tag; } public int getFluidAmount() { return multiBlock == null ? 0 : multiBlock.getFluidAmount(); } public int getCapacity() { return multiBlock == null ? 0 : multiBlock.getCapacity(); } private void notifyChanges(boolean b){ if (multiBlock != null && b){ for (Map.Entry<EnumFacing, ITankHook> entry : getConnectedHooks().entrySet()){ entry.getValue().onContentChanged(this, entry.getKey().getOpposite()); } } } private Map<EnumFacing, ITankHook> getConnectedHooks(){ /*Map<ITankHook, EnumFacing> ret = Maps.newHashMap(); for (EnumFacing direction : EnumFacing.VALUES){ try { TileEntity tile = WorldHelper.getTileAt(worldObj, getPos().offset(direction)); if (tile instanceof ITankHook) ret.put((ITankHook) tile, direction.getOpposite()); } catch (Exception e){ e.printStackTrace(); } } return ret;*/ return tankHooks; } public boolean isInput(EnumFacing direction){ return direction == null || settings.get(direction) == Mode.SETTING_ACCEPT; } public boolean isOutput(EnumFacing direction){ return direction == null || settings.get(direction) == Mode.SETTING_PROVIDE; } @Override public NBTTagCompound getUpdateTag() { return super.getUpdateTag(); } @Override public void readClientDataFromNBT(NBTTagCompound tagCompound) { super.readClientDataFromNBT(tagCompound); this.clientRenderFluid = FluidRegistry.getFluid(tagCompound.getString("fluid")); this.renderHeight = tagCompound.getFloat("render"); } public static final int ID_GENERIC = 1; public static final int ID_SETFLUID = 2; public static final int ID_SETHEIGHT = 3; @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) { if (packet.getTileEntityType() == ID_GENERIC) { super.onDataPacket(net, packet); } else { this.onDataPacket(packet.getTileEntityType(), packet.getNbtCompound()); } } @Override public void onDataPacket(int id, NBTTagCompound tag) { switch (id){ case ID_SETFLUID: this.clientRenderFluid = FluidRegistry.getFluid(tag.getString("fluid")); return; case ID_SETHEIGHT: this.renderHeight = tag.getFloat("render"); } } }
package org.restheart.handlers; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import org.restheart.db.DBCursorPool.EAGER_CURSOR_ALLOCATION_POLICY; import org.restheart.utils.URLUtils; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.Methods; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List; import org.restheart.Bootstrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Andrea Di Cesare <andrea@softinstigate.com> */ public class RequestContext { private static final Logger LOGGER = LoggerFactory.getLogger(RequestContext.class); public enum TYPE { ERROR, ROOT, DB, COLLECTION, DOCUMENT, COLLECTION_INDEXES, INDEX, FILES_BUCKET, FILE, FILE_BINARY, AGGREGATION, SCHEMA, SCHEMA_STORE }; public enum METHOD { GET, POST, PUT, DELETE, PATCH, OPTIONS, OTHER }; public enum DOC_ID_TYPE { OID, // ObjectId STRING_OID, // String eventually converted to ObjectId in case ObjectId.isValid() is true STRING, // String NUMBER, // any Number (including mongodb NumberLong) DATE, // Date MINKEY, //org.bson.types.MinKey; MAXKEY // org.bson.types.MaxKey } public enum HAL_MODE { FULL, // default value F, // alias for full COMPACT, C // alias for compact } public enum ETAG_CHECK_POLICY { REQUIRED, // always requires the etag, return PRECONDITION FAILED if missing REQUIRED_FOR_DELETE, // only requires the etag for DELETE, return PRECONDITION FAILED if missing OPTIONAL // checks the etag only if provided by client via If-Match header } public static final String PAGE_QPARAM_KEY = "page"; public static final String PAGESIZE_QPARAM_KEY = "pagesize"; public static final String COUNT_QPARAM_KEY = "count"; public static final String SORT_BY_QPARAM_KEY = "sort_by"; public static final String FILTER_QPARAM_KEY = "filter"; public static final String AGGREGATION_VARIABLES_QPARAM_KEY = "avars"; public static final String KEYS_QPARAM_KEY = "keys"; public static final String EAGER_CURSOR_ALLOCATION_POLICY_QPARAM_KEY = "eager"; public static final String DOC_ID_TYPE_KEY = "id_type"; public static final String SLASH = "/"; public static final String PATCH = "PATCH"; public static final String UNDERSCORE = "_"; public static final String SYSTEM = "system."; public static final String LOCAL = "local"; public static final String ADMIN = "admin"; public static final String FS_CHUNKS_SUFFIX = ".chunks"; public static final String FS_FILES_SUFFIX = ".files"; public static final String _INDEXES = "_indexes"; public static final String AGGREGATIONS_QPARAM_KEY = "aggrs"; public static final String _SCHEMAS = "_schemas"; public static final String _AGGREGATIONS = "_aggrs"; public static final String BINARY_CONTENT = "binary"; public static final String HAL_QPARAM_KEY = "hal"; public static final String MAX_KEY_ID = "_MaxKey"; public static final String MIN_KEY_ID = "_MinKey"; public static final String ETAG_DOC_POLICY_METADATA_KEY = "etagDocPolicy"; public static final String ETAG_POLICY_METADATA_KEY = "etagPolicy"; public static final String ETAG_CHECK_QPARAM_KEY = "checkEtag"; private final String whereUri; private final String whatUri; private final TYPE type; private final METHOD method; private final String[] pathTokens; private DBObject dbProps; private DBObject collectionProps; private DBObject content; private File file; private DBObject responseContent; private final List<String> warnings = new ArrayList<>(); private int page = 1; private int pagesize = 100; private boolean count = false; private EAGER_CURSOR_ALLOCATION_POLICY cursorAllocationPolicy; private Deque<String> filter = null; private BasicDBObject aggregationVars = null; // aggregation vars private Deque<String> keys = null; private Deque<String> sortBy = null; private DOC_ID_TYPE docIdType = DOC_ID_TYPE.STRING_OID; private Object documentId; private String mappedUri = null; private String unmappedUri = null; private static final String NUL = Character.toString('\0'); private final String etag; private boolean forceEtagCheck = false; /** * the HAL mode */ private HAL_MODE halMode = HAL_MODE.FULL; /** * * @param exchange the url rewriting feature is implemented by the whatUri * and whereUri parameters. * * the exchange request path (mapped uri) is rewritten replacing the * whereUri string with the whatUri string the special whatUri value * means * any resource: the whereUri is replaced with / * * example 1 * * whatUri = /mydb/mycollection whereUri = / * * then the requestPath / is rewritten to /mydb/mycollection * * example 2 * * whatUri = * whereUri = /data * * then the requestPath /data is rewritten to / * * @param whereUri the uri to map to * @param whatUri the uri to map */ public RequestContext(HttpServerExchange exchange, String whereUri, String whatUri) { this.whereUri = URLUtils.removeTrailingSlashes(whereUri == null ? null : whereUri.startsWith("/") ? whereUri : "/" + whereUri); this.whatUri = URLUtils.removeTrailingSlashes( whatUri == null ? null : whatUri.startsWith("/") || "*".equals(whatUri) ? whatUri : "/" + whatUri); this.mappedUri = exchange.getRequestPath(); this.unmappedUri = unmapUri(exchange.getRequestPath()); // "/db/collection/document" --> { "", "mappedDbName", "collection", "document" } this.pathTokens = this.unmappedUri.split(SLASH); this.type = selectRequestType(pathTokens); this.method = selectRequestMethod(exchange.getRequestMethod()); // etag HeaderValues etagHvs = exchange.getRequestHeaders() == null ? null : exchange.getRequestHeaders().get(Headers.IF_MATCH); this.etag = etagHvs == null || etagHvs.getFirst() == null ? null : etagHvs.getFirst(); this.forceEtagCheck = exchange.getQueryParameters().get(ETAG_CHECK_QPARAM_KEY) != null; } protected static METHOD selectRequestMethod(HttpString _method) { METHOD method; if (Methods.GET.equals(_method)) { method = METHOD.GET; } else if (Methods.POST.equals(_method)) { method = METHOD.POST; } else if (Methods.PUT.equals(_method)) { method = METHOD.PUT; } else if (Methods.DELETE.equals(_method)) { method = METHOD.DELETE; } else if (PATCH.equals(_method.toString())) { method = METHOD.PATCH; } else if (Methods.OPTIONS.equals(_method)) { method = METHOD.OPTIONS; } else { method = METHOD.OTHER; } return method; } protected static TYPE selectRequestType(String[] pathTokens) { TYPE type; if (pathTokens.length < 2) { type = TYPE.ROOT; } else if (pathTokens.length < 3) { type = TYPE.DB; } else if (pathTokens.length >= 3 && pathTokens[2].endsWith(FS_FILES_SUFFIX)) { if (pathTokens.length == 3) { type = TYPE.FILES_BUCKET; } else if (pathTokens.length == 4 && pathTokens[3].equalsIgnoreCase(_INDEXES)) { type = TYPE.COLLECTION_INDEXES; } else if (pathTokens.length == 4 && !pathTokens[3].equalsIgnoreCase(_INDEXES)) { type = TYPE.FILE; } else if (pathTokens.length > 4 && pathTokens[3].equalsIgnoreCase(_INDEXES)) { type = TYPE.INDEX; } else if (pathTokens.length > 4 && !pathTokens[3].equalsIgnoreCase(_INDEXES) && !pathTokens[4].equalsIgnoreCase(BINARY_CONTENT)) { type = TYPE.FILE; } else if (pathTokens.length == 5 && pathTokens[4].equalsIgnoreCase(BINARY_CONTENT)) { // URL: <host>/db/bucket.file/xxx/binary type = TYPE.FILE_BINARY; } else { type = TYPE.DOCUMENT; } } else if (pathTokens.length >= 3 && pathTokens[2].endsWith(_SCHEMAS)) { if (pathTokens.length == 3) { type = TYPE.SCHEMA_STORE; } else { type = TYPE.SCHEMA; } } else if (pathTokens.length < 4) { type = TYPE.COLLECTION; } else if (pathTokens.length == 4 && pathTokens[3].equalsIgnoreCase(_INDEXES)) { type = TYPE.COLLECTION_INDEXES; } else if (pathTokens.length > 4 && pathTokens[3].equalsIgnoreCase(_INDEXES)) { type = TYPE.INDEX; } else if (pathTokens.length > 4 && pathTokens[3].equalsIgnoreCase(_AGGREGATIONS)) { type = TYPE.AGGREGATION; } else { type = TYPE.DOCUMENT; } return type; } /** * given a mapped uri (/some/mapping/coll) returns the canonical uri * (/db/coll) URLs are mapped to mongodb resources by using the mongo-mounts * configuration properties * * @param mappedUri * @return */ public final String unmapUri(String mappedUri) { String ret = URLUtils.removeTrailingSlashes(mappedUri); if (whatUri.equals("*")) { if (!this.whereUri.equals(SLASH)) { ret = ret.replaceFirst("^" + this.whereUri, ""); } } else if (!this.whereUri.equals(SLASH)) { ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + this.whereUri, this.whatUri)); } else { ret = URLUtils.removeTrailingSlashes(URLUtils.removeTrailingSlashes(this.whatUri) + ret); } if (ret.isEmpty()) { ret = SLASH; } return ret; } /** * given a canonical uri (/db/coll) returns the mapped uri * (/some/mapping/uri) relative to this context. URLs are mapped to mongodb * resources via the mongo-mounts configuration properties * * @param unmappedUri * @return */ public final String mapUri(String unmappedUri) { String ret = URLUtils.removeTrailingSlashes(unmappedUri); if (whatUri.equals("*")) { if (!this.whereUri.equals(SLASH)) { return this.whereUri + unmappedUri; } } else { ret = URLUtils.removeTrailingSlashes(ret.replaceFirst("^" + this.whatUri, this.whereUri)); } if (ret.isEmpty()) { ret = SLASH; } return ret; } /** * check if the parent of the requested resource is accessible in this * request context * * for instance if /mydb/mycollection is mapped to /coll then: * * the db is accessible from the collection the root is not accessible from * the collection (since / is actually mapped to the db) * * @return true if parent of the requested resource is accessible */ public final boolean isParentAccessible() { return type == TYPE.DB ? mappedUri.split(SLASH).length > 1 : mappedUri.split(SLASH).length > 2; } /** * * @return type */ public TYPE getType() { return type; } /** * * @return DB Name */ public String getDBName() { return getPathTokenAt(1); } /** * * @return collection name */ public String getCollectionName() { return getPathTokenAt(2); } /** * * @return document id */ public String getDocumentIdRaw() { return getPathTokenAt(3); } /** * * @return index id */ public String getIndexId() { return getPathTokenAt(4); } /** * * @return collection name */ public String getAggregationOperation() { return getPathTokenAt(4); } /** * * @return URI * @throws URISyntaxException */ public URI getUri() throws URISyntaxException { return new URI(Arrays.asList(pathTokens).stream().reduce(SLASH, (t1, t2) -> t1 + SLASH + t2)); } /** * * @return method */ public METHOD getMethod() { return method; } /** * * @param dbName * @return true if the dbName is a reserved resource */ public static boolean isReservedResourceDb(String dbName) { return dbName.equals(ADMIN) || dbName.equals(LOCAL) || dbName.startsWith(SYSTEM) || dbName.startsWith(UNDERSCORE); } /** * * @param collectionName * @return true if the collectionName is a reserved resource */ public static boolean isReservedResourceCollection(String collectionName) { return collectionName != null && !collectionName.equalsIgnoreCase(_SCHEMAS) && (collectionName.startsWith(SYSTEM) || collectionName.startsWith(UNDERSCORE) || collectionName.endsWith(FS_CHUNKS_SUFFIX)); } /** * * @param type * @param documentIdRaw * @return true if the documentIdRaw is a reserved resource */ public static boolean isReservedResourceDocument(TYPE type, String documentIdRaw) { if (documentIdRaw == null) { return false; } return documentIdRaw.startsWith(UNDERSCORE) && !documentIdRaw.equalsIgnoreCase(_INDEXES) && !documentIdRaw.equalsIgnoreCase(MIN_KEY_ID) && !documentIdRaw.equalsIgnoreCase(MAX_KEY_ID) && (type != TYPE.AGGREGATION && _AGGREGATIONS.equalsIgnoreCase(documentIdRaw)) && !(type == TYPE.AGGREGATION); } /** * * @return isReservedResource */ public boolean isReservedResource() { if (type == TYPE.ROOT) { return false; } return isReservedResourceDb(getDBName()) || isReservedResourceCollection(getCollectionName()) || isReservedResourceDocument(type, getDocumentIdRaw()); } /** * @return the whereUri */ public String getUriPrefix() { return whereUri; } /** * @return the whatUri */ public String getMappingUri() { return whatUri; } /** * @return the page */ public int getPage() { return page; } /** * @param page the page to set */ public void setPage(int page) { this.page = page; } /** * @return the pagesize */ public int getPagesize() { return pagesize; } /** * @param pagesize the pagesize to set */ public void setPagesize(int pagesize) { this.pagesize = pagesize; } /** * @return the count */ public boolean isCount() { return count; } /** * @param count the count to set */ public void setCount(boolean count) { this.count = count; } /** * @return the filter */ public Deque<String> getFilter() { return filter; } /** * @param filter the filter to set */ public void setFilter(Deque<String> filter) { this.filter = filter; } /** * @return the aggregationVars */ public BasicDBObject getAggreationVars() { return aggregationVars; } /** * @param aggregationVars the aggregationVars to set */ public void setAggregationVars(BasicDBObject aggregationVars) { this.aggregationVars = aggregationVars; } /** * @return the sortBy */ public Deque<String> getSortBy() { return sortBy; } /** * @param sortBy the sortBy to set */ public void setSortBy(Deque<String> sortBy) { this.sortBy = sortBy; } /** * @return the collectionProps */ public DBObject getCollectionProps() { return collectionProps; } /** * @param collectionProps the collectionProps to set */ public void setCollectionProps(DBObject collectionProps) { this.collectionProps = collectionProps; } /** * @return the dbProps */ public DBObject getDbProps() { return dbProps; } /** * @param dbProps the dbProps to set */ public void setDbProps(DBObject dbProps) { this.dbProps = dbProps; } /** * @return the content */ public DBObject getContent() { return content; } /** * @param content the content to set */ public void setContent(DBObject content) { this.content = content; } /** * @return the warnings */ public List<String> getWarnings() { return warnings; } /** * @param warning */ public void addWarning(String warning) { warnings.add(warning); } /** * * The unmapped uri is the cononical uri of a mongodb resource (e.g. * /db/coll). * * @return the unmappedUri */ public String getUnmappedRequestUri() { return unmappedUri; } /** * The mapped uri is the exchange request uri. This is "mapped" by the * mongo-mounts mapping paramenters. * * @return the mappedUri */ public String getMappedRequestUri() { return mappedUri; } /** * * @param index * @return pathTokens[index] if pathTokens.length > index, else null */ private String getPathTokenAt(int index) { return pathTokens.length > index ? pathTokens[index] : null; } /** * * @return the cursorAllocationPolicy */ public EAGER_CURSOR_ALLOCATION_POLICY getCursorAllocationPolicy() { return cursorAllocationPolicy; } /** * @param cursorAllocationPolicy the cursorAllocationPolicy to set */ public void setCursorAllocationPolicy(EAGER_CURSOR_ALLOCATION_POLICY cursorAllocationPolicy) { this.cursorAllocationPolicy = cursorAllocationPolicy; } /** * @return the docIdType */ public DOC_ID_TYPE getDocIdType() { return docIdType; } /** * @param docIdType the docIdType to set */ public void setDocIdType(DOC_ID_TYPE docIdType) { this.docIdType = docIdType; } /** * @param documentId the documentId to set */ public void setDocumentId(Object documentId) { this.documentId = documentId; } /** * @return the documentId */ public Object getDocumentId() { return documentId; } /** * @return the responseContent */ public DBObject getResponseContent() { return responseContent; } /** * @param responseContent the responseContent to set */ public void setResponseContent(DBObject responseContent) { this.responseContent = responseContent; } /** * @return the file */ public File getFile() { return file; } /** * @param file the file to set */ public void setFile(File file) { this.file = file; } /** * @return keys */ public Deque<String> getKeys() { return keys; } /** * @param keys keys to set */ public void setKeys(Deque<String> keys) { this.keys = keys; } /** * @return the halMode */ public HAL_MODE getHalMode() { return halMode; } public boolean isFullHalMode() { return halMode == HAL_MODE.FULL || halMode == HAL_MODE.F; } /** * @param halMode the halMode to set */ public void setHalMode(HAL_MODE halMode) { this.halMode = halMode; } public boolean isDbNameInvalid() { return isDbNameInvalid(getDBName()); } public boolean isDbNameInvalid(String dbName) { return (dbName == null || dbName.contains(NUL) || dbName.contains(" ") || dbName.contains("/") || dbName.contains("\\") || dbName.contains(".") || dbName.contains("\"") || dbName.contains("$") || dbName.length() > 64 || dbName.length() == 0); } public boolean isDbNameInvalidOnWindows() { return isDbNameInvalidOnWindows(getDBName()); } public boolean isDbNameInvalidOnWindows(String dbName) { return (isDbNameInvalid() || dbName.contains("*") || dbName.contains("<") || dbName.contains(">") || dbName.contains(":") || dbName.contains(".") || dbName.contains("|") || dbName.contains("?")); } public boolean isCollectionNameInvalid() { return isCollectionNameInvalid(getCollectionName()); } public boolean isCollectionNameInvalid(String collectionName) { // collection starting with system. will return FORBIDDEN return (collectionName == null || collectionName.contains(NUL) || collectionName.contains("$") || collectionName.length() == 64); } public String getETag() { return etag; } public boolean isETagCheckRequired() { // if client specifies the If-Match header, than check it if (getETag() != null) { return true; } // if client requires the check via qparam return true if (forceEtagCheck) { return true; } // for documents consider db and coll etagDocPolicy metadata if (type == TYPE.DOCUMENT || type == TYPE.FILE) { // check the coll metadata Object _policy = collectionProps != null ? collectionProps.get(ETAG_DOC_POLICY_METADATA_KEY) : null; LOGGER.debug("collection etag policy (from coll properties) {}", _policy); if (_policy == null) { // check the db metadata _policy = dbProps != null ? dbProps.get(ETAG_DOC_POLICY_METADATA_KEY) : null; LOGGER.debug("collection etag policy (from db properties) {}", _policy); } ETAG_CHECK_POLICY policy = null; if (_policy != null && _policy instanceof String) { try { policy = ETAG_CHECK_POLICY.valueOf((String) _policy); } catch (IllegalArgumentException iae) { policy = null; } } if (null != policy) { if (method == METHOD.DELETE) { return policy != ETAG_CHECK_POLICY.OPTIONAL; } else { return policy == ETAG_CHECK_POLICY.REQUIRED; } } } // for db consider db etagPolicy metadata if (type == TYPE.DB && dbProps != null) { // check the coll metadata Object _policy = dbProps.get(ETAG_POLICY_METADATA_KEY); LOGGER.debug("db etag policy (from db properties) {}", _policy); ETAG_CHECK_POLICY policy = null; if (_policy != null && _policy instanceof String) { try { policy = ETAG_CHECK_POLICY.valueOf((String) _policy); } catch (IllegalArgumentException iae) { policy = null; } } if (null != policy) { if (method == METHOD.DELETE) { return policy != ETAG_CHECK_POLICY.OPTIONAL; } else { return policy == ETAG_CHECK_POLICY.REQUIRED; } } } // for collection consider coll etagPolicy metadata if (type == TYPE.DB && collectionProps != null) { // check the coll metadata Object _policy = collectionProps.get(ETAG_POLICY_METADATA_KEY); LOGGER.debug("coll etag policy (from coll properties) {}", _policy); ETAG_CHECK_POLICY policy = null; if (_policy != null && _policy instanceof String) { try { policy = ETAG_CHECK_POLICY.valueOf((String) _policy); } catch (IllegalArgumentException iae) { policy = null; } } if (null != policy) { if (method == METHOD.DELETE) { return policy != ETAG_CHECK_POLICY.OPTIONAL; } else { return policy == ETAG_CHECK_POLICY.REQUIRED; } } } // apply the default policy from configuration ETAG_CHECK_POLICY dbP = Bootstrapper.getConfiguration().getDbEtagCheckPolicy(); ETAG_CHECK_POLICY collP = Bootstrapper.getConfiguration().getCollEtagCheckPolicy(); ETAG_CHECK_POLICY docP = Bootstrapper.getConfiguration().getDocEtagCheckPolicy(); LOGGER.debug("default etag db check (from conf) {}", dbP); LOGGER.debug("default etag coll check (from conf) {}", collP); LOGGER.debug("default etag doc check (from conf) {}", docP); ETAG_CHECK_POLICY policy = null; if (null != type) { switch (type) { case DB: policy = dbP; break; case COLLECTION: case FILES_BUCKET: case SCHEMA_STORE: policy = collP; break; default: policy = docP; } } if (null != policy) { if (method == METHOD.DELETE) { return policy != ETAG_CHECK_POLICY.OPTIONAL; } else { return policy == ETAG_CHECK_POLICY.REQUIRED; } } return false; } }
package org.openlmis.upload.model; import lombok.Getter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.ListUtils; import org.apache.commons.collections.Predicate; import org.openlmis.upload.Importable; import org.openlmis.upload.annotation.ImportField; import org.openlmis.upload.annotation.ImportFields; import org.openlmis.upload.exception.UploadException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ModelClass { @Getter private Class<? extends Importable> clazz; private List<Field> importFields; public ModelClass(Class<? extends Importable> clazz) { this.clazz = clazz; importFields = fieldsWithImportFieldAnnotation(); } public void validateHeaders(List<String> headers) { List<String> lowerCaseHeaders = lowerCase(headers); validateInvalidHeaders(lowerCaseHeaders); validateMandatoryFields(lowerCaseHeaders); } public String[] getFieldNameMappings(String[] headers) { List<String> fieldMappings = new ArrayList<>(); for (String header : headers) { Field importField = findImportFieldWithName(header); if (importField != null) { String nestedProperty = importField.getNested(); if (nestedProperty.isEmpty()) { fieldMappings.add(importField.getField().getName()); } else { fieldMappings.add(importField.getField().getName() + "." + nestedProperty); } } } return fieldMappings.toArray(new String[fieldMappings.size()]); } public Field findImportFieldWithName(final String name) { Object result = CollectionUtils.find(importFields, new Predicate() { @Override public boolean evaluate(Object object) { Field field = (Field) object; return field.hasName(name); } }); return (Field) result; } private List<Field> fieldsWithImportFieldAnnotation() { List<java.lang.reflect.Field> fieldsList = Arrays.asList(clazz.getDeclaredFields()); List<Field> result = new ArrayList<>(); for (java.lang.reflect.Field field : fieldsList) { if (field.isAnnotationPresent(ImportField.class)) { result.add(new Field(field, field.getAnnotation(ImportField.class))); } if (field.isAnnotationPresent(ImportFields.class)) { final ImportFields importFields = field.getAnnotation(ImportFields.class); for (ImportField importField : importFields.importFields()) { result.add(new Field(field, importField)); } } } return result; } private void validateMandatoryFields(List<String> headers) { List<String> missingFields = findMissingFields(headers); if (!missingFields.isEmpty()) { throw new UploadException("Missing Mandatory columns in upload file: " + missingFields); } } private void validateInvalidHeaders(List<String> headers) { List<String> fieldNames = getAllImportedFieldNames(); List invalidHeaders = ListUtils.subtract(headers, lowerCase(fieldNames)); if (!invalidHeaders.isEmpty()) { throw new UploadException("Invalid Headers in upload file: " + invalidHeaders); } } private List<String> findMissingFields(List<String> headers) { List<String> missingFields = new ArrayList<>(); for (Field field : importFields) { if (field.isMandatory()) { String fieldName = field.getName(); if (!headers.contains(fieldName.toLowerCase())) { missingFields.add(fieldName); } } } return missingFields; } private List<String> lowerCase(List<String> headers) { List<String> lowerCaseHeaders = new ArrayList<>(); for (String header : headers) { lowerCaseHeaders.add(header.toLowerCase()); } return lowerCaseHeaders; } private List<String> getAllImportedFieldNames() { List<String> outputCollection = new ArrayList<>(); for (Field field : importFields) { outputCollection.add(field.getName()); } return outputCollection; } }
package mcjty.xnet.apiimpl.items; import mcjty.lib.varia.ItemStackList; import mcjty.xnet.compat.ForestrySupport; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import javax.annotation.Nonnull; import java.util.HashSet; import java.util.Set; public class ItemFilterCache { private boolean matchDamage = true; private boolean oredictMode = false; private boolean blacklistMode = true; private boolean nbtMode = false; private ItemStackList stacks; private Set<Integer> oredictMatches = new HashSet<>(); public ItemFilterCache(boolean matchDamage, boolean oredictMode, boolean blacklistMode, boolean nbtMode, @Nonnull ItemStackList stacks) { this.matchDamage = matchDamage; this.oredictMode = oredictMode; this.blacklistMode = blacklistMode; this.nbtMode = nbtMode; this.stacks = stacks; for (ItemStack s : stacks) { for (int id : OreDictionary.getOreIDs(s)) { oredictMatches.add(id); } } } public boolean match(ItemStack stack) { if (!stack.isEmpty()) { boolean match = false; if (oredictMode) { int[] oreIDs = OreDictionary.getOreIDs(stack); if (oreIDs.length == 0) { match = itemMatches(stack); } else { for (int id : oreIDs) { if (oredictMatches.contains(id)) { match = true; break; } } } } else { match = itemMatches(stack); } return match != blacklistMode; } return false; } private boolean itemMatches(ItemStack stack) { if (stacks != null) { int forestryFlags = ForestrySupport.Tag.GEN.getFlag() | ForestrySupport.Tag.IS_ANALYZED.getFlag(); ItemStack cleanedStack = null; if(nbtMode && ForestrySupport.isLoaded() && ForestrySupport.isBreedable(stack)) { cleanedStack = ForestrySupport.sanitize(stack, forestryFlags); } for (ItemStack itemStack : stacks) { if (matchDamage && itemStack.getMetadata() != stack.getMetadata()) { continue; } if (nbtMode) { if((cleanedStack != null) && ForestrySupport.isBreedable(itemStack)) { ItemStack cleanedItemStack = ForestrySupport.sanitize(itemStack, forestryFlags); if(!ItemStack.areItemStackTagsEqual(cleanedItemStack, cleanedStack)) { continue; } } else if(!ItemStack.areItemStackTagsEqual(itemStack, stack)) { continue; } } if (itemStack.getItem().equals(stack.getItem())) { return true; } } } return false; } }