answer
stringlengths 17
10.2M
|
|---|
package io.jenkins.plugins.analysis.core.util;
import org.apache.commons.lang.StringUtils;
import edu.hm.hafner.util.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import hudson.EnvVars;
import hudson.Util;
/**
* Resolves environment parameters in a string value.
*
* @author Ullrich Hafner
*/
public class EnvironmentResolver {
/** Maximum number of times that the environment expansion is executed. */
private static final int RESOLVE_VARIABLE_DEPTH_DEFAULT = 10;
private int resolveVariablesDepth;
/**
* Creates a new instance of {@link EnvironmentResolver}. Attempts up to {@link #RESOLVE_VARIABLE_DEPTH_DEFAULT}
* times to resolve a variable.
*/
public EnvironmentResolver() {
this(RESOLVE_VARIABLE_DEPTH_DEFAULT);
}
@VisibleForTesting
EnvironmentResolver(final int resolveVariablesDepth) {
this.resolveVariablesDepth = resolveVariablesDepth;
}
/**
* Resolves build parameters in the specified string value to {@link #resolveVariablesDepth} times.
*
* @param environment
* environment variables
* @param nonExpanded
* the string to expand
*/
public String expandEnvironmentVariables(@CheckForNull final EnvVars environment, final String nonExpanded) {
String expanded = nonExpanded;
if (environment != null && !environment.isEmpty()) {
for (int i = 0; i < resolveVariablesDepth && StringUtils.isNotBlank(expanded); i++) {
String old = expanded;
expanded = Util.replaceMacro(expanded, environment);
if (old.equals(expanded)) {
return expanded;
}
}
}
return expanded;
}
}
|
package net.blay09.mods.cookingbook.container;
import com.google.common.collect.ArrayListMultimap;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import invtweaks.api.container.IgnoreContainer;
import net.blay09.mods.cookingbook.KitchenMultiBlock;
import net.blay09.mods.cookingbook.api.kitchen.IKitchenItemProvider;
import net.blay09.mods.cookingbook.registry.CookingRegistry;
import net.blay09.mods.cookingbook.registry.food.FoodRecipe;
import net.blay09.mods.cookingbook.network.MessageClickRecipe;
import net.blay09.mods.cookingbook.network.MessageRecipeInfo;
import net.blay09.mods.cookingbook.network.MessageSyncList;
import net.blay09.mods.cookingbook.network.NetworkHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@IgnoreContainer
public class ContainerRecipeBook extends Container {
private final EntityPlayer player;
private final boolean allowCrafting;
private final boolean allowSmelting;
private final boolean isClientSide;
private final InventoryRecipeBook recipeBook;
private final SlotRecipe[] recipeBookSlots = new SlotRecipe[12];
private final InventoryRecipeBookMatrix craftMatrix;
private final SlotCraftMatrix[] craftMatrixSlots = new SlotCraftMatrix[9];
private final ArrayListMultimap<String, FoodRecipe> availableRecipes = ArrayListMultimap.create();
private final List<ItemStack> sortedRecipes = new ArrayList<>();
private String searchTerm = "";
private final InventoryCraftBook craftBook;
private Comparator<ItemStack> currentSort = new ComparatorName();
private int scrollOffset;
private boolean isFurnaceRecipe;
private boolean isSelectionDirty;
private boolean isRecipeListDirty;
private int syncSlotIndex = -1;
private int currentSlotIndex = -1;
private FoodRecipe currentRecipe;
private boolean hasVariants;
private boolean isMissingTools;
private boolean isMissingOven;
private String currentRecipeKey;
private List<FoodRecipe> currentRecipeList;
private int currentRecipeIdx;
private boolean noFilter;
private final List<IKitchenItemProvider> emptyProviderList = new ArrayList<>();
private final List<IInventory> playerInventoryList = new ArrayList<>();
private KitchenMultiBlock kitchenMultiBlock;
public ContainerRecipeBook(EntityPlayer player, boolean allowCrafting, boolean allowSmelting, boolean isClientSide) {
this.player = player;
this.playerInventoryList.add(player.inventory);
this.allowCrafting = allowCrafting;
this.allowSmelting = allowSmelting;
this.isClientSide = isClientSide;
craftMatrix = new InventoryRecipeBookMatrix();
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
craftMatrixSlots[j + i * 3] = new SlotCraftMatrix(player, craftMatrix, j + i * 3, 24 + j * 18, 20 + i * 18);
craftMatrixSlots[j + i * 3].setSourceInventories(playerInventoryList);
craftMatrixSlots[j + i * 3].setItemProviders(emptyProviderList);
addSlotToContainer(craftMatrixSlots[j + i * 3]);
}
}
recipeBook = new InventoryRecipeBook();
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++) {
recipeBookSlots[j + i * 3] = new SlotRecipe(recipeBook, j + i * 3, 102 + j * 18, 11 + i * 18);
addSlotToContainer(recipeBookSlots[j + i * 3]);
}
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(player.inventory, j + i * 9 + 9, 8 + j * 18, 92 + i * 18));
}
}
for(int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(player.inventory, i, 8 + i * 18, 150));
}
updateRecipeList();
craftBook = new InventoryCraftBook(this);
craftBook.setItemProviders(emptyProviderList);
craftBook.setInventories(playerInventoryList);
findAvailableRecipes();
}
public void setCraftMatrix(FoodRecipe recipe) {
if(recipe != null) {
isFurnaceRecipe = recipe.isSmeltingRecipe();
if(isFurnaceRecipe) {
for(SlotCraftMatrix previewSlot : craftMatrixSlots) {
previewSlot.setIngredient(null);
previewSlot.setEnabled(false);
if(!isClientSide) {
previewSlot.updateVisibleStacks();
}
}
craftMatrixSlots[4].setIngredient(recipe.getCraftMatrix().get(0));
craftMatrixSlots[4].setEnabled(true);
if(!isClientSide) {
craftMatrixSlots[4].updateVisibleStacks();
}
} else {
int offset = 0;
if (recipe.getCraftMatrix().size() <= 3) {
offset += 3;
}
if(recipe.getCraftMatrix().size() == 1) {
offset++;
}
for (int i = 0; i < craftMatrix.getSizeInventory(); i++) {
int recipeIdx = i - offset;
if (recipeIdx >= 0 && recipeIdx < recipe.getCraftMatrix().size()) {
craftMatrixSlots[i].setIngredient(recipe.getCraftMatrix().get(recipeIdx));
} else {
craftMatrixSlots[i].setIngredient(null);
}
craftMatrixSlots[i].setEnabled(true);
if(!isClientSide) {
craftMatrixSlots[i].updateVisibleStacks();
}
}
}
} else {
for(SlotCraftMatrix previewSlot : craftMatrixSlots) {
previewSlot.setIngredient(null);
previewSlot.setEnabled(false);
}
}
}
public boolean hasVariants() {
return hasVariants;
}
public void setScrollOffset(int scrollOffset) {
this.scrollOffset = scrollOffset;
updateRecipeList();
}
public void search(String term) {
this.searchTerm = term;
}
public void updateRecipeList() {
boolean noRecipes = getAvailableRecipeCount() == 0;
for(int i = 0; i < recipeBook.getSizeInventory(); i++) {
int recipeIdx = i + scrollOffset * 3;
if(recipeIdx < sortedRecipes.size()) {
recipeBook.setFoodItem(i, availableRecipes.get(sortedRecipes.get(recipeIdx).toString()));
} else {
recipeBook.setFoodItem(i, null);
}
recipeBookSlots[i].putStack(recipeBook.getStackInSlot(i));
recipeBookSlots[i].setEnabled(!noRecipes);
}
if(noRecipes) {
setCraftMatrix(null);
if(!isClientSide) {
currentRecipeList = null;
currentRecipeIdx = -1;
}
} else if(!isClientSide) {
currentRecipeList = availableRecipes.get(currentRecipeKey);
}
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public ItemStack slotClick(int slotIdx, int button, int mode, EntityPlayer player) {
if((mode == 0 || mode == 1)) {
if(isClientSide) {
clickRecipe(slotIdx, mode == 1);
NetworkHandler.instance.sendToServer(new MessageClickRecipe(slotIdx, scrollOffset, mode == 1));
}
}
return super.slotClick(slotIdx, button, mode, player);
}
public void clickRecipe(int slotIdx, boolean shiftClick) {
if(slotIdx > 0 && slotIdx < inventorySlots.size() && inventorySlots.get(slotIdx) instanceof SlotRecipe) {
SlotRecipe slot = (SlotRecipe) inventorySlots.get(slotIdx);
if (slot.getStack() != null) {
if(!isClientSide && canClickCraft((scrollOffset * 3) + slot.getSlotIndex())) {
tryCraft(player, currentRecipe, shiftClick);
return;
} else if(!isClientSide && !isMissingOven && canClickSmelt((scrollOffset * 3) + slot.getSlotIndex())) {
trySmelt(player, currentRecipe, shiftClick);
return;
}
int oldSlotIndex = currentSlotIndex;
currentSlotIndex = (scrollOffset * 3) + slot.getSlotIndex();
if(oldSlotIndex != currentSlotIndex) {
if(!isClientSide) {
currentRecipeKey = recipeBook.getStackInSlot(slot.getSlotIndex()).toString();
currentRecipeList = recipeBook.getFoodList(slot.getSlotIndex());
currentRecipeIdx = 0;
currentRecipe = currentRecipeList.get(currentRecipeIdx);
setCraftMatrix(currentRecipe);
isSelectionDirty = true;
}
}
}
}
}
private void trySmelt(EntityPlayer player, FoodRecipe recipe, boolean isShiftDown) {
if(!recipe.isSmeltingRecipe()) {
return;
}
List<IInventory> sourceInventories = kitchenMultiBlock.getSourceInventories(player.inventory);
for(int i = 0; i < sourceInventories.size(); i++) {
for(int j = 0; j < sourceInventories.get(i).getSizeInventory(); j++) {
ItemStack itemStack = sourceInventories.get(i).getStackInSlot(j);
if(itemStack != null) {
for (ItemStack ingredientStack : recipe.getCraftMatrix().get(0).getItemStacks()) {
if (CookingRegistry.areItemStacksEqualWithWildcard(itemStack, ingredientStack)) {
int count = isShiftDown ? Math.min(itemStack.stackSize, ingredientStack.getMaxStackSize()) : 1;
ItemStack restStack = kitchenMultiBlock.smeltItem(itemStack, count);
sourceInventories.get(i).setInventorySlotContents(j, restStack);
if(i == 0) { // Player Inventory
if(j < 9) {
((EntityPlayerMP) player).sendSlotContents(this, 48 + j, restStack);
} else {
((EntityPlayerMP) player).sendSlotContents(this, 21 + j - 9, restStack);
}
}
return;
}
}
}
}
}
}
private void tryCraft(EntityPlayer player, FoodRecipe recipe, boolean isShiftDown) {
if(recipe.isSmeltingRecipe()) {
return;
}
if(!isShiftDown) {
if(craftBook.canMouseItemHold(player, recipe)) {
ItemStack craftingResult = craftBook.craft(player, recipe);
if(craftingResult != null) {
ItemStack mouseItem = player.inventory.getItemStack();
if (mouseItem != null) {
mouseItem.stackSize += craftingResult.stackSize;
((EntityPlayerMP)player).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, 0, mouseItem));
} else {
player.inventory.setItemStack(craftingResult);
((EntityPlayerMP)player).playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, 0, craftingResult));
}
}
}
} else {
ItemStack craftingResult;
int crafted = 0;
while(crafted < 64 && (craftingResult = craftBook.craft(player, recipe)) != null) {
crafted += craftingResult.stackSize;
if(!player.inventory.addItemStackToInventory(craftingResult)) {
if (player.inventory.getItemStack() == null) {
player.inventory.setItemStack(craftingResult);
} else {
player.dropPlayerItemWithRandomChoice(craftingResult, false);
}
break;
}
}
player.inventory.markDirty();
player.inventoryContainer.detectAndSendChanges();
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int i) {
ItemStack itemStack = null;
Slot slot = (Slot) inventorySlots.get(i);
if (slot != null && slot.getHasStack()) {
ItemStack slotStack = slot.getStack();
itemStack = slotStack.copy();
if (i >= 48 && i < 57) { // Inventory to Hotbar
if (!mergeItemStack(slotStack, 21, 48, false)) {
return null;
}
} else if(i >= 21 && i < 48) { // Hotbar to Inventory
if (!mergeItemStack(slotStack, 48, 57, false)) {
return null;
}
}
if (slotStack.stackSize == 0) {
slot.putStack(null);
} else {
slot.onSlotChanged();
}
if (slotStack.stackSize == itemStack.stackSize) {
return null;
}
slot.onPickupFromSlot(player, slotStack);
}
return itemStack;
}
public int getAvailableRecipeCount() {
return sortedRecipes.size();
}
public boolean isFurnaceRecipe() {
return isFurnaceRecipe;
}
public boolean hasSelection() {
return currentRecipe != null;
}
public boolean canClickSmelt(int slotIndex) {
return allowSmelting && currentSlotIndex == slotIndex && currentRecipe != null && currentRecipe.isSmeltingRecipe();
}
public boolean canClickCraft(int slotIndex) {
return allowCrafting && currentSlotIndex == slotIndex && currentRecipe != null && !currentRecipe.isSmeltingRecipe();
}
public boolean isMissingTools() {
return isMissingTools;
}
public boolean isRecipeListDirty() {
return isRecipeListDirty;
}
public void markDirty(boolean dirty) {
this.isRecipeListDirty = dirty;
}
@SideOnly(Side.CLIENT)
public void setAvailableItems(List<ItemStack> sortedRecipes, ArrayListMultimap<String, FoodRecipe> availableRecipes) {
this.sortedRecipes.clear();
this.sortedRecipes.addAll(sortedRecipes);
this.availableRecipes.clear();
this.availableRecipes.putAll(availableRecipes);
search(searchTerm);
markDirty(true);
}
public boolean gotRecipeInfo() {
return syncSlotIndex == currentSlotIndex;
}
/**
* SERVER ONLY
*/
public void findAvailableRecipes() {
availableRecipes.clear();
sortedRecipes.clear();
for(FoodRecipe foodRecipe : CookingRegistry.getFoodRecipes()) {
ItemStack foodStack = foodRecipe.getOutputItem();
if(foodStack != null) {
if(noFilter || CookingRegistry.areIngredientsAvailableFor(foodRecipe.getCraftMatrix(), kitchenMultiBlock != null ? kitchenMultiBlock.getSourceInventories(player.inventory) : playerInventoryList, kitchenMultiBlock != null ? kitchenMultiBlock.getItemProviders() : emptyProviderList)) {
String foodStackString = foodStack.toString();
if(!availableRecipes.containsKey(foodStackString)) {
sortedRecipes.add(foodStack);
}
availableRecipes.put(foodStackString, foodRecipe);
}
}
}
isRecipeListDirty = true;
}
/**
* SERVER ONLY
* @param comparator
*/
public void sortRecipes(Comparator<ItemStack> comparator) {
currentSort = comparator;
Collections.sort(sortedRecipes, comparator);
updateRecipeList();
sortingChanged();
isRecipeListDirty = true;
}
/**
* SERVER ONLY
*/
public void prevRecipe() {
if(currentRecipeList != null) {
currentRecipeIdx
if (currentRecipeIdx < 0) {
currentRecipeIdx = currentRecipeList.size() - 1;
}
setCraftMatrix(currentRecipeList.get(currentRecipeIdx));
isSelectionDirty = true;
}
}
/**
* SERVER ONLY
*/
public void nextRecipe() {
if(currentRecipeList != null) {
currentRecipeIdx++;
if (currentRecipeIdx >= currentRecipeList.size()) {
currentRecipeIdx = 0;
}
setCraftMatrix(currentRecipeList.get(currentRecipeIdx));
isSelectionDirty = true;
}
}
/**
* SERVER ONLY
*/
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
if(!isClientSide) {
if (player.inventory.inventoryChanged) {
findAvailableRecipes();
sortRecipes(currentSort);
player.inventory.inventoryChanged = false;
}
if (isSelectionDirty) {
isSelectionDirty = false;
if (currentRecipe != null && !currentRecipe.isSmeltingRecipe()) {
craftBook.prepareRecipe(player, currentRecipe);
isMissingTools = !craftBook.matches(player.worldObj);
} else {
isMissingTools = false;
}
hasVariants = currentRecipeList != null && currentRecipeList.size() > 1;
isMissingOven = kitchenMultiBlock == null || !kitchenMultiBlock.hasSmeltingProvider();
NetworkHandler.instance.sendTo(new MessageRecipeInfo(currentSlotIndex, currentRecipe, isMissingTools, hasVariants, isMissingOven), (EntityPlayerMP) player);
}
if (isRecipeListDirty) {
NetworkHandler.instance.sendTo(new MessageSyncList(sortedRecipes, availableRecipes), (EntityPlayerMP) player);
isRecipeListDirty = false;
}
for (SlotCraftMatrix previewSlot : craftMatrixSlots) {
previewSlot.update();
}
}
}
/**
* SERVER ONLY
* @return
*/
public ContainerRecipeBook setNoFilter() {
this.noFilter = true;
for(SlotCraftMatrix slotCraftMatrix : craftMatrixSlots) {
slotCraftMatrix.setNoFilter(true);
}
findAvailableRecipes();
sortRecipes(currentSort);
return this;
}
/**
* SERVER ONLY
* @param kitchenMultiBlock
*/
public ContainerRecipeBook setKitchenMultiBlock(KitchenMultiBlock kitchenMultiBlock) {
this.kitchenMultiBlock = kitchenMultiBlock;
findAvailableRecipes();
List<IInventory> sourceInventories = kitchenMultiBlock.getSourceInventories(player.inventory);
for(int i = 0; i < craftMatrixSlots.length; i++) {
craftMatrixSlots[i].setSourceInventories(sourceInventories);
craftMatrixSlots[i].setItemProviders(kitchenMultiBlock.getItemProviders());
}
craftBook.setInventories(sourceInventories);
craftBook.setItemProviders(kitchenMultiBlock.getItemProviders());
return this;
}
@SideOnly(Side.CLIENT)
public void setSelectedRecipe(int currentSlotIndex, FoodRecipe currentRecipe, boolean hasVariants, boolean isMissingTools, boolean isMissingOven) {
this.currentSlotIndex = currentSlotIndex;
this.syncSlotIndex = currentSlotIndex;
this.currentRecipe = currentRecipe;
this.hasVariants = hasVariants;
this.isMissingTools = isMissingTools;
this.isMissingOven = isMissingOven;
setCraftMatrix(currentRecipe);
}
public boolean isMissingOven() {
return isMissingOven;
}
public void sortingChanged() {
currentSlotIndex = -1;
syncSlotIndex = -1;
}
}
|
package net.coobird.thumbnailator.tasks.io;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.util.exif.ExifFilterUtils;
import net.coobird.thumbnailator.util.exif.ExifUtils;
import net.coobird.thumbnailator.util.exif.Orientation;
/**
* An {@link ImageSource} which uses an {@link InputStream} to read the
* source image.
*
* @author coobird
*
*/
public class InputStreamImageSource extends AbstractImageSource<InputStream> {
/**
* The index used to obtain the first image in an image file.
*/
private static final int FIRST_IMAGE_INDEX = 0;
/**
* A {@link InputStream} from which the source image is to be read.
*/
private InputStream is;
/**
* Instantiates an {@link InputStreamImageSource} with the
* {@link InputStream} which will be used to read the source image.
*
* @param is The {@link InputStream} which is to be used to obtain
* the source image.
* @throws NullPointerException If the {@link InputStream} is
* {@code null}.
*/
public InputStreamImageSource(InputStream is) {
super();
if (is == null) {
throw new NullPointerException("InputStream cannot be null.");
}
if (!Boolean.getBoolean("thumbnailator.disableExifWorkaround")) {
this.is = new ExifCaptureInputStream(is);
} else {
this.is = is;
}
}
@Override
public void setThumbnailParameter(ThumbnailParameter param) {
super.setThumbnailParameter(param);
if (param == null || !param.useExifOrientation()) {
if (is instanceof ExifCaptureInputStream) {
// Revert to original `InputStream` and use that directly.
is = ((ExifCaptureInputStream)is).is;
}
}
}
/**
* An {@link InputStream} which intercepts the data stream to find Exif
* data and captures it if present.
*/
private static final class ExifCaptureInputStream extends InputStream {
/**
* Original {@link InputStream} which reads from the image source.
*/
private final InputStream is;
// Following are states for this input stream.
/**
* Flag to indicate data stream should be intercepted and collected.
*/
private boolean doIntercept = true;
/**
* A threshold on how much data to be intercepted.
* This is a safety mechanism to prevent buffering too much information.
*/
private static final int INTERCEPT_THRESHOLD = 1024 * 1024;
/**
* Buffer to collect the input data to read JPEG images for JFIF marker segments.
* This will also be used to store the Exif data, if found.
*/
private byte[] buffer = new byte[0];
/**
* Current position for reading the buffer.
*/
int position = 0;
/**
* Total bytes intercepted from the data stream.
*/
int totalRead = 0;
/**
* Number of remaining bytes to skip ahead in the buffer.
* This value is positive when next location to skip to is outside the
* buffer's current contents.
*/
int remainingSkip = 0;
/**
* Marker for the beginning of the APP1 marker segment.
* Its position is where the APP1 marker starts, not the payload.
*/
private int startApp1 = Integer.MIN_VALUE;
/**
* Marker for the end of the APP1 marker segment.
*/
private int endApp1 = Integer.MAX_VALUE;
/**
* A flag to indicate that we expect APP1 payload (which contains Exif
* contents) is being streamed, so they should be captured into the
* {@code buffer}.
*/
private boolean doCaptureApp1 = false;
/**
* A flag to indicate that the {@code buffer} contains the complete
* Exif information.
*/
private boolean hasCapturedExif = false;
/**
* A flag to indicate whether to output debug logs.
*/
private final boolean isDebug = Boolean.getBoolean("thumbnailator.debugLog.exifWorkaround")
|| Boolean.getBoolean("thumbnailator.debugLog");
/**
* Returns Exif data captured from the JPEG image.
* @return Returns captured Exif data, or {@code null} if unavailable.
*/
private byte[] getExifData() {
return hasCapturedExif ? buffer : null;
}
// TODO Any performance penalties?
private ExifCaptureInputStream(InputStream is) {
this.is = is;
}
/**
* Terminate intercept.
* Drops the collected buffer to relieve pressure on memory.
*
* Do not call this when Exif was found, as buffer (containing Exif)
* will be lost.
*/
private void terminateIntercept() {
doIntercept = false;
buffer = null;
}
/**
* Debug message.
*/
private void debugln(String format, Object... args) {
if (isDebug) {
System.err.printf("[thumbnailator.exifWorkaround] " + format + "%n", args);
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int bytesRead = is.read(b, off, len);
if (bytesRead == -1) {
return bytesRead;
}
if (!doIntercept) {
debugln("Skip intercept.");
return bytesRead;
}
if (off != 0) {
debugln("Offset: %s != 0; terminating intercept.", off);
terminateIntercept();
return bytesRead;
}
totalRead += bytesRead;
if (totalRead > INTERCEPT_THRESHOLD) {
debugln("Exceeded intercept threshold, terminating intercept. %s > %s", totalRead, INTERCEPT_THRESHOLD);
terminateIntercept();
return bytesRead;
}
debugln("Total read: %s", totalRead);
debugln("Bytes read: %s", bytesRead);
byte[] tmpBuffer = new byte[totalRead];
System.arraycopy(buffer, 0, tmpBuffer, 0, Math.min(tmpBuffer.length, buffer.length));
System.arraycopy(b, off, tmpBuffer, totalRead - bytesRead, bytesRead);
buffer = tmpBuffer;
debugln("Source: %s", Arrays.toString(b));
debugln("Buffer: %s", Arrays.toString(buffer));
while (position < totalRead && (totalRead - position) >= 2) {
debugln("Start loop, position: %s", position);
if (remainingSkip > 0) {
position += remainingSkip;
remainingSkip = 0;
debugln("Skip requested, new position: %s", position);
continue;
}
if (doCaptureApp1) {
// Check we can buffer up to "Exif" identifier.
if (startApp1 + 8 > position) {
debugln("APP1 shorter than expected, terminating intercept.");
terminateIntercept();
break;
}
byte[] header = new byte[4];
System.arraycopy(buffer, startApp1 + 4, header, 0, header.length);
if (new String(header).equals("Exif")) {
debugln("Found Exif!");
hasCapturedExif = true;
doIntercept = false;
byte[] exifData = new byte[endApp1 - (startApp1 + 4)];
System.arraycopy(buffer, startApp1 + 4, exifData, 0, exifData.length);
buffer = exifData;
break;
} else {
debugln("APP1 was not Exif.");
hasCapturedExif = false;
doIntercept = true;
doCaptureApp1 = false;
}
}
if (position == 0 && totalRead >= 2) {
// Check the first two bytes of stream to see if SOI exists.
// If SOI is not found, this is not a JPEG.
debugln("Check if JPEG. buffer: %s", Arrays.toString(buffer));
if (!(buffer[position] == (byte) 0xFF && buffer[position + 1] == (byte) 0xD8)) {
// Not SOI, so it's not a JPEG.
// We no longer need to keep intercepting.
debugln("JFIF SOI not found. Not JPEG.");
terminateIntercept();
break;
}
position += 2;
continue;
}
debugln("Prior to 2-byte section. position: %s, total read: %s", position, totalRead);
if (position + 2 <= totalRead) {
if (buffer[position] == (byte) 0xFF) {
if (buffer[position + 1] >= (byte) 0xD0 && buffer[position + 1] <= (byte) 0xD7) {
// RSTn - a 2-byte marker.
debugln("Found RSTn marker.");
position += 2;
continue;
} else if (buffer[position + 1] == (byte) 0xDA || buffer[position + 1] == (byte) 0xD9) {
// 0xDA -> SOS - Start of Scan
// 0xD9 -> EOI - End of Image
// In both cases, terminate the scan for Exif data.
debugln("Stop scan for Exif. Found: %s, %s", buffer[position], buffer[position + 1]);
terminateIntercept();
break;
}
}
}
debugln("Prior to 4-byte section. position: %s, total read: %s", position, totalRead);
if (position + 4 <= totalRead) {
try {
if (buffer[position] == (byte) 0xFF) {
if (buffer[position + 1] == (byte) 0xE1) {
// APP1
doCaptureApp1 = true;
startApp1 = position;
// payload + marker
int incrementBy = getPayloadLength(buffer[position + 2], buffer[position + 3]) + 4;
debugln("Prior to 2-byte section. position: %s, total read: %s", position, totalRead);
int newPosition = incrementBy + position;
endApp1 = newPosition;
debugln("Found APP1. position: %s, total read: %s, increment by: %s", position, totalRead, incrementBy);
debugln("Found APP1. start: %s, end: %s", startApp1, endApp1);
if (newPosition > totalRead) {
remainingSkip = newPosition - totalRead;
position = totalRead;
debugln("Skip request; remaining skip: %s", remainingSkip);
} else {
position = newPosition;
debugln("No skip needed; new position: %s", newPosition);
}
continue;
} else if (buffer[1] == (byte) 0xDD) {
// DRI (this is a 4-byte marker w/o payload.)
debugln("Found DRI.");
position += 4;
continue;
}
// Other markers like APP0, DQT don't need any special processing.
int incrementBy = getPayloadLength(buffer[position + 2], buffer[position + 3]) + 4;
int newPosition = incrementBy + position;
debugln("Other 4-byte. position: %s, total read: %s, increment by: %s", position, totalRead, incrementBy);
debugln("Other 4-byte. start: %s, end: %s", startApp1, endApp1);
if (newPosition > totalRead) {
remainingSkip = newPosition - totalRead;
position = totalRead;
debugln("Skip request; remaining skip: %s", remainingSkip);
} else {
position = newPosition;
debugln("No skip needed; new position: %s", newPosition);
}
continue;
}
} catch (Exception e) {
// Immediately drop everything, as we can't recover.
// TODO Record what went wrong.
debugln("[Exception] Exception thrown. Terminating intercept.");
debugln("[Exception] %s", e.toString());
for (StackTraceElement el : e.getStackTrace()) {
debugln("[Exception] %s", el.toString());
}
terminateIntercept();
break;
}
}
if (totalRead <= 6) {
// SOI (2 bytes) + marker+length (4 bytes) == 6 bytes
// If we didn't find a 2-byte (standalone) marker, then
// we'll need to wait around to get enough one for 4-byte.
debugln("Not enough data read. Attempt one additional read.");
break;
}
terminateIntercept();
debugln("Shouldn't be here. Terminating intercept.");
break;
}
return bytesRead;
}
@Override
public int read() throws IOException {
return is.read();
}
/**
* Returns the payload length from the marker header.
* @param a First byte of payload length.
* @param b Second byte of payload length.
* @return Length as an integer.
*/
private static int getPayloadLength(byte a, byte b) {
int length = ByteBuffer.wrap(new byte[] {a, b}).getShort() - 2;
if (length <= 0) {
throw new IllegalStateException(
"Expected a positive payload length, but was " + length
);
}
return length;
}
}
public BufferedImage read() throws IOException {
ImageInputStream iis = ImageIO.createImageInputStream(is);
if (iis == null) {
throw new IOException("Could not open InputStream.");
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
iis.close();
throw new UnsupportedFormatException(
UnsupportedFormatException.UNKNOWN,
"No suitable ImageReader found for source data."
);
}
ImageReader reader = readers.next();
reader.setInput(iis);
boolean isExceptionThrown = false;
try {
BufferedImage img = readImage(reader);
return finishedReading(img);
} catch (IOException e) {
isExceptionThrown = true;
throw e;
} finally {
reader.dispose();
try {
iis.close();
} catch (IOException e) {
// TODO If above Java 7, we can use Throwable.addSuppressed
// Suppress this exception from superseding the original exception.
// Original exception is likely to be more informational than this one.
if (!isExceptionThrown) {
throw e;
}
}
}
}
private BufferedImage readImage(ImageReader reader) throws IOException {
try {
if (param.useExifOrientation()) {
Orientation orientation = null;
// Attempt to use Exif reader of the ImageReader.
// If the ImageReader fails like seen in Issue #108, use the
// backup method of using the captured Exif data.
boolean useExifFromRawData = false;
try {
orientation = ExifUtils.getExifOrientation(reader, FIRST_IMAGE_INDEX);
} catch (Exception e) {
// TODO Would be useful to capture why it didn't work.
useExifFromRawData = true;
}
if (useExifFromRawData && is instanceof ExifCaptureInputStream) {
byte[] exifData = ((ExifCaptureInputStream)is).getExifData();
if (exifData != null) {
orientation = ExifUtils.getOrientationFromExif(exifData);
}
}
// Skip this code block if there's no rotation needed.
if (orientation != null && orientation != Orientation.TOP_LEFT) {
List<ImageFilter> filters = param.getImageFilters();
// EXIF orientation filter is added to the beginning, as
// it should be performed early to prevent mis-orientation
// in later filters.
filters.add(0, ExifFilterUtils.getFilterForOrientation(orientation));
}
}
} catch (Exception e) {
// If something goes wrong, then skip the orientation-related
// processing.
// TODO Ought to have some way to track errors.
}
inputFormatName = reader.getFormatName();
ImageReadParam irParam = reader.getDefaultReadParam();
int width = reader.getWidth(FIRST_IMAGE_INDEX);
int height = reader.getHeight(FIRST_IMAGE_INDEX);
if (param != null && param.getSourceRegion() != null) {
Region region = param.getSourceRegion();
Rectangle sourceRegion = region.calculate(width, height);
irParam.setSourceRegion(sourceRegion);
}
if (param != null &&
Boolean.getBoolean("thumbnailator.conserveMemoryWorkaround") &&
width > 1800 && height > 1800 &&
(width * height * 4L > Runtime.getRuntime().freeMemory() / 4)
) {
int subsampling = 1;
// Calculate the maximum subsampling that can be used.
if (param.getSize() != null && (param.getSize().width * 2 < width && param.getSize().height * 2 < height)) {
int targetWidth = param.getSize().width;
int targetHeight = param.getSize().height;
// Handle cases where .width() or .height() is called. (Issue 161)
targetWidth = targetWidth != Integer.MAX_VALUE ? targetWidth : targetHeight;
targetHeight = targetHeight != Integer.MAX_VALUE ? targetHeight : targetWidth;
double widthScaling = (double)width / (double)targetWidth;
double heightScaling = (double)height / (double)targetHeight;
subsampling = (int)Math.floor(Math.min(widthScaling, heightScaling));
} else if (param.getSize() == null) {
subsampling = (int)Math.max(1, Math.floor(1 / Math.max(param.getHeightScalingFactor(), param.getWidthScalingFactor())));
}
// Prevent excessive subsampling that can ruin image quality.
// This will ensure that at least a 600 x 600 image will be used as source.
for (; (width / subsampling) < 600 || (height / subsampling) < 600; subsampling
// If scaling factor based resize is used, need to change the scaling factor.
if (param.getSize() == null) {
try {
Class<?> c = param.getClass();
Field heightField = c.getDeclaredField("heightScalingFactor");
Field widthField = c.getDeclaredField("widthScalingFactor");
heightField.setAccessible(true);
widthField.setAccessible(true);
heightField.set(param, param.getHeightScalingFactor() * (double)subsampling);
widthField.set(param, param.getWidthScalingFactor() * (double)subsampling);
} catch (Exception e) {
// If we can't update the parameter, then disable subsampling.
subsampling = 1;
}
}
irParam.setSourceSubsampling(subsampling, subsampling, 0, 0);
}
return reader.read(FIRST_IMAGE_INDEX, irParam);
}
public InputStream getSource() {
return is;
}
}
|
package net.itarray.automotion.validation;
import org.openqa.selenium.WebElement;
@Chunks({
@Chunk(id = "empty",
description = "empty", elements ={
}),
@Chunk(id = "one",
description = "one element", elements ={
@Element({10, 20, 40, 50})
}),
@Chunk(id = "two_overlapping",
description = "two overlapping elements", elements ={
@Element({10, 20, 30, 35}),
@Element({15, 25, 35, 50}),
}),
@Chunk(id = "two_horizontally_overlapping",
description = "two elements which horizontally projections overlap", elements ={
@Element({10, 20, 30, 35}),
@Element({15, 40, 35, 50}),
}),
@Chunk(id = "two_vertically_overlapping",
description = "two elements which vertically projections overlap", elements ={
@Element({10, 20, 30, 35}),
@Element({40, 25, 60, 50}),
}),
@Chunk(id = "two_not_overlapping_in_any_direction",
description = "two elements which horizontal and vertical projections don not overlap", elements ={
@Element({10, 20, 30, 35}),
@Element({40, 40, 60, 60}),
}),
@Chunk(id = "three",
description ="three elements with different sizes in a row with different gutters", elements ={
@Element({100, 50, 300, 60}),
@Element({400, 50, 700, 60}),
@Element({900, 50, 1200, 60}),
}),
@Chunk(id = "seven",
description ="seven elements in three rows with different sizes and gutters", elements ={
@Element({100, 50, 300, 60}),
@Element({400, 50, 700, 70}),
@Element({900, 50, 1200, 80}),
@Element({100, 150, 300, 160}),
@Element({400, 150, 700, 170}),
@Element({900, 150, 1200, 180}),
@Element({100, 160, 300, 250}),
})
})
public interface ChunkUIElementValidator {
boolean validate();
// ? filled needs to be expressed somehow
// areAlignedInColumns(numberOfColumns)
@Valid({
@Scenario(chunk = "empty", params = {"3"}),
@Scenario(chunk = "one", params = {"1"}),
@Scenario(chunk = "three", params = {"3", "4"}),
@Scenario(chunk = "seven", params = {"3"}),
})
@NotValid({
@Scenario(chunk = "empty", params = {"3"}, oneOrMore = true),
@Scenario(chunk = "three", params = {"2"}),
@Scenario(chunk = "seven", params = {"2", "4"}),
})
ChunkUIElementValidator alignedAsGrid(int horizontalGridSize);
// areAlignedInColumnsAndRows(numberOfColumns)
/**
* Validate that this chunks elements are aligned in a grid of cells (not areas).
* This is an alpha version - don't expect detailed error messages
*
* <img src="./doc-files/sample.svg" style="display: block"></img>
*
* @return this
*/
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
@Scenario(chunk = "two_not_overlapping_in_any_direction"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
@Scenario(chunk = "two_overlapping"),
@Scenario(chunk = "two_horizontally_overlapping"),
@Scenario(chunk = "two_vertically_overlapping"),
@Scenario(chunk = "seven"),
})
ChunkUIElementValidator areAlignedAsGridCells();
// area
@Valid({
@Scenario(chunk = "one", params = {"1, 1"}),
@Scenario(chunk = "three", params = {"3, 1", "4, 1"}),
@Scenario(chunk = "seven", params = {"3, 3"}),
})
@NotValid({
@Scenario(chunk = "empty", params = {"3, 3"}, oneOrMore = true),
@Scenario(chunk = "empty", params = {"3, 3"}),
@Scenario(chunk = "three", params = {"3, 2", "4, 2"}),
@Scenario(chunk = "seven", params = {"3, 2", "3, 4", "4, 1"}),
})
ChunkUIElementValidator alignedAsGrid(int horizontalGridSize, int verticalGridSize);
ChunkUIElementValidator doNotOverlap(); // tolerance
ChunkUIElementValidator areInsideOf(WebElement containerElement, String readableContainerName);
// size
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveEqualSize(); // tolerance
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveEqualWidth();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveEqualHeight();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveDifferentSizes();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveDifferentWidths();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator haveDifferentHeights();
// alignment
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator areLeftAligned();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator areRightAligned();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator areTopAligned();
@Valid({
@Scenario(chunk = "empty"),
@Scenario(chunk = "one"),
})
@NotValid({
@Scenario(chunk = "empty", oneOrMore = true),
})
ChunkUIElementValidator areBottomAligned();
ChunkUIElementValidator areCenteredOnPageVertically();
ChunkUIElementValidator areCenteredOnPageHorizontally();
// equal distribution (horizontal, vertically, both)?
/**
* @deprecated As of release 2.0, replaced by {@link net.itarray.automotion.validation.ResponsiveUIValidator#drawMap()}
*/
@Deprecated
ChunkUIElementValidator drawMap();
/**
* @deprecated As of release 2.0, replaced by {@link net.itarray.automotion.validation.ResponsiveUIValidator#dontDrawMap()}
*/
@Deprecated
ChunkUIElementValidator dontDrawMap();
/**
* @deprecated As of release 2.0, replaced by {@link net.itarray.automotion.validation.properties.Expression#percent(int, net.itarray.automotion.internal.properties.PercentReference)}
*/
@Deprecated
ChunkUIElementValidator changeMetricsUnitsTo(util.validator.ResponsiveUIValidator.Units units);
/**
* @deprecated As of release 2.0, replaced by {@link net.itarray.automotion.validation.properties.Expression#percent(int, net.itarray.automotion.internal.properties.PercentReference)}
*/
@Deprecated
ChunkUIElementValidator changeMetricsUnitsTo(Units units);
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#doNotOverlap()}
*/
@Deprecated
default ChunkUIElementValidator areNotOverlappedWithEachOther() { return doNotOverlap(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveEqualSize()}
*/
@Deprecated
default ChunkUIElementValidator withSameSize() { return haveEqualSize(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveEqualWidth()}
*/
@Deprecated
default ChunkUIElementValidator withSameWidth() { return haveEqualWidth(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveEqualHeight()}
*/
@Deprecated
default ChunkUIElementValidator withSameHeight() { return haveEqualHeight(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveDifferentSizes()}
*/
@Deprecated
default ChunkUIElementValidator withNotSameSize() { return haveDifferentSizes(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveDifferentWidths()}
*/
@Deprecated
default ChunkUIElementValidator withNotSameWidth() { return haveDifferentWidths(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#haveDifferentHeights()}
*/
@Deprecated
default ChunkUIElementValidator withNotSameHeight() { return haveDifferentHeights(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areRightAligned()}
*/
@Deprecated
default ChunkUIElementValidator sameRightOffset() { return areRightAligned(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areLeftAligned()}
*/
@Deprecated
default ChunkUIElementValidator sameLeftOffset() { return areLeftAligned(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areTopAligned()}
*/
@Deprecated
default ChunkUIElementValidator sameTopOffset() { return areTopAligned(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areBottomAligned()}
*/
@Deprecated
default ChunkUIElementValidator sameBottomOffset() { return areBottomAligned(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areCenteredOnPageVertically()}
*/
@Deprecated
default ChunkUIElementValidator equalLeftRightOffset() { return areCenteredOnPageVertically(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areCenteredOnPageHorizontally()}
*/
@Deprecated
default ChunkUIElementValidator equalTopBottomOffset() { return areCenteredOnPageHorizontally(); }
/**
* @deprecated As of release 2.0, replaced by {@link ChunkUIElementValidator#areInsideOf(org.openqa.selenium.WebElement, String)}
*/
@Deprecated
default ChunkUIElementValidator insideOf(WebElement containerElement, String readableContainerName) { return areInsideOf(containerElement, readableContainerName); }
}
|
package org.blitzortung.android.data.provider;
import org.blitzortung.android.data.beans.*;
import org.blitzortung.android.jsonrpc.JsonRpcClient;
import org.blitzortung.android.util.TimeFormat;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
public class JsonRpcDataProvider extends DataProvider {
private static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
static {
TimeZone tz = TimeZone.getTimeZone("UTC");
DATE_TIME_FORMATTER.setTimeZone(tz);
}
static private final String[] SERVERS = new String[]{"http://bo1.tryb.de:7080/"};
static private int CURRENT_SERVER = 0;
private JsonRpcClient client;
private int nextId = 0;
private int[] histogram;
private RasterParameters rasterParameters = null;
private boolean incrementalResult;
public List<AbstractStroke> getStrokes(int timeInterval, int intervalOffset, int region) {
List<AbstractStroke> strokes = new ArrayList<AbstractStroke>();
rasterParameters = null;
if (intervalOffset < 0) {
nextId = 0;
}
incrementalResult = nextId != 0;
try {
JSONObject response = client.call("get_strokes", timeInterval, intervalOffset < 0 ? intervalOffset : nextId);
readStrokes(response, strokes);
readHistogramData(response);
} catch (Exception e) {
skipServer();
throw new RuntimeException(e);
}
return strokes;
}
public boolean returnsIncrementalData()
{
return incrementalResult;
}
public List<AbstractStroke> getStrokesRaster(int intervalDuration, int intervalOffset, int rasterSize, int region) {
List<AbstractStroke> strokes = new ArrayList<AbstractStroke>();
nextId = 0;
incrementalResult = false;
try {
JSONObject response = client.call("get_strokes_raster", intervalDuration, rasterSize, intervalOffset, region);
readRasterData(response, strokes);
readHistogramData(response);
} catch (Exception e) {
skipServer();
throw new RuntimeException(e);
}
return strokes;
}
public int[] getHistogram() {
return histogram;
}
public RasterParameters getRasterParameters() {
return rasterParameters;
}
@Override
public List<Participant> getStations(int region) {
List<Participant> stations = new ArrayList<Participant>();
try {
JSONObject response = client.call("get_stations");
JSONArray stations_array = (JSONArray) response.get("stations");
for (int i = 0; i < stations_array.length(); i++) {
stations.add(new Participant(stations_array.getJSONArray(i)));
}
} catch (Exception e) {
skipServer();
throw new RuntimeException(e);
}
return stations;
}
@Override
public DataProviderType getType() {
return DataProviderType.RPC;
}
@Override
public void setUp() {
String agentSuffix = pInfo != null ? "-" + Integer.toString(pInfo.versionCode) : "";
client = new JsonRpcClient(getServer(), agentSuffix);
client.setConnectionTimeout(40000);
client.setSocketTimeout(40000);
}
@Override
public void shutDown() {
client.shutdown();
client = null;
}
@Override
public void reset() {
nextId = 0;
}
@Override
public boolean isCapableOfHistoricalData() {
return true;
}
private void readStrokes(JSONObject response, List<AbstractStroke> strokes) throws JSONException {
long referenceTimestamp = getReferenceTimestamp(response);
JSONArray strokes_array = (JSONArray) response.get("s");
for (int i = 0; i < strokes_array.length(); i++) {
strokes.add(new Stroke(referenceTimestamp, strokes_array.getJSONArray(i)));
}
if (response.has("next")) {
nextId = (Integer) response.get("next");
}
}
private void readRasterData(JSONObject response, List<AbstractStroke> strokes) throws JSONException {
rasterParameters = new RasterParameters(response);
long referenceTimestamp = getReferenceTimestamp(response);
JSONArray strokes_array = (JSONArray) response.get("r");
for (int i = 0; i < strokes_array.length(); i++) {
strokes.add(new RasterElement(rasterParameters, referenceTimestamp, strokes_array.getJSONArray(i)));
}
}
private long getReferenceTimestamp(JSONObject response) throws JSONException {
return TimeFormat.parseTime(response.getString("t"));
}
private void readHistogramData(JSONObject response) throws JSONException {
if (response.has("h")) {
JSONArray histogram_array = (JSONArray) response.get("h");
if (histogram == null || histogram.length != histogram_array.length()) {
histogram = new int[histogram_array.length()];
}
for (int i = 0; i < histogram_array.length(); i++) {
histogram[i] = histogram_array.getInt(i);
}
}
}
private static String getServer()
{
return SERVERS[CURRENT_SERVER];
}
private void skipServer()
{
CURRENT_SERVER = (CURRENT_SERVER + 1) % SERVERS.length;
}
}
|
package org.camunda.bpm.extension.mockito.query;
import static com.google.common.base.Throwables.propagate;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import org.camunda.bpm.engine.query.Query;
import org.camunda.bpm.extension.mockito.answer.FluentAnswer;
import com.google.common.base.Supplier;
/**
* This looks more complicated than it actually is ... To easily mock the
* behaviour of queries, all common functionality is extracted to this abstract
* super class, the high level of Generics is needed for the fluent api pattern,
* so the abstract mock implementing the generic Query interface must also keep
* a reference to itself.
*
* @param <M>
* the type of the AbstractQueryMock (repeat the type of the class you
* are building). Used to "return this"
* @param <Q>
* the type of the query to mock (for example: TaskQuery).
* @param <R>
* the type of the expected result (for example: Execution).
* @param <S>
* the type of the service the query belongs to (used for "forService"
* binding), for Example: TaskService.
*
* @author Jan Galinski
*/
abstract class AbstractQueryMock<M extends AbstractQueryMock<M, Q, R, S>, Q extends Query<?, R>, R extends Object, S> implements Supplier<Q> {
/**
* The internally stored query instance.
*/
private final Q query;
/**
* Used for mocking the query creation via reflection.
*/
private final Method createMethod;
/**
* Creates a new query mock and mocks fluent api behavior by adding a default
* answer to the mock. Every createMethod will return the mock itself, except
* <ul>
* <li>list() - returns empty ArrayList</li>
* <lI>singeResult() - returns null</lI>
* </ul>
*
* @param queryType
* the type of the query to mock.
* @param serviceType
* the type of service that generates this query
*/
protected AbstractQueryMock(@Nonnull final Class<Q> queryType, @Nonnull final Class<S> serviceType) {
query = FluentAnswer.createMock(queryType);
createMethod = createMethod(queryType, serviceType);
list(new ArrayList<R>());
singleResult(null);
}
private Method createMethod(@Nonnull final Class<Q> queryType, @Nonnull Class<S> serviceType) {
try {
return serviceType.getDeclaredMethod("create" + queryType.getSimpleName());
} catch (NoSuchMethodException e) {
throw propagate(e);
}
}
public Q list(final List<R> result) {
when(query.list()).thenReturn(result);
return get();
}
public Q singleResult(final R result) {
when(query.singleResult()).thenReturn(result);
return get();
}
public Q count(long count) {
when(query.count()).thenReturn(count);
return get();
}
public M forService(S service) {
try {
when(createMethod.invoke(service)).thenReturn(get());
} catch (Exception e) {
propagate(e);
}
return (M) this;
}
@Override
public final Q get() {
return query;
}
}
|
package org.corpus_tools.annis.gui.security;
import com.google.common.base.Preconditions;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
public class DesktopAuthentication implements Authentication {
private static final long serialVersionUID = -7671167490817088267L;
private final DefaultOAuth2User principal;
private final String token;
private boolean isAuthenticated;
public DesktopAuthentication(DefaultOAuth2User principal, String token) {
super();
Preconditions.checkNotNull(principal);
Preconditions.checkNotNull(token);
this.principal = principal;
this.token = token;
this.isAuthenticated = true;
}
@Override
public String getName() {
return principal.getName();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return principal.getAuthorities();
}
@Override
public Object getCredentials() {
return token;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return principal;
}
@Override
public boolean isAuthenticated() {
return isAuthenticated;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
this.isAuthenticated = isAuthenticated;
}
}
|
package org.cyclops.commoncapabilities.modcompat.ic2;
import ic2.core.item.tool.ItemToolWrench;
import ic2.core.item.tool.ItemToolWrenchElectric;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fml.common.ModAPIManager;
import org.cyclops.commoncapabilities.CommonCapabilities;
import org.cyclops.commoncapabilities.GeneralConfig;
import org.cyclops.commoncapabilities.Reference;
import org.cyclops.commoncapabilities.api.capability.wrench.DefaultWrench;
import org.cyclops.commoncapabilities.api.capability.wrench.IWrench;
import org.cyclops.commoncapabilities.capability.wrench.WrenchConfig;
import org.cyclops.commoncapabilities.modcompat.ic2.capability.tesla.Ic2TeslaIntegration;
import org.cyclops.cyclopscore.modcompat.IModCompat;
import org.cyclops.cyclopscore.modcompat.capabilities.CapabilityConstructorRegistry;
import org.cyclops.cyclopscore.modcompat.capabilities.DefaultCapabilityProvider;
import org.cyclops.cyclopscore.modcompat.capabilities.ICapabilityConstructor;
import javax.annotation.Nullable;
/**
* Capabilities for IC2.
* @author rubensworks
*/
public class Ic2ModCompat implements IModCompat {
@Override
public String getModID() {
return Reference.MOD_IC2;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getComment() {
return "Tesla and wrench capabilities for IC2 tiles and items.";
}
@Override
public void onInit(Step initStep) {
if(initStep == Step.PREINIT && ModAPIManager.INSTANCE.hasAPI(Reference.MOD_TESLA_API) && GeneralConfig.ic2EuToTesla) {
Ic2TeslaIntegration.load();
CapabilityConstructorRegistry registry = CommonCapabilities._instance.getCapabilityConstructorRegistry();
// Wrench
registry.registerItem(ItemToolWrenchElectric.class,
new ICapabilityConstructor<IWrench, ItemToolWrenchElectric, ItemStack>() {
@Override
public Capability<IWrench> getCapability() {
return WrenchConfig.CAPABILITY;
}
@Nullable
@Override
public ICapabilityProvider createProvider(ItemToolWrenchElectric hostType, final ItemStack host) {
return new DefaultCapabilityProvider<>(WrenchConfig.CAPABILITY, new DefaultWrench());
}
});
registry.registerItem(ItemToolWrench.class,
new ICapabilityConstructor<IWrench, ItemToolWrench, ItemStack>() {
@Override
public Capability<IWrench> getCapability() {
return WrenchConfig.CAPABILITY;
}
@Nullable
@Override
public ICapabilityProvider createProvider(ItemToolWrench hostType, final ItemStack host) {
return new DefaultCapabilityProvider<>(WrenchConfig.CAPABILITY, new DefaultWrench());
}
});
}
}
}
|
package baza;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gui.GlavnoOkno;
/**
* @author campovski
* Razred PripravljalecPodatkov skrbi za zvezo med uporabniskim vmesnikom in SqlManager-jem.
* Tako sta njegovi nalogi priprava podatkov za posiljanje v bazo in dajanja ukazov, kaj naj
* SqlManager naredi s podatki. Prav tako lahko PripravljalecPodatkov zahteva podatke iz baze,
* torej jih lahko od tam tudi dobi.
*/
public class PripravljalecPodatkov {
private static Map<String, List<List<String>>> slovar;
private static Map<String, List<List<String>>> elementiZaDodajanje = new HashMap<String, List<List<String>>>();
/**
* Naredi testni slovar. Mogoce v prihodnosti se kaj drugega...
*/
public PripravljalecPodatkov(){
slovar = new HashMap<String, List<List<String>>>();
List<List<String>> seznamSeznamovFilmi = new ArrayList<List<String>>();
List<String> seznamFilmiStolpci = new ArrayList<String>();
seznamFilmiStolpci.add("Naslov");
seznamFilmiStolpci.add("Leto");
seznamSeznamovFilmi.add(seznamFilmiStolpci);
List<String> seznamFilmi1 = new ArrayList<String>();
seznamFilmi1.add("Star Wars");
seznamFilmi1.add("2016");
seznamSeznamovFilmi.add(seznamFilmi1);
List<String> seznamFilmi2 = new ArrayList<String>();
seznamFilmi2.add("Me Before You");
seznamFilmi2.add("2016");
seznamSeznamovFilmi.add(seznamFilmi2);
List<String> seznamFilmi3 = new ArrayList<String>();
seznamFilmi3.add("The Adventures of Sherlock Holmes");
seznamFilmi3.add("1984");
seznamSeznamovFilmi.add(seznamFilmi3);
List<List<String>> seznamSeznamovFilmskiPlakati = new ArrayList<List<String>>();
List<String> seznamFilmskiPlakatiStolpci = new ArrayList<String>();
seznamFilmskiPlakatiStolpci.add("Naslov");
seznamFilmskiPlakatiStolpci.add("Velikost");
seznamSeznamovFilmskiPlakati.add(seznamFilmskiPlakatiStolpci);
List<String> seznamFilmskiPlakati1 = new ArrayList<String>();
seznamFilmskiPlakati1.add("Houston we have a problem");
seznamFilmskiPlakati1.add("Velik");
seznamSeznamovFilmskiPlakati.add(seznamFilmskiPlakati1);
List<String> seznamFilmskiPlakati2 = new ArrayList<String>();
seznamFilmskiPlakati2.add("Othello");
seznamFilmskiPlakati2.add("Srednji");
seznamSeznamovFilmskiPlakati.add(seznamFilmskiPlakati2);
slovar.put("Pivo", seznamSeznamovFilmi);
slovar.put("Filmi", seznamSeznamovFilmi);
slovar.put("Filmski plakati", seznamSeznamovFilmskiPlakati);
}
/**
* @param stolpci
* Metoda dobljen seznam doda v slovar, pri cemer je prvi element stolpcev
* ime zbirke, ostali pa so imena stolpcev. Pred tem zbirko se doda v bazo.
*/
public static void dodajZbirko(List<String> stolpci){
List<List<String>> seznamSeznamov = new ArrayList<List<String>>();
List<String> prvaVrstica = new ArrayList<String>();
for (int i = 1; i < stolpci.size(); i++){
prvaVrstica.add(stolpci.get(i));
}
seznamSeznamov.add(prvaVrstica);
SqlManager.dodajZbirko(stolpci);
slovar.put(stolpci.get(0), seznamSeznamov);
}
/**
* Metoda se pozene v novem vlaknu, ki po branju JCheckBox-ov pocaka, ali
* bo uporabnik potrdil izbris. Ce ga, nadaljujemo, drugace se vlakno ustavi.
*/
public static void izbrisiZbirke(List<String> zbirke){
SqlManager.odstraniZbirke(zbirke);
System.out.println(zbirke);
}
public static void dodajElement(String zbirka, List<String> element){
if (elementiZaDodajanje.containsKey(zbirka)){
if (!elementiZaDodajanje.get(zbirka).contains(element)){
elementiZaDodajanje.get(zbirka).add(element);
}
}
else {
List<List<String>> dodanElement = new ArrayList<List<String>>();
dodanElement.add(element);
elementiZaDodajanje.put(zbirka, dodanElement);
}
System.out.println(elementiZaDodajanje);
}
public static void dodajElemente(){
if (!elementiZaDodajanje.isEmpty()){
SqlManager.dodajElemente(elementiZaDodajanje);
System.out.println("To so dodani elementi: " + elementiZaDodajanje);
elementiZaDodajanje.clear();
}
}
/**
* Metoda iz JCheckBoxov prebere, katere elemente je potrebno izbrisati. Ker elementi
* niso tako nevarni za izbris, kakor zbirke, tu ni potrebno preverjati, ali res zelimo
* izbris ali ne.
*/
public static void izbrisiElemente(List<List<String>> elementi){
SqlManager.odstraniElemente(GlavnoOkno.getZbirkaZaRisanje(), elementi);
System.out.println(elementi);
}
/**
* @return slovar
*/
public Map<String, List<List<String>>> getSlovar() {
return slovar;
}
}
|
package org.minimalj.frontend.impl.swing.toolkit;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.LayoutManager2;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import org.minimalj.frontend.Frontend.FormContent;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.form.element.FormElementConstraint;
import org.minimalj.frontend.impl.swing.component.SwingCaption;
public class SwingFormContent extends JPanel implements FormContent {
private static final long serialVersionUID = 1L;
private final int columnWidth;
private final Map<IComponent, SwingCaption> captionByComponent = new HashMap<>();
public SwingFormContent(int columns, int columnWidthPercentage) {
columnWidth = getColumnWidth() * columnWidthPercentage / 100;
setLayout(new GridFormLayoutManager(columns, columnWidth, 5));
setBorder(null);
}
private int getColumnWidth() {
FontMetrics fm = getFontMetrics(getFont());
return (int)fm.getStringBounds("The quick brown fox jumps over the lazy dog", getGraphics()).getWidth();
}
@Override
public void add(IComponent c, FormElementConstraint constraint) {
Component component = (Component) c;
add(component, new GridFormLayoutConstraint(-1, constraint));
}
@Override
public void add(String caption, IComponent c, FormElementConstraint constraint, int span) {
Component component = (Component) c;
SwingCaption swingCaption = new SwingCaption(component, caption);
captionByComponent.put(c, swingCaption);
add(swingCaption, new GridFormLayoutConstraint(span, constraint));
}
@Override
public void setValidationMessages(IComponent component, List<String> validationMessages) {
SwingCaption swingCaption = captionByComponent.get(component);
if (swingCaption != null) {
swingCaption.setValidationMessages(validationMessages);
}
}
private static class GridFormLayoutConstraint {
private final int span;
private final FormElementConstraint formElementConstraint;
public GridFormLayoutConstraint(int span, FormElementConstraint formElementConstraint) {
super();
this.span = span;
this.formElementConstraint = formElementConstraint;
}
protected int getSpan() {
return span;
}
protected boolean isVerticallyGrowing() {
return formElementConstraint != null && formElementConstraint.grow;
}
public boolean isCompleteRow() {
return span < 1;
}
}
private static class GridFormLayoutManager implements LayoutManager2 {
private final int columns;
private final int minColumnWidth;
private final int ins;
private final List<List<Component>> rows = new LinkedList<>();
private final Map<Component, GridFormLayoutConstraint> constraints = new HashMap<>();
private Dimension size;
private Rectangle lastParentBounds = null;
private int column = Integer.MAX_VALUE;
public GridFormLayoutManager(int columns, int minColumnWidth, int ins) {
this.columns = columns;
this.minColumnWidth = minColumnWidth;
this.ins = ins;
}
@Override
public Dimension preferredLayoutSize(Container parent) {
layoutContainer(parent);
return size;
}
@Override
public Dimension minimumLayoutSize(Container parent) {
layoutContainer(parent);
return size;
}
@Override
public void layoutContainer(Container parent) {
if (lastParentBounds != null && lastParentBounds.equals(parent.getBounds())) {
return;
}
lastParentBounds = parent.getBounds();
int fixHeight = calcFixHeight(true);
int fixHeightWithoutCaption = calcFixHeight(false);
int y = ins;
int width = parent.getWidth();
int widthWithoutIns = width - 2 * ins;
for (List<Component> row : rows) {
int height;
boolean hasCaption = hasCaption(row);
if (isRowVerticallyGrowing(row)) {
height = Math.max(getHeight(row), fixHeight);
} else {
height = hasCaption ? fixHeight : fixHeightWithoutCaption;
}
layoutRow(widthWithoutIns, row, y, height, hasCaption ? fixHeight : fixHeightWithoutCaption);
y += height;
}
y+= ins;
size = new Dimension(Math.max(minColumnWidth * columns, width), y);
}
private void layoutRow(int width, List<Component> row, int y, int height, int minimalHeight) {
int x = ins;
for (Component component : row) {
component.setLocation(x, y);
GridFormLayoutConstraint constraint = constraints.get(component);
int componentWidth = constraint.isCompleteRow() ? width : constraint.getSpan() * width / columns;
x += componentWidth;
if (constraint.isVerticallyGrowing()) {
component.setSize(componentWidth, height);
} else {
// even non growing components are stretched to fixHeight (they should no collapse to 0 height)
component.setSize(componentWidth, Math.max(component.getPreferredSize().height, minimalHeight));
}
}
}
private int getHeight(List<Component> row) {
int height = 0;
for (Component component : row) {
height = Math.max(height, component.getPreferredSize().height);
}
return height;
}
private boolean isRowVerticallyGrowing(List<Component> row) {
for (Component component : row) {
GridFormLayoutConstraint constraint = constraints.get(component);
if (constraint.isVerticallyGrowing()) {
return true;
}
}
return false;
}
private boolean hasCaption(List<Component> row) {
for (Component component : row) {
if (component instanceof SwingCaption) {
return true;
}
}
return false;
}
private int calcFixHeight(boolean caption) {
int height = 0;
for (List<Component> row : rows) {
for (Component component : row) {
GridFormLayoutConstraint constraint = constraints.get(component);
if (!constraint.isVerticallyGrowing()) {
boolean hasCaption = component instanceof SwingCaption;
if (hasCaption == caption) {
height = Math.max(height, component.getPreferredSize().height);
}
}
}
}
return height;
}
@Override
public void addLayoutComponent(Component comp, Object constraint) {
GridFormLayoutConstraint formConstraint = (GridFormLayoutConstraint) constraint;
constraints.put(comp, formConstraint);
List<Component> row;
if (column >= columns) {
row = new ArrayList<>();
rows.add(row);
column = 0;
} else {
row = rows.get(rows.size()-1);
}
row.add(comp);
column = formConstraint.isCompleteRow() ? columns : column + formConstraint.getSpan();
lastParentBounds = null;
}
@Override
public Dimension maximumLayoutSize(Container target) {
return new Dimension(30000, 30000);
}
@Override
public void invalidateLayout(Container target) {
lastParentBounds = null;
}
@Override
public float getLayoutAlignmentX(Container target) {
return 0;
}
@Override
public float getLayoutAlignmentY(Container target) {
return 0;
}
@Override
public void addLayoutComponent(String name, Component comp) {
// not used
}
@Override
public void removeLayoutComponent(Component comp) {
// not used
}
}
}
|
package org.openlmis.referencedata.service;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.openlmis.referencedata.dto.RightAssignmentDto;
import org.openlmis.referencedata.util.Resource2Db;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;
/**
* RightAssignmentInitializer runs after its associated Spring application has loaded. It
* automatically re-generates right assignments into the database, after dropping the existing
* right assignments. This component only runs when the "refresh-db" Spring profile is set.
*/
@Service
public class RightAssignmentService {
private static final XLogger XLOGGER = XLoggerFactory.getXLogger(RightAssignmentService.class);
private static final String RIGHT_ASSIGNMENTS_PATH = "classpath:db/right-assignments/";
static final String DELETE_SQL = "DELETE FROM referencedata.right_assignments;";
@Value(value = RIGHT_ASSIGNMENTS_PATH + "get_right_assignments.sql")
private Resource rightAssignmentsResource;
@Value(value = RIGHT_ASSIGNMENTS_PATH + "get_all_supervised_facilities_from_node.sql")
private Resource supervisedFacilitiesResource;
@Autowired
JdbcTemplate template;
@Async
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
public void regenerateRightAssignments() {
XLOGGER.entry();
// Drop existing rows; we are regenerating from scratch
XLOGGER.debug("Drop existing right assignments");
template.update(DELETE_SQL);
// Get a right assignment matrix from database
XLOGGER.debug("Get intermediate right assignments from role assignments");
List<RightAssignmentDto> dbRightAssignments = new ArrayList<>();
try {
dbRightAssignments = getRightAssignmentsFromDbResource(rightAssignmentsResource);
} catch (IOException ioe) {
XLOGGER.warn("Error when getting right assignments: " + ioe.getMessage());
}
Resource2Db r2db = new Resource2Db(template);
try {
for ( List partialRightAssignments : ListUtils.partition(dbRightAssignments, 100) ) {
insertFromDbRightAssignmentList(r2db, partialRightAssignments);
}
} catch (IOException ioe) {
XLOGGER.warn("Error when getting inserting right assignments: " + ioe.getMessage());
}
XLOGGER.exit();
}
private void insertFromDbRightAssignmentList(Resource2Db resource2Db,
List<RightAssignmentDto> rightAssignmentDtos)
throws IOException {
// Convert matrix to a set of right assignments to insert
XLOGGER.debug("Convert intermediate right assignments to right assignments for insert");
Set<RightAssignmentDto> rightAssignmentsToInsert = convertForInsert(rightAssignmentDtos,
supervisedFacilitiesResource);
// Convert set of right assignments to insert to a set of SQL inserts
XLOGGER.debug("Convert right assignments to SQL inserts");
MutablePair dataWithHeader = new MutablePair<List<String>, List<Object[]>>();
dataWithHeader.setRight( rightAssignmentsToInsert.stream()
.map(rad -> rad.toColumnArray())
.collect(Collectors.toList()) );
// set column headers
dataWithHeader.setLeft(Arrays.asList("id",
"userid",
"rightname",
"facilityid",
"programid"));
// insert into right_assignments
XLOGGER.debug("Perform SQL inserts");
resource2Db.insertToDbFromBatchedPair("referencedata.right_assignments", dataWithHeader);
}
List<RightAssignmentDto> getRightAssignmentsFromDbResource(Resource resource)
throws IOException {
return template.query(
resourceToString(resource),
(ResultSet rs, int rowNum) -> {
RightAssignmentDto rightAssignmentMap = new RightAssignmentDto();
rightAssignmentMap.setUserId(UUID.fromString(rs.getString("userid")));
rightAssignmentMap.setRightName(rs.getString("rightname"));
if (null != rs.getString("facilityid")) {
rightAssignmentMap.setFacilityId(UUID.fromString(rs.getString("facilityid")));
}
if (null != rs.getString("programid")) {
rightAssignmentMap.setProgramId(UUID.fromString(rs.getString("programid")));
}
if (null != rs.getString("supervisorynodeid")) {
rightAssignmentMap.setSupervisoryNodeId(
UUID.fromString(rs.getString("supervisorynodeid")));
}
return rightAssignmentMap;
}
);
}
Set<RightAssignmentDto> convertForInsert(List<RightAssignmentDto> rightAssignments,
Resource supervisedFacilitiesResource)
throws IOException {
Set<RightAssignmentDto> rightAssignmentsToInsert = new HashSet<>();
for (RightAssignmentDto rightAssignment : rightAssignments) {
if (null != rightAssignment.getSupervisoryNodeId()) {
// Special case: supervisory node is present. We need to expand the supervisory node and
// turn it into a list of all facility IDs being supervised by this node.
// Get all supervised facilities. Add each facility to the set.
List<UUID> facilityIds = getSupervisedFacilityIds(supervisedFacilitiesResource,
rightAssignment.getSupervisoryNodeId(),
rightAssignment.getProgramId());
for (UUID facilityId : facilityIds) {
rightAssignmentsToInsert.add(new RightAssignmentDto(
rightAssignment.getUserId(),
rightAssignment.getRightName(),
facilityId,
rightAssignment.getProgramId()));
}
} else {
// All other cases: home facility supervision, fulfillment and direct right assignments.
// Just copy everything but the supervisoryNodeId and add it to the set.
rightAssignmentsToInsert.add(new RightAssignmentDto(
rightAssignment.getUserId(),
rightAssignment.getRightName(),
rightAssignment.getFacilityId(),
rightAssignment.getProgramId()));
}
}
return rightAssignmentsToInsert;
}
private List<UUID> getSupervisedFacilityIds(Resource supervisedFacilitiesResource,
UUID supervisoryNodeId, UUID programId)
throws IOException {
return template.queryForList(
resourceToString(supervisedFacilitiesResource),
UUID.class,
supervisoryNodeId,
programId);
}
private String resourceToString(final Resource resource) throws IOException {
XLOGGER.entry(resource.getDescription());
String str;
try (InputStream is = resource.getInputStream()) {
str = StreamUtils.copyToString(is, Charset.defaultCharset());
}
XLOGGER.exit();
return str;
}
}
|
package ru.taximaxim.pgsqlblocks.dbcdata;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.DecorationOverlayIcon;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import ru.taximaxim.pgsqlblocks.utils.Images;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class DbcDataListLabelProvider implements ITableLabelProvider {
private static final int BLOCKED_ICON_QUADRANT = IDecoration.TOP_RIGHT;
private static final int UPDATE_ICON_QUADRANT = IDecoration.BOTTOM_RIGHT;
private List<ILabelProviderListener> listeners;
private ConcurrentMap<String, Image> imagesMap = new ConcurrentHashMap<>();
private ConcurrentMap<String, ImageDescriptor> decoratorsMap = new ConcurrentHashMap<>();
/**
* Constructs a FileTreeLabelProvider
*/
public DbcDataListLabelProvider() {
listeners = new ArrayList<>();
}
@Override
public void addListener(ILabelProviderListener listener) {
listeners.add(listener);
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
DbcData dbcData = (DbcData) element;
switch (columnIndex) {
case 0:
return getImage(dbcData);
default:
return null;
}
}
@Override
public String getColumnText(Object element, int columnIndex) {
DbcData dbcData = (DbcData) element;
switch (columnIndex) {
case 0:
return dbcData.getName();
default:
return null;
}
}
private Image getImage(DbcData dbcData) {
String imagePath = dbcData.getStatus().getStatusImage().getImageAddr();
Image image = imagesMap.computeIfAbsent(imagePath,
k -> new Image(null, getClass().getClassLoader().getResourceAsStream(k)));
if (dbcData.hasBlockedProcess()) {
String decoratorBlockedPath = Images.DECORATOR_BLOCKED.getImageAddr();
ImageDescriptor decoratorBlockedImageDesc = decoratorsMap.computeIfAbsent(decoratorBlockedPath, path -> {
Image blockedImage = new Image(null, getClass().getClassLoader().getResourceAsStream(path));
return ImageDescriptor.createFromImage(blockedImage);
});
image = decorateImage(image, decoratorBlockedImageDesc, BLOCKED_ICON_QUADRANT);
}
if (dbcData.isInUpdateState()){
String decoratorUpdatePath = Images.DECORATOR_UPDATE.getImageAddr();
ImageDescriptor decoratorUpdateImageDesc = decoratorsMap.computeIfAbsent(decoratorUpdatePath, path -> {
Image updateImage = new Image(null, getClass().getClassLoader().getResourceAsStream(path));
return ImageDescriptor.createFromImage(updateImage);
});
Image old = image;
image = decorateImage(image, decoratorUpdateImageDesc, UPDATE_ICON_QUADRANT);
if (dbcData.hasBlockedProcess()) {
old.dispose();
}
}
return image;
}
private Image decorateImage(Image image, ImageDescriptor imageDescriptor, int iconQuadrant) {
DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image, imageDescriptor, iconQuadrant);
return overlayIcon.createImage();
}
}
|
package sizebay.catalog.client.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class ProductBasicInformationToVFR {
private Long id;
private Modeling.Gender gender;
private Product.AgeGroupEnum ageGroup;
private StrongCategoryType strongCategoryType;
private boolean isPending;
private boolean isAccessory;
private boolean isShoe;
private boolean status;
}
|
package org.tigris.subversion.svnclientadapter.commandline;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Common superclass for both SvnCommandLine and SvnAdminCommandLine
*
* @author Philip Schatz (schatz at tigris)
* @author Cdric Chabanois (cchabanois at no-log.org)
* @author Daniel Rall
*/
abstract class CommandLine {
protected String commandName;
protected CmdLineNotificationHandler notificationHandler;
protected Process process;
protected CommandLine(String commandName, CmdLineNotificationHandler notificationHandler) {
this.commandName = commandName;
this.notificationHandler = notificationHandler;
}
String version() throws CmdLineException {
ArrayList args = new ArrayList();
args.add("--version");
return execString(args,false);
}
/**
* Executes the given svn command and returns the corresponding
* <code>Process</code> object.
*
* @param svnArguments The command-line arguments to execute.
*/
protected Process execProcess(ArrayList svnArguments)
throws CmdLineException {
// We add "svn" or "svnadmin" to the arguments (as
// appropriate), and convert it to an array of strings.
int svnArgsLen = svnArguments.size();
String[] cmdline = new String[svnArgsLen + 1];
cmdline[0] = commandName;
StringBuffer svnCommand = new StringBuffer();
boolean nextIsPassword = false;
for (int i = 0; i < svnArgsLen; i++) {
if (i != 0)
svnCommand.append(' ');
Object arg = svnArguments.get(i);
if (arg != null)
arg = arg.toString();
if ("".equals(arg)) {
arg = "\"\"";
}
if (nextIsPassword) {
// Avoid showing the password on the console.
svnCommand.append("*******");
nextIsPassword = false;
} else {
svnCommand.append(arg);
}
if ("--password".equals(arg)) {
nextIsPassword = true;
}
// Regardless of the data type passed in via svnArguments,
// at this point we expect to have a String object.
cmdline[i + 1] = (String) arg;
}
notificationHandler.logCommandLine(svnCommand.toString());
// Run the command, and return the associated Process object.
try {
return process = Runtime.getRuntime().exec(cmdline, getEnvironmentVariables());
} catch (IOException e) {
throw new CmdLineException(e);
}
}
/**
* Get environment variables to be set when invoking the command-line.
* Includes <code>LANG</code> and <code>LC_ALL</code> so Subversion's output is not localized.
* <code>Systemroot</code> is required on windows platform.
* Without this variable present, the windows' DNS resolver does not work.
* <code>APR_ICONV_PATH</code> is required on windows platform for UTF-8 translation.
* The <code>PATH</code> is there, well, just to be sure ;-)
*/
protected String[] getEnvironmentVariables()
{
final String path = CmdLineClientAdapter.getEnvironmentVariable("PATH");
final String systemRoot = CmdLineClientAdapter.getEnvironmentVariable("SystemRoot");
final String aprIconv = CmdLineClientAdapter.getEnvironmentVariable("APR_ICONV_PATH");
int i = 3;
if (path != null)
i++;
if (systemRoot != null)
i++;
if (aprIconv != null)
i++;
String[] lcVars = getLocaleVariables();
String[] env = new String[i + lcVars.length];
i = 0;
//Clear the LC_ALL, we're going to override the LC_MESSAGES and LC_TIME
env[i] = "LC_ALL=";
i++;
//Set the LC_MESSAGES to "C" to avoid translated svn output. (We're parsing the english one)
env[i] = "LC_MESSAGES=C";
i++;
env[i] = "LC_TIME=C";
i++;
if (path != null) {
env[i] = "PATH=" + path;
i++;
}
if (systemRoot != null) {
env[i] = "SystemRoot=" + systemRoot;
i++;
}
if (aprIconv != null) {
env[i] = "APR_ICONV_PATH=" + aprIconv;
i++;
}
//Add the remaining LC vars
for (int j = 0; j < lcVars.length; j++) {
env[i] = lcVars[j];
i++;
}
return env;
}
private String[] getLocaleVariables()
{
String LC_ALL = CmdLineClientAdapter.getEnvironmentVariable("LC_ALL");
if ((LC_ALL == null) || (LC_ALL.length() == 0)) {
LC_ALL = CmdLineClientAdapter.getEnvironmentVariable("LANG");
if (LC_ALL == null) {
LC_ALL="";
}
}
final String[] lcVarNames = new String[] {
"LC_CTYPE",
"LC_NUMERIC",
"LC_COLLATE",
"LC_MONETARY",
"LC_PAPER",
"LC_NAME",
"LC_ADDRESS",
"LC_TELEPHONE",
"LC_MEASUREMENT",
"LC_IDENTIFICATION" };
List variables = new ArrayList(lcVarNames.length);
for (int i = 0; i < lcVarNames.length; i++) {
String varValue = CmdLineClientAdapter.getEnvironmentVariable(lcVarNames[i]);
variables.add(lcVarNames[i] + "=" + ((varValue != null) ? varValue : LC_ALL));
}
return (String[]) variables.toArray(new String[variables.size()]);
}
/**
* Pumps the output from both provided streams, blocking until
* complete.
*
* @param outPumper The process output stream.
* @param outPumper The process error stream.
*/
private void pumpProcessStreams(StreamPumper outPumper,
StreamPumper errPumper) {
new Thread(outPumper).start();
new Thread(errPumper).start();
try {
outPumper.waitFor();
errPumper.waitFor();
} catch (InterruptedException ignored) {
notificationHandler.logError("Command output processing interrupted !");
}
}
/**
* Runs the process and returns the results.
*
* @param svnArguments The command-line arguments to execute.
* @param coalesceLines
* @return Any output returned from execution of the command-line.
*/
protected String execString(ArrayList svnArguments, boolean coalesceLines)
throws CmdLineException {
Process proc = execProcess(svnArguments);
StreamPumper outPumper =
new CharacterStreamPumper(proc.getInputStream(), coalesceLines);
StreamPumper errPumper =
new CharacterStreamPumper(proc.getErrorStream(), false);
pumpProcessStreams(outPumper, errPumper);
try {
String errMessage = errPumper.toString();
if (errMessage.length() > 0) {
throw new CmdLineException(errMessage);
}
String outputString = outPumper.toString();
notifyFromSvnOutput(outputString);
return outputString;
} catch (CmdLineException e) {
notificationHandler.logException(e);
throw e;
}
}
/**
* Runs the process and returns the results.
* @param svnArguments The arguments to pass to the command-line
* binary.
* @param assumeUTF8 Whether the output of the command should be
* treated as UTF-8 (as opposed to the JVM's default encoding).
* @return String
*/
protected byte[] execBytes(ArrayList svnArguments, boolean assumeUTF8)
throws CmdLineException {
Process proc = execProcess(svnArguments);
ByteStreamPumper outPumper =
new ByteStreamPumper(proc.getInputStream());
StreamPumper errPumper =
new CharacterStreamPumper(proc.getErrorStream(), false);
pumpProcessStreams(outPumper, errPumper);
try {
String errMessage = errPumper.toString();
if (errMessage.length() > 0) {
throw new CmdLineException(errMessage);
}
byte[] bytes = outPumper.getBytes();
String notifyMessage = "";
if (assumeUTF8) {
try {
notifyMessage = new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// It is guaranteed to be there!
}
} else {
// This uses the default charset, which is likely
// wrong if we are trying to get the bytes, anyway...
notifyMessage = new String(bytes);
}
notifyFromSvnOutput(notifyMessage);
return bytes;
} catch (CmdLineException e) {
notificationHandler.logException(e);
throw e;
}
}
/**
* runs the command (returns nothing)
* @param svnArguments
* @throws CmdLineException
*/
protected void execVoid(ArrayList svnArguments) throws CmdLineException {
execString(svnArguments,false);
}
/**
* notify the listeners from the output. This is the default implementation
*
* @param svnOutput
*/
protected void notifyFromSvnOutput(String svnOutput) {
StringTokenizer st = new StringTokenizer(svnOutput, Helper.NEWLINE);
int size = st.countTokens();
//do everything but the last line
for (int i = 1; i < size; i++) {
notificationHandler.logMessage(st.nextToken());
}
//log the last line as the completed message.
if (size > 0)
notificationHandler.logCompleted(st.nextToken());
}
protected void stopProcess() {
process.destroy();
}
/**
* Pulls all the data out of a stream. Inspired by Ant's
* StreamPumper (by Robert Field).
*/
private static abstract class StreamPumper implements Runnable {
private boolean finished;
/**
* Constructor
*
*/
protected StreamPumper()
{
super();
}
/**
* Copies data from the input stream to the internal buffer.
* Terminates as soon as the input stream is closed, or an
* error occurs.
*/
public void run() {
synchronized (this) {
// Just in case this object is reused in the future.
this.finished = false;
}
try {
pumpStream();
} finally {
synchronized (this) {
this.finished = true;
notify();
}
}
}
/**
* Called by {@link #run()} to pull the data out of the
* stream.
*/
protected abstract void pumpStream();
/**
* Tells whether the end of the stream has been reached.
* @return true is the stream has been exhausted.
**/
public synchronized boolean isFinished() {
return this.finished;
}
/**
* This method blocks until the stream pumper finishes.
* @see #isFinished()
* @throws InterruptedException
**/
public synchronized void waitFor()
throws InterruptedException {
while (!isFinished()) {
wait();
}
}
}
/** Extracts character data from streams. */
private static class CharacterStreamPumper extends StreamPumper {
private BufferedReader reader;
private StringBuffer sb = new StringBuffer();
private boolean coalesceLines = false;
/**
* @param is Input stream from which to read the data.
* @param coalesceLines Whether to coalesce lines.
*/
public CharacterStreamPumper(InputStream is, boolean coalesceLines) {
this.reader = new BufferedReader(new InputStreamReader(is));
this.coalesceLines = coalesceLines;
}
/**
* Copies data from the input stream to the internal string
* buffer.
*/
protected void pumpStream() {
try {
String line;
while ((line = this.reader.readLine()) != null) {
if (this.coalesceLines) {
this.sb.append(line);
} else {
this.sb.append(line).append(Helper.NEWLINE);
}
}
} catch (IOException ex) {
System.err
.println("Problem occured during fetching the command output: "
+ ex.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
// Exception during closing the stream. Just ignore.
}
}
}
public synchronized String toString() {
return this.sb.toString();
}
}
/** Extracts byte data from streams. */
private static class ByteStreamPumper extends StreamPumper {
private InputStream bis;
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private final static int BUFFER_LENGTH = 1024;
private byte[] inputBuffer = new byte[BUFFER_LENGTH];
/**
* Create a new stream pumper.
*
* @param is input stream to read data from
*/
public ByteStreamPumper(InputStream is) {
this.bis = is;
}
/**
* Copies data from the input stream to the string buffer
*
* Terminates as soon as the input stream is closed or an error occurs.
*/
protected void pumpStream() {
try {
int bytesRead;
while ((bytesRead = this.bis.read(this.inputBuffer)) != -1) {
this.bytes.write(this.inputBuffer, 0, bytesRead);
}
} catch (IOException ex) {
System.err
.println("Problem occured during fetching the command output: "
+ ex.getMessage());
} finally {
try {
this.bytes.flush();
this.bytes.close();
this.bis.close();
} catch (IOException e) {
// Exception during closing the stream. Just ignore.
}
}
}
/**
* @return A byte array contaning the raw bytes read from the input
* stream.
*/
public synchronized byte[] getBytes() {
return bytes.toByteArray();
}
}
}
|
package org.openspaces.grid.gsm.strategy;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jini.rio.monitor.event.EventsStore;
import org.openspaces.admin.Admin;
import org.openspaces.admin.bean.BeanConfigurationException;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.gsa.events.DefaultElasticGridServiceAgentProvisioningFailureEvent;
import org.openspaces.admin.internal.gsa.events.DefaultElasticGridServiceAgentProvisioningProgressChangedEvent;
import org.openspaces.admin.internal.gsc.events.DefaultElasticGridServiceContainerProvisioningFailureEvent;
import org.openspaces.admin.internal.gsc.events.DefaultElasticGridServiceContainerProvisioningProgressChangedEvent;
import org.openspaces.admin.internal.machine.events.DefaultElasticMachineProvisioningFailureEvent;
import org.openspaces.admin.internal.machine.events.DefaultElasticMachineProvisioningProgressChangedEvent;
import org.openspaces.admin.internal.pu.elastic.ElasticMachineIsolationConfig;
import org.openspaces.admin.internal.pu.elastic.ProcessingUnitSchemaConfig;
import org.openspaces.admin.internal.pu.elastic.ScaleStrategyConfigUtils;
import org.openspaces.admin.internal.pu.elastic.events.DefaultElasticProcessingUnitInstanceProvisioningFailureEvent;
import org.openspaces.admin.internal.pu.elastic.events.DefaultElasticProcessingUnitInstanceProvisioningProgressChangedEvent;
import org.openspaces.admin.internal.pu.elastic.events.DefaultElasticProcessingUnitScaleProgressChangedEvent;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.elastic.config.ManualCapacityScaleConfig;
import org.openspaces.core.bean.Bean;
import org.openspaces.core.internal.commons.math.fraction.Fraction;
import org.openspaces.core.util.StringProperties;
import org.openspaces.grid.gsm.ElasticMachineProvisioningAware;
import org.openspaces.grid.gsm.LogPerProcessingUnit;
import org.openspaces.grid.gsm.ProcessingUnitAware;
import org.openspaces.grid.gsm.SingleThreadedPollingLog;
import org.openspaces.grid.gsm.containers.exceptions.ContainersSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.MachinesSlaUtils;
import org.openspaces.grid.gsm.machines.exceptions.GridServiceAgentSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.isolation.DedicatedMachineIsolation;
import org.openspaces.grid.gsm.machines.isolation.ElasticProcessingUnitMachineIsolation;
import org.openspaces.grid.gsm.machines.isolation.SharedMachineIsolation;
import org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioning;
import org.openspaces.grid.gsm.rebalancing.exceptions.RebalancingSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.sla.exceptions.SlaEnforcementFailure;
import org.openspaces.grid.gsm.sla.exceptions.SlaEnforcementInProgressException;
public abstract class AbstractScaleStrategyBean implements
ElasticMachineProvisioningAware ,
ProcessingUnitAware,
ElasticScaleStrategyEventStorageAware,
ScaleStrategyBean,
Bean,
Runnable{
private static final int MAX_NUMBER_OF_MACHINES = 1000; // a very large number representing max number of machines per pu, but that would not overflow when multiplied by container capacity in MB
// injected
private InternalAdmin admin;
private ProcessingUnit pu;
private ProcessingUnitSchemaConfig schemaConfig;
private NonBlockingElasticMachineProvisioning machineProvisioning;
private StringProperties properties;
private ElasticMachineIsolationConfig isolationConfig;
private Log logger;
private int minimumNumberOfMachines;
private ElasticProcessingUnitMachineIsolation isolation;
private ScheduledFuture<?> scheduledTask;
// state
private ElasticMachineProvisioningDiscoveredMachinesCache provisionedMachines;
private boolean isScaleInProgress;
// events state
private ScaleStrategyProgressEventState machineProvisioningEventState;
private ScaleStrategyProgressEventState agentProvisioningEventState;
private ScaleStrategyProgressEventState containerProvisioningEventState;
private ScaleStrategyProgressEventState puProvisioningEventState;
private ScaleStrategyProgressEventState scaleEventState;
private EventsStore eventStorage;
private boolean discoveryQuiteMode;
protected InternalAdmin getAdmin() {
return this.admin;
}
protected Log getLogger() {
return this.logger;
}
protected int getMinimumNumberOfMachines() {
return minimumNumberOfMachines;
}
@Override
public Map<String, String> getProperties() {
return properties.getProperties();
}
@Override
public void setProcessingUnit(ProcessingUnit pu) {
this.pu = pu;
}
protected ProcessingUnit getProcessingUnit() {
return pu;
}
protected long getPollingIntervalSeconds() {
return ScaleStrategyConfigUtils.getPollingIntervalSeconds(properties);
}
@Override
public void setElasticMachineIsolation(ElasticMachineIsolationConfig isolationConfig) {
this.isolationConfig = isolationConfig;
}
protected ElasticProcessingUnitMachineIsolation getIsolation() {
return isolation;
}
@Override
public void setProcessingUnitSchema(ProcessingUnitSchemaConfig schemaConfig) {
this.schemaConfig = schemaConfig;
}
protected ProcessingUnitSchemaConfig getSchemaConfig() {
return schemaConfig;
}
@Override
public void setAdmin(Admin admin) {
this.admin = (InternalAdmin) admin;
}
@Override
public void setElasticMachineProvisioning(NonBlockingElasticMachineProvisioning machineProvisioning) {
this.machineProvisioning = machineProvisioning;
}
protected NonBlockingElasticMachineProvisioning getMachineProvisioning() {
return machineProvisioning;
}
@Override
public void setElasticScaleStrategyEventStorage(EventsStore eventQueue) {
this.eventStorage = eventQueue;
}
protected void setMachineDiscoveryQuiteMode(boolean discoveryQuiteMode) {
this.discoveryQuiteMode = discoveryQuiteMode;
}
public void afterPropertiesSet() {
if (pu == null) {
throw new IllegalStateException("pu cannot be null");
}
if (properties == null) {
throw new IllegalStateException("properties cannot be null.");
}
if (admin == null) {
throw new IllegalStateException("admin cannot be null.");
}
if (machineProvisioning == null) {
throw new IllegalStateException("machine provisioning cannot be null.");
}
if (schemaConfig == null) {
throw new IllegalStateException("schemaConfig cannot be null.");
}
if (isolationConfig == null) {
throw new IllegalStateException("isolationConfig cannot be null");
}
if (isolationConfig.isDedicatedIsolation()) {
isolation = new DedicatedMachineIsolation(pu.getName());
}
else if (isolationConfig.isSharedIsolation()) {
isolation = new SharedMachineIsolation(isolationConfig.getSharingId());
}
else {
throw new IllegalStateException("unsupported PU isolation");
}
logger = new LogPerProcessingUnit(
new SingleThreadedPollingLog(
LogFactory.getLog(this.getClass())),
pu);
logger.info("properties: "+properties);
machineProvisioningEventState = new ScaleStrategyProgressEventState(eventStorage, isUndeploying(), pu.getName(), DefaultElasticMachineProvisioningProgressChangedEvent.class, DefaultElasticMachineProvisioningFailureEvent.class);
agentProvisioningEventState = new ScaleStrategyProgressEventState(eventStorage, isUndeploying(), pu.getName(), DefaultElasticGridServiceAgentProvisioningProgressChangedEvent.class, DefaultElasticGridServiceAgentProvisioningFailureEvent.class );
containerProvisioningEventState = new ScaleStrategyProgressEventState(eventStorage, isUndeploying(), pu.getName(), DefaultElasticGridServiceContainerProvisioningProgressChangedEvent.class, DefaultElasticGridServiceContainerProvisioningFailureEvent.class );
puProvisioningEventState = new ScaleStrategyProgressEventState(eventStorage, isUndeploying(), pu.getName(), DefaultElasticProcessingUnitInstanceProvisioningProgressChangedEvent.class, DefaultElasticProcessingUnitInstanceProvisioningFailureEvent.class );
scaleEventState = new ScaleStrategyProgressEventState(eventStorage, isUndeploying(), pu.getName(), DefaultElasticProcessingUnitScaleProgressChangedEvent.class);
minimumNumberOfMachines = calcMinimumNumberOfMachines();
provisionedMachines = new ElasticMachineProvisioningDiscoveredMachinesCache(pu,machineProvisioning, discoveryQuiteMode, getPollingIntervalSeconds());
isScaleInProgress = true;
scheduledTask =
admin.scheduleWithFixedDelayNonBlockingStateChange(
this,
0L,
getPollingIntervalSeconds(),
TimeUnit.SECONDS);
logger.debug(pu.getName() + " is being monitored for SLA violations every " + getPollingIntervalSeconds() + " seconds");
}
public void destroy() {
if (scheduledTask != null) {
scheduledTask.cancel(false);
scheduledTask = null;
}
provisionedMachines.destroy();
}
public void setProperties(Map<String, String> properties) {
this.properties = new StringProperties(properties);
}
protected DiscoveredMachinesCache getDiscoveredMachinesCache() {
return provisionedMachines;
}
private int calcMinimumNumberOfMachines() {
if (getSchemaConfig().isDefaultSchema()) {
return 1;
}
if (getSchemaConfig().isPartitionedSync2BackupSchema()) {
int minNumberOfMachines;
if (getProcessingUnit().getMaxInstancesPerMachine() == 0) {
minNumberOfMachines = 1;
getLogger().info("minNumberOfMachines=1 (since max instances from same partition per machine is not defined)");
}
else {
minNumberOfMachines = (int)Math.ceil(
(1 + getProcessingUnit().getNumberOfBackups())/(1.0*getProcessingUnit().getMaxInstancesPerMachine()));
getLogger().info("minNumberOfMachines= " +
"ceil((1+backupsPerPartition)/maxInstancesPerPartitionPerMachine)= "+
"ceil("+(1+getProcessingUnit().getNumberOfBackups())+"/"+getProcessingUnit().getMaxInstancesPerMachine() + ")= " +
minNumberOfMachines);
}
return minNumberOfMachines;
}
throw new BeanConfigurationException(
"Processing Unit " + pu.getName() +
"needs to be either stateless, or stateful or a space (it is " + schemaConfig.getSchema());
}
protected int getMaximumNumberOfInstances() {
if (getSchemaConfig().isPartitionedSync2BackupSchema()) {
return getProcessingUnit().getTotalNumberOfInstances();
}
else {
return MAX_NUMBER_OF_MACHINES;
}
}
public Fraction getContainerNumberOfCpuCores(ManualCapacityScaleConfig slaConfig) {
if (getSchemaConfig().isPartitionedSync2BackupSchema()) {
Fraction cpuCores = MachinesSlaUtils.convertCpuCoresFromDoubleToFraction(slaConfig.getNumberOfCpuCores());
return cpuCores.divide(pu.getNumberOfInstances());
}
else {
return Fraction.ONE;
}
}
@Override
public void run() {
try {
if (getLogger().isDebugEnabled()) {
getLogger().debug("enforcing SLA.");
}
enforceSla();
if (getLogger().isDebugEnabled()) {
getLogger().debug("SLA enforced.");
}
scaleEventState.enqueuProvisioningCompletedEvent();
isScaleInProgress = false;
}
catch (SlaEnforcementInProgressException e) {
if (e instanceof SlaEnforcementFailure) {
getLogger().warn("SLA has not been reached",e);
}
else if (getLogger().isDebugEnabled()) {
getLogger().debug("SLA has not been reached",e);
}
// we do not pass the exception into the event since there are other fine grained events that report failures.
scaleEventState.enqueuProvisioningInProgressEvent();
isScaleInProgress = true;
}
catch (Throwable e) {
getLogger().error("Unhandled Exception",e);
scaleEventState.enqueuProvisioningInProgressEvent();
isScaleInProgress = true;
}
}
protected abstract void enforceSla() throws SlaEnforcementInProgressException;
/**
* @return true if this is an undeployment strategy (pu is undeploying)
*/
protected abstract boolean isUndeploying();
public boolean isScaleInProgress() {
return isScaleInProgress;
}
protected void agentProvisioningCompletedEvent() {
agentProvisioningEventState.enqueuProvisioningCompletedEvent();
}
protected void agentProvisioningInProgressEvent(GridServiceAgentSlaEnforcementInProgressException e) {
agentProvisioningEventState.enqueuProvisioningInProgressEvent(e);
}
protected void machineProvisioningCompletedEvent() {
machineProvisioningEventState.enqueuProvisioningCompletedEvent();
}
protected void machineProvisioningInProgressEvent(MachinesSlaEnforcementInProgressException e) {
machineProvisioningEventState.enqueuProvisioningInProgressEvent(e);
}
protected void containerProvisioningCompletedEvent() {
containerProvisioningEventState.enqueuProvisioningCompletedEvent();
}
protected void containerProvisioningInProgressEvent(ContainersSlaEnforcementInProgressException e) {
containerProvisioningEventState.enqueuProvisioningInProgressEvent(e);
}
protected void puInstanceProvisioningCompletedEvent() {
puProvisioningEventState.enqueuProvisioningCompletedEvent();
}
protected void puInstanceProvisioningInProgressEvent(RebalancingSlaEnforcementInProgressException e) {
puProvisioningEventState.enqueuProvisioningInProgressEvent(e);
}
}
|
package ee.ria.xroad.monitor;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.pattern.Patterns;
import akka.testkit.TestActorRef;
import akka.util.Timeout;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;
import com.typesafe.config.ConfigFactory;
import ee.ria.xroad.monitor.common.SystemMetricsRequest;
import ee.ria.xroad.monitor.common.SystemMetricsResponse;
import ee.ria.xroad.monitor.common.dto.HistogramDto;
import ee.ria.xroad.monitor.common.dto.MetricDto;
import ee.ria.xroad.monitor.common.dto.MetricSetDto;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* MetricsProviderActorTest
*/
@Slf4j
public class MetricsProviderActorTest {
private static ActorSystem actorSystem;
private MetricRegistry metricsRegistry;
private static final String HISTOGRAM_NAME = "TestHistogram";
private static final String GAUGE_NAME = "TestGauge";
/**
* Before test handler
*/
@Before
public void init() {
actorSystem = ActorSystem.create("AkkaRemoteServer", ConfigFactory.load());
metricsRegistry = new MetricRegistry();
Histogram testHistogram = metricsRegistry.histogram(HISTOGRAM_NAME);
testHistogram.update(100);
testHistogram.update(10);
//MetricRegistry.MetricSupplier<Gauge> x;
Gauge g = metricsRegistry.gauge(GAUGE_NAME, () -> new SimpleSensor<String>("Test gauge String value."));
MetricRegistryHolder.getInstance().setMetrics(metricsRegistry);
}
/**
* Shut down actor system and wait for clean up, so that other tests are not disturbed
*/
@After
public void tearDown() {
actorSystem.shutdown();
actorSystem.awaitTermination();
}
@Test
public void testAllSystemMetricsRequest() throws Exception {
final Props props = Props.create(MetricsProviderActor.class);
final TestActorRef<MetricsProviderActor> ref = TestActorRef.create(actorSystem, props, "testActorRef");
Future<Object> future = Patterns.ask(ref, new SystemMetricsRequest(null, true), Timeout.apply(1, TimeUnit.MINUTES));
Object result = Await.result(future, Duration.apply(1, TimeUnit.MINUTES));
assertTrue(future.isCompleted());
assertTrue(result instanceof SystemMetricsResponse);
SystemMetricsResponse response = (SystemMetricsResponse) result;
MetricSetDto metricSetDto = response.getMetrics();
Set<MetricDto> dtoSet = metricSetDto.getMetrics();
log.info("metricSetDto: " + metricSetDto);
assertEquals(2, dtoSet.stream().count());
for (MetricDto metricDto : dtoSet) {
// Order of entries is undefined -> Must handle by name
switch (metricDto.getName()) {
case HISTOGRAM_NAME:
log.info("metricDto: " + metricDto);
assertEquals(HISTOGRAM_NAME, metricDto.getName());
assertTrue(metricDto instanceof HistogramDto);
HistogramDto h = (HistogramDto) metricDto;
assertEquals(100L, (long) h.getMax());
assertEquals(10L, (long) h.getMin());
assertEquals(55L, (long) h.getMean());
break;
case GAUGE_NAME:
log.info("metricDto: " + metricDto);
assertEquals(GAUGE_NAME, metricDto.getName());
break;
default:
Assert.fail("Unknown metric found in response.");
}
}
}
@Test
public void testParametrizedSystemMetricsRequest() throws Exception {
final Props props = Props.create(MetricsProviderActor.class);
final TestActorRef<MetricsProviderActor> ref = TestActorRef.create(actorSystem, props, "testActorRef");
Future<Object> future = Patterns.ask(
ref,
new SystemMetricsRequest(Arrays.asList(HISTOGRAM_NAME), true),
Timeout.apply(1, TimeUnit.MINUTES));
Object result = Await.result(future, Duration.apply(1, TimeUnit.MINUTES));
assertTrue(future.isCompleted());
assertTrue(result instanceof SystemMetricsResponse);
SystemMetricsResponse response = (SystemMetricsResponse) result;
MetricSetDto metricSetDto = response.getMetrics();
Set<MetricDto> dtoSet = metricSetDto.getMetrics();
log.info("metricSetDto: " + metricSetDto);
assertEquals(1, dtoSet.stream().count());
// Note: findFirst() works only because of single result
MetricDto metricDto = dtoSet.stream().findFirst().get();
assertEquals(HISTOGRAM_NAME, metricDto.getName());
assertTrue(metricDto instanceof HistogramDto);
HistogramDto h = (HistogramDto) metricDto;
assertEquals(100L, (long) h.getMax());
assertEquals(10L, (long) h.getMin());
assertEquals(55L, (long) h.getMean());
}
}
|
package polytheque.model.DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import polytheque.model.pojos.Jeu;
public class JeuDAO extends DAO {
/**
* Methode de creation
* @param Jeu
* @return boolean
*/
public boolean create(Jeu jeu, int idCategorie, int idEditeur) {
try {
super.connect();
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO "
+ "JEU(nom, description, annee_parution, statut, nombre_exemplaires, nombre_reserves,"
+ "age_mini, nombre_joueurs, id_categorie, id_editeur)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
psInsert.setString(1, jeu.getNom());
psInsert.setString(2, jeu.getDescription());
psInsert.setInt(3, jeu.getAnneeParution());
psInsert.setString(4, jeu.getStatut());
psInsert.setInt(5, jeu.getNbExemplaires());
psInsert.setInt(6, jeu.getNbReserves());
psInsert.setInt(7, jeu.getAgeMini());
psInsert.setInt(8, jeu.getNbJoueurs());
psInsert.setInt(9, idCategorie);
psInsert.setInt(10, idEditeur);
psInsert.executeUpdate();
ResultSet idResult = psInsert.getGeneratedKeys();
if (idResult != null && idResult.next()) {
jeu.setIdJeu(idResult.getInt(1));;
} else {
throw new SQLException();
}
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Methode pour effacer
* @param Jeu
* @return boolean
*/
public boolean delete(int id) {
try {
super.connect();
PreparedStatement psDelete = connection.prepareStatement("DELETE * FROM JEU WHERE id_jeu = ?");
psDelete.setInt(1, id);
psDelete.execute();
psDelete.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Methode de mise a jour
* @param obj
* @return boolean
*/
public boolean update(Jeu jeu, int idCategorie, int idEditeur) {
try {
super.connect();
PreparedStatement psUpdate = connection.prepareStatement("UPDATE JEU "
+ "SET nom = ?, description = ?, annee_parution = ?, statut = ?, nombre_exemplaires = ?,"
+ "nombre_reserves = ?, age_mini = ?, nombre_joueurs = ?, id_categorie = ?, id_editeur = ?)"
+ " WHERE id_jeu = ?");
psUpdate.setString(1, jeu.getNom());
psUpdate.setString(2, jeu.getDescription());
psUpdate.setInt(3, jeu.getAnneeParution());
psUpdate.setString(4, jeu.getStatut());
psUpdate.setInt(5, jeu.getNbExemplaires());
psUpdate.setInt(6, jeu.getNbReserves());
psUpdate.setInt(7, jeu.getAgeMini());
psUpdate.setInt(8, jeu.getNbJoueurs());
psUpdate.setInt(9, idCategorie);
psUpdate.setInt(10, idEditeur);
psUpdate.setInt(11, jeu.getIdJeu());
psUpdate.executeUpdate();
psUpdate.closeOnCompletion();
super.disconnect();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Methode de recherche des informations
* @param id
* @return T
*/
public Jeu retreive(int id) {
try {
super.connect();
PreparedStatement psSelect = connection.prepareStatement("SELECT * FROM JEU WHERE id_jeu = ?");
psSelect.setInt(1, id);
psSelect.execute();
psSelect.closeOnCompletion();
ResultSet resSet = psSelect.getResultSet();
Jeu jeu = null;
if (resSet.next()) {
jeu = new Jeu(id, resSet.getString(1), resSet.getString(2), resSet.getInt(3), resSet.getString(4),
resSet.getInt(5), resSet.getInt(6), resSet.getInt(7), resSet.getInt(8), resSet.getString(9), resSet.getString(10));
}
super.disconnect();
return jeu;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
}
|
package org.ow2.proactive.scheduler.core;
import java.security.KeyException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.common.RMState;
import org.ow2.proactive.resourcemanager.frontend.topology.TopologyDisabledException;
import org.ow2.proactive.scheduler.common.NotificationData;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.SchedulerStatus;
import org.ow2.proactive.scheduler.common.job.JobDescriptor;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.JobType;
import org.ow2.proactive.scheduler.common.task.EligibleTaskDescriptor;
import org.ow2.proactive.scheduler.common.task.TaskDescriptor;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.util.SchedulerLoggers;
import org.ow2.proactive.scheduler.core.db.DatabaseManager;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scheduler.core.rmproxies.RMProxyCreationException;
import org.ow2.proactive.scheduler.job.InternalJob;
import org.ow2.proactive.scheduler.job.JobResultImpl;
import org.ow2.proactive.scheduler.task.ExecutableContainerInitializer;
import org.ow2.proactive.scheduler.task.internal.InternalTask;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncher;
import org.ow2.proactive.scheduler.util.SchedulerDevLoggers;
import org.ow2.proactive.scripting.ScriptException;
import org.ow2.proactive.threading.ExecutorServiceTasksInvocator;
import org.ow2.proactive.topology.descriptor.TopologyDescriptor;
import org.ow2.proactive.utils.NodeSet;
import edu.emory.mathcs.backport.java.util.Collections;
/**
* SchedulingMethodImpl is the default implementation for the scheduling process
*
* @author The ProActive Team
* @since ProActive Scheduling 2.0
*/
final class SchedulingMethodImpl implements SchedulingMethod {
/** Scheduler logger */
protected static final Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.SCHEDULE);
protected static final Logger logger_dev = ProActiveLogger.getLogger(SchedulerDevLoggers.SCHEDULE);
/** Number of time to retry an active object creation if it fails to create */
protected static final int ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER = 3;
/** Maximum blocking time for the do task action */
protected static final int DOTASK_ACTION_TIMEOUT = PASchedulerProperties.SCHEDULER_STARTTASK_TIMEOUT
.getValueAsInt();
/** MAximum number of thread used for the doTask action */
protected static final int DOTASK_ACTION_THREADNUMBER = PASchedulerProperties.SCHEDULER_STARTTASK_THREADNUMBER
.getValueAsInt();
protected int activeObjectCreationRetryTimeNumber;
protected SchedulerCore core = null;
protected ExecutorService threadPool;
protected PrivateKey corePrivateKey;
SchedulingMethodImpl(SchedulerCore core) {
this.core = core;
this.threadPool = Executors.newFixedThreadPool(DOTASK_ACTION_THREADNUMBER);
try {
this.corePrivateKey = Credentials.getPrivateKey(PASchedulerProperties
.getAbsolutePath(PASchedulerProperties.SCHEDULER_AUTH_PRIVKEY_PATH.getValueAsString()));
} catch (KeyException e) {
SchedulerCore.exitFailure(e, null);
}
}
/**
* Scheduling process. For this implementation, steps are :<br>
* <ul>
* <li>Select running and pending jobs to be scheduled
* <li>Get an ordered list of the selected tasks to be scheduled
* <li>While returned tasks list is not empty :
* <ul>
* <li>Get n first compatible tasks (same selection script, same node exclusion
* <li>Ask nodes to RM according to the previous specification
* <li>Try to start each tasks
* <li>Job started event if needed
* <li>Task started event
* </ul>
* <li>Manage exception while deploying tasks on nodes
* </ul>
*
* @return the number of tasks that have been started
*/
public int schedule() {
int numberOfTaskStarted = 0;
//Number of time to retry an active object creation before leaving scheduling loop
activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER;
//get job Descriptor list with eligible jobs (running and pending)
ArrayList<JobDescriptor> jobDescriptorList = createJobDescriptorList();
//ask the policy all the tasks to be schedule according to the jobs list.
LinkedList<EligibleTaskDescriptor> taskRetrivedFromPolicy = new LinkedList<EligibleTaskDescriptor>(
core.policy.getOrderedTasks(jobDescriptorList));
//if there is no task to scheduled, return
if (taskRetrivedFromPolicy == null || taskRetrivedFromPolicy.size() == 0) {
return numberOfTaskStarted;
}
logger_dev.info("Number of tasks ready to be scheduled : " + taskRetrivedFromPolicy.size());
while (!taskRetrivedFromPolicy.isEmpty()) {
//get rmState and update it in scheduling policy
RMState rmState = null;
try {
rmState = core.rmProxiesManager.getSchedulerRMProxy().getState();
} catch (RMProxyCreationException rmpce) {
logger_dev.error("", rmpce);
break;
}
core.policy.RMState = rmState;
int freeResourcesNb = rmState.getFreeNodesNumber();
logger_dev.info("Number of free resources : " + freeResourcesNb);
//if there is no free resources, stop it right now
if (freeResourcesNb == 0) {
break;
}
//get the next compatible tasks from the whole returned policy tasks
LinkedList<EligibleTaskDescriptor> tasksToSchedule = new LinkedList<EligibleTaskDescriptor>();
int neededResourcesNumber = 0;
while (taskRetrivedFromPolicy.size() > 0 && neededResourcesNumber == 0) {
//the loop will search for next compatible task until it find something
neededResourcesNumber = getNextcompatibleTasks(taskRetrivedFromPolicy, freeResourcesNb,
tasksToSchedule);
}
logger.debug("Number of nodes to ask for : " + neededResourcesNumber);
if (neededResourcesNumber == 0) {
break;
}
//ask nodes to the RM, fail tasks and jobs if selection script fails (tasks could never be started)
NodeSet nodeSet = getRMNodes(neededResourcesNumber, tasksToSchedule);
//start selected tasks
Node node = null;
InternalJob currentJob = null;
try {
while (nodeSet != null && !nodeSet.isEmpty()) {
EligibleTaskDescriptor taskDescriptor = tasksToSchedule.removeFirst();
currentJob = core.jobs.get(taskDescriptor.getJobId());
InternalTask internalTask = currentJob.getIHMTasks().get(taskDescriptor.getId());
// load and Initialize the executable container
loadAndInit(currentJob, internalTask);
//create launcher and try to start the task
node = nodeSet.get(0);
numberOfTaskStarted++;
createExecution(nodeSet, node, currentJob, internalTask, taskDescriptor);
//if every task that should be launched have been removed
if (tasksToSchedule.isEmpty()) {
//get back unused nodes to the RManager
if (!nodeSet.isEmpty()) {
core.rmProxiesManager.getUserRMProxy(currentJob).releaseNodes(nodeSet);
}
//and leave the loop
break;
}
}
} catch (ActiveObjectCreationException e1) {
//Something goes wrong with the active object creation (createLauncher)
logger.warn("An exception occured while creating the task launcher.", e1);
//so try to get back every remaining nodes to the resource manager
try {
core.rmProxiesManager.getUserRMProxy(currentJob).releaseNodes(nodeSet);
} catch (Exception e2) {
logger_dev.info("Unable to get back the nodeSet to the RM", e2);
}
if (--activeObjectCreationRetryTimeNumber == 0) {
return numberOfTaskStarted;
}
} catch (CancellationException e1) {
// timeout occurs on doTask
logger.warn("A timeout occured while deploying a task, performances may suffer. "
+ "Value of pa.scheduler.core.starttask.timeout should be increased.");
logger.debug("Timeout while deploying task", e1);
//so try to get back every remaining nodes to the resource manager
try {
core.rmProxiesManager.getUserRMProxy(currentJob).releaseNodes(nodeSet);
} catch (Exception e2) {
logger_dev.info("Unable to get back the nodeSet to the RM", e2);
}
} catch (Exception e1) {
//if we are here, it is that something append while launching the current task.
logger.warn("An exception occured while starting task.", e1);
//so try to get back every remaining nodes to the resource manager
try {
core.rmProxiesManager.getUserRMProxy(currentJob).releaseNodes(nodeSet);
} catch (Exception e2) {
logger_dev.info("Unable to get back the nodeSet to the RM", e2);
}
}
}
return numberOfTaskStarted;
}
/**
* Create the eligible job descriptor list.
* This list contains every eligible jobs containing eligible tasks.
*
* @return eligible job descriptor list
*/
protected ArrayList<JobDescriptor> createJobDescriptorList() {
ArrayList<JobDescriptor> list = new ArrayList<JobDescriptor>();
//add running jobs
for (InternalJob j : core.runningJobs) {
if (j.getJobDescriptor().getEligibleTasks().size() > 0) {
list.add(j.getJobDescriptor());
}
}
//if scheduler is not paused, add pending jobs
if (core.status != SchedulerStatus.PAUSED) {
for (InternalJob j : core.pendingJobs) {
if (j.getJobDescriptor().getEligibleTasks().size() > 0) {
list.add(j.getJobDescriptor());
}
}
}
if (list.size() > 0) {
logger_dev.info("Number of jobs containing tasks to be scheduled : " + list.size());
}
return list;
}
/**
* Extract the n first compatible tasks from the first argument list,
* and return them according that the extraction is stopped when the maxResource number is reached.<br>
* Two tasks are compatible if and only if they have the same list of selection script and
* the same list of node exclusion.
* The check of compliance is currently done by the {@link SchedulingTaskComparator} class.<br>
* This method has two side effects : extracted tasks are removed from the bagOfTasks and put in the toFill list
*
* @param bagOfTasks the list of tasks form which to extract tasks
* @param maxResource the limit number of resources that the extraction should not exceed
* @param toFill the list that will contains the task to schedule at the end. This list must not be null but must be empty.<br>
* this list will be filled with the n first compatible tasks according that the number of resources needed
* by these tasks does not exceed the given max resource number.
* @return the number of nodes needed to start every task present in the 'toFill' argument at the end of the method.
*/
protected int getNextcompatibleTasks(LinkedList<EligibleTaskDescriptor> bagOfTasks, int maxResource,
LinkedList<EligibleTaskDescriptor> toFill) {
if (toFill == null || bagOfTasks == null) {
throw new IllegalArgumentException("The two given lists must not be null !");
}
int neededResource = 0;
if (maxResource > 0 && !bagOfTasks.isEmpty()) {
EligibleTaskDescriptor etd = bagOfTasks.removeFirst();
InternalJob currentJob = core.jobs.get(etd.getJobId());
InternalTask internalTask = currentJob.getIHMTasks().get(etd.getId());
int neededNodes = internalTask.getNumberOfNodesNeeded();
SchedulingTaskComparator referent = new SchedulingTaskComparator(internalTask, currentJob
.getOwner());
logger_dev.debug("Get the most nodes matching the current selection ");
boolean firstLoop = true;
do {
if (!firstLoop) {
//if bagOfTasks is not empty
if (!bagOfTasks.isEmpty()) {
etd = bagOfTasks.removeFirst();
currentJob = core.jobs.get(etd.getJobId());
internalTask = currentJob.getIHMTasks().get(etd.getId());
neededNodes = internalTask.getNumberOfNodesNeeded();
}
} else {
firstLoop = false;
}
if (neededNodes > maxResource) {
//no instruction is important :
//in this case, a multi node task leads the search to be stopped and the
//the current task would be retried on the next step
//we continue to start the maximum number of task in a single scheduling loop.
//this case will focus on starting single node task first if lot of resources are busy.
//(multi-nodes starvation may occurs)
} else {
//check if the task is compatible with the other previous one
if (referent.equals(new SchedulingTaskComparator(internalTask, currentJob.getOwner()))) {
neededResource += neededNodes;
maxResource -= neededNodes;
toFill.add(etd);
} else {
bagOfTasks.addFirst(etd);
break;
}
}
} while (maxResource > 0 && !bagOfTasks.isEmpty());
}
return neededResource;
}
/**
* Ask to the RM the given number of node resources.<br>
* If there is a problem with these task selection (such as bad selectionScript) this method
* will terminate the corresponding tasks and jobs. As the selection scripts contain errors, the task
* and its surrounding jobs must be stopped.
*
* @param neededResourcesNumber the number of resources to ask for (must be > 0).
* @param tasksToSchedule the task to be scheduled
* @return A nodeSet that contains at most 'neededResourcesNumber' available compatible resources.
* An empty nodeSet if no nodes could be found
* null if the their was an exception when asking for the nodes (ie : selection script has failed)
*/
protected NodeSet getRMNodes(int neededResourcesNumber, LinkedList<EligibleTaskDescriptor> tasksToSchedule) {
NodeSet nodeSet = new NodeSet();
if (neededResourcesNumber <= 0) {
throw new IllegalArgumentException("Args 'neededResourcesNumber' must be > 0");
}
EligibleTaskDescriptor etd = tasksToSchedule.getFirst();
InternalJob currentJob = core.jobs.get(etd.getJobId());
InternalTask internalTask = currentJob.getIHMTasks().get(etd.getId());
if (logger.isDebugEnabled()) {
SchedulingTaskComparator referent = new SchedulingTaskComparator(internalTask, currentJob
.getOwner());
logger.debug("Referent task : " + internalTask.getId());
logger.debug("Selection script(s) : " +
((referent.getSsHashCode() == 0) ? "no" : "yes (" + referent.getSsHashCode() + ")"));
logger.debug("Node(s) exclusion : " + internalTask.getNodeExclusion());
}
try {
TopologyDescriptor descriptor = null;
if (internalTask.isParallel()) {
descriptor = internalTask.getParallelEnvironment().getTopologyDescriptor();
if (descriptor == null) {
logger.debug("Topology is not defined for the task " + internalTask.getName());
}
}
if (descriptor == null) {
// descriptor is not defined, use default
descriptor = TopologyDescriptor.ARBITRARY;
}
try {
nodeSet = core.rmProxiesManager.getUserRMProxy(currentJob).getAtMostNodes(
neededResourcesNumber, descriptor, internalTask.getSelectionScripts(),
internalTask.getNodeExclusion());
} catch (TopologyDisabledException tde) {
logger_dev.info("Cancel job " + currentJob.getName() + " as the topology is disabled");
simulateJobStartAndCancelIt(tasksToSchedule, "Topology is disabled");
return null;
}
//the following line is used to unwrap the future, warning when moving or removing
//it may also throw a ScriptException which is a RuntimeException
PAFuture.waitFor(nodeSet, true);
logger.debug("Got " + nodeSet.size() + " node(s)");
return nodeSet;
} catch (ScriptException e) {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
}
logger_dev.info("Selection script throws an exception : " + t);
logger_dev.debug("", t);
//simulate jobs starts and cancel it
simulateJobStartAndCancelIt(tasksToSchedule, "Selection script has failed : " + t);
//leave the method by ss failure
return null;
} catch (RMProxyCreationException e) {
logger_dev.info("Failed to create User RM Proxy : " + e.getMessage());
logger_dev.debug("", e);
//simulate jobs starts and cancel it
simulateJobStartAndCancelIt(tasksToSchedule,
"Failed to create User RM Proxy : Authentication Failed to Resource Manager for user '" +
currentJob.getOwner() + "'");
//leave the method by ss failure
return null;
}
}
/**
* simulate jobs starts and cancel it
*/
private void simulateJobStartAndCancelIt(LinkedList<EligibleTaskDescriptor> tasksToSchedule,
String errorMsg) {
Set<InternalJob> alreadyDone = new HashSet<InternalJob>();
for (EligibleTaskDescriptor eltd : tasksToSchedule) {
InternalJob ij = core.jobs.get(eltd.getJobId());
InternalTask it = ij.getIHMTasks().get(eltd.getId());
if (alreadyDone.contains(ij)) {
continue;
} else {
alreadyDone.add(ij);
}
// set the different informations on job if it is the first task of this job
if (ij.getStartTime() < 0) {
ij.start();
core.pendingJobs.remove(ij);
core.runningJobs.add(ij);
//update tasks events list and send it to front-end
core.updateTaskInfosList(ij, SchedulerEvent.JOB_PENDING_TO_RUNNING);
logger.info("Job '" + ij.getId() + "' started");
}
//selection script has failed : end the job
core.endJob(ij, it, errorMsg, JobStatus.CANCELED);
}
}
/**
* Load and initialize the task to be started
*
* @param job the job owning the task to be initialized
* @param task the task to be initialized
*/
protected void loadAndInit(InternalJob job, InternalTask task) {
logger_dev.debug("Load and Initialize the executable container for task '" + task.getId() + "'");
DatabaseManager.getInstance().load(task);
ExecutableContainerInitializer eci = new ExecutableContainerInitializer();
// TCS can be null for non-java task
eci.setClassServer(SchedulerCore.getTaskClassServer(job.getId()));
task.getExecutableContainer().init(eci);
}
/**
* Create launcher and try to start the task.
*
* @param nodeSet the node set containing every available nodes that can be used for execution
* @param node the node on which to start the task
* @param job the job that owns the task to be started
* @param task the task to be started
* @param taskDescriptor the descriptor of the task to be started
*
*/
@SuppressWarnings("unchecked")
protected void createExecution(NodeSet nodeSet, Node node, InternalJob job, InternalTask task,
TaskDescriptor taskDescriptor) throws Exception {
TaskLauncher launcher = null;
//enough nodes to be launched at same time for a communicating task
if (nodeSet.size() >= task.getNumberOfNodesNeeded()) {
//start dataspace app for this job
job.startDataSpaceApplication(core.dataSpaceNSStarter.getNamingService(), core.dataSpaceNSStarter
.getNamingServiceURL());
//create launcher
launcher = task.createLauncher(job, node);
activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER;
nodeSet.remove(0);
NodeSet nodes = new NodeSet();
try {
//if topology is enabled and it is a multi task, give every nodes to the multi-nodes task
// we will need to update this code once topology will be allowed for single-node task
if (task.isParallel()) {
nodes = new NodeSet(nodeSet);
task.getExecuterInformations().addNodes(nodes);
nodeSet.clear();
}
// activate loggers for this task if needed
if (core.jobsToBeLogged.containsKey(job.getId()) ||
core.jobsToBeLoggedinAFile.containsKey(job.getId())) {
launcher.activateLogs(core.lfs.getAppenderProvider());
}
// Set to empty array to emulate varargs behavior (i.e. not defined is
// equivalent to empty array, not null.
TaskResult[] params = new TaskResult[0];
//if job is TASKSFLOW, preparing the list of parameters for this task.
int resultSize = taskDescriptor.getParents().size();
if ((job.getType() == JobType.TASKSFLOW) && (resultSize > 0) && task.handleResultsArguments()) {
params = new TaskResult[resultSize];
for (int i = 0; i < resultSize; i++) {
//get parent task number i
InternalTask parentTask = job.getIHMTasks().get(
taskDescriptor.getParents().get(i).getId());
//set the task result in the arguments array.
params[i] = job.getJobResult().getResult(parentTask.getName());
//if this result has been unloaded, (extremely rare but possible)
if (params[i].getOutput() == null) {
//get the result and load the content from database
DatabaseManager.getInstance().load(params[i]);
}
}
}
//set nodes in the executable container
task.getExecutableContainer().setNodes(nodes);
logger_dev.info("Starting deployment of task '" + task.getName() + "' for job '" +
job.getId() + "'");
//enqueue next instruction, and execute whole process in the thread-pool controller
TimedDoTaskAction tdta = new TimedDoTaskAction(job, task, launcher,
(SchedulerCore) PAActiveObject.getStubOnThis(), params, corePrivateKey);
List<Future<TaskResult>> futurResults = ExecutorServiceTasksInvocator
.invokeAllWithTimeoutAction(threadPool, Collections.singletonList(tdta),
DOTASK_ACTION_TIMEOUT);
//wait for only one result
Future<TaskResult> future = futurResults.get(0);
if (future.isDone()) {
//if task has finished
if (future.get() != null) {
//and result is not null
((JobResultImpl) job.getJobResult()).storeFuturResult(task.getName(), future.get());
//mark the task and job (if needed) as started and send events
finalizeStarting(job, task, node, launcher);
} else {
//if there was a problem, free nodeSet for multi-nodes task (1)
throw new RuntimeException(
"An exception occured while starting the task. See previous exceptions for details.");
}
} else {
//if there was a problem, free nodeSet for multi-nodes task (2)
throw new RuntimeException(
"This is an unexpected behavior : task start should be done at this point.");
}
} catch (Exception t) {
try {
//if there was a problem, free nodeSet for multi-nodes task
//exception can come from future.get() -> cancellationException
//exception can also come from (1) or (2)
nodes.add(node);
core.rmProxiesManager.getUserRMProxy(job).releaseNodes(nodes);
} catch (Throwable ni) {
//miam miam
}
throw t;
}
}
}
/**
* Finalize the start of the task by mark it as started. Also mark the job if it is not already started.
*
* @param job the job that owns the task to be started
* @param task the task to be started
* @param node the node on which the task will be started
* @param launcher the taskLauncher that has just been launched
*/
void finalizeStarting(InternalJob job, InternalTask task, Node node, TaskLauncher launcher) {
logger.info("Task '" + task.getId() + "' started on " +
node.getNodeInformation().getVMInformation().getHostName());
// set the different informations on job
if (job.getStartTime() < 0) {
// if it is the first task of this job
job.start();
core.pendingJobs.remove(job);
core.runningJobs.add(job);
//update tasks events list and send it to front-end
core.updateTaskInfosList(job, SchedulerEvent.JOB_PENDING_TO_RUNNING);
logger.info("Job '" + job.getId() + "' started");
}
// set the different informations on task
job.startTask(task);
//set this task as started
core.currentlyRunningTasks.get(task.getJobId()).put(task.getId(), launcher);
// send task event to front-end
core.frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_PENDING_TO_RUNNING, task.getTaskInfo()));
}
}
|
package au.gov.ga.geodesy.support.spring;
import java.io.FileNotFoundException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import au.gov.ga.geodesy.domain.model.SynchronousEventPublisher;
import au.gov.ga.geodesy.domain.model.event.EventPublisher;
import au.gov.ga.geodesy.port.adapter.geodesyml.GeodesyMLValidator;
@Configuration
public class GeodesyServiceTestConfig extends GeodesyServiceConfig {
@Bean
@Override
public EventPublisher eventPublisher() {
return new SynchronousEventPublisher();
}
@Bean
public GeodesyMLValidator getGeodesyMLValidator() throws FileNotFoundException {
String catalog = ResourceUtils.getFile("classpath:xsd/geodesyml-1.0.0-SNAPSHOT/catalog.xml").getAbsolutePath();
return new GeodesyMLValidator(catalog);
}
}
|
package by.bsuir.mpp.computershop;
import by.bsuir.mpp.computershop.config.PrimaryConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {PrimaryConfiguration.class})
@SpringBootTest
public class ComputerShopMppApplicationTests {
@Test
public void contextLoads() {
}
}
|
package com.akiban.server.test.mt.mtatomics;
import com.akiban.server.api.DMLFunctions;
import com.akiban.server.api.dml.scan.CursorId;
import com.akiban.server.api.dml.scan.NewRow;
import com.akiban.server.api.dml.scan.ScanAllRequest;
import com.akiban.server.api.dml.scan.ScanFlag;
import com.akiban.server.api.dml.scan.ScanLimit;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.test.ApiTestBase;
import com.akiban.server.test.mt.mtutil.TimePoints;
import com.akiban.server.test.mt.mtutil.TimedCallable;
import com.akiban.server.test.mt.mtutil.Timing;
import com.akiban.server.service.dxl.ConcurrencyAtomicsDXLService;
import com.akiban.server.service.session.Session;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import static org.junit.Assert.*;
class DelayableScanCallable extends TimedCallable<List<NewRow>> {
private final int tableId;
private final int indexId;
private final DelayerFactory topOfLoopDelayer;
private final DelayerFactory beforeConversionDelayer;
private final boolean markFinish;
private final long finishDelay;
private final long initialDelay;
private final int aisGeneration;
private final boolean markOpenCursor;
private volatile ApiTestBase.ListRowOutput output;
DelayableScanCallable(int aisGeneration,
int tableId, int indexId,
DelayerFactory topOfLoopDelayer, DelayerFactory beforeConversionDelayer,
boolean markFinish, long initialDelay, long finishDelay, boolean markOpenCursor)
{
this.aisGeneration = aisGeneration;
this.tableId = tableId;
this.indexId = indexId;
this.topOfLoopDelayer = topOfLoopDelayer;
this.beforeConversionDelayer = beforeConversionDelayer;
this.markFinish = markFinish;
this.initialDelay = initialDelay;
this.finishDelay = finishDelay;
this.markOpenCursor = markOpenCursor;
}
private Delayer topOfLoopDelayer(TimePoints timePoints) {
return topOfLoopDelayer == null ? null : topOfLoopDelayer.delayer(timePoints);
}
private Delayer beforeConversionDelayer(TimePoints timePoints){
return beforeConversionDelayer == null ? null : beforeConversionDelayer.delayer(timePoints);
}
@Override
protected final List<NewRow> doCall(final TimePoints timePoints, Session session) throws Exception {
Timing.sleep(initialDelay);
final Delayer topOfLoopDelayer = topOfLoopDelayer(timePoints);
final Delayer beforeConversionDelayer = beforeConversionDelayer(timePoints);
ConcurrencyAtomicsDXLService.ScanHooks scanHooks = new ConcurrencyAtomicsDXLService.ScanHooks() {
@Override
public void loopStartHook() {
if (topOfLoopDelayer != null) {
topOfLoopDelayer.delay();
}
}
@Override
public void preWroteRowHook() {
if (beforeConversionDelayer != null) {
beforeConversionDelayer.delay();
}
}
@Override
public void scanSomeFinishedWellHook() {
if (markFinish) {
timePoints.mark("SCAN: FINISH");
}
Timing.sleep(finishDelay);
}
};
ScanAllRequest request = new ScanAllRequest(
tableId,
new HashSet<Integer>(Arrays.asList(0, 1)),
indexId,
EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END),
ScanLimit.NONE
);
assertNull("previous scanhook defined!", ConcurrencyAtomicsDXLService.installScanHook(session, scanHooks));
assertTrue("scanhook not installed correctly", ConcurrencyAtomicsDXLService.isScanHookInstalled(session));
try {
final CursorId cursorId;
DMLFunctions dml = ServiceManagerImpl.get().getDXL().dmlFunctions();
try {
if (markOpenCursor) {
timePoints.mark("(SCAN: OPEN CURSOR)>");
}
cursorId = dml.openCursor(session, aisGeneration, request);
if (markOpenCursor) {
timePoints.mark("<(SCAN: OPEN CURSOR)");
}
} catch (Exception e) {
ConcurrencyAtomicsDXLService.ScanHooks removed = ConcurrencyAtomicsDXLService.removeScanHook(session);
if (removed != scanHooks) {
throw new RuntimeException("hook not removed correctly", e);
}
throw e;
}
output = new ApiTestBase.ListRowOutput();
timePoints.mark("SCAN: START");
dml.scanSome(session, cursorId, output);
dml.closeCursor(session, cursorId);
if (ConcurrencyAtomicsDXLService.isScanHookInstalled(session)) {
throw new ScanHooksNotRemovedException();
}
return output.getRows();
} catch (Exception e) {
timePoints.mark("SCAN: exception " + e.getClass().getSimpleName());
if (ConcurrencyAtomicsDXLService.isScanHookInstalled(session)) {
throw new ScanHooksNotRemovedException(e);
}
else throw e;
}
}
public List<NewRow> getRows() {
ApiTestBase.ListRowOutput outputLocal = output;
return outputLocal == null ? Collections.<NewRow>emptyList() : outputLocal.getRows();
}
private static class ScanHooksNotRemovedException extends RuntimeException {
private ScanHooksNotRemovedException() {
super("scanhooks not removed!");
}
private ScanHooksNotRemovedException(Throwable cause) {
super("scanhooks not removed!", cause);
}
}
}
|
package com.hierynomus.sshj.connection.channel.direct;
import com.hierynomus.sshj.test.SshFixture;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
public class CommandTest {
@Rule
public SshFixture fixture = new SshFixture();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void shouldExecuteBackgroundCommand() throws IOException {
SSHClient sshClient = fixture.setupConnectedDefaultClient();
sshClient.authPassword("jeroen", "jeroen");
File file = new File(temp.getRoot(), "testdir");
assertThat("File should not exist", !file.exists());
// TODO figure out why this does not really execute in the background.
Session.Command exec = sshClient.startSession().exec("mkdir " + file.getPath() + " &");
exec.join();
assertThat("File should exist", file.exists());
assertThat("File should be directory", file.isDirectory());
}
}
|
package no.finn.unleash.strategy;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class GradualRolloutRandomStrategyTest {
private static GradualRolloutRandomStrategy gradualRolloutRandomStrategy;
@Before
public void setUp() {
long seed = new Random().nextLong();
System.out.println("GradualRolloutRandomStrategyTest running with seed: " + seed);
gradualRolloutRandomStrategy = new GradualRolloutRandomStrategy(seed);
}
@Test
public void should_not_be_enabled_when_percentage_not_set() {
final Map<String, String> parameters = new HashMap<>();
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
assertFalse(enabled);
}
@Test
public void should_not_be_enabled_when_percentage_is_not_a_not_a_number() {
final Map<String, String> parameters = new HashMap<String, String>() {{
put("percentage", "foo");
}};
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
assertFalse(enabled);
}
@Test
public void should_not_be_enabled_when_percentage_is_not_a_not_a_valid_percentage_value() {
final Map<String, String> parameters = new HashMap<String, String>() {{
put("percentage", "ab");
}};
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
assertFalse(enabled);
}
@Test
public void should_never_be_enabled_when_0_percent() {
final Map<String, String> parameters = new HashMap<String, String>() {{
put("percentage", "0");
}};
for (int i = 0; i < 1000; i++) {
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
assertFalse(enabled);
}
}
@Test
public void should_always_be_enabled_when_100_percent() {
final Map<String, String> parameters = new HashMap<String, String>() {{
put("percentage", "100");
}};
for (int i = 0; i <= 100; i++) {
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
assertTrue("Should be enabled for p="+i, enabled);
}
}
@Ignore
@Test
public void localTest() {
final Map<String, String> parameters = new HashMap<String, String>() {{
put("percentage", "55");
}};
int rounds = 20000;
int countEnabled = 0;
for (int i = 0; i < rounds; i++) {
final boolean enabled = gradualRolloutRandomStrategy.isEnabled(parameters);
if(enabled) {
countEnabled = countEnabled + 1;
}
}
System.out.println("Percentage: " + ((double)countEnabled / rounds));
}
}
|
package org.dainst.chronontology.store;
import org.dainst.chronontology.JsonTestUtils;
import org.dainst.chronontology.it.ESClientTestUtil;
import org.dainst.chronontology.store.rest.JsonRestClient;
import org.testng.annotations.*;
import java.io.IOException;
import java.util.Arrays;
import static org.dainst.chronontology.TestConstants.TEST_INDEX;
import static org.dainst.chronontology.TestConstants.TEST_TYPE;
import static org.testng.Assert.assertEquals;
/**
* @author Daniel M. de Oliveira
*/
public class ElasticsearchDatastoreTest {
private final JsonRestClient client= new JsonRestClient(ESServerTestUtil.getUrl());
private final ElasticsearchDatastore store=
new ElasticsearchDatastore(client,TEST_INDEX);
@BeforeClass
public void setUp() {
ESServerTestUtil.startElasticSearchServer();
}
@AfterClass
public void tearDown() {
ESServerTestUtil.stopElasticSearchServer();
}
@BeforeMethod
public void before() {
store.put(TEST_TYPE,"a", JsonTestUtils.sampleDocument("a","1","none"));
store.put(TEST_TYPE,"b", JsonTestUtils.sampleDocument("a","2","dataset1"));
store.put(TEST_TYPE,"c", JsonTestUtils.sampleDocument("a","3","none"));
store.put(TEST_TYPE,"d", JsonTestUtils.sampleDocument("a","4","dataset1"));
store.put(TEST_TYPE,"e", JsonTestUtils.sampleDocument("a","5","none"));
ESClientTestUtil.refreshES();
}
@AfterMethod
public void afterMethod() {
store.remove(TEST_TYPE, "a");
store.remove(TEST_TYPE, "b");
store.remove(TEST_TYPE, "c");
store.remove(TEST_TYPE, "d");
store.remove(TEST_TYPE, "e");
ESClientTestUtil.refreshES();
}
@Test
public void findDocsWhereDatasetIsNone() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("1","3","5"));
}
@Test
public void findDocsMatchingTermWithFromAndSizeAndDatasetNone() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE, "a?from=0&size=1", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("1"));
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE, "a?from=1&size=1", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("3"));
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"a?from=1&size=2", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("3","5"));
}
@Test
public void findAllDocsWithDifferentDatasets() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"", Arrays.asList(new String[]{"dataset:none","dataset:dataset1"})).j(),
Arrays.asList("1","2","3","4","5"));
}
@Test
public void findAllDocsWithDifferentDatasetsAndSizeAndFrom() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"a?from=1&size=2", Arrays.asList(new String[]{"dataset:none","dataset:dataset1"})).j(),
Arrays.asList("2","3"));
}
@Test
public void findInAllPossibleDatasets() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"a", null).j(),
Arrays.asList("1","2","3","4","5"));
}
@Test
public void findWithSizeAndFromWithoutOtherSearchTerms() {
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"size=1", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("1"));
JsonTestUtils.assertResultsAreFound(
store.search(TEST_TYPE,"size=1&from=2", Arrays.asList(new String[]{"dataset:none"})).j(),
Arrays.asList("5"));
}
@Test
public void getItemForId() throws IOException {
assertEquals(store.get(TEST_TYPE,"a"),JsonTestUtils.sampleDocument("a","1","none"));
}
@Test
public void deleteAnItem() throws IOException, InterruptedException {
store.remove(TEST_TYPE, "a");
Thread.sleep(100);
assertEquals(store.get(TEST_TYPE,"a"), null);
}
}
|
package gov.va.med.srcalc.controller;
import gov.va.med.srcalc.domain.variable.MultiSelectOption;
import gov.va.med.srcalc.domain.variable.MultiSelectVariable;
import gov.va.med.srcalc.domain.variable.NumericalVariable;
import gov.va.med.srcalc.domain.variable.VariableVisitor;
import java.io.IOException;
import java.io.Writer;
/**
* Writes an HTML input control for visited {@link Variable}s.
*/
class InputGeneratorVisitor implements VariableVisitor
{
private final Writer fWriter;
public InputGeneratorVisitor(Writer writer)
{
fWriter = writer;
}
protected void writeRadio(MultiSelectVariable variable) throws IOException
{
for (final MultiSelectOption option : variable.getOptions())
{
fWriter.write(String.format(
"<label class=\"radioLabel\">" +
"<input type=\"radio\" name=\"%s\" value=\"%s\"> " +
"%s</label>",
variable.getDisplayName(),
option.getValue(),
option.getValue()));
}
}
protected void writeDropdown(MultiSelectVariable variable)
{
throw new UnsupportedOperationException("not implemented yet");
}
@Override
public void visitMultiSelect(MultiSelectVariable variable) throws IOException
{
// Display differently based on configured displayType.
switch (variable.getDisplayType())
{
case Radio:
writeRadio(variable);
break;
case Dropdown:
writeDropdown(variable);
break;
default:
throw new UnsupportedOperationException("Unsupported displayType.");
}
}
@Override
public void visitNumerical(NumericalVariable variable) throws Exception
{
// The maximum number of digits we expect.
final int maxExpectedDigits = 8;
fWriter.write(String.format(
"<input type=\"text\" name=\"%s\" size=\"%d\">",
variable.getDisplayName(), maxExpectedDigits));
}
}
|
package com.splicemachine.si.api;
import com.splicemachine.constants.SIConstants;
import com.splicemachine.constants.SpliceConfiguration;
import com.splicemachine.constants.SpliceConstants;
import com.splicemachine.hbase.table.BetterHTablePool;
import com.splicemachine.hbase.table.SpliceHTableFactory;
import com.splicemachine.si.data.api.SDataLib;
import com.splicemachine.si.data.api.STableReader;
import com.splicemachine.si.data.api.STableWriter;
import com.splicemachine.si.data.hbase.HDataLib;
import com.splicemachine.si.data.hbase.HHasher;
import com.splicemachine.si.data.hbase.HPoolTableSource;
import com.splicemachine.si.data.hbase.HTableReader;
import com.splicemachine.si.data.hbase.HTableWriter;
import com.splicemachine.si.data.hbase.IHTable;
import com.splicemachine.si.impl.ActiveTransactionCacheEntry;
import com.splicemachine.si.impl.CacheMap;
import com.splicemachine.si.impl.DataStore;
import com.splicemachine.si.impl.ImmutableTransaction;
import com.splicemachine.si.impl.PermissionArgs;
import com.splicemachine.si.impl.SITransactor;
import com.splicemachine.si.impl.SystemClock;
import com.splicemachine.si.impl.Transaction;
import com.splicemachine.si.impl.TransactionSchema;
import com.splicemachine.si.impl.TransactionStore;
import com.splicemachine.si.jmx.ManagedTransactor;
import com.splicemachine.si.jmx.TransactorStatus;
import com.splicemachine.si.txn.ZooKeeperStatTimestampSource;
import com.splicemachine.si.txn.ZooKeeperTimestampSource;
import com.splicemachine.utils.ZkUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.OperationWithAttributes;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.OperationStatus;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Used to construct a transactor object that is bound to the HBase types and that provides SI functionality. This is
* the main entry point for applications using SI. Keeps track of a global, static instance that is shared by all callers.
* Also defines the various configuration options and plugins for the transactor instance.
*/
public class HTransactorFactory extends SIConstants {
private final static Map<Long, ImmutableTransaction> immutableCache = CacheMap.makeCache(true);
private final static Map<Long, ActiveTransactionCacheEntry> activeCache = CacheMap.makeCache(true);
private final static Map<Long, Transaction> cache = CacheMap.makeCache(true);
private final static Map<Long, Transaction> committedCache = CacheMap.makeCache(true);
private final static Map<Long, Transaction> failedCache = CacheMap.makeCache(true);
private final static Map<PermissionArgs, Byte> permissionCache = CacheMap.makeCache(true);
private static volatile ManagedTransactor managedTransactor;
public static void setTransactor(ManagedTransactor managedTransactorToUse) {
managedTransactor = managedTransactorToUse;
}
public static TransactorStatus getTransactorStatus() {
return getTransactorDirect();
}
public static TransactorControl getTransactorControl() {
return getTransactorDirect().getTransactor();
}
public static ClientTransactor<Put, Get, Scan, Mutation, byte[]> getClientTransactor() {
return getTransactorDirect().getTransactor();
}
public static Transactor<IHTable, Put, Get, Scan, Mutation, OperationStatus, Result, KeyValue, byte[], ByteBuffer, Integer> getTransactor() {
return getTransactorDirect().getTransactor();
}
private static ManagedTransactor getTransactorDirect() {
if (managedTransactor != null) {
return managedTransactor;
}
synchronized (HTransactorFactory.class) {
//double-checked locking--make sure someone else didn't already create it
if (managedTransactor != null) {
return managedTransactor;
}
final Configuration configuration = SpliceConstants.config;
TimestampSource timestampSource = new ZooKeeperStatTimestampSource(ZkUtils.getRecoverableZooKeeper(),zkSpliceTransactionPath);
BetterHTablePool hTablePool = new BetterHTablePool(new SpliceHTableFactory(),
SpliceConstants.tablePoolCleanerInterval, TimeUnit.SECONDS,
SpliceConstants.tablePoolMaxSize,SpliceConstants.tablePoolCoreSize);
// HTablePool hTablePool = new HTablePool(configuration, Integer.MAX_VALUE);
final HPoolTableSource tableSource = new HPoolTableSource(hTablePool);
SDataLib dataLib = new HDataLib();
final STableReader reader = new HTableReader(tableSource);
final STableWriter writer = new HTableWriter();
final TransactionSchema transactionSchema = new TransactionSchema(TRANSACTION_TABLE,
DEFAULT_FAMILY,
SI_PERMISSION_FAMILY,
EMPTY_BYTE_ARRAY,
TRANSACTION_ID_COLUMN,
TRANSACTION_START_TIMESTAMP_COLUMN,
TRANSACTION_PARENT_COLUMN_BYTES,
TRANSACTION_DEPENDENT_COLUMN_BYTES,
TRANSACTION_ALLOW_WRITES_COLUMN_BYTES,
TRANSACTION_ADDITIVE_COLUMN_BYTES,
TRANSACTION_READ_UNCOMMITTED_COLUMN_BYTES,
TRANSACTION_READ_COMMITTED_COLUMN_BYTES,
TRANSACTION_KEEP_ALIVE_COLUMN, TRANSACTION_STATUS_COLUMN,
TRANSACTION_COMMIT_TIMESTAMP_COLUMN,
TRANSACTION_GLOBAL_COMMIT_TIMESTAMP_COLUMN,
TRANSACTION_COUNTER_COLUMN
);
ManagedTransactor builderTransactor = new ManagedTransactor();
final TransactionStore transactionStore = new TransactionStore(transactionSchema, dataLib, reader, writer,
immutableCache, activeCache, cache, committedCache, failedCache, permissionCache, 1000, managedTransactor);
final DataStore rowStore = new DataStore(dataLib, reader, writer, SI_NEEDED, SI_NEEDED_VALUE,
ONLY_SI_FAMILY_NEEDED_VALUE, SI_TRANSACTION_ID_KEY,
SI_DELETE_PUT, SNAPSHOT_ISOLATION_FAMILY, SNAPSHOT_ISOLATION_COMMIT_TIMESTAMP_COLUMN_STRING,
SNAPSHOT_ISOLATION_TOMBSTONE_COLUMN_STRING, EMPTY_BYTE_ARRAY, SI_ANTI_TOMBSTONE_VALUE,
SNAPSHOT_ISOLATION_FAILED_TIMESTAMP, DEFAULT_FAMILY);
final Transactor transactor = new SITransactor<IHTable, OperationWithAttributes, Mutation, Put, Get, Scan, Result, KeyValue, byte[], ByteBuffer, Delete, Integer, OperationStatus, RegionScanner>
(timestampSource, dataLib, writer, rowStore, transactionStore, new SystemClock(), TRANSACTION_TIMEOUT,
new HHasher(), managedTransactor);
builderTransactor.setTransactor(transactor);
managedTransactor = builderTransactor;
}
return managedTransactor;
}
}
|
package io.enmasse.systemtest.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.enmasse.address.model.AddressSpace;
import io.enmasse.address.model.EndpointSpec;
import io.enmasse.address.model.EndpointStatus;
import io.enmasse.systemtest.*;
import io.enmasse.systemtest.timemeasuring.SystemtestsOperation;
import io.enmasse.systemtest.timemeasuring.TimeMeasuringSystem;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
public class AddressSpaceUtils {
private static Logger log = CustomLogger.getLogger();
public static void syncAddressSpaceObject(AddressSpace addressSpace) {
AddressSpace data = Kubernetes.getInstance().getAddressSpaceClient(addressSpace.getMetadata().getNamespace())
.withName(addressSpace.getMetadata().getName()).get();
addressSpace.setMetadata(data.getMetadata());
addressSpace.setSpec(data.getSpec());
addressSpace.setStatus(data.getStatus());
}
public static JsonObject addressSpaceToJson(AddressSpace addressSpace) throws Exception {
return new JsonObject(new ObjectMapper().writeValueAsString(addressSpace));
}
public static String getAddressSpaceInfraUuid(AddressSpace addressSpace) {
return addressSpace.getMetadata().getAnnotations().get("enmasse.io/infra-uuid");
}
public static boolean existAddressSpace(String namespace, String addressSpaceName) {
log.info("Following addressspaces are deployed {} in namespace {}", Kubernetes.getInstance().getAddressSpaceClient(namespace).list().getItems().stream()
.map(addressSpace -> addressSpace.getMetadata().getName()).collect(Collectors.toList()), namespace);
return Kubernetes.getInstance().getAddressSpaceClient(namespace).list().getItems().stream()
.map(addressSpace -> addressSpace.getMetadata().getName()).collect(Collectors.toList()).contains(addressSpaceName);
}
public static boolean isAddressSpaceReady(AddressSpace addressSpace) {
return addressSpace != null && addressSpace.getStatus().isReady();
}
public static boolean matchAddressSpacePlan(AddressSpace received, AddressSpace expected) {
return received != null && received.getMetadata().getAnnotations().get("enmasse.io/applied-plan").equals(expected.getSpec().getPlan());
}
public static AddressSpace waitForAddressSpaceReady(AddressSpace addressSpace) throws Exception {
return waitForAddressSpaceReady(addressSpace, new TimeoutBudget(15, TimeUnit.MINUTES));
}
public static AddressSpace waitForAddressSpaceReady(AddressSpace addressSpace, TimeoutBudget budget) throws Exception {
boolean isReady = false;
var client = Kubernetes.getInstance().getAddressSpaceClient(addressSpace.getMetadata().getNamespace());
String name = addressSpace.getMetadata().getName();
AddressSpace clientAddressSpace = addressSpace;
while (budget.timeLeft() >= 0 && !isReady) {
clientAddressSpace = client.withName(name).get();
isReady = isAddressSpaceReady(clientAddressSpace);
if (!isReady) {
Thread.sleep(10000);
}
log.info("Waiting until Address space: '{}' messages {} will be in ready state", name,
(clientAddressSpace != null && clientAddressSpace.getStatus() != null) ? clientAddressSpace.getStatus().getMessages() : null);
}
if (!isReady) {
String status = (clientAddressSpace != null && clientAddressSpace.getStatus() != null) ? clientAddressSpace.getStatus().toString() : null;
throw new IllegalStateException(String.format("Address Space %s is not in Ready state within timeout: %s", name, status));
}
log.info("Address space {} is ready for use", clientAddressSpace);
return clientAddressSpace;
}
public static void waitForAddressSpacePlanApplied(AddressSpace addressSpace) throws Exception {
AddressSpace addressSpaceObject = null;
TimeoutBudget budget = new TimeoutBudget(15, TimeUnit.MINUTES);
boolean isPlanApplied = false;
while (budget.timeLeft() >= 0 && !isPlanApplied) {
addressSpaceObject = Kubernetes.getInstance().getAddressSpaceClient(addressSpace.getMetadata().getNamespace()).withName(addressSpace.getMetadata().getName()).get();
isPlanApplied = matchAddressSpacePlan(addressSpaceObject, addressSpace);
if (!isPlanApplied) {
Thread.sleep(2000);
}
log.info("Waiting until Address space plan will be applied: '{}', current: {}",
addressSpace.getSpec().getPlan(),
addressSpaceObject.getMetadata().getAnnotations().get("enmasse.io/applied-plan"));
}
isPlanApplied = matchAddressSpacePlan(addressSpaceObject, addressSpace);
if (!isPlanApplied) {
String jsonStatus = addressSpaceObject != null ? addressSpaceObject.getMetadata().getAnnotations().get("enmasse.io/applied-plan") : "";
throw new IllegalStateException("Address Space " + addressSpace + " contains wrong plan: " + jsonStatus);
}
log.info("Address plan {} successfully applied", addressSpace.getSpec().getPlan());
}
public static void deleteAddressSpaceAndWait(AddressSpace addressSpace, GlobalLogCollector logCollector) throws Exception {
String operationID = TimeMeasuringSystem.startOperation(SystemtestsOperation.DELETE_ADDRESS_SPACE);
deleteAddressSpace(addressSpace, logCollector);
waitForAddressSpaceDeleted(addressSpace);
TimeMeasuringSystem.stopOperation(operationID);
}
private static void deleteAddressSpace(AddressSpace addressSpace, GlobalLogCollector logCollector) throws Exception {
logCollector.collectEvents();
logCollector.collectApiServerJmapLog();
logCollector.collectLogsTerminatedPods();
logCollector.collectConfigMaps();
logCollector.collectRouterState("deleteAddressSpace");
Kubernetes.getInstance().getAddressSpaceClient(addressSpace.getMetadata().getNamespace()).withName(addressSpace.getMetadata().getName()).cascading(true).delete();
}
public static void deleteAllAddressSpaces(GlobalLogCollector logCollector) throws Exception {
String operationID = TimeMeasuringSystem.startOperation(SystemtestsOperation.DELETE_ADDRESS_SPACE);
logCollector.collectEvents();
logCollector.collectApiServerJmapLog();
logCollector.collectLogsTerminatedPods();
logCollector.collectConfigMaps();
logCollector.collectRouterState("deleteAddressSpace");
Kubernetes.getInstance().getAddressSpaceClient().delete();
TimeMeasuringSystem.stopOperation(operationID);
}
public static void waitForAddressSpaceDeleted(AddressSpace addressSpace) throws Exception {
Kubernetes kube = Kubernetes.getInstance();
log.info("Waiting for AddressSpace {} to be deleted", addressSpace.getMetadata().getName());
TimeoutBudget budget = new TimeoutBudget(10, TimeUnit.MINUTES);
waitForItems(addressSpace, budget, () -> kube.listPods(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listConfigMaps(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listServices(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listSecrets(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listDeployments(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listStatefulSets(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listServiceAccounts(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
waitForItems(addressSpace, budget, () -> kube.listPersistentVolumeClaims(Collections.singletonMap("infraUuid", getAddressSpaceInfraUuid(addressSpace))));
}
private static <T> void waitForItems(AddressSpace addressSpace, TimeoutBudget budget, Callable<List<T>> callable) throws Exception {
List<T> resources = null;
while (budget.timeLeft() >= 0) {
resources = callable.call();
if (resources == null || resources.isEmpty()) {
break;
}
Thread.sleep(1000);
}
resources = callable.call();
if (resources != null && resources.size() > 0) {
throw new TimeoutException("Timed out waiting for address space " + addressSpace.getMetadata().getName() + " to disappear. Resources left: " + resources);
}
}
public static Endpoint getEndpointByName(AddressSpace addressSpace, String endpoint) {
for (EndpointSpec addrSpaceEndpoint : addressSpace.getSpec().getEndpoints()) {
if (addrSpaceEndpoint.getName().equals(endpoint)) {
EndpointStatus status = getEndpointByName(addrSpaceEndpoint.getName(), addressSpace.getStatus().getEndpointStatuses());
log.debug("Got endpoint: name: {}, service-name: {}, host: {}, port: {}",
addrSpaceEndpoint.getName(), addrSpaceEndpoint.getService(), status.getExternalHost(),
status.getExternalPorts().values().stream().findAny().get());
if (status.getExternalHost() == null) {
return null;
} else {
return new Endpoint(status.getExternalHost(), status.getExternalPorts().values().stream().findAny().get());
}
}
}
throw new IllegalStateException(String.format("Endpoint wih name '%s-%s' doesn't exist in address space '%s'",
endpoint, getAddressSpaceInfraUuid(addressSpace), addressSpace.getMetadata().getName()));
}
public static Endpoint getEndpointByServiceName(AddressSpace addressSpace, String endpointService) {
for (EndpointSpec addrSpaceEndpoint : addressSpace.getSpec().getEndpoints()) {
if (addrSpaceEndpoint.getService().equals(endpointService)) {
EndpointStatus status = getEndpointByServiceName(addrSpaceEndpoint.getService(), addressSpace.getStatus().getEndpointStatuses());
log.info("Got endpoint: name: {}, service-name: {}, host: {}, port: {}",
addrSpaceEndpoint.getName(), addrSpaceEndpoint.getService(), status.getExternalHost(),
status.getExternalPorts().values().stream().findAny().get());
if (status.getExternalHost() == null) {
return null;
} else {
return new Endpoint(status.getExternalHost(), status.getExternalPorts().values().stream().findAny().get());
}
}
}
throw new IllegalStateException(String.format("Endpoint with service name '%s' doesn't exist in address space '%s'",
endpointService, addressSpace.getMetadata().getName()));
}
public static String getExternalEndpointName(AddressSpace addressSpace, String service) {
for (EndpointSpec endpoint : addressSpace.getSpec().getEndpoints()) {
if (endpoint.getService().equals(service) && endpoint.getName() != null && !endpoint.getName().isEmpty()) {
return endpoint.getName();
}
}
return service;
}
private static EndpointStatus getEndpointByName(String name, List<EndpointStatus> endpoints) {
return endpoints.stream().filter(endpointStatus -> endpointStatus.getName().equals(name)).findAny().get();
}
private static EndpointStatus getEndpointByServiceName(String serviceName, List<EndpointStatus> endpoints) {
return endpoints.stream().filter(endpointStatus -> endpointStatus.getServiceHost().startsWith(serviceName)).findAny().get();
}
}
|
package com.bbn.kbp.events2014.bin;
import com.bbn.bue.common.parameters.Parameters;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.CorpusEventFrame;
import com.bbn.kbp.events2014.CorpusEventFrameFunctions;
import com.bbn.kbp.events2014.CorpusEventLinking;
import com.bbn.kbp.events2014.TACKBPEALException;
import com.bbn.kbp.events2014.io.SystemOutputStore2016;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import static com.bbn.kbp.events2014.CorpusEventFrameFunctions.id;
import static com.google.common.collect.Iterables.concat;
/**
* Merge together system output stores over disjoint documents sets.
*/
public final class MergeSystemOutputs {
private static final Logger log = LoggerFactory.getLogger(MergeSystemOutputs.class);
private MergeSystemOutputs() {
throw new UnsupportedOperationException();
}
public static void main(String[] argv) {
// we wrap the main method in this way to
// ensure a non-zero return value on failure
try {
trueMain(argv);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static void trueMain(String[] argv) throws IOException {
final Parameters params = Parameters.loadSerifStyle(new File(argv[0]));
final File inputStore = params.getExistingDirectory("input1");
final File inputStore2 = params.getExistingDirectory("input2");
final File outputStore = params.getCreatableDirectory("outputStore");
final boolean changeDuplicatedIDs = params.getOptionalBoolean("changeDuplicatedIDs").or(false);
final SystemOutputStore2016 input1 = SystemOutputStore2016.open(inputStore);
final SystemOutputStore2016 input2 = SystemOutputStore2016.open(inputStore2);
final SystemOutputStore2016 output = SystemOutputStore2016.openOrCreate(outputStore);
final Set<Symbol> commonDocIDs = Sets.intersection(input1.docIDs(), input2.docIDs());
if (!commonDocIDs.isEmpty()) {
if (changeDuplicatedIDs) {
log.warn("Duplicated document IDs found! {}", commonDocIDs);
} else {
throw new TACKBPEALException(
"Can only merge disjoint system output stores, but the following"
+ "docIDs are shared: " + commonDocIDs);
}
}
// merge document-level output
for (final SystemOutputStore2016 input : ImmutableList.of(input1, input2)) {
for (final Symbol docID : input.docIDs()) {
output.write(input.read(docID));
}
}
// merge corpus-event frames
output.writeCorpusEventFrames(
merge(input1.readCorpusEventFrames(), input2.readCorpusEventFrames(), changeDuplicatedIDs));
input1.close();
input2.close();
output.close();
}
private static CorpusEventLinking merge(final CorpusEventLinking corpusLinking1,
final CorpusEventLinking corpusLinking2, final boolean changeDuplicatedIDs) {
final Set<String> commonIDs = Sets.intersection(
FluentIterable.from(corpusLinking1.corpusEventFrames())
.transform(id())
.toSet(),
FluentIterable.from(corpusLinking2.corpusEventFrames())
.transform(id())
.toSet());
if (!commonIDs.isEmpty()) {
if (changeDuplicatedIDs) {
final Set<String> allIds = ImmutableSet.copyOf(FluentIterable
.from(concat(corpusLinking1.corpusEventFrames(), corpusLinking2.corpusEventFrames()))
.transform(CorpusEventFrameFunctions.id()).toSet());
// some systems may produce IDs in order, this isn't strictly necessary
int newId = allIds.size();
final CorpusEventLinking.Builder ret = CorpusEventLinking.builder()
.addAllCorpusEventFrames(corpusLinking1.corpusEventFrames());
for (final CorpusEventFrame cef : corpusLinking2.corpusEventFrames()) {
if (commonIDs.contains(cef.id())) {
while (allIds.contains(Integer.toHexString(newId))) {
newId++;
}
final String id = Integer.toHexString(newId);
ret.addCorpusEventFrames(cef.withId(id));
log.info("Frame id {} remapped to {}", cef.id(), id);
} else {
ret.addCorpusEventFrames(cef);
}
}
} else {
throw new TACKBPEALException("Expected no common corpus event frame IDs, but got "
+ commonIDs);
}
}
return CorpusEventLinking.builder()
.addAllCorpusEventFrames(corpusLinking1.corpusEventFrames())
.addAllCorpusEventFrames(corpusLinking2.corpusEventFrames())
.build();
}
}
|
package graph;
import gcm.parser.GCMFile;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import parser.Parser;
import parser.TSDParser;
import reb2sac.Reb2Sac;
import util.Utility;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private Reb2Sac reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock, lock2;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim,
String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
lock2 = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
ArrayList<String> runs = new ArrayList<String>();
if (directory == null) {
String[] files = new File(outDir).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
else {
String[] files = new File(outDir + separator + directory).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(runs, 0, directory, warn, false);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(runs, 1, directory, warn, false);
}
else {
return calculateAverageVarianceDeviation(runs, 2, directory, warn, false);
}
}
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent()).getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j
}
}
}
else {
simDir.remove(i);
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
count++;
}
}
if (count == 3) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
simDir.remove(j);
j
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) {
((IconNode) simDir.getChildAt(i)).remove(j);
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
count++;
}
}
if (count == 3) {
File dir2 = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir2.isDirectory()) {
biomodelsim.deleteDir(dir2);
}
else {
dir2.delete();
}
directories.remove(((IconNode) simDir.getChildAt(i)).getName());
for (int k = 0; k < graphed.size(); k++) {
if (graphed.get(k).getDirectory().equals(((IconNode) simDir.getChildAt(i)).getName())) {
graphed.remove(k);
k
}
}
simDir.remove(i);
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-") || file.contains("mean") || file.contains("variance") || file.contains("standard_deviation")) {
add = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// files3[j] = files3[j - 1];
// j = j - 1;
// files3[j] = index;
for (String getFile : files3) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean add2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-") || f.contains("mean") || f.contains("variance") || f.contains("standard_deviation")) {
add2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean add3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f2.contains("run-") || f2.contains("mean") || f2.contains("variance")
|| f2.contains("standard_deviation")) {
add3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (add3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator
+ (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName()) && node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
if (biomodelsim.lema || biomodelsim.atacs) {
specs = new JLabel("Variables");
}
else {
specs = new JLabel("Species");
}
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(),
series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning,
boolean output) {
if (files.size() > 0) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data;
if (directory == null) {
data = readData(outDir + separator + files.get(0), "", directory, warn);
}
else {
data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn);
}
averageOrder = graphSpecies;
boolean first = true;
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
for (String run : files) {
if (directory == null) {
if (new File(outDir + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
else {
if (new File(outDir + separator + directory + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (output) {
Parser m = new Parser(graphSpecies, average);
Parser d = new Parser(graphSpecies, deviation);
Parser v = new Parser(graphSpecies, variance);
if (directory == null) {
m.outputTSD(outDir + separator + "mean.tsd");
v.outputTSD(outDir + separator + "variance.tsd");
d.outputTSD(outDir + separator + "standard_deviation.tsd");
}
else {
m.outputTSD(outDir + separator + directory + separator + "mean.tsd");
v.outputTSD(outDir + separator + directory + separator + "variance.tsd");
d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd");
}
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
return null;
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", ""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next)
.trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), xnumber,
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next),
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
lock2.lock();
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
data = readData(
outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
lock2.unlock();
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species,
int xnumber, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator + f).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f).list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory()
.equals(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText()
.trim(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
GCMFile gcm = new GCMFile(biomodelsim.getRoot());
gcm.load(background);
HashMap<String, Properties> speciesMap = gcm.getSpecies();
for (String s : speciesMap.keySet()) {
learnSpecs.add(s);
}
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
/*
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
import java.util.ArrayList;
public class SchroedingerIntegration {
public static double h = 6.626070040*Math.pow(10, -34); // wirkungsquantum
public static double u = 9.10938356*Math.pow(10,-31); //elementarmasse
public static double e = 1.6021766208*Math.pow(10,-19); //elementarladung
public static double e0 = 8.85418781762*Math.pow(10,-12);
public static void main(String[] args) throws InterruptedException{
Game g = new Game();
g.drawpoints = false; // Befehl sodass die Punkte des Plots miteinander verbunden werden
g.growingrange = true;
g.plotThickness = 2;
g.calcTime = 100;
g.xlabel = "Abstand des Kerns in m";
g.ylabel = "Energie in eV";
Energieeigenwerte E = new Energieeigenwerte(new Coulomb(), -16*e, -0.1*e);
for(int i = 0; i<5;i++){
E.step();
System.out.println(E.getEnergy()/e);
g.addEnergy(E.getEnergy()/e);
g.addMeasures(E.getSolution());
}
g.plot();
}
}
|
package graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import main.util.Utility;
import main.util.dataparser.DTSDParser;
import main.util.dataparser.DataParser;
import main.util.dataparser.TSDParser;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import analysis.AnalysisView;
import biomodel.parser.BioModel;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private AnalysisView reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock, lock2;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(AnalysisView reb2sac, String printer_track_quantity, String label, String printer_id, String outDir, String time, Gui biomodelsim,
String open, Log log, String graphName, boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
lock2 = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1] + ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset, String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
Dimension dim = new Dimension(1,1);
XVariable.setPreferredSize(dim);
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator + ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (file.contains(".dtsd"))
graphSpecies = (new DTSDParser(file)).getSpecies();
else
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory, boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean")) || (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
ArrayList<String> runs = new ArrayList<String>();
if (directory == null) {
String[] files = new File(outDir).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
else {
String[] files = new File(outDir + separator + directory).list();
for (String f : files) {
if (f.contains(stem) && f.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(f);
}
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(runs, 0, directory, warn, false);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(runs, 1, directory, warn, false);
}
else {
return calculateAverageVarianceDeviation(runs, 2, directory, warn, false);
}
}
//if it's not a stats file
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
DTSDParser dtsdParser;
TSDParser p;
ArrayList<ArrayList<Double>> data;
if (file.contains(".dtsd")) {
dtsdParser = new DTSDParser(file);
Gui.frame.setCursor(null);
warn = false;
graphSpecies = dtsdParser.getSpecies();
data = dtsdParser.getData();
}
else {
p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
data = p.getData();
}
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0 && ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("recalculate")) {
TreePath select = tree.getSelectionPath();
String[] files;
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
files = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName()).list();
}
else {
files = new File(outDir).list();
}
ArrayList<String> runs = new ArrayList<String>();
for (String file : files) {
if (file.contains("run-") && file.endsWith("." + printer_id.substring(0, printer_id.length() - 8))) {
runs.add(file);
}
}
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
calculateAverageVarianceDeviation(runs, 0, ((IconNode) select.getLastPathComponent()).getName(), warn, true);
}
else {
calculateAverageVarianceDeviation(runs, 0, null, warn, true);
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator + ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent()).getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j
}
}
}
else {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
simDir.remove(i);
}
else if (name.equals("Termination Time")) {
name = "term-time";
simDir.remove(i);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
simDir.remove(i);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
simDir.remove(i);
}
else {
simDir.remove(i);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
d = true;
}
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(j)).getName().contains("Average") && !m) {
simDir.remove(j);
j
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Variance") && !v) {
simDir.remove(j);
j
}
else if (((IconNode) simDir.getChildAt(j)).getName().contains("Deviation") && !d) {
simDir.remove(j);
j
}
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select.getLastPathComponent())) {
String name = ((IconNode) select.getLastPathComponent()).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Termination Time")) {
name = "term-time";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
((IconNode) simDir.getChildAt(i)).remove(j);
}
else {
((IconNode) simDir.getChildAt(i)).remove(j);
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
boolean m = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
m = true;
}
boolean v = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
v = true;
}
boolean d = false;
if (new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName() + separator + "standard_deviation"
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
d = true;
}
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("run-")) {
count++;
}
}
}
if (count == 0) {
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getChildCount() == 0) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Average") && !m) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Variance") && !v) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
else if (((IconNode) simDir.getChildAt(i).getChildAt(k)).getName().contains("Deviation") && !d) {
((IconNode) simDir.getChildAt(i)).remove(k);
k
}
}
}
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
String name = ((IconNode) simDir.getChildAt(i)).getName();
if (name.equals("Average")) {
name = "mean";
}
else if (name.equals("Variance")) {
name = "variance";
}
else if (name.equals("Standard Deviation")) {
name = "standard_deviation";
}
else if (name.equals("Percent Termination")) {
name = "percent-term-time";
}
else if (name.equals("Termination Time")) {
name = "term-time";
}
else if (name.equals("Constraint Termination")) {
name = "sim-rep";
}
else if (name.equals("Bifurcation Statistics")) {
name = "bifurcation";
}
name += "." + printer_id.substring(0, printer_id.length() - 8);
File dir = new File(outDir + separator + name);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator + ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0) {
JMenuItem recalculate = new JMenuItem("Recalculate Statistics");
recalculate.addActionListener(this);
recalculate.setActionCommand("recalculate");
popup.add(recalculate);
}
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Log plots are not allowed with data\nvalues less than or equal to zero.", "Error",
JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean addMean = false;
boolean addVar = false;
boolean addDev = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
boolean addBif = false;
directories = new ArrayList<String>();
for (String file : files) {
if ((file.length() > 3 && (file.substring(file.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (file.length() > 4 && file.substring(file.length() - 5).equals(".dtsd"))) {
if (file.contains("run-") || file.contains("mean")) {
addMean = true;
}
else if (file.contains("run-") || file.contains("variance")) {
addVar = true;
}
else if (file.contains("run-") || file.contains("standard_deviation")) {
addDev = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else if (file.contains("bifurcation")) {
addBif = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// files3[j] = files3[j - 1];
// j = j - 1;
// files3[j] = index;
for (String getFile : files3) {
if ((getFile.length() > 3
&& (getFile.substring(getFile.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile.length() > 4 && getFile.substring(getFile.length() - 5).equals(".dtsd"))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if ((getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))))
|| (getFile2.length() > 4 && getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean addMean2 = false;
boolean addVar2 = false;
boolean addDev2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
boolean addBif2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8)) ||
f.contains(".dtsd")) {
if (f.contains("run-") || f.contains("mean")) {
addMean2 = true;
}
else if (f.contains("run-") || f.contains("variance")) {
addVar2 = true;
}
else if (f.contains("run-") || f.contains("standard_deviation")) {
addDev2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else if (f.contains("bifurcation")) {
addBif2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& (getFile2.substring(getFile2.length() - 4).equals("." + printer_id.substring(0, printer_id.length() - 8))
|| getFile2.substring(getFile2.length() - 5).equals(".dtsd"))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean addMean3 = false;
boolean addVar3 = false;
boolean addDev3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
boolean addBif3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id.substring(0, printer_id.length() - 8))
|| f2.contains(".dtsd")) {
if (f2.contains("run-") || f2.contains("mean")) {
addMean3 = true;
}
else if (f2.contains("run-") || f2.contains("variance")) {
addVar3 = true;
}
else if (f2.contains("run-") || f2.contains("standard_deviation")) {
addDev3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else if (f2.contains("bifurcation")) {
addBif3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (addMean3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev3) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar3) {
IconNode n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif3) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics")
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator
+ (d.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (addMean2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev2) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar2) {
IconNode n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif2) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + "." + printer_id.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (addMean) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addDev) {
IconNode n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addVar) {
IconNode n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addBif) {
IconNode n = new IconNode("Bifurcation Statistics", "Bifurcation Statistics");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Bifurcation Statistics") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.equals(".dtsd")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + "run-" + (i + 1) + ".dtsd").exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)), "run-" + (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p.get("run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1)) && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
scroll.getVerticalScrollBar().setUnitIncrement(10);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) &&
(graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() ||
new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(outDir + separator + g.getRunNumber() + "." + extension,
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation") && !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination") && !g.getRunNumber().equals("Constraint Termination")
&& !g.getRunNumber().equals("Bifurcation Statistics")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()
|| new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + ".dtsd").exists()) {
ArrayList<ArrayList<Double>> data;
//if the data has already been put into the data structure
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists() == false
&& new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + ".dtsd").exists()) {
extension = "dtsd";
}
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ extension, g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
//if it's one of the stats/termination files
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end average
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end variance
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end standard deviation
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end termination time
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end percent termination
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
} //end constraint termination
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
} //end of "Ok" option being true
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName()) && node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName() + separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else if (selected.equals("Bifurcation Statistics")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", " + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", " + s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
String extension = printer_id.substring(0, printer_id.length() - 8);
if (new File(outDir + separator + selected + "." + extension).exists() == false)
extension = "dtsd";
readGraphSpecies(outDir + separator + selected + "." + extension);
}
}
else {
if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")
|| selected.equals("Termination Time") || selected.equals("Percent Termination") || selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Bifurcation Statistics")
&& new File(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + directory + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "." + printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
specs = new JLabel("Variables");
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i).getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected, boxes.get(i).getName(),
series.get(i).getText().trim(), XVariable.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaint("Custom_" + colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4) && (filename.substring((filename.length() - 4), filename.length()).equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY, export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + " Overwrite?", "File Already Exists",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame, "Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame, "Data series do not have the same number of points!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame, "Data series time points are not the same!", "Unable to Export Data File",
JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(ArrayList<String> files, int choice, String directory, boolean warning,
boolean output) {
if (files.size() > 0) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data;
if (directory == null) {
data = readData(outDir + separator + files.get(0), "", directory, warn);
}
else {
data = readData(outDir + separator + directory + separator + files.get(0), "", directory, warn);
}
averageOrder = graphSpecies;
boolean first = true;
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
for (String run : files) {
if (directory == null) {
if (new File(outDir + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
else {
if (new File(outDir + separator + directory + separator + run).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator + directory + separator + run, "", directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(k - 1) - data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1) + (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old + (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (output) {
DataParser m = new DataParser(graphSpecies, average);
DataParser d = new DataParser(graphSpecies, deviation);
DataParser v = new DataParser(graphSpecies, variance);
if (directory == null) {
m.outputTSD(outDir + separator + "mean.tsd");
v.outputTSD(outDir + separator + "variance.tsd");
d.outputTSD(outDir + separator + "standard_deviation.tsd");
}
else {
m.outputTSD(outDir + separator + directory + separator + "mean.tsd");
v.outputTSD(outDir + separator + directory + separator + "variance.tsd");
d.outputTSD(outDir + separator + directory + separator + "standard_deviation.tsd");
}
}
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
return null;
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", "" + ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", "" + ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", "" + ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", "" + ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", "" + (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator + graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:", "Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint().getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint().getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(
outDir.substring(0, outDir.length() - outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient", ""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", "" + ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i, outDir.split(separator)[outDir.split(separator).length - 1] + "/"
+ probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape." + next)), graph.getProperty("species.paint." + next)
.trim(), filled, visible, connected, graph.getProperty("species.run.number." + next), graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), xnumber,
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot().setBackgroundPaint(new Color(Integer.parseInt(graph.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(new Color(Integer.parseInt(graph.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend") && graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id." + next), graph.getProperty("species.name." + next),
Integer.parseInt(graph.getProperty("species.number." + next)), graph.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
lock2.lock();
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "mean." + printer_id.substring(0, printer_id.length() - 8), g.getRunNumber()
.toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "standard_deviation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "sim-rep." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + "bifurcation" + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(outDir + separator + "bifurcation." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time") && !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(
outDir + separator + g.getDirectory() + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Bifurcation Statistics")
&& new File(outDir + separator + g.getDirectory() + separator + "bifurcation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
data = readData(
outDir + separator + g.getDirectory() + separator + "bifurcation."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
data = readData(
outDir + separator + g.getDirectory() + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g.getRunNumber().toLowerCase(),
g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
if (i < data.get(g.getXNumber()).size() && i < data.get(g.getNumber() + 1).size()) {
graphData.get(graphData.size() - 1).add((data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
lock2.unlock();
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected, String runNumber, String id, String species,
int xnumber, int number, String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(), PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer()).setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer()).getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile).isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator + getFile).list()) {
if (getFile2.length() > 3 && getFile2.substring(getFile2.length() - 4).equals(".txt") && getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator + f).list()) {
if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals(".txt") && getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f).list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4), f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(d2.toString()) > 0)
|| new File(outDir + separator + d.toString() + separator + (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator + (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph." + "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory()
.equals(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground((Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground((Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent()).getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, all, "Edit Probability Graph", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground((Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground((Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color, boxes.get(i).getName(), series.get(i).getText()
.trim(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals("" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i).setBackground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
colorsButtons.get(i).setForeground((Color) colors.get(((JComboBox) (e.getSource())).getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource()).getSelectedItem());
g.setPaint(colory.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_" + colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color", ((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination") && ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel, DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0) && (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot().getRangeAxis()
.getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator + split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir.substring(0, outDir.length() - split[split.length - 1].length()) + separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
BioModel gcm = new BioModel(biomodelsim.getRoot());
gcm.load(background);
learnSpecs = gcm.getSpecies();
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
/*
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number, String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
//import java.util.Objects;
import javax.swing.*;
// import javax.swing.plaf.ButtonUI;
// import javax.swing.plaf.basic.BasicRadioButtonUI;
// import javax.swing.plaf.synth.*;
public final class MainPanel extends JPanel {
private int count;
private MainPanel() {
super(new BorderLayout());
JTabbedPane tabs = new JTabbedPane() {
@Override public void addTab(String title, Component content) {
super.addTab(title, content);
// //TEST:
// JCheckBox check = new JCheckBox(title) {
// private final Rectangle viewRect = new Rectangle();
// private final Rectangle textRect = new Rectangle();
// private final Rectangle iconRect = new Rectangle();
// @Override public boolean contains(int x, int y) {
// Icon icon;
// ButtonUI ui = getUI();
// if (ui instanceof BasicRadioButtonUI) {
// icon = ((BasicRadioButtonUI) ui).getDefaultIcon();
// } else if (ui instanceof SynthButtonUI) {
// //icon = ((SynthButtonUI) ui).getDefaultIcon(this);
// SynthContext context = ((SynthButtonUI) ui).getContext(this);
// icon = context.getStyle().getIcon(context, "CheckBox.icon");
// //context.dispose();
// } else {
// icon = getIcon();
// if (Objects.nonNull(icon)) {
// // layout the text and icon
// int width = getWidth();
// int height = getHeight();
// FontMetrics fm = getFontMetrics(getFont());
// Insets i = getInsets();
// viewRect.setBounds(i.left, i.top, width - i.right - i.left, height - i.bottom - i.top);
// textRect.setBounds(0, 0, 0, 0);
// iconRect.setBounds(0, 0, 0, 0);
// SwingUtilities.layoutCompoundLabel(
// this, fm, getText(), icon,
// getVerticalAlignment(), getHorizontalAlignment(),
// getVerticalTextPosition(), getHorizontalTextPosition(),
// viewRect, iconRect, textRect,
// getIconTextGap());
// return iconRect.contains(x, y);
// } else {
// return super.contains(x, y);
// @Override public void updateUI() {
// super.updateUI();
// setOpaque(false);
// setFocusable(false);
// setTabComponentAt(getTabCount() - 1, check);
JCheckBox check = new JCheckBox();
check.setOpaque(false);
check.setFocusable(false);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
p.setOpaque(false);
p.add(check, BorderLayout.WEST);
p.add(new JLabel(title));
setTabComponentAt(getTabCount() - 1, p);
}
};
tabs.addTab("JTree", new JScrollPane(new JTree()));
tabs.addTab("JLabel", new JLabel("aaaaaaaaaaaaa"));
JButton button = new JButton("Add");
button.addActionListener(e -> addTab(tabs));
add(tabs);
add(button, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
protected void addTab(JTabbedPane tabs) {
JComponent c = count % 2 == 0 ? new JTree() : new JLabel("Tab" + count);
tabs.addTab("Title" + count, c);
tabs.setSelectedIndex(tabs.getTabCount() - 1);
count++;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.Objects;
import java.util.stream.IntStream;
import javax.swing.*;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.plaf.basic.BasicRadioButtonUI;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.text.View;
public final class MainPanel extends JPanel {
private static final LinkViewRadioButtonUI LINKVIEW_RADIOBUTTON_UI = new LinkViewRadioButtonUI();
private static final int LR_PAGE_SIZE = 5;
private final Box box = Box.createHorizontalBox();
private final String[] columnNames = {"Year", "String", "Comment"};
private final DefaultTableModel model = new DefaultTableModel(null, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return column == 0 ? Integer.class : Object.class;
}
};
private final transient TableRowSorter<? extends TableModel> sorter = new TableRowSorter<>(model);
private MainPanel() {
super(new BorderLayout());
JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension());
table.setShowGrid(false);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.setRowSorter(sorter);
IntStream.rangeClosed(1, 2016)
.mapToObj(i -> new Object[] {i, "Test: " + i, i % 2 == 0 ? "" : "comment..."})
.forEach(model::addRow);
initLinkBox(100, 1);
box.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
add(box, BorderLayout.NORTH);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
private void initLinkBox(int itemsPerPage, int currentPageIndex) {
// assert currentPageIndex > 0;
sorter.setRowFilter(new RowFilter<TableModel, Integer>() {
@Override public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
int ti = currentPageIndex - 1;
int ei = entry.getIdentifier();
return ti * itemsPerPage <= ei && ei < ti * itemsPerPage + itemsPerPage;
}
});
int startPageIndex = currentPageIndex - LR_PAGE_SIZE;
if (startPageIndex <= 0) {
startPageIndex = 1;
}
// #if 0 // BUG
// int maxPageIndex = (model.getRowCount() / itemsPerPage) + 1;
// #else
/* "maxPageIndex" gives one blank page if the module of the division is not zero.
* pointed out by erServi
* e.g. rowCount=100, maxPageIndex=100
*/
int rowCount = model.getRowCount();
int v = rowCount % itemsPerPage == 0 ? 0 : 1;
int maxPageIndex = rowCount / itemsPerPage + v;
// #endif
int endPageIndex = currentPageIndex + LR_PAGE_SIZE - 1;
if (endPageIndex > maxPageIndex) {
endPageIndex = maxPageIndex;
}
box.removeAll();
if (startPageIndex >= endPageIndex) {
// if I only have one page, Y don't want to see pagination buttons
// suggested by erServi
return;
}
ButtonGroup bg = new ButtonGroup();
JRadioButton f = makePrevNextRadioButton(itemsPerPage, 1, "|<", currentPageIndex > 1);
box.add(f);
bg.add(f);
JRadioButton p = makePrevNextRadioButton(itemsPerPage, currentPageIndex - 1, "<", currentPageIndex > 1);
box.add(p);
bg.add(p);
box.add(Box.createHorizontalGlue());
for (int i = startPageIndex; i <= endPageIndex; i++) {
JRadioButton c = makeRadioButton(itemsPerPage, currentPageIndex, i);
box.add(c);
bg.add(c);
}
box.add(Box.createHorizontalGlue());
JRadioButton n = makePrevNextRadioButton(itemsPerPage, currentPageIndex + 1, ">", currentPageIndex < maxPageIndex);
box.add(n);
bg.add(n);
JRadioButton l = makePrevNextRadioButton(itemsPerPage, maxPageIndex, ">|", currentPageIndex < maxPageIndex);
box.add(l);
bg.add(l);
box.revalidate();
box.repaint();
}
private JRadioButton makeRadioButton(int itemsPerPage, int current, int target) {
JRadioButton radio = new JRadioButton(Objects.toString(target)) {
@Override protected void fireStateChanged() {
ButtonModel bm = getModel();
if (bm.isEnabled()) {
if (bm.isPressed() && bm.isArmed()) {
setForeground(Color.GREEN);
} else if (bm.isSelected()) {
setForeground(Color.RED);
}
// } else if (isRolloverEnabled() && bm.isRollover()) {
// setForeground(Color.BLUE);
} else {
setForeground(Color.GRAY);
}
super.fireStateChanged();
}
};
radio.setForeground(Color.BLUE);
radio.setUI(LINKVIEW_RADIOBUTTON_UI);
if (target == current) {
radio.setSelected(true);
}
radio.addActionListener(e -> initLinkBox(itemsPerPage, target));
return radio;
}
private JRadioButton makePrevNextRadioButton(int itemsPerPage, int target, String title, boolean flag) {
JRadioButton radio = new JRadioButton(title);
radio.setForeground(Color.BLUE);
radio.setUI(LINKVIEW_RADIOBUTTON_UI);
radio.setEnabled(flag);
radio.addActionListener(e -> initLinkBox(itemsPerPage, target));
return radio;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class LinkViewRadioButtonUI extends BasicRadioButtonUI {
// private static final LinkViewRadioButtonUI radioButtonUI = new LinkViewRadioButtonUI();
// private boolean defaults_initialized = false;
private static final Rectangle VIEW_RECT = new Rectangle();
private static final Rectangle ICON_RECT = new Rectangle();
private static final Rectangle TEXT_RECT = new Rectangle();
// public static ComponentUI createUI(JComponent b) {
// return radioButtonUI;
// @Override protected void installDefaults(AbstractButton b) {
// super.installDefaults(b);
// if (!defaults_initialized) {
// icon = null; // UIManager.getIcon(getPropertyPrefix() + "icon");
// defaults_initialized = true;
// @Override protected void uninstallDefaults(AbstractButton b) {
// super.uninstallDefaults(b);
// defaults_initialized = false;
@Override public Icon getDefaultIcon() {
return null;
}
// [UnsynchronizedOverridesSynchronized]
// Unsynchronized method paint overrides synchronized method in BasicRadioButtonUI
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
@Override public synchronized void paint(Graphics g, JComponent c) {
if (!(c instanceof AbstractButton)) {
return;
}
AbstractButton b = (AbstractButton) c;
Font f = b.getFont();
g.setFont(f);
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.fillRect(0, 0, c.getWidth(), c.getHeight());
}
SwingUtilities.calculateInnerArea(c, VIEW_RECT);
ICON_RECT.setBounds(0, 0, 0, 0);
TEXT_RECT.setBounds(0, 0, 0, 0);
String text = SwingUtilities.layoutCompoundLabel(
c, c.getFontMetrics(f), b.getText(), null, // altIcon != null ? altIcon : getDefaultIcon(),
b.getVerticalAlignment(), b.getHorizontalAlignment(),
b.getVerticalTextPosition(), b.getHorizontalTextPosition(), VIEW_RECT, ICON_RECT, TEXT_RECT,
0); // b.getText() == null ? 0 : b.getIconTextGap());
// // Changing Component State During Painting (an infinite repaint loop)
// // pointed out by Peter
// // note: http://today.java.net/pub/a/today/2007/08/30/debugging-swing.html#changing-component-state-during-the-painting
// // b.setForeground(Color.BLUE);
// if (!model.isEnabled()) {
// // b.setForeground(Color.GRAY);
// } else if (model.isPressed() && model.isArmed() || model.isSelected()) {
// // b.setForeground(Color.BLACK);
// } else if (b.isRolloverEnabled() && model.isRollover()) {
ButtonModel model = b.getModel();
g.setColor(c.getForeground());
if (!model.isSelected() && !model.isPressed() && !model.isArmed() && b.isRolloverEnabled() && model.isRollover()) {
int vy = VIEW_RECT.y + VIEW_RECT.height;
g.drawLine(VIEW_RECT.x, vy, VIEW_RECT.x + VIEW_RECT.width, vy);
}
View v = (View) c.getClientProperty(BasicHTML.propertyKey);
if (Objects.nonNull(v)) {
v.paint(g, TEXT_RECT);
} else {
paintText(g, c, TEXT_RECT, text);
}
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.geom.*;
import java.util.Objects;
import javax.swing.*;
import javax.swing.border.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
Box box = Box.createVerticalBox();
box.add(new TitledSeparator("TitledBorder", 2, TitledBorder.DEFAULT_POSITION));
box.add(new JCheckBox("JCheckBox 0"));
box.add(new JCheckBox("JCheckBox 1"));
box.add(Box.createVerticalStrut(10));
box.add(new TitledSeparator("TitledBorder ABOVE TOP", new Color(100, 180, 200), 2, TitledBorder.ABOVE_TOP));
box.add(new JCheckBox("JCheckBox 2"));
box.add(new JCheckBox("JCheckBox 3"));
box.add(Box.createVerticalStrut(10));
box.add(new JSeparator());
box.add(new JCheckBox("JCheckBox 4"));
box.add(new JCheckBox("JCheckBox 5"));
//box.add(Box.createVerticalStrut(8));
add(box, BorderLayout.NORTH);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TitledSeparator extends JLabel {
private final String title;
private final Color target;
private final int height;
private final int titlePosition;
protected TitledSeparator(String title, int height, int titlePosition) {
this(title, null, height, titlePosition);
}
protected TitledSeparator(String title, Color target, int height, int titlePosition) {
super();
this.title = title;
this.target = target;
this.height = height;
this.titlePosition = titlePosition;
updateBorder();
}
private void updateBorder() {
Icon icon = new TitledSeparatorIcon();
setBorder(BorderFactory.createTitledBorder(
BorderFactory.createMatteBorder(height, 0, 0, 0, icon), title,
TitledBorder.DEFAULT_JUSTIFICATION, titlePosition));
}
@Override public Dimension getMaximumSize() {
Dimension d = super.getPreferredSize();
d.width = Short.MAX_VALUE;
return d;
}
@Override public void updateUI() {
super.updateUI();
updateBorder();
}
private class TitledSeparatorIcon implements Icon {
private int width = -1;
private Paint painter1;
private Paint painter2;
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
int w = c.getWidth();
Color color = getBackground();
if (w != width || Objects.isNull(painter1) || Objects.isNull(painter2)) {
width = w;
Point2D start = new Point2D.Float(0f, 0f);
Point2D end = new Point2D.Float((float) width, 0f);
float[] dist = {0f, 1f};
color = Objects.nonNull(color) ? color : UIManager.getColor("Panel.background");
Color tc = Objects.nonNull(target) ? target : color;
painter1 = new LinearGradientPaint(start, end, dist, new Color[] {tc.darker(), color});
painter2 = new LinearGradientPaint(start, end, dist, new Color[] {tc.brighter(), color});
}
int h = getIconHeight() / 2;
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(painter1);
g2.fillRect(x, y, width, getIconHeight());
g2.setPaint(painter2);
g2.fillRect(x, y + h, width, getIconHeight() - h);
g2.dispose();
}
@Override public int getIconWidth() {
return 200; //dummy width
}
@Override public int getIconHeight() {
return height;
}
}
}
|
package com.badlogic.gdx.utils;
import com.badlogic.gdx.math.Vector2;
/** @author Nathan Sweet */
public enum Scaling {
/** Scales the source to fit the target while keeping the same aspect ratio. This may cause the source to be smaller than the
* target in one direction. */
fit,
/** Scales the source to fill the target while keeping the same aspect ratio. This may cause the source to be larger than the
* target in one direction. */
fill,
/** Scales the source to fill the target in the x direction while keeping the same aspect ratio. This may cause the source to be
* smaller or larger than the target in the y direction. */
fillX,
/** Scales the source to fill the target in the y direction while keeping the same aspect ratio. This may cause the source to be
* smaller or larger than the target in the x direction. */
fillY,
/** Scales the source to fill the target. This may cause the source to not keep the same aspect ratio. */
stretch,
/** Scales the source to fill the target in the x direction, without changing the y direction. This may cause the source to not
* keep the same aspect ratio. */
stretchX,
/** Scales the source to fill the target in the y direction, without changing the x direction. This may cause the source to not
* keep the same aspect ratio. */
stretchY,
/** The source is not scaled. */
none;
static private Vector2 temp = new Vector2();
/** Returns the size of the source scaled to the target. Note the same Vector2 instance is always returned and should never be
* cached. */
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
switch (this) {
case fit: {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio > sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
break;
}
case fill: {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio < sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
break;
}
case fillX: {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetWidth / sourceWidth;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
break;
}
case fillY: {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
break;
}
case stretch:
temp.x = targetWidth;
temp.y = targetHeight;
break;
case stretchX:
temp.x = targetWidth;
temp.y = sourceHeight;
break;
case stretchY:
temp.x = sourceWidth;
temp.y = targetHeight;
break;
case none:
temp.x = sourceWidth;
temp.y = sourceHeight;
break;
}
return temp;
}
}
|
import java.util.*;
/*
*
Commands: L,4
Commands: L,4
Commands: L,6
Commands: R,10
Commands: L,6
= A
Commands: L,4
Commands: L,4
Commands: L,6
Commands: R,10
Commands: L,6
= A
Commands: L,12
Commands: L,6
Commands: R,10
Commands: L,6
= B
Commands: R,8
Commands: R,10
Commands: L,6
= C
Commands: R,8
Commands: R,10
Commands: L,6
= C
Commands: L,4
Commands: L,4
Commands: L,6
Commands: R,10
Commands: L,6
= A
Commands: R,8
Commands: R,10
Commands: L,6
= C
Commands: L,12
Commands: L,6
Commands: R,10
Commands: L,6
= B
Commands: R,8
Commands: R,10
Commands: L,6
= C
Commands: L,12
Commands: L,6
Commands: R,10
Commands: L,6
= B
*/
public class FunctionRoutine
{
public static final int NUMBER_OF_FUNCTIONS = 3;
public static final int ROUTINE_A = 0;
public static final int ROUTINE_B = 1;
public static final int ROUTINE_C = 2;
public static final int MAX_CHARACTERS = 20;
public FunctionRoutine (Stack<String> pathTaken, boolean debug)
{
_path = pathTaken;
_functions = null;
/*
* Now convert the path into a series of commands
* such as L,4 or R,8.
*/
_commands = getCommands();
_debug = debug;
}
public Vector<MovementRoutine> createMovementFunctions ()
{
/*
* Now turn the series of commands into functions
* A, B and C based on repeated commands.
*
* There are only 3 possible functions.
*
* This means one function always starts at the beginning.
*
* One function always ends at the ending (!) assuming it's not a repeat
* of the first.
*
* Then using both the first and the last fragment to find the third
* and split the entire sequence into functions.
*/
String fullCommand = "";
for (int i = _commands.size() -1; i >= 0; i
{
fullCommand += _commands.elementAt(i);
}
System.out.println("Full command "+fullCommand);
/*
* Find repeated strings. Assume minimum of 2 commands.
*/
String str = fullCommand;
_functions = new Vector<MovementRoutine>();
System.out.println("fullCommand length "+fullCommand.length());
System.out.println("search string is "+str);
MovementRoutine func = getFirstMovementRoutine(str, 2);
System.out.println("First function is "+func+"\n");
if (func != null)
{
int commandStart = func.numberOfCommands();
int beginIndex = func.getLength();
str = fullCommand.substring(beginIndex);
func = getLastMovementRoutine(str, 2);
System.out.println("Last function is "+func+"\n");
System.exit(0);
if (func != null)
{
int endIndex = fullCommand.length() - func.getLength();
int commandEnd = func.numberOfCommands();
str = fullCommand.substring(beginIndex, endIndex);
func = getMovementRoutine(str, commandStart, commandEnd, 2);
}
}
return _functions;
}
/*
* Return the first repeating function.
*
* fullCommand is the String to search.
* startingCommand is the command from which to begin the search.
* numberOfCommands is the number of commands to pull together.
*/
private MovementRoutine getFirstMovementRoutine (String commandString, int numberOfCommands)
{
System.out.println("getFirstMovementRoutine searching "+commandString+" with "+numberOfCommands+" number of commands");
MovementRoutine routine = getMovementRoutine(commandString, 0, _commands.size(), numberOfCommands);
System.out.println("**got back "+routine);
if (routine == null)
{
System.out.println("Error - no repeating function!");
return null;
}
else
{
/*
* Is this a unique function? If so, add it to
* the list.
*/
if (!_functions.contains(routine))
_functions.add(routine);
return routine;
}
}
private MovementRoutine getLastMovementRoutine (String commandString, int numberOfCommands)
{
System.out.println("getLastMovementRoutine searching "+commandString+" with "+numberOfCommands+" number of commands");
MovementRoutine routine = findLastRepeatRoutine(commandString, numberOfCommands);
System.out.println("**got back "+routine);
if (routine == null)
{
System.out.println("Error - no repeating function!");
return null;
}
else
{
/*
* Is this a unique function? If so, add it to
* the list.
*/
if (!_functions.contains(routine))
_functions.add(routine);
return routine;
}
}
private MovementRoutine getMovementRoutine (String commandString, int startingCommand, int endCommand, int numberOfCommands)
{
System.out.println("getUniqueFunction searching "+commandString+" with "+numberOfCommands+" number of commands");
MovementRoutine routine = findRepeatRoutine(commandString, startingCommand, endCommand, numberOfCommands);
System.out.println("**got back "+routine);
if (routine == null)
{/*
String repeat = getRemainingRoutine(startingCommand);
routine = new MovementRoutine(repeat, _commands.size() - startingCommand);
*
* Not a repeat but maybe it's part of an existing function? Or maybe
* an existing routine is within the String?
*
Vector<MovementRoutine> embedded = findEmbeddedRoutine(routine);
System.out.println("After checking, commands used "+routine.numberOfCommands());
if (routine.numberOfCommands() > 0)
{
routine = findRoutineFromPartial(routine);
}
else
routine = embedded.elementAt(embedded.size() -1); // the last entry;
return routine;*/
return null;
}
else
{
/*
* Is this a unique function? If so, add it to
* the list.
*/
if (!_functions.contains(routine))
_functions.add(routine);
return routine;
}
}
private Vector<MovementRoutine> findEmbeddedRoutine (MovementRoutine toCheck)
{
Vector<MovementRoutine> toReturn = new Vector<MovementRoutine>();
Enumeration<MovementRoutine> iter = _functions.elements();
while (iter.hasMoreElements())
{
MovementRoutine temp = iter.nextElement();
if (toCheck.containsRoutine(temp)) // since no duplicates we know this can only happen once per function
{
toCheck.removeRoutine(temp); // update the routine contents along the way
System.out.println("Found embedded routine "+temp);
System.out.println("Remaining "+toCheck);
}
}
return toReturn;
}
private MovementRoutine findRepeatRoutine (String commandString, int startingCommand, int endCommand, int numberOfCommands)
{
System.out.println("findRoutine searching "+commandString+" with "+numberOfCommands+" number of commands");
if (numberOfCommands < (startingCommand + endCommand))
{
String repeat = getCommandString(startingCommand, numberOfCommands);
if (commandString.indexOf(repeat, repeat.length()) != -1) // it repeats so try another command
{
System.out.println("Repeat: "+repeat);
MovementRoutine next = findRepeatRoutine(commandString, startingCommand, endCommand, numberOfCommands +1);
if (next == null)
return new MovementRoutine(repeat, numberOfCommands);
else
return next;
}
else
System.out.println("Does not repeat: "+repeat);
}
return null;
}
private String getCommandString (int start, int numberOfCommands)
{
String str = "";
System.out.println("getCommandString starting command "+start+" and number "+numberOfCommands);
for (int i = start; i < (start + numberOfCommands); i++)
{
int commandNumber = _commands.size() - 1 - i;
System.out.println("Adding command "+commandNumber);
str += _commands.elementAt(commandNumber);
}
System.out.println("**Command string created: "+str);
return str;
}
private MovementRoutine findLastRepeatRoutine (String commandString, int numberOfCommands)
{
System.out.println("findLastRoutine searching "+commandString+" with "+numberOfCommands+" commands");
String repeat = getLastCommandString(numberOfCommands);
if (commandString.indexOf(repeat, repeat.length()) != -1) // it repeats so try another command
{
System.out.println("Repeat: "+repeat);
MovementRoutine next = findLastRepeatRoutine(commandString, numberOfCommands +1);
if (next == null)
return new MovementRoutine(repeat, numberOfCommands);
else
return next;
}
else
System.out.println("Does not repeat: "+repeat);
return null;
}
private String getLastCommandString (int numberOfCommands)
{
String str = "";
System.out.println("getLastCommandString using "+numberOfCommands+" commands");
for (int i = numberOfCommands -1; i >= 0; i
{
System.out.println("Adding command "+i);
str += _commands.elementAt(i);
}
System.out.println("**Last command string created: "+str);
return str;
}
private Vector<String> getCommands ()
{
Vector<String> commands = new Vector<String>(_path.size());
String pathElement = null;
/*
* Pop the track to reverse it and get commands from the
* starting position.
*/
do
{
try
{
pathElement = _path.pop();
String str = pathElement.charAt(0)+","+pathElement.length();
commands.add(str);
}
catch (Exception ex)
{
pathElement = null;
}
} while (pathElement != null);
if (_debug)
{
for (int i = commands.size() -1; i >= 0; i
{
System.out.println("Commands: "+commands.elementAt(i));
}
}
return commands;
}
private Stack<String> _path;
private Vector<MovementRoutine>_functions;
private Vector<String> _commands;
private boolean _debug;
}
|
package am.tools.seals;
import java.net.URI;
import java.util.ArrayList;
import javax.jws.WebService;
import javax.swing.SwingWorker.StateValue;
import eu.sealsproject.omt.ws.matcher.AlignmentWS;
import am.GlobalStaticVariables;
import am.app.Core;
import am.app.mappingEngine.AbstractMatcher;
import am.app.mappingEngine.AbstractMatcherParametersPanel;
import am.app.mappingEngine.AbstractParameters;
import am.app.mappingEngine.MatcherFactory;
import am.app.mappingEngine.MatchersRegistry;
import am.app.ontology.ontologyParser.OntoTreeBuilder;
import am.output.AlignmentOutput;
import am.userInterface.MatchingProgressDisplay;
/**
* This class handles the align requests from the published Endpoint.
* @author cosmin
*
*/
@WebService(endpointInterface="eu.sealsproject.omt.ws.matcher.AlignmentWS")
public class SealsServer implements AlignmentWS {
// private AbstractMatcher matcher;
private MatchersRegistry matcherRegistry;
private MatchingProgressDisplay progressDisplay;
private double threshold;
private int sourceRelations;
private int targetRelations;
private AbstractParameters parameters;
public SealsServer( MatchersRegistry mR, MatchingProgressDisplay pD, double th, int sourceR, int targetR, AbstractParameters params ) {
matcherRegistry = mR;
progressDisplay = pD;
threshold = th;
sourceRelations = sourceR;
targetRelations = targetR;
parameters = params;
}
@Override
public String align(URI source, URI target) {
// 0. Instantiate the matcher.
AbstractMatcher m = MatcherFactory.getMatcherInstance(matcherRegistry, Core.getInstance().getMatcherInstances().size());
m.setProgressDisplay(progressDisplay);
m.setThreshold(threshold);
m.setMaxSourceAlign(sourceRelations);
m.setMaxTargetAlign(targetRelations);
// 1. Load ontologies.
progressDisplay.appendToReport("Loading source ontology. URI: " + source + "\n");
OntoTreeBuilder otb1 = new OntoTreeBuilder(".", GlobalStaticVariables.SOURCENODE, GlobalStaticVariables.LANG_OWL, "RDF/XML", true, false);
otb1.setURI(source.toString());
progressDisplay.appendToReport("Building source Ontology().\n");
otb1.build( OntoTreeBuilder.Profile.noReasoner );
m.setSourceOntology( otb1.getOntology() );
progressDisplay.appendToReport("Sucessfully loaded source ontology.\n");
progressDisplay.appendToReport("Loading target ontology. URI: " + target + "\n");
OntoTreeBuilder otb2 = new OntoTreeBuilder( ".", GlobalStaticVariables.TARGETNODE, GlobalStaticVariables.LANG_OWL, "RDF/XML", true, false);
otb2.setURI(target.toString());
progressDisplay.appendToReport("Building target Ontology().\n");
otb2.build( OntoTreeBuilder.Profile.noReasoner );
m.setTargetOntology( otb2.getOntology() );
progressDisplay.appendToReport("Sucessfully loaded target ontology.\n");
// 2. Run the matcher.
try {
m.match();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
progressDisplay.appendToReport( e.getMessage() + "\n");
progressDisplay.appendToReport("Exception has been thrown, stopping matcher.\n");
m.cancel(true);
return "";
}
// 3. Parse the alignment set into OAEI format.
AlignmentOutput output = new AlignmentOutput(m.getAlignmentSet());
String sourceUri = m.getSourceOntology().getURI();
String targetUri = m.getTargetOntology().getURI();
String alignment = output.compileString(sourceUri, targetUri, sourceUri, targetUri);
// debugging
progressDisplay.appendToReport(alignment + "\n");
// 3. Return the parsed alignment.
return alignment;
}
}
|
package com.rgi.geopackage.tiles;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import utility.DatabaseUtility;
import com.rgi.common.BoundingBox;
import com.rgi.common.util.jdbc.ResultSetStream;
import com.rgi.geopackage.core.GeoPackageCore;
import com.rgi.geopackage.verification.Assert;
import com.rgi.geopackage.verification.AssertionError;
import com.rgi.geopackage.verification.ColumnDefinition;
import com.rgi.geopackage.verification.ForeignKeyDefinition;
import com.rgi.geopackage.verification.Requirement;
import com.rgi.geopackage.verification.Severity;
import com.rgi.geopackage.verification.TableDefinition;
import com.rgi.geopackage.verification.VerificationLevel;
import com.rgi.geopackage.verification.Verifier;
/**
* @author Jenifer Cochran
*
*/
public class TilesVerifier extends Verifier
{
/**
* This Epsilon is the greatest difference we allow when comparing doubles
*/
public static final double EPSILON = 0.0001;
/**
* @param sqliteConnection
* the connection to the database
* @param verificationLevel
* Controls the level of verification testing performed
* @throws SQLException
* throws if the method {@link DatabaseUtility#tableOrViewExists(Connection, String) tableOrViewExists} throws
*/
public TilesVerifier(final Connection sqliteConnection, final VerificationLevel verificationLevel) throws SQLException
{
super(sqliteConnection, verificationLevel);
final String queryTables = "SELECT tbl_name FROM sqlite_master " +
"WHERE tbl_name NOT LIKE 'gpkg_%' " +
"AND (type = 'table' OR type = 'view');";
try(PreparedStatement createStmt = this.getSqliteConnection().prepareStatement(queryTables);
ResultSet possiblePyramidTables = createStmt.executeQuery();)
{
this.allPyramidUserDataTables = ResultSetStream.getStream(possiblePyramidTables)
.map(resultSet ->
{ try
{
final TableDefinition possiblePyramidTable = new TilePyramidUserDataTableDefinition(resultSet.getString("tbl_name"));
this.verifyTable(possiblePyramidTable);
return possiblePyramidTable.getName();
}
catch(final SQLException | AssertionError ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.allPyramidUserDataTables = Collections.emptySet();
}
final String query2 = String.format("SELECT table_name FROM %s WHERE data_type = 'tiles';", GeoPackageCore.ContentsTableName);
try(PreparedStatement createStmt2 = this.getSqliteConnection().prepareStatement(query2);
ResultSet contentsPyramidTables = createStmt2.executeQuery())
{
this.pyramidTablesInContents = ResultSetStream.getStream(contentsPyramidTables)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.pyramidTablesInContents = Collections.emptySet();
}
final String query3 = String.format("SELECT DISTINCT table_name FROM %s;", GeoPackageTiles.MatrixTableName);
try(PreparedStatement createStmt3 = this.getSqliteConnection().prepareStatement(query3);
ResultSet tileMatrixPyramidTables = createStmt3.executeQuery())
{
this.pyramidTablesInTileMatrix = ResultSetStream.getStream(tileMatrixPyramidTables)
.map(resultSet -> { try
{
final String pyramidName = resultSet.getString("table_name");
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(),
pyramidName) ? pyramidName
: null;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
catch(final SQLException ex)
{
this.pyramidTablesInTileMatrix = Collections.emptySet();
}
this.hasTileMatrixSetTable = this.tileMatrixSetTableExists();
this.hasTileMatrixTable = this.tileMatrixTableExists();
}
/**
* Requirement 33
*
* <blockquote>
* The <code>gpkg_contents</code> table SHALL contain a row with
* a <code>data_type</code> column value of 'tiles' for each
* tile pyramid user data table or view.
* </blockquote>
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(number = 33,
text = "The gpkg_contents table SHALL contain a row with a "
+ "data_type column value of \"tiles\" for each "
+ "tile pyramid user data table or view.",
severity = Severity.Warning)
public void Requirement33() throws AssertionError
{
for(final String tableName: this.allPyramidUserDataTables)
{
Assert.assertTrue(String.format("The Tile Pyramid User Data table that is not refrenced in gpkg_contents table is: %s. "
+ "This table needs to be referenced in the gpkg_contents table.", tableName),
this.pyramidTablesInContents.contains(tableName));
}
}
/**
* Requirement 34
*
* <blockquote>
* In a GeoPackage that contains a tile pyramid user data table
* that contains tile data, by default, zoom level pixel sizes
* for that table SHALL vary by a factor of 2 between adjacent
* zoom levels in the tile matrix metadata table.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement(number = 34,
text = "In a GeoPackage that contains a tile pyramid user data table"
+ "that contains tile data, by default, zoom level pixel sizes for that "
+ "table SHALL vary by a factor of 2 between zoom levels in tile matrix metadata table.",
severity = Severity.Warning)
public void Requirement34() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for (final String tableName : this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT table_name, "
+ "zoom_level, "
+ "pixel_x_size, "
+ "pixel_y_size,"
+ "matrix_width,"
+ "matrix_height,"
+ "tile_width,"
+ "tile_height "
+ "FROM %s "
+ "WHERE table_name = '?' "
+ "ORDER BY zoom_level ASC;", GeoPackageTiles.MatrixTableName);
try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1))
{
stmt.setString(1, tableName);
try(ResultSet pixelInfo = stmt.executeQuery())
{
final List<TileData> tileDataSet = ResultSetStream.getStream(pixelInfo)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.pixelXSize = resultSet.getDouble("pixel_x_size");
tileData.pixelYSize = resultSet.getDouble("pixel_y_size");
tileData.zoomLevel = resultSet.getInt("zoom_level");
tileData.matrixHeight = resultSet.getInt("matrix_height");
tileData.matrixWidth = resultSet.getInt("matrix_width");
tileData.tileHeight = resultSet.getInt("tile_height");
tileData.tileWidth = resultSet.getInt("tile_width");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
for(int index = 0; index < tileDataSet.size()-1; ++index)
{
final TileData current = tileDataSet.get(index);
final TileData next = tileDataSet.get(index + 1);
if(current.zoomLevel == next.zoomLevel - 1)
{
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not vary by factors of 2"
+ " between adjacent zoom levels in the tile matrix metadata table: %f, %f",
next.pixelXSize,
next.pixelYSize),
TilesVerifier.isEqual((current.pixelXSize / 2.0), next.pixelXSize) &&
TilesVerifier.isEqual((current.pixelYSize / 2.0), next.pixelYSize));
}
}
//TODO Test will be moved on later release//This tests if the pixel x values and pixel y values are valid based on their bounding box in the tile matrix set
if(this.hasTileMatrixSetTable)
{
final String query2 = String.format("SELECT min_x, min_y, max_x, max_y FROM %s WHERE table_name = '%s'",
GeoPackageTiles.MatrixSetTableName,
tableName);
try(Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet boundingBoxRS = stmt2.executeQuery(query2))
{
if(boundingBoxRS.next())
{
final double minX = boundingBoxRS.getDouble("min_x");
final double minY = boundingBoxRS.getDouble("min_y");
final double maxX = boundingBoxRS.getDouble("max_x");
final double maxY = boundingBoxRS.getDouble("max_y");
final BoundingBox boundingBox = new BoundingBox(minX, minY, maxX, maxY);
final List<TileData> invalidPixelValues = tileDataSet.stream()
.filter(tileData -> !validPixelValues(tileData, boundingBox))
.collect(Collectors.toList());
Assert.assertTrue(String.format("Based on the bounding box given in the Tile Matrix Set for tiles table %s, "
+ "tile_height, "
+ "tile_width, "
+ "matrix_width, and "
+ "matrix_height, "
+ "the following pixel values are invalid.\n%s",
tableName,
invalidPixelValues.stream()
.map(tileData -> String.format("Invalid pixel_x_size: %f, Invalid pixel_y_size: %f at zoom_level %d",
tileData.pixelXSize,
tileData.pixelYSize,
tileData.zoomLevel))
.collect(Collectors.joining("\n"))),
invalidPixelValues.isEmpty());
}
}
}
}
}
}
}
}
@Requirement(number = 35,
text = "In a GeoPackage that contains a tile pyramid user data table that contains tile data SHALL store that tile data in MIME type image/jpeg or image/png",
severity = Severity.Warning)
public void Requirement35() throws AssertionError
{
Assert.assertTrue("Test skipped when verification level is not set to " + VerificationLevel.Full,
this.verificationLevel == VerificationLevel.Full);
final Collection<ImageReader> jpegImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/jpeg"));
final Collection<ImageReader> pngImageReaders = TilesVerifier.iteratorToCollection(ImageIO.getImageReadersByMIMEType("image/png"));
for (final String tableName : this.allPyramidUserDataTables)
{
final String selectTileDataQuery = String.format("SELECT tile_data, id FROM ?;");
try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(selectTileDataQuery))
{
stmt.setString(1, tableName);
try(ResultSet tileDataResultSet = stmt.executeQuery())
{
final Map<Integer, byte[]> allTileData = ResultSetStream.getStream(tileDataResultSet)
.map(resultSet -> { try
{
final int tileId = resultSet.getInt("id");
final byte[] tileData = resultSet.getBytes("tile_data");
return new AbstractMap.SimpleImmutableEntry<>(tileId, tileData);
}
catch (final Exception ex1)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toMap(entry -> entry.getKey(),
entry -> entry.getValue()));
for(final Integer imageID : allTileData.keySet())
{
try(ByteArrayInputStream byteArray = new ByteArrayInputStream(allTileData.get(imageID));
MemoryCacheImageInputStream cacheImage = new MemoryCacheImageInputStream(byteArray))
{
Assert.assertTrue(String.format("The tile id: %d in the table: %s is not in the correct format. The image must be of MIME type image/jpeg or image/png.",
imageID,
tableName),
TilesVerifier.canReadImage(pngImageReaders, cacheImage) ||
TilesVerifier.canReadImage(jpegImageReaders, cacheImage));
}
catch(final IOException ex)
{
Assert.fail(ex.getMessage());
}
}
}
}
catch (final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
@Requirement(number = 36,
text = "In a GeoPackage that contains a tile pyramid user data table that "
+ "contains tile data that is not MIME type image png, "
+ "by default SHALL store that tile data in MIME type image jpeg",
severity = Severity.Warning)
public void Requirement36()
{
// This requirement is tested through Requirement 35 test in TilesVerifier.
}
@Requirement(number = 37,
text = "A GeoPackage that contains a tile pyramid user data table SHALL "
+ "contain gpkg_tile_matrix_set table or view per Table Definition, "
+ "Tile Matrix Set Table or View Definition and gpkg_tile_matrix_set Table Creation SQL. ",
severity = Severity.Error)
public void Requirement37() throws AssertionError, SQLException
{
if(!this.allPyramidUserDataTables.isEmpty())
{
Assert.assertTrue("The GeoPackage does not contain a gpkg_tile_matrix_set table. Every GeoPackage with a Pyramid User "
+ "Data Table must also have a gpkg_tile_matrix_set table.",
this.hasTileMatrixSetTable);
this.verifyTable(TilesVerifier.TileMatrixSetTableDefinition);
}
}
/**
* Requirement 38
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix_set</code> <code>table_name</code>
* column SHALL reference values in the gpkg_contents table_name column
* for rows with a data type of "tiles".
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(number = 38,
text = "Values of the gpkg_tile_matrix_set table_name column "
+ "SHALL reference values in the gpkg_contents table_name "
+ "column for rows with a data type of \"tiles\".",
severity = Severity.Warning)
public void Requirement38() throws AssertionError
{
if(this.hasTileMatrixSetTable)
{
final String queryMatrixSetPyramid = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName);
try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(queryMatrixSetPyramid);
ResultSet tileTablesInTileMatrixSet = stmt.executeQuery(queryMatrixSetPyramid))
{
final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch (final SQLException ex1)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final String table: this.pyramidTablesInContents)
{
Assert.assertTrue(String.format("The table_name %s in the gpkg_tile_matrix_set is not referenced in the gpkg_contents table. Either delete the table %s "
+ "or create a record for that table in the gpkg_contents table",
table,
table),
tileMatrixSetTables.contains(table));
}
}
catch (final Exception ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 39
*
* <blockquote>
* The gpkg_tile_matrix_set table or view SHALL contain one row record for each tile pyramid user data table.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(number = 39,
text = "The gpkg_tile_matrix_set table or view SHALL "
+ "contain one row record for each tile "
+ "pyramid user data table. ",
severity = Severity.Error)
public void Requirement39() throws AssertionError
{
if (this.hasTileMatrixSetTable)
{
final String queryMatrixSet = String.format("SELECT table_name FROM %s;", GeoPackageTiles.MatrixSetTableName);
try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(queryMatrixSet);
ResultSet tileTablesInTileMatrixSet = stmt.executeQuery())
{
final Set<String> tileMatrixSetTables = ResultSetStream.getStream(tileTablesInTileMatrixSet)
.map(resultSet -> { try
{
return resultSet.getString("table_name");
}
catch (final SQLException ex1)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final String table: this.allPyramidUserDataTables)
{
Assert.assertTrue(String.format("The Pyramid User Data Table %s is not referenced in the gpkg_tile_matrix_set.", table),
tileMatrixSetTables.contains(table));
}
}
catch (final Exception ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 40
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix_set </code> <code> srs_id</code> column
* SHALL reference values in the <code>gpkg_spatial_ref_sys </code> <code> srs_id</code> column.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 40,
text = "Values of the gpkg_tile_matrix_set srs_id column "
+ "SHALL reference values in the gpkg_spatial_ref_sys srs_id column. ",
severity = Severity.Error)
public void Requirement40() throws AssertionError
{
if(this.hasTileMatrixSetTable)
{
final String query1 = String.format("SELECT srs_id from %s AS tms " +
"WHERE srs_id NOT IN" +
"(SELECT srs_id " +
"FROM %s);",
GeoPackageTiles.MatrixSetTableName,
GeoPackageCore.SpatialRefSysTableName);
try (PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query1);
ResultSet unreferencedSRS = stmt.executeQuery())
{
if (unreferencedSRS.next())
{
Assert.fail(String.format("The gpkg_tile_matrix_set table contains a reference to an srs_id that is not defined in the gpkg_spatial_ref_sys Table. "
+ "Unreferenced srs_id: %s",
unreferencedSRS.getInt("srs_id")));
}
}
catch (final Exception ex)
{
Assert.fail(ex.getMessage());
}
}
}
@Requirement (number = 41,
text = "A GeoPackage that contains a tile pyramid user data table "
+ "SHALL contain a gpkg_tile_matrix table or view per clause "
+ "2.2.7.1.1 Table Definition, Table Tile Matrix Metadata Table "
+ "or View Definition and Table gpkg_tile_matrix Table Creation SQL. ",
severity = Severity.Error)
public void Requirement41() throws AssertionError, SQLException
{
if(!this.allPyramidUserDataTables.isEmpty())
{
Assert.assertTrue("The GeoPackage does not contain a gpkg_tile_matrix table. Every GeoPackage with a Pyramid User "
+ "Data Table must also have a gpkg_tile_matrix table.",
this.hasTileMatrixTable);
this.verifyTable(TilesVerifier.TileMatrixTableDefinition);
}
}
/**
* Requirement 42
*
* <blockquote>
* Values of the <code>gpkg_tile_matrix</code>
* <code>table_name</code> column SHALL reference
* values in the <code>gpkg_contents</code> <code>
* table_name</code> column for rows with a <code>
* data_type</code> of 'tiles'.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 42,
text = "Values of the gpkg_tile_matrix table_name column "
+ "SHALL reference values in the gpkg_contents table_name "
+ "column for rows with a data_type of 'tiles'. ",
severity = Severity.Warning)
public void Requirement42() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT table_name FROM %s AS tm " +
"WHERE table_name NOT IN" +
"(SELECT table_name " +
"FROM %s AS gc " +
"WHERE tm.table_name = gc.table_name AND gc.data_type = 'tiles');",
GeoPackageTiles.MatrixTableName,
GeoPackageCore.ContentsTableName);
try(PreparedStatement stmt = this.getSqliteConnection().prepareStatement(query);
ResultSet unreferencedTables = stmt.executeQuery())
{
if (unreferencedTables.next())
{
Assert.fail(String.format("There are Pyramid user data tables in gpkg_tile_matrix table_name field such that the table_name does not"
+ " reference values in the gpkg_contents table_name column for rows with a data type of 'tiles'."
+ " Unreferenced table: %s",
unreferencedTables.getString("table_name")));
}
}
catch (final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 43
*
* <blockquote>
* The <code>gpkg_tile_matrix</code> table or view SHALL contain one row record for
* each zoom level that contains one or more tiles in each tile pyramid user data table or view.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 43,
text = "The gpkg_tile_matrix table or view SHALL contain "
+ "one row record for each zoom level that contains "
+ "one or more tiles in each tile pyramid user data table or view. ",
severity = Severity.Error)
public void Requirement43() throws AssertionError
{
if(this.hasTileMatrixTable)
{
for (final String tableName : this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT DISTINCT zoom_level FROM gpkg_tile_matrix WHERE table_name ='?' ORDER BY zoom_level;", GeoPackageTiles.MatrixTableName);
final String query2 = String.format("SELECT DISTINCT zoom_level FROM ? ORDER BY zoom_level;");
// final String query1 = String.format("SELECT DISTINCT zoom_level FROM gpkg_tile_matrix WHERE table_name ='%s' ORDER BY zoom_level;", tableName);
// final String query2 = String.format("SELECT DISTINCT zoom_level FROM %s ORDER BY zoom_level;", tableName);
//TODO fix me!!!
try (PreparedStatement stmt1 = this.getSqliteConnection().prepareStatement(query1);
ResultSet gm_zoomLevels = stmt1.executeQuery();
PreparedStatement stmt2 = this.getSqliteConnection().prepareStatement(query2);
ResultSet py_zoomLevels = stmt2.executeQuery())
{
final Set<Integer> tileMatrixZooms = ResultSetStream.getStream(gm_zoomLevels)
.map(resultSet -> { try
{
return resultSet.getInt("zoom_level");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
final Set<Integer> tilePyramidZooms = ResultSetStream.getStream(py_zoomLevels)
.map(resultSet -> { try
{
return resultSet.getInt("zoom_level");
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toSet());
for(final Integer zoom: tilePyramidZooms)
{
Assert.assertTrue(String.format("The gpkg_tile_matrix does not contain a row record for zoom level %d in the Pyramid User Data Table %s.",
zoom,
tableName),
tileMatrixZooms.contains(zoom));
}
}
catch (final Exception ex)
{
Assert.fail(ex.getMessage());
}
}
}
}
/**
* Requirement 44
*
* <blockquote>
* The <code>zoom_level</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL not be negative.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 44,
text = "The zoom_level column value in a gpkg_tile_matrix table row SHALL not be negative." ,
severity = Severity.Error)
public void Requirement44() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = String.format("SELECT min(zoom_level) FROM gpkg_tile_matrix;");
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minZoom = stmt.executeQuery(query))
{
final int minZoomLevel = minZoom.getInt("min(zoom_level)");
if(!minZoom.wasNull())
{
Assert.assertTrue(String.format("The zoom_level in gpkg_tile_matrix must be greater than 0. Invalid zoom_level: %d", minZoomLevel),
minZoomLevel >= 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 45
*
* <blockquote>
* <code>matrix_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 45,
text = "The matrix_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.",
severity = Severity.Error)
public void Requirement45() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(matrix_width) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minMatrixWidthRS = stmt.executeQuery(query);)
{
final int minMatrixWidth = minMatrixWidthRS.getInt("min(matrix_width)");
if(!minMatrixWidthRS.wasNull())
{
Assert.assertTrue(String.format("The matrix_width in gpkg_tile_matrix must be greater than 0. Invalid matrix_width: %d", minMatrixWidth),
minMatrixWidth > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 46
*
* <blockquote>
* <code>matrix_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 46,
text = "The matrix_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.",
severity = Severity.Error)
public void Requirement46() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(matrix_height) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minMatrixHeightRS = stmt.executeQuery(query);)
{
final int minMatrixHeight = minMatrixHeightRS.getInt("min(matrix_height)");
if(!minMatrixHeightRS.wasNull())
{
Assert.assertTrue(String.format("The matrix_height in gpkg_tile_matrix must be greater than 0. Invalid matrix_height: %d", minMatrixHeight),
minMatrixHeight > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 47
*
* <blockquote>
* <code>tile_width</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 47,
text = "The tile_width column value in a gpkg_tile_matrix table row SHALL be greater than 0.",
severity = Severity.Error)
public void Requirement47() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(tile_width) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minTileWidthRS = stmt.executeQuery(query);)
{
final int minTileWidth = minTileWidthRS.getInt("min(tile_width)");
if (!minTileWidthRS.wasNull())
{
Assert.assertTrue(String.format("The tile_width in gpkg_tile_matrix must be greater than 0. Invalid tile_width: %d", minTileWidth),
minTileWidth > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 47
*
* <blockquote>
* <code>tile_height</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement(number = 48,
text = "The tile_height column value in a gpkg_tile_matrix table row SHALL be greater than 0.",
severity = Severity.Error)
public void Requirement48() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(tile_height) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minTileHeightRS = stmt.executeQuery(query);)
{
final int testMinTileHeight = minTileHeightRS.getInt("min(tile_height)");
if (!minTileHeightRS.wasNull())
{
Assert.assertTrue(String.format("The tile_height in gpkg_tile_matrix must be greater than 0. Invalid tile_height: %d",
testMinTileHeight),
testMinTileHeight > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 49
*
* <blockquote>
* <code>pixel_x_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 49,
text = "The pixel_x_size column value in a gpkg_tile_matrix table row SHALL be greater than 0." ,
severity = Severity.Error)
public void Requirement49() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(pixel_x_size) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minPixelXSizeRS = stmt.executeQuery(query);)
{
final double minPixelXSize = minPixelXSizeRS.getDouble("min(pixel_x_size)");
if (!minPixelXSizeRS.wasNull())
{
Assert.assertTrue(String.format("The pixel_x_size in gpkg_tile_matrix must be greater than 0. Invalid pixel_x_size: %f",
minPixelXSize),
minPixelXSize > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 50
*
* <blockquote>
* <code>pixel_y_size</code> column value in a <code>gpkg_tile_matrix</code> table row SHALL be greater than 0.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 50,
text = "The pixel_y_size column value in a gpkg_tile_matrix table row SHALL be greater than 0.",
severity = Severity.Error)
public void Requirement50() throws AssertionError
{
if(this.hasTileMatrixTable)
{
final String query = "SELECT min(pixel_y_size) FROM gpkg_tile_matrix;";
try (Statement stmt = this.getSqliteConnection().createStatement();
ResultSet minPixelYSizeRS = stmt.executeQuery(query);)
{
final double minPixelYSize = minPixelYSizeRS.getDouble("min(pixel_y_size)");
if (!minPixelYSizeRS.wasNull())
{
Assert.assertTrue(String.format("The pixel_y_size in gpkg_tile_matrix must be greater than 0. Invalid pixel_y_size: %f",
minPixelYSize),
minPixelYSize > 0);
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 51
*
* <blockquote>
* The <code>pixel_x_size</code> and <code>pixel_y_size</code>
* column values for <code>zoom_level</code> column values in a
* <code>gpkg_tile_matrix</code> table sorted in ascending order
* SHALL be sorted in descending order.
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
*/
@Requirement (number = 51,
text = "The pixel_x_size and pixel_y_size column values for zoom_level "
+ "column values in a gpkg_tile_matrix table sorted in ascending "
+ "order SHALL be sorted in descending order.",
severity = Severity.Error)
public void Requirement51() throws AssertionError
{
if(this.hasTileMatrixTable)
{
for (final String pyramidTable : this.allPyramidUserDataTables)
{
final String query2 = String.format("SELECT pixel_x_size, pixel_y_size "
+ "FROM gpkg_tile_matrix WHERE table_name = '%s' ORDER BY zoom_level ASC;",
pyramidTable);
Double pixelX2 = null;
Double pixelY2 = null;
try (Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet zoomPixxPixy = stmt2.executeQuery(query2))
{
while (zoomPixxPixy.next())
{
final Double pixelX = zoomPixxPixy.getDouble("pixel_x_size");
final Double pixelY = zoomPixxPixy.getDouble("pixel_y_size");
if (pixelX2 != null && pixelY2 != null)
{
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while "
+ "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.",
pixelX.toString(), pixelY.toString()),
pixelX2 > pixelX && pixelY2 > pixelY);
pixelX2 = pixelX;
pixelY2 = pixelY;
}
else if (zoomPixxPixy.next())
{
pixelX2 = zoomPixxPixy.getDouble("pixel_x_size");
pixelY2 = zoomPixxPixy.getDouble("pixel_y_size");
Assert.assertTrue(String.format("Pixel sizes for tile matrix user data tables do not increase while "
+ "the zoom level decrease. Invalid pixel_x_size %s. Invalid pixel_y_size: %s.",
pixelX2.toString(), pixelY2.toString()),
pixelX > pixelX2 && pixelY > pixelY2);
}
}
}
catch (final Exception ex)
{
Assert.fail(ex.getMessage());
}
}
}
}
@Requirement (number = 52,
text = "Each tile matrix set in a GeoPackage SHALL "
+ "be stored in a different tile pyramid user "
+ "data table or updateable view with a unique "
+ "name that SHALL have a column named \"id\" with"
+ " column type INTEGER and PRIMARY KEY AUTOINCREMENT"
+ " column constraints per Clause 2.2.8.1.1 Table Definition,"
+ " Tiles Table or View Definition and EXAMPLE: tiles table "
+ "Insert Statement (Informative). ",
severity = Severity.Error)
public void Requirement52() throws AssertionError, SQLException
{
//verify the tables are defined correctly
for(final String table: this.pyramidTablesInContents)
{
if(DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), table))
{
this.verifyTable(new TilePyramidUserDataTableDefinition(table));
}
else
{
throw new AssertionError(String.format("The tiles table %s does not exist even though it is defined in the gpkg_contents table. "
+ "Either create the table %s or delete the record in gpkg_contents table referring to table %s.",
table,
table,
table));
}
}
//Ensure that the pyramid tables are referenced in tile matrix set
if(this.hasTileMatrixSetTable)
{
final String query2 = "SELECT DISTINCT table_name "
+ "FROM gpkg_contents WHERE data_type = 'tiles' "
+ "AND table_name NOT IN"
+ " (SELECT DISTINCT table_name "
+ " FROM gpkg_tile_matrix_set);";
try(Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet unreferencedPyramidTableInTMS = stmt2.executeQuery(query2))
{
//verify that all the pyramid user data tables are referenced in the Tile Matrix Set table
if(unreferencedPyramidTableInTMS.next())
{
Assert.fail(String.format("There are Pyramid User Data Tables that do not contain a record in the gpkg_tile_matrix_set."
+ " Unreferenced Pyramid table: %s",
unreferencedPyramidTableInTMS.getString("table_name")));
}
}
catch(final SQLException ex)
{
Assert.fail(ex.getMessage());
}
}
}
/**
* Requirement 53
*
* <blockquote>
* For each distinct <code>table_name</code> from the <code>gpkg_tile_matrix</code>
* (tm) table, the tile pyramid (tp) user data table <code>zoom_level</code>
* column value in a GeoPackage SHALL be in the range min(tm.zoom_level) <= tp.zoom_level <= max(tm.zoom_level).
* </blockquote>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement (number = 53,
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, "
+ "the tile pyramid (tp) user data table zoom_level column value in a "
+ "GeoPackage SHALL be in the range min(tm.zoom_level) less than or equal "
+ "to tp.zoom_level less than or equal to max(tm.zoom_level).",
severity = Severity.Error)
public void Requirement53() throws AssertionError, SQLException
{
if(this.hasTileMatrixTable)
{
for(final String pyramidName: this.pyramidTablesInTileMatrix)
{
final String query2 = String.format("SELECT MIN(zoom_level) AS min_gtm_zoom, MAX(zoom_level) "
+ "AS max_gtm_zoom FROM gpkg_tile_matrix WHERE table_name = '%s'",
pyramidName);
try (Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet minMaxZoom = stmt2.executeQuery(query2))
{
final int minZoom = minMaxZoom.getInt("min_gtm_zoom");
final int maxZoom = minMaxZoom.getInt("max_gtm_zoom");
if (!minMaxZoom.wasNull())
{
final String query3 = String.format("SELECT id FROM %s WHERE zoom_level < %d OR zoom_level > %d", pyramidName, minZoom, maxZoom);
try (Statement stmt3 = this.getSqliteConnection().createStatement();
ResultSet invalidZooms = stmt3.executeQuery(query3))
{
if (invalidZooms.next())
{
Assert.fail(String.format("There are zoom_levels in the Pyramid User Data Table: %s such that the zoom level "
+ "is bigger than the maximum zoom level: %d or smaller than the minimum zoom_level: %d"
+ " that was determined by the gpkg_tile_matrix Table. Invalid tile with an id of %d from table %s",
pyramidName,
maxZoom,
minZoom,
invalidZooms.getInt("id"),
pyramidName));
}
}
}
}
}
}
}
/**
* Requirement 54
*
* <blockquote> For each distinct
* <code>table_name</code> from the <code>gpkg_tile_matrix</code> (tm)
* table, the tile pyramid (tp) user data table <code>tile_column</code>
* column value in a GeoPackage SHALL be in the range 0 <= tp.tile_column <=
* tm.matrix_width 1 where the tm and tp <code>zoom_level</code> column
* values are equal. </blockquote> </div>
*
* @throws AssertionError throws if the GeoPackage fails to meet the requirement
* @throws SQLException throws if an SQLException occurs
*/
@Requirement(number = 54,
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, "
+ "the tile pyramid (tp) user data table tile_column column value in a "
+ "GeoPackage SHALL be in the range 0 <= tp.tile_column <= tm.matrix_width - 1 "
+ "where the tm and tp zoom_level column values are equal. ",
severity = Severity.Warning)
public void Requirement54() throws AssertionError, SQLException
{
if (this.hasTileMatrixTable)
{
for(final String pyramidName : this.pyramidTablesInTileMatrix)
{
// this query will only pull the incorrect values for the
// pyramid user data table's column width, the value
// of the tile_column value for the pyramid user data table
// SHOULD be null otherwise those fields are in violation
// of the range
final String query2 = String.format("SELECT DISTINCT gtmm.zoom_level AS udt_zoom,"
+ "gtmm.matrix_width AS gtmm_width,"
+ "udt.id AS udt_id, "
+ "udt.tile_column AS udt_column "
+ "FROM gpkg_tile_matrix AS gtmm "
+ "LEFT OUTER JOIN %s AS udt ON"
+ " udt.zoom_level = gtmm.zoom_level AND"
+ " gtmm.table_name = '%s' AND"
+ " (udt_column < 0 OR udt_column > (gtmm_width - 1));",
pyramidName, pyramidName);
try (Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet incorrectColumns = stmt2.executeQuery(query2))
{
final Map<Integer, List<TileData>> incorrectColumnSet = ResultSetStream.getStream(incorrectColumns)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.tileColumn = resultSet.getInt("udt_column");
//if tileColumn is null, then it is a a correct value
if(resultSet.wasNull())
{
return null;
}
tileData.matrixWidth = resultSet.getInt("gtmm_width");
tileData.zoomLevel = resultSet.getInt("udt_zoom");
tileData.tileID = resultSet.getInt("udt_id");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(tileData -> tileData.zoomLevel));
Assert.assertTrue(String.format(" The following tiles in table '%s' have incorrect tile column values: %s",
pyramidName,
incorrectColumnSet.entrySet()
.stream()
.map(tileData -> String.format("\n Zoom level %d:\n%s",
tileData.getKey(),
tileData.getValue()
.stream()
.sorted()
.map(tileInfo ->tileInfo.columnInvalidToString())
.collect(Collectors.joining("\n"))))
.collect(Collectors.joining("\n"))),
incorrectColumnSet.isEmpty());
}
}
//TODO this test will be moved in a later release to its own individual test, this is not necessarily part of this requirement (wording is below requirement 37 but this is closest to what we are checking).
for(final String pyramidTable: this.allPyramidUserDataTables)
{
final String query1 = String.format("SELECT MIN(tile_column), MIN(tile_row), MAX(tile_row), MAX(tile_column) FROM %s WHERE zoom_level = (SELECT MIN(zoom_level) FROM %s);", pyramidTable, pyramidTable);
try(Statement stmt1 = this.getSqliteConnection().createStatement();
ResultSet minXMaxXMinYMaxYRS = stmt1.executeQuery(query1))
{
final int minX = minXMaxXMinYMaxYRS.getInt("MIN(tile_column)");//this should always be 0
final int minY = minXMaxXMinYMaxYRS.getInt("MIN(tile_row)"); //this should always be 0
final int maxX = minXMaxXMinYMaxYRS.getInt("MAX(tile_column)");
final int maxY = minXMaxXMinYMaxYRS.getInt("MAX(tile_row)");
final String query2 = String.format("SELECT matrix_width, matrix_height, zoom_level FROM %s WHERE table_name = '%s' AND zoom_level = (SELECT MIN(zoom_level) FROM %s)", GeoPackageTiles.MatrixTableName, pyramidTable, pyramidTable);
try(Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet dimensionsRS = stmt2.executeQuery(query2))
{
while(dimensionsRS.next())
{
final int matrixWidth = dimensionsRS.getInt("matrix_width");
final int matrixHeight = dimensionsRS.getInt("matrix_height");
final int zoomLevel = dimensionsRS.getInt("zoom_level");
Assert.assertTrue(String.format("The BoundingBox in gpkg_tile_matrix_set does not define the minimum bounding box for all content in the table %s.\n "
+ "\tActual Values: MIN(tile_column): %4d, MIN(tile_row): %4d, MAX(tile_column): %4d, MAX(tile_row): %4d\n "
+ "\tExpected values: MIN(tile_column): 0, MIN(tile_row): 0, MAX(tile_column): %4d (matrix_width -1), MAX(tile_row): %4d (matrix_height -1),"
+ "\n\tExpected values based on the Tile Matrix given at the MIN(zoom_level) %d.",
pyramidTable,
minX,
minY,
maxX,
maxY,
matrixWidth - 1,
matrixHeight - 1,
zoomLevel),
minX == 0 &&
minY == 0 &&
maxX == (matrixWidth - 1) &&
maxY == (matrixHeight - 1));
}
}
}
}
}
}
@Requirement (number = 55,
text = "For each distinct table_name from the gpkg_tile_matrix (tm) table, the tile pyramid (tp) "
+ "user data table tile_row column value in a GeoPackage SHALL be in the range 0 <= tp.tile_row <= tm.matrix_height - 1 "
+ "where the tm and tp zoom_level column values are equal. ",
severity = Severity.Warning)
public void Requirement55() throws AssertionError, SQLException
{
if (this.hasTileMatrixTable)
{
for(final String pyramidName: this.pyramidTablesInTileMatrix)
{
// this query will only pull the incorrect values for the
// pyramid user data table's column height, the value
// of the tile_row value for the pyramid user data table
// SHOULD be null otherwise those fields are in violation
// of the range
final String query2 = String.format("SELECT DISTINCT gtmm.zoom_level AS gtmm_zoom, "
+ "gtmm.matrix_height AS gtmm_height,"
+ "udt.zoom_level AS udt_zoom, "
+ "udt.tile_row AS udt_row, "
+ "udt.id AS udt_id "
+ "FROM gpkg_tile_matrix AS gtmm "
+ "LEFT OUTER JOIN %s AS udt ON "
+ "udt.zoom_level = gtmm.zoom_level "
+ "AND gtmm.table_name = '%s' "
+ "AND (udt_row < 0 OR udt_row > (gtmm_height- 1));",
pyramidName,
pyramidName);
try (Statement stmt2 = this.getSqliteConnection().createStatement();
ResultSet incorrectTileRow = stmt2.executeQuery(query2))
{
final Map<Integer, List<TileData>> incorrectTileRowSet = ResultSetStream.getStream(incorrectTileRow)
.map(resultSet -> { try
{
final TileData tileData = new TileData();
tileData.tileRow = resultSet.getInt("udt_row");
//if tileRow is null, then it is a a correct value
if(resultSet.wasNull())
{
return null;
}
tileData.matrixHeight = resultSet.getInt("gtmm_height");
tileData.zoomLevel = resultSet.getInt("udt_zoom");
tileData.tileID = resultSet.getInt("udt_id");
return tileData;
}
catch(final SQLException ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(tileData -> tileData.zoomLevel));
Assert.assertTrue(String.format(" The following tiles in table '%s' have incorrect tile row values: %s",
pyramidName,
incorrectTileRowSet.entrySet()
.stream()
.map(tileData -> String.format("\n Zoom level %d:\n%s",
tileData.getKey(),
tileData.getValue().stream()
.sorted()
.map(tileInfo -> tileInfo.rowInvalidToString())
.collect(Collectors.joining("\n"))))
.collect(Collectors.joining("\n"))),
incorrectTileRowSet.isEmpty());
}
}
}
}
private static boolean validPixelValues(final TileData tileData, final BoundingBox boundingBox)
{
return isEqual(tileData.pixelXSize, (boundingBox.getWidth() / tileData.matrixWidth) / tileData.tileWidth) &&
isEqual(tileData.pixelYSize, (boundingBox.getHeight() / tileData.matrixHeight) / tileData.tileHeight);
}
/**
* This method determines if the two doubles are
* equal based upon the maximum level of allowable
* differenced determined by the Epsilon value 0.001
* @param first
* @param second
* @return
*/
private static boolean isEqual(final double first, final double second)
{
return Math.abs(first - second) < TilesVerifier.EPSILON;
}
private static <T> Collection<T> iteratorToCollection(final Iterator<T> iterator)
{
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This Verifies if the Tile Matrix Table exists.
* @return true if the gpkg_tile_matrix table exists
* @throws AssertionError throws an assertion error if the gpkg_tile_matrix table
* doesn't exist and the GeoPackage contains a tiles table
*/
private boolean tileMatrixTableExists() throws SQLException
{
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixTableName);
}
/**
* This Verifies if the Tile Matrix Set Table exists in the
* GeoPackage.
* @return true if the gpkg_tile_matrix Set table exists
* @throws AssertionError throws an assertion error if the gpkg_tile_matrix_set table
* doesn't exist and the GeoPackage contains a tiles table
* @throws SQLException
*/
private boolean tileMatrixSetTableExists() throws SQLException
{
return DatabaseUtility.tableOrViewExists(this.getSqliteConnection(), GeoPackageTiles.MatrixSetTableName);
}
private static boolean canReadImage(final Collection<ImageReader> imageReaders, final ImageInputStream image)
{
return imageReaders.stream()
.anyMatch(imageReader -> { try
{
image.mark();
return imageReader.getOriginatingProvider().canDecodeInput(image);
}
catch(final Exception ex)
{
return false;
}
finally
{
try
{
image.reset();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
});
}
private class TileData implements Comparable<TileData>
{
int matrixWidth;
int matrixHeight;
int zoomLevel;
Integer tileID;
int tileRow;
int tileColumn;
double pixelXSize;
double pixelYSize;
int tileWidth;
int tileHeight;
public String columnInvalidToString()
{
return String.format(" Tile id: %d, column: %2d (max: %d)", this.tileID, this.tileColumn, this.matrixWidth-1);
}
public String rowInvalidToString()
{
return String.format(" Tile id: %d, row: %2d (max: %d)", this.tileID, this.tileRow, this.matrixHeight-1);
}
@Override
public int compareTo(final TileData other)
{
return this.tileID.compareTo(other.tileID);
}
}
private Set<String> allPyramidUserDataTables;
private Set<String> pyramidTablesInContents;
private Set<String> pyramidTablesInTileMatrix;
private boolean hasTileMatrixTable;
private boolean hasTileMatrixSetTable;
private static final TableDefinition TileMatrixSetTableDefinition;
private static final TableDefinition TileMatrixTableDefinition;
static
{
final Map<String, ColumnDefinition> tileMatrixSetColumns = new HashMap<>();
tileMatrixSetColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null));
tileMatrixSetColumns.put("srs_id", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixSetColumns.put("min_x", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("min_y", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("max_x", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixSetColumns.put("max_y", new ColumnDefinition("DOUBLE", true, false, false, null));
TileMatrixSetTableDefinition = new TableDefinition("gpkg_tile_matrix_set",
tileMatrixSetColumns,
new HashSet<>(Arrays.asList(new ForeignKeyDefinition("gpkg_spatial_ref_sys", "srs_id", "srs_id"),
new ForeignKeyDefinition("gpkg_contents", "table_name", "table_name"))));
final Map<String, ColumnDefinition> tileMatrixColumns = new HashMap<>();
tileMatrixColumns.put("table_name", new ColumnDefinition("TEXT", true, true, true, null));
tileMatrixColumns.put("zoom_level", new ColumnDefinition("INTEGER", true, true, true, null));
tileMatrixColumns.put("matrix_width", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("matrix_height", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("tile_width", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("tile_height", new ColumnDefinition("INTEGER", true, false, false, null));
tileMatrixColumns.put("pixel_x_size", new ColumnDefinition("DOUBLE", true, false, false, null));
tileMatrixColumns.put("pixel_y_size", new ColumnDefinition("DOUBLE", true, false, false, null));
TileMatrixTableDefinition = new TableDefinition("gpkg_tile_matrix",
tileMatrixColumns,
new HashSet<>(Arrays.asList(new ForeignKeyDefinition("gpkg_contents", "table_name", "table_name"))));
}
}
|
package data_manipulation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class D1011_MonteCarol_TTN_fit_CCDSHash {
public static void main(String[] args) throws IOException{
D0723_Extract_exonHash_from_CCDSHs373 CCDSHash = new D0723_Extract_exonHash_from_CCDSHs373();
//Initial a HashMap; //call run() method, to get all exons, and update the HashMap;
HashMap<String, ArrayList<Exon_objects>> exonHash = CCDSHash.run();
//create an arrayList to store all exon-objects;
ArrayList<Exon_objects> exonList = exonHash.get("TTN");
System.out.println("There are " + exonList.size() + " exons in current gene: " + exonList.get(0).gene_name + ".. " + exonList.get(0).exon_name);
//2nd, read-in TTN exac variants of LoF from D:/PhD/TTN_pulled_from_ExAC/exac_TTN_LoF.CSV
Scanner variants_reader = new Scanner(new File("D:/PhD/ExAC_datasets/All_LOF/TTN.CSV"));
/********
* the first line:
* "Chrom","Position","RSID","Reference","Alternate","Consequence","Protein Consequence","Transcript Consequence",
* "Filter","Annotation","Flags","Allele Count","Allele Number","Number of Homozygotes","Allele Frequency",
* "Allele Count African","Allele Number African","Homozygote Count African","Allele Count East Asian",
* "Allele Number East Asian","Homozygote Count East Asian","Allele Count European (Non-Finnish)",
* "Allele Number European (Non-Finnish)","Homozygote Count European (Non-Finnish)","Allele Count Finnish",
* "Allele Number Finnish","Homozygote Count Finnish","Allele Count Latino","Allele Number Latino",
* "Homozygote Count Latino","Allele Count Other","Allele Number Other","Homozygote Count Other",
* "Allele Count South Asian","Allele Number South Asian","Homozygote Count South Asian"
*
* the second line:
* "2","179391750",".","G","A","p.Arg35989Ter","p.Arg35989Ter","c.107965C>T","PASS","stop gained",
* "LC LoF","1","108206","0","0.000009242","0","9042","0","0","7868","0","0","60554","0","0",
* "6278","0","1","10212","0","0","802","0","0","13450","0"
*
* Since each item is wrapped by "", and seperated by comma, so we have to delete all "s, and split the string by comma.
* then we keep the chrom, position, Allele Frequency. (so far only these columns)
*
*/
String titleLine = variants_reader.nextLine();
titleLine = remove_quotes(titleLine);
System.out.println("\nvariants reader, exac_TTN_LoF.CSV title line done. \n" );
//get index of position and allele_frequency;
int index_pos = 1;
int index_af = 14;
String[] title = titleLine.split(",");
for(int i=0; i<title.length; i++){
if(title[i].equals("Position")) index_pos = i;
if(title[i].equals("Allele Frequency")) index_af = i;
}
//printout the index of Position and Allele-Frequency;
System.out.println("For each line of data, the variant position index: " + index_pos + ", Allele-Frequency index: " + index_af +"\n");
//initial VariantsOnExons to indicate the number of variants hit exons;
int VariantsOnExons = 0;
//initial an ArrayList to store all allele-frequencies of variants on exons;
ArrayList<Double> alleleFreq_list = new ArrayList<Double>();
//initial a buffer-writer to write all variants within exons;
File output = new File("D:/PhD/TTN_variants_OnExons.txt");
BufferedWriter outWriter = new BufferedWriter(new FileWriter(output));
//write in the titleLine without any quotes.
outWriter.write(titleLine + "\n");
while(variants_reader.hasNextLine()){
String currLine = variants_reader.nextLine();
currLine = remove_quotes(currLine);
//System.out.println(currLine);
//split the line by ",";
String[] variants = currLine.split(",");
int position = Integer.parseInt( variants[index_pos] );
if( check_If_hits_Exons(position, exonList) ){
//System.out.println(" One hit: " + position);
//check the 10% threshold:
double allel_freq = Double.parseDouble( variants[index_af]);
if(allel_freq < 0.1){
VariantsOnExons ++;
alleleFreq_list.add( allel_freq );
outWriter.write(currLine + "\n");
} //end if allele-frequency greater than 10% threshold;
}//end if allele hits exon condition;
} //end while loop;
System.out.println("There are " + VariantsOnExons + " variants on exons.");
//3rd, calculate the probability of homozygous:
double homo = 1;
double hit_one_gene = 1;
for(int i=0; i<alleleFreq_list.size(); i++){
hit_one_gene *= (1 - alleleFreq_list.get(i));
}
hit_one_gene = 1 - hit_one_gene;
homo = hit_one_gene * hit_one_gene;
System.out.println("The probability of getting homozygos TTN gene: " + homo);
variants_reader.close();
outWriter.close();
//4th, Monte Carol Integration
for(int i=0; i<10000000; i++){
double Pai2gTimesRhgo = MonteCarol(alleleFreq_list);
if(Pai2gTimesRhgo > 0)
System.out.println("This Pai2gTimesRhgo: " + Pai2gTimesRhgo);
}
}//end main()
private static double MonteCarol(ArrayList<Double> alleleFreq_list) {
// TODO Auto-generated method stub
//4.1 get the arrayList of qualified allele frequencies alleleFreq_list
//4.2 get an range of random integers for each allele frequency
double Pai2g = 1;
double Rhog = 1;
int n1 = 0;
int n2 = 0;
for(int i=0; i<alleleFreq_list.size(); i++){
int range = (int) ( 1/alleleFreq_list.get(i)) * 10;
int pivot1 = range/2 - 5;
int pivot2 = range/2 + 5;
// System.out.println(alleleFreq_list.get(i) + "\t " + range + "\t [" + (range/2-5) +"-" + (range/2+5)+"]");
int random1 = (int)(Math.random() * range*10);
int random2 = (int)(Math.random() * range*10);
if(random1 >= pivot1 && random1 <= pivot2 && random2 >= pivot1 && random2 <= pivot2){
n2 ++;
Rhog *= alleleFreq_list.get(i);
Rhog *= alleleFreq_list.get(i);
} else if (random1 >= pivot1 && random1 <= pivot2){
n1 ++;
Rhog *= alleleFreq_list.get(i);
} else if (random2 >= pivot1 && random2 <= pivot2){
n1 ++;
Rhog *= alleleFreq_list.get(i);
} //end if-else n1 and n2 conditions;
}//end for loop;
//calculate Pai2g based on n1 and n2 values
//double Pai2g = 0;
if(n2 > 0) {
System.out.println("get one n2.");
Pai2g = 1;
} else if( n1 < 2 ) {
Pai2g = 0;
} else {
Pai2g = 1 - Math.pow(0.5, n1 -1);
}
// System.out.println("The Pai2_g * Rho = " + Pai2g * Rhog);
return Pai2g * Rhog;
}
/*******************
* check if a variant hits any exon
* @param position
* @param exonList
* @return
*/
private static boolean check_If_hits_Exons(int position, ArrayList<Exon_objects> exonList) {
// TODO Auto-generated method stub
boolean hits = false;
for(int i=0; i<exonList.size(); i++){
if(position >= exonList.get(i).exonStart && position <= exonList.get(i).exonEnd) {
hits = true;
//System.out.print(" " + exonList.get(i).exon_name);
}
}
return hits;
} //end of check_If_hits_Exons() method;
/******************
* remove all quotes within the string;
* @param str
* @return
*/
private static String remove_quotes(String str) {
// TODO Auto-generated method stub
String retStr = "";
for(int i=0; i<str.length(); i++){
if(str.charAt(i)!= '"')
retStr += str.charAt(i);
}
return retStr;
}//end remove_quotes() method;
}
|
/*
* $Log: Wsdl.java,v $
* Revision 1.29 2013-01-24 16:49:54 m00f069
* Removed header message. Added header part to request and response message.
* Cleaned code a little.
*
* Revision 1.28 2012/12/06 15:19:28 Jaco de Groot <jaco.de.groot@ibissource.org>
* Resolved warnings which showed up when using addNamespaceToSchema (src-include.2.1: The targetNamespace of the referenced schema..., src-resolve.4.2: Error resolving component...)
* Handle includes in XSD's properly when generating a WSDL
* Removed XSD download (unused and XSD's were not adjusted according to e.g. addNamespaceToSchema)
* Sort schema's in WSDL (made sure the order is always the same)
* Indent WSDL with tabs instead of spaces
* Some cleaning and refactoring (made WSDL generator and XmlValidator share code)
*
* Revision 1.27 2012/11/21 14:11:00 Jaco de Groot <jaco.de.groot@ibissource.org>
* Bugfix: Get root tags from root xsd's only otherwise when root tag name found in non root xsd, the non root xsd may be used which has no prefix, hence an exception is thrown.
*
* Revision 1.26 2012/10/26 15:43:18 Jaco de Groot <jaco.de.groot@ibissource.org>
* Made WSDL without separate XSD's the default
*
* Revision 1.25 2012/10/24 14:34:00 Jaco de Groot <jaco.de.groot@ibissource.org>
* Load imported XSD's into the WSDL too
* When more than one XSD with the same namespace is present merge them into one schema element in the WSDL
* Exclude SOAP Envelope XSD
*
* Revision 1.24 2012/10/19 11:52:28 Jaco de Groot <jaco.de.groot@ibissource.org>
* Removed unused param
*
* Revision 1.23 2012/10/17 13:02:10 Jaco de Groot <jaco.de.groot@ibissource.org>
* Check paradigm against list of valid values.
* Use schemaLocation instead of outputWrapper as main source for ESB SOAP vars.
*
* Revision 1.22 2012/10/17 08:40:49 Jaco de Groot <jaco.de.groot@ibissource.org>
* Added esbSoapOperationName and esbSoapOperationVersion
*
* Revision 1.21 2012/10/12 13:07:47 Jaco de Groot <jaco.de.groot@ibissource.org>
* Removed "Unrecognized listener" comment from WSDL (when no useful listener found WSDL is marked abstract)
*
* Revision 1.20 2012/10/12 09:55:17 Jaco de Groot <jaco.de.groot@ibissource.org>
* Some extra checks on configuration at WSDL listing time to prevent the user from being disappointed at WSDL generation time.
* Handle retrieval of XSD's from outputValidator the same as for inputValidator (check on usage of schema instead of schemaLocation attribute and usage of recursiveXsds)
*
* Revision 1.19 2012/10/11 10:01:58 Jaco de Groot <jaco.de.groot@ibissource.org>
* Use concrete filename with WebServiceListener too
*
* Revision 1.18 2012/10/11 09:45:58 Jaco de Groot <jaco.de.groot@ibissource.org>
* Added WSDL filename to WSDL documentation
*
* Revision 1.17 2012/10/11 09:10:43 Jaco de Groot <jaco.de.groot@ibissource.org>
* To lower case on targetAddress destination (QUEUE -> queue)
*
* Revision 1.16 2012/10/10 09:43:53 Jaco de Groot <jaco.de.groot@ibissource.org>
* Added comment on ESB_SOAP_JMS
*
* Revision 1.15 2012/10/04 11:28:57 Jaco de Groot <jaco.de.groot@ibissource.org>
* Fixed ESB Soap namespace
* Added location (url) of WSDL generation to the WSDL documentation
* Show warning add the bottom of the WSDL (if any) instead of Ibis logging
*
* Revision 1.14 2012/10/03 14:30:46 Jaco de Groot <jaco.de.groot@ibissource.org>
* Different filename for ESB Soap WSDL
*
* Revision 1.13 2012/10/03 12:22:41 Jaco de Groot <jaco.de.groot@ibissource.org>
* Different transport uri, jndi properties and connectionFactory for ESB Soap.
* Fill targetAddress with a value when running locally.
*
* Revision 1.12 2012/10/02 16:12:14 Jaco de Groot <jaco.de.groot@ibissource.org>
* Bugfix for one-way WSDL (switched esbSoapOperationName and esbSoapOperationVersion).
* Log a warning in case paradigm could not be extracted from the soap body.
*
* Revision 1.11 2012/10/01 15:23:44 Jaco de Groot <jaco.de.groot@ibissource.org>
* Strip schemaLocation from xsd import in case of generated WSDL with inline XSD's.
*
* Revision 1.10 2012/09/28 14:39:47 Jaco de Groot <jaco.de.groot@ibissource.org>
* Bugfix WSLD target namespace for ESB Soap, part XSD should be WSDL
*
* Revision 1.9 2012/09/27 14:28:59 Jaco de Groot <jaco.de.groot@ibissource.org>
* Better error message / adapter name when constructor throws exception.
*
* Revision 1.8 2012/09/27 13:44:31 Jaco de Groot <jaco.de.groot@ibissource.org>
* Updates in generating wsdl namespace, wsdl input message name, wsdl output message name, wsdl port type name and wsdl operation name in case of EsbSoap
*
* Revision 1.7 2012/09/26 12:41:05 Jaco de Groot <jaco.de.groot@ibissource.org>
* Bugfix in WSDL generator: Wrong prefix being used in element attribute of PipeLineInput and PipeLineOutput message part when using EsbSoapValidator.
*
* Revision 1.6 2012/08/23 11:57:43 Jaco de Groot <jaco.de.groot@ibissource.org>
* Updates from Michiel
*
* Revision 1.5 2012/05/08 15:53:59 Jaco de Groot <jaco.de.groot@ibissource.org>
* Fix invalid chars in wsdl:service name.
*
* Revision 1.4 2012/03/30 17:03:45 Jaco de Groot <jaco.de.groot@ibissource.org>
* Michiel added JMS binding/service to WSDL generator, made WSDL validator work for Bis WSDL and made console show syntax problems for schema's used in XmlValidator
*
* Revision 1.3 2012/03/16 15:35:43 Jaco de Groot <jaco.de.groot@ibissource.org>
* Michiel added EsbSoapValidator and WsdlXmlValidator, made WSDL's available for all adapters and did a bugfix on XML Validator where it seems to be dependent on the order of specified XSD's
*
* Revision 1.2 2011/12/15 10:08:06 Jaco de Groot <jaco.de.groot@ibissource.org>
* Added CVS log
*
*/
package nl.nn.adapterframework.soap;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.naming.NamingException;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import nl.nn.adapterframework.core.IListener;
import nl.nn.adapterframework.core.IPipe;
import nl.nn.adapterframework.core.PipeLine;
import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe;
import nl.nn.adapterframework.http.WebServiceListener;
import nl.nn.adapterframework.jms.JmsListener;
import nl.nn.adapterframework.pipes.XmlValidator;
import nl.nn.adapterframework.util.AppConstants;
import nl.nn.adapterframework.util.XmlUtils;
import nl.nn.adapterframework.validation.SchemaUtils;
import nl.nn.adapterframework.validation.XSD;
import org.apache.commons.lang.StringUtils;
/**
* Utility class to generate the WSDL. Straight-forwardly implemented using stax only.
*
* An object of this class represents the WSDL associated with one IBIS pipeline.
*
* @author Michiel Meeuwissen
* @author Jaco de Groot
*/
class Wsdl {
protected static final String WSDL = "http://schemas.xmlsoap.org/wsdl/";
protected static final String SOAP_WSDL = "http://schemas.xmlsoap.org/wsdl/soap/";
protected static final String SOAP_HTTP = "http://schemas.xmlsoap.org/soap/http";
protected static final String SOAP_JMS = "http:
// Tibco BW will not detect the transport when SOAP_JMS is being used
// instead of ESB_SOAP_JMS.
protected static final String ESB_SOAP_JMS = "http:
protected static final String ESB_SOAP_JNDI = "http:
protected static final String ESB_SOAP_TNS_BASE_URI = "http://nn.nl/WSDL";
protected static final List<String> excludeXsds = new ArrayList<String>();
static {
excludeXsds.add("http://schemas.xmlsoap.org/soap/envelope/");
};
private boolean indent = true;
private boolean useIncludes = false;
private final String name;
private final String filename;
private final String targetNamespace;
private final PipeLine pipeLine;
private final XmlValidator inputValidator;
private final XmlValidator outputValidator;
private String webServiceListenerNamespace;
private Set<XSD> rootXsds;
private Set<XSD> xsdsRecursive;
private Map<String, Set<XSD>> rootXsdsGroupedByNamespace;
private LinkedHashMap<XSD, String> prefixByXsd;
private LinkedHashMap<String, String> namespaceByPrefix;
private String wsdlInputMessageName = "PipeLineInput";
private String wsdlOutputMessageName = "PipeLineOutput";
private String wsdlPortTypeName = "PipeLine";
private String wsdlOperationName = "Process";
private boolean esbSoap = false;
private String esbSoapBusinessDomain;
private String esbSoapServiceName;
private String esbSoapServiceContext;
private String esbSoapServiceContextVersion;
private String esbSoapOperationName;
private String esbSoapOperationVersion;
private String documentation;
private List<String> warnings = new ArrayList<String>();
Wsdl(PipeLine pipeLine) {
this.pipeLine = pipeLine;
this.name = this.pipeLine.getAdapter().getName();
if (this.name == null) {
throw new IllegalArgumentException("The adapter '" + pipeLine.getAdapter() + "' has no name");
}
inputValidator = (XmlValidator)pipeLine.getInputValidator();
if (inputValidator == null) {
throw new IllegalStateException("The adapter '" + getName() + "' has no input validator");
}
outputValidator = (XmlValidator)pipeLine.getOutputValidator();
String filename = name;
AppConstants appConstants = AppConstants.getInstance();
String tns = appConstants.getResolvedProperty("wsdl." + getName() + ".targetNamespace");
if (tns == null) {
tns = appConstants.getResolvedProperty("wsdl.targetNamespace");
}
if (tns == null) {
EsbSoapWrapperPipe inputWrapper = getEsbSoapInputWrapper();
EsbSoapWrapperPipe outputWrapper = getEsbSoapOutputWrapper();
if (inputWrapper != null || outputWrapper != null) {
esbSoap = true;
String schemaLocation = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator);
if (EsbSoapWrapperPipe.isValidNamespace(schemaLocation)) {
String s = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator);
int i = s.lastIndexOf('/');
esbSoapOperationVersion = s.substring(i + 1);
s = s.substring(0, i);
i = s.lastIndexOf('/');
esbSoapOperationName = s.substring(i + 1);
s = s.substring(0, i);
i = s.lastIndexOf('/');
esbSoapServiceContextVersion = s.substring(i + 1);
s = s.substring(0, i);
i = s.lastIndexOf('/');
esbSoapServiceContext = s.substring(i + 1);
s = s.substring(0, i);
i = s.lastIndexOf('/');
esbSoapServiceName = s.substring(i + 1);
s = s.substring(0, i);
i = s.lastIndexOf('/');
esbSoapBusinessDomain = s.substring(i + 1);
} else {
warn("Namespace '" + schemaLocation + "' invalid according to ESB SOAP standard");
if (outputWrapper != null) {
esbSoapBusinessDomain = outputWrapper.getBusinessDomain();
esbSoapServiceName = outputWrapper.getServiceName();
esbSoapServiceContext = outputWrapper.getServiceContext();
esbSoapServiceContextVersion = outputWrapper.getServiceContextVersion();
esbSoapOperationName = outputWrapper.getOperationName();
esbSoapOperationVersion = outputWrapper.getOperationVersion();
}
}
if (esbSoapBusinessDomain == null) {
warn("Could not determine business domain");
} else if (esbSoapServiceName == null) {
warn("Could not determine service name");
} else if (esbSoapServiceContext == null) {
warn("Could not determine service context");
} else if (esbSoapServiceContextVersion == null) {
warn("Could not determine service context version");
} else if (esbSoapOperationName == null) {
warn("Could not determine operation name");
} else if (esbSoapOperationVersion == null) {
warn("Could not determine operation version");
} else {
String wsdlType = "abstract";
for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) {
if (l instanceof WebServiceListener
|| l instanceof JmsListener) {
wsdlType = "concrete";
}
}
filename = esbSoapBusinessDomain + "_"
+ esbSoapServiceName + "_"
+ esbSoapServiceContext + "_"
+ esbSoapServiceContextVersion + "_"
+ esbSoapOperationName + "_"
+ esbSoapOperationVersion + "_"
+ wsdlType;
tns = ESB_SOAP_TNS_BASE_URI + "/"
+ esbSoapBusinessDomain + "/"
+ esbSoapServiceName + "/"
+ esbSoapServiceContext + "/"
+ esbSoapServiceContextVersion + "/"
+ esbSoapOperationName + "/"
+ esbSoapOperationVersion;
String inputParadigm = WsdlUtils.getEsbSoapParadigm(inputValidator);
if (inputParadigm != null) {
wsdlInputMessageName = esbSoapOperationName + "_"
+ esbSoapOperationVersion + "_" + inputParadigm;
if (!"Action".equals(inputParadigm)
&& !"Event".equals(inputParadigm)
&& !"Request".equals(inputParadigm)
&& !"Solicit".equals(inputParadigm)) {
warn("Paradigm for input message which was extracted from soapBody should be on of Action, Event, Request or Solicit instead of '"
+ inputParadigm + "'");
}
} else {
warn("Could not extract paradigm from soapBody attribute of inputValidator");
}
if (outputValidator != null) {
String outputParadigm = WsdlUtils.getEsbSoapParadigm(outputValidator);
if (outputParadigm != null) {
wsdlOutputMessageName = esbSoapOperationName + "_"
+ esbSoapOperationVersion + "_" + outputParadigm;
if (!"Response".equals(outputParadigm)) {
warn("Paradigm for output message which was extracted from soapBody should be Response instead of '"
+ outputParadigm + "'");
}
} else {
warn("Could not extract paradigm from soapBody attribute of outputValidator");
}
}
wsdlPortTypeName = esbSoapOperationName + "_Interface_" + esbSoapOperationVersion;
wsdlOperationName = esbSoapOperationName + "_" + esbSoapOperationVersion;
}
}
if (tns == null) {
for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) {
if (l instanceof WebServiceListener) {
webServiceListenerNamespace = ((WebServiceListener)l).getServiceNamespaceURI();
tns = webServiceListenerNamespace;
}
}
if (tns == null) {
tns = WsdlUtils.getFirstNamespaceFromSchemaLocation(inputValidator);
}
if (tns != null) {
if (tns.endsWith("/")) {
tns = tns + "wsdl/";
} else {
tns = tns + "/wsdl/";
}
} else {
tns = "${wsdl." + getName() + ".targetNamespace}";
}
}
}
this.filename = filename;
this.targetNamespace = WsdlUtils.validUri(tns);
}
public String getName() {
return name;
}
public String getFilename() {
return filename;
}
public String getTargetNamespace() {
return targetNamespace;
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
this.documentation = documentation;
}
public boolean isIndent() {
return indent;
}
public void setIndent(boolean indent) {
this.indent = indent;
}
public boolean isUseIncludes() {
return useIncludes;
}
public void setUseIncludes(boolean useIncludes) {
this.useIncludes = useIncludes;
}
public void init() throws IOException, XMLStreamException {
init(false);
}
public void init(boolean checkSchemaLocationOnly) throws IOException, XMLStreamException {
Set<XSD> xsds = new TreeSet<XSD>();
xsds.addAll(initXsds(inputValidator, checkSchemaLocationOnly));
if (outputValidator != null) {
xsds.addAll(initXsds(outputValidator, checkSchemaLocationOnly));
}
if (!checkSchemaLocationOnly) {
rootXsds = new TreeSet<XSD>();
xsdsRecursive = new TreeSet<XSD>();
rootXsds.addAll(xsds);
xsdsRecursive.addAll(SchemaUtils.getXsdsRecursive(rootXsds));
prefixByXsd = new LinkedHashMap<XSD, String>();
namespaceByPrefix = new LinkedHashMap<String, String>();
int prefixCount = 1;
rootXsdsGroupedByNamespace =
SchemaUtils.getXsdsGroupedByNamespace(rootXsds);
for (String namespace: rootXsdsGroupedByNamespace.keySet()) {
xsds = rootXsdsGroupedByNamespace.get(namespace);
for (XSD xsd: xsds) {
prefixByXsd.put(xsd, "ns" + prefixCount);
}
namespaceByPrefix.put("ns" + prefixCount, namespace);
prefixCount++;
}
}
}
public Set<XSD> initXsds(XmlValidator xmlValidator,
boolean checkSchemaLocationOnly)
throws IOException, XMLStreamException {
Set<XSD> xsds = new TreeSet<XSD>();
String inputSchema = xmlValidator.getSchema();
if (inputSchema != null) {
// In case of a WebServiceListener using soap=true it might be
// valid to use the schema attribute (in which case the schema
// doesn't have a namespace) as the WebServiceListener will
// remove the soap envelop and body element before it is
// validated. In this case we use the serviceNamespaceURI from
// the WebServiceListener as the namespace for the schema.
if (webServiceListenerNamespace != null) {
if (!checkSchemaLocationOnly) {
XSD xsd = SchemaUtils.getXSD(inputSchema, webServiceListenerNamespace, true, true);
xsds.add(xsd);
}
} else {
throw new IllegalStateException("The adapter " + pipeLine + " has a validator using the schema attribute but a namespace is required");
}
} else {
xsds = SchemaUtils.getXsds(xmlValidator.getSchemaLocation(),
excludeXsds, xmlValidator.isAddNamespaceToSchema(),
checkSchemaLocationOnly);
}
return xsds;
}
/**
* Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's.
* @see {@link #wsdl(java.io.OutputStream, String)}
*/
public void zip(OutputStream stream, String servletName) throws IOException, XMLStreamException, NamingException {
ZipOutputStream out = new ZipOutputStream(stream);
// First an entry for the WSDL itself:
ZipEntry wsdlEntry = new ZipEntry(getFilename() + ".wsdl");
out.putNextEntry(wsdlEntry);
wsdl(out, servletName);
out.closeEntry();
//And then all XSD's
Set<String> entries = new HashSet<String>();
for (XSD xsd : xsdsRecursive) {
String zipName = xsd.getBaseUrl() + xsd.getName();
if (entries.add(zipName)) {
ZipEntry xsdEntry = new ZipEntry(zipName);
out.putNextEntry(xsdEntry);
XMLStreamWriter writer = WsdlUtils.getWriter(out, false);
SchemaUtils.xsdToXmlStreamWriter(xsd, writer, true);
out.closeEntry();
} else {
warn("Duplicate xsds in " + this + " " + xsd + " " + xsdsRecursive);
}
}
out.close();
}
/**
* Writes the WSDL to an output stream
* @param out
* @param servlet The servlet what is used as the web service (because this needs to be present in the WSDL)
* @throws XMLStreamException
* @throws IOException
*/
public void wsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, NamingException {
XMLStreamWriter w = WsdlUtils.getWriter(out, isIndent());
w.writeStartDocument(XmlUtils.STREAM_FACTORY_ENCODING, "1.0");
w.setPrefix("wsdl", WSDL);
w.setPrefix("xsd", SchemaUtils.XSD);
w.setPrefix("soap", SOAP_WSDL);
if (esbSoap) {
w.setPrefix("jms", ESB_SOAP_JMS);
w.setPrefix("jndi", ESB_SOAP_JNDI);
} else {
w.setPrefix("jms", SOAP_JMS);
}
w.setPrefix("ibis", getTargetNamespace());
for (String prefix: namespaceByPrefix.keySet()) {
w.setPrefix(prefix, namespaceByPrefix.get(prefix));
}
w.writeStartElement(WSDL, "definitions"); {
w.writeNamespace("wsdl", WSDL);
w.writeNamespace("xsd", SchemaUtils.XSD);
w.writeNamespace("soap", SOAP_WSDL);
if (esbSoap) {
w.writeNamespace("jndi", ESB_SOAP_JNDI);
}
w.writeNamespace("ibis", getTargetNamespace());
for (String prefix: namespaceByPrefix.keySet()) {
w.writeNamespace(prefix, namespaceByPrefix.get(prefix));
}
w.writeAttribute("targetNamespace", getTargetNamespace());
documentation(w);
types(w);
messages(w);
portType(w);
binding(w);
service(w, servlet);
}
w.writeEndDocument();
warnings(w);
w.close();
}
/**
* Outputs a 'documentation' section of the WSDL
*/
protected void documentation(XMLStreamWriter w) throws XMLStreamException {
if (documentation != null) {
w.writeStartElement(WSDL, "documentation");
w.writeCharacters(documentation);
w.writeEndElement();
}
}
/**
* Output the 'types' section of the WSDL
* @param w
* @throws XMLStreamException
* @throws IOException
*/
protected void types(XMLStreamWriter w) throws XMLStreamException, IOException {
w.writeStartElement(WSDL, "types");
if (isUseIncludes()) {
SchemaUtils.mergeRootXsdsGroupedByNamespaceToSchemasWithIncludes(
rootXsdsGroupedByNamespace, w);
} else {
Map<String, Set<XSD>> xsdsGroupedByNamespace =
SchemaUtils.getXsdsGroupedByNamespace(xsdsRecursive);
SchemaUtils.mergeXsdsGroupedByNamespaceToSchemasWithoutIncludes(
xsdsGroupedByNamespace, w);
}
w.writeEndElement();
}
/**
* Outputs the 'messages' section.
* @param w
* @throws XMLStreamException
* @throws IOException
*/
protected void messages(XMLStreamWriter w) throws XMLStreamException, IOException {
List<QName> parts = new ArrayList<QName>();
parts.addAll(getInputHeaderTags());
parts.addAll(getInputBodyTags());
message(w, wsdlInputMessageName, parts);
XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator();
if (outputValidator != null) {
parts.clear();
parts.addAll(getOutputHeaderTags());
parts.addAll(getOutputBodyTags());
message(w, wsdlOutputMessageName, parts);
}
}
protected void message(XMLStreamWriter w, String name, Collection<QName> tags) throws XMLStreamException, IOException {
if (tags == null) throw new IllegalArgumentException("Tag cannot be null for " + name);
if (!tags.isEmpty()) {
w.writeStartElement(WSDL, "message");
w.writeAttribute("name", name);
{
for (QName tag : tags) {
w.writeEmptyElement(WSDL, "part");
w.writeAttribute("name", getIbisName(tag));
String typ = tag.getPrefix() + ":" + tag.getLocalPart();
w.writeAttribute("element", typ);
}
}
w.writeEndElement();
}
}
protected void portType(XMLStreamWriter w) throws XMLStreamException, IOException {
w.writeStartElement(WSDL, "portType");
w.writeAttribute("name", wsdlPortTypeName); {
w.writeStartElement(WSDL, "operation");
w.writeAttribute("name", wsdlOperationName); {
w.writeEmptyElement(WSDL, "input");
w.writeAttribute("message", "ibis:" + wsdlInputMessageName);
if (outputValidator != null) {
w.writeEmptyElement(WSDL, "output");
w.writeAttribute("message", "ibis:" + wsdlOutputMessageName);
}
}
w.writeEndElement();
}
w.writeEndElement();
}
protected String getSoapAction() {
AppConstants appConstants = AppConstants.getInstance();
String sa = appConstants.getResolvedProperty("wsdl." + getName() + ".soapAction");
if (sa != null) return sa;
sa = appConstants.getResolvedProperty("wsdl.soapAction");
if (sa != null) return sa;
if (esbSoapOperationName != null && esbSoapOperationVersion != null) {
return esbSoapOperationName + "_" + esbSoapOperationVersion;
}
return "${wsdl." + getName() + ".soapAction}";
}
protected void binding(XMLStreamWriter w) throws XMLStreamException, IOException {
for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) {
if (listener instanceof WebServiceListener) {
httpBinding(w);
} else if (listener instanceof JmsListener) {
jmsBinding(w);
}
}
}
protected void httpBinding(XMLStreamWriter w) throws XMLStreamException, IOException {
w.writeStartElement(WSDL, "binding");
w.writeAttribute("name", "SoapBinding");
w.writeAttribute("type", "ibis:" + wsdlPortTypeName); {
w.writeEmptyElement(SOAP_WSDL, "binding");
w.writeAttribute("transport", SOAP_HTTP);
w.writeAttribute("style", "document");
writeSoapOperation(w);
}
w.writeEndElement();
}
protected void writeSoapOperation(XMLStreamWriter w) throws XMLStreamException, IOException {
w.writeStartElement(WSDL, "operation");
w.writeAttribute("name", wsdlOperationName); {
w.writeEmptyElement(SOAP_WSDL, "operation");
w.writeAttribute("style", "document");
w.writeAttribute("soapAction", getSoapAction());
w.writeStartElement(WSDL, "input"); {
writeSoapHeader(w, wsdlInputMessageName, getInputHeaderTags());
writeSoapBody(w, getInputBodyTags());
}
w.writeEndElement();
if (outputValidator != null) {
w.writeStartElement(WSDL, "output"); {
writeSoapHeader(w, wsdlOutputMessageName, getOutputHeaderTags());
writeSoapBody(w, getOutputBodyTags());
}
w.writeEndElement();
}
}
w.writeEndElement();
}
protected void writeSoapHeader(XMLStreamWriter w, String wsdlMessageName, Collection<QName> tags) throws XMLStreamException, IOException {
if (!tags.isEmpty()) {
if (tags.size() > 1) {
warn("Can only deal with one soap header. Taking only the first of " + tags);
}
w.writeEmptyElement(SOAP_WSDL, "header");
w.writeAttribute("part", getIbisName(tags.iterator().next()));
w.writeAttribute("use", "literal");
w.writeAttribute("message", "ibis:" + wsdlMessageName);
}
}
protected void writeSoapBody(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException, IOException {
w.writeEmptyElement(SOAP_WSDL, "body");
writeParts(w, tags);
w.writeAttribute("use", "literal");
}
protected void writeParts(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException {
StringBuilder builder = new StringBuilder();
for (QName outputTag : tags) {
if (builder.length() > 0) builder.append(" ");
builder.append(getIbisName(outputTag));
}
w.writeAttribute("parts", builder.toString());
}
protected String getIbisName(QName qname) {
return qname.getLocalPart();
}
protected void jmsBinding(XMLStreamWriter w) throws XMLStreamException, IOException {
w.writeStartElement(WSDL, "binding");
w.writeAttribute("name", "SoapBinding");
w.writeAttribute("type", "ibis:" + wsdlPortTypeName); {
w.writeEmptyElement(SOAP_WSDL, "binding");
w.writeAttribute("style", "document");
if (esbSoap) {
w.writeAttribute("transport", ESB_SOAP_JMS);
w.writeEmptyElement(ESB_SOAP_JMS, "binding");
w.writeAttribute("messageFormat", "Text");
writeSoapOperation(w);
} else {
w.writeAttribute("transport", SOAP_JMS);
}
}
w.writeEndElement();
}
protected void service(XMLStreamWriter w, String servlet) throws XMLStreamException, NamingException {
for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) {
if (listener instanceof WebServiceListener) {
httpService(w, servlet);
} else if (listener instanceof JmsListener) {
jmsService(w, (JmsListener) listener);
}
}
}
protected void httpService(XMLStreamWriter w, String servlet) throws XMLStreamException {
w.writeStartElement(WSDL, "service");
w.writeAttribute("name", WsdlUtils.getNCName(getName())); {
w.writeStartElement(WSDL, "port");
w.writeAttribute("name", "SoapHttp");
w.writeAttribute("binding", "ibis:SoapBinding"); {
w.writeEmptyElement(SOAP_WSDL, "address");
w.writeAttribute("location", servlet);
}
w.writeEndElement();
}
w.writeEndElement();
}
protected void jmsService(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException {
w.writeStartElement(WSDL, "service");
w.writeAttribute("name", WsdlUtils.getNCName(getName())); {
if (!esbSoap) {
w.writeStartElement(SOAP_JMS, "jndiConnectionFactoryName");
w.writeCharacters(listener.getQueueConnectionFactoryName());
}
w.writeStartElement(WSDL, "port");
w.writeAttribute("name", "SoapJMS");
w.writeAttribute("binding", "ibis:SoapBinding"); {
w.writeEmptyElement(SOAP_WSDL, "address");
String destinationName = listener.getDestinationName();
if (destinationName != null) {
w.writeAttribute("location", destinationName);
}
if (esbSoap) {
writeEsbSoapJndiContext(w, listener);
w.writeStartElement(ESB_SOAP_JMS, "connectionFactory"); {
w.writeCharacters("externalJndiName-for-"
+ listener.getQueueConnectionFactoryName()
+ "-on-"
+ AppConstants.getInstance().getResolvedProperty("otap.stage"));
w.writeEndElement();
}
w.writeStartElement(ESB_SOAP_JMS, "targetAddress"); {
w.writeAttribute("destination",
listener.getDestinationType().toLowerCase());
String queueName = listener.getPhysicalDestinationShortName();
if (queueName == null) {
queueName = "queueName-for-"
+ listener.getDestinationName() + "-on-"
+ AppConstants.getInstance().getResolvedProperty("otap.stage");
}
w.writeCharacters(queueName);
w.writeEndElement();
}
}
}
w.writeEndElement();
}
w.writeEndElement();
}
protected void writeEsbSoapJndiContext(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException {
w.writeStartElement(ESB_SOAP_JNDI, "context"); {
w.writeStartElement(ESB_SOAP_JNDI, "property"); {
w.writeAttribute("name", "java.naming.factory.initial");
w.writeAttribute("type", "java.lang.String");
w.writeCharacters("com.tibco.tibjms.naming.TibjmsInitialContextFactory");
w.writeEndElement();
}
w.writeStartElement(ESB_SOAP_JNDI, "property"); {
w.writeAttribute("name", "java.naming.provider.url");
w.writeAttribute("type", "java.lang.String");
String qcf = "";
String stage = "";
try {
qcf = URLEncoder.encode(
listener.getQueueConnectionFactoryName(), "UTF-8");
stage = URLEncoder.encode(
AppConstants.getInstance().getResolvedProperty("otap.stage"),
"UTF-8");
} catch (UnsupportedEncodingException e) {
}
w.writeCharacters("tibjmsnaming://host-for-" + qcf + "-on-"
+ stage + ":37222");
w.writeEndElement();
}
w.writeStartElement(ESB_SOAP_JNDI, "property"); {
w.writeAttribute("name", "java.naming.factory.object");
w.writeAttribute("type", "java.lang.String");
w.writeCharacters("com.tibco.tibjms.custom.CustomObjectFactory");
w.writeEndElement();
}
}
w.writeEndElement();
}
protected void warnings(XMLStreamWriter w) throws XMLStreamException {
for (String warning : warnings) {
w.writeComment(warning);
}
}
protected PipeLine getPipeLine() {
return pipeLine;
}
protected EsbSoapWrapperPipe getEsbSoapInputWrapper() {
IPipe inputWrapper = pipeLine.getInputWrapper();
if (inputWrapper instanceof EsbSoapWrapperPipe) {
return (EsbSoapWrapperPipe) inputWrapper;
}
return null;
}
protected EsbSoapWrapperPipe getEsbSoapOutputWrapper() {
IPipe outputWrapper = pipeLine.getOutputWrapper();
if (outputWrapper instanceof EsbSoapWrapperPipe) {
return (EsbSoapWrapperPipe) outputWrapper;
}
return null;
}
protected Collection<QName> getHeaderTags(XmlValidator xmlValidator) throws XMLStreamException, IOException {
if (xmlValidator instanceof SoapValidator) {
String root = ((SoapValidator)xmlValidator).getSoapHeader();
QName q = getRootTag(root);
if (q != null) {
return Collections.singleton(q);
}
}
return Collections.emptyList();
}
protected Collection<QName> getRootTags(XmlValidator xmlValidator) throws IOException, XMLStreamException {
String root;
if (xmlValidator instanceof SoapValidator) {
root = ((SoapValidator)xmlValidator).getSoapBody();
} else {
root = xmlValidator.getRoot();
}
QName q = getRootTag(root);
if (q != null) {
return Collections.singleton(q);
}
return Collections.emptyList();
}
protected QName getRootTag(String tag) throws XMLStreamException, IOException {
if (StringUtils.isNotEmpty(tag)) {
for (XSD xsd : rootXsds) {
for (String rootTag : xsd.rootTags) {
if (tag.equals(rootTag)) {
String prefix = prefixByXsd.get(xsd);
return new QName(namespaceByPrefix.get(prefix), tag, prefix);
}
}
}
warn("Root element '" + tag + "' not found in XSD's");
}
return null;
}
protected Collection<QName> getInputHeaderTags() throws IOException, XMLStreamException {
return getHeaderTags(inputValidator);
}
protected Collection<QName> getInputBodyTags() throws IOException, XMLStreamException {
return getRootTags(inputValidator);
}
protected Collection<QName> getOutputHeaderTags() throws IOException, XMLStreamException {
return getHeaderTags(outputValidator);
}
protected Collection<QName> getOutputBodyTags() throws IOException, XMLStreamException {
return getRootTags((XmlValidator)getPipeLine().getOutputValidator());
}
protected void warn(String warning) {
warning = "Warning: " + warning;
if (!warnings.contains(warning)) {
warnings.add(warning);
}
}
}
|
package test.ccn.security.access;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
public class GroupTest {
/**
* Have to make a bunch of users.
* @throws Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void testReady() {
fail("Not yet implemented");
}
@Test
public void testPrivateKeyDirectory() {
fail("Not yet implemented");
}
@Test
public void testFriendlyName() {
fail("Not yet implemented");
}
@Test
public void testMembershipList() {
fail("Not yet implemented");
}
@Test
public void testMembershipListName() {
fail("Not yet implemented");
}
@Test
public void testMembershipListVersion() {
fail("Not yet implemented");
}
@Test
public void testClearCachedMembershipList() {
fail("Not yet implemented");
}
@Test
public void testPublicKey() {
fail("Not yet implemented");
}
@Test
public void testPublicKeyName() {
fail("Not yet implemented");
}
@Test
public void testPublicKeyVersion() {
fail("Not yet implemented");
}
@Test
public void testSetMembershipList() {
fail("Not yet implemented");
}
@Test
public void testNewGroupPublicKey() {
fail("Not yet implemented");
}
@Test
public void testCreateGroupPublicKey() {
fail("Not yet implemented");
}
@Test
public void testUpdateGroupPublicKey() {
fail("Not yet implemented");
}
@Test
public void testModify() {
fail("Not yet implemented");
}
@Test
public void testDelete() {
fail("Not yet implemented");
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-11-02");
this.setApiVersion("15.10.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-03-29");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-11-10");
this.setApiVersion("17.12.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:18-04-10");
this.setApiVersion("3.3.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-11-01");
this.setApiVersion("15.9.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-02-13");
this.setApiVersion("16.16.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-04-11");
this.setApiVersion("18.2.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-03-01");
this.setApiVersion("15.18.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:19-09-16");
this.setApiVersion("15.7.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.gc.materialdesign.views;
import com.gc.materialdesign.R;
import com.gc.materialdesign.utils.Utils;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class Switch extends CustomView {
int backgroundColor = Color.parseColor("#4CAF50");
Ball ball;
boolean check = false;
boolean eventCheck = false;
boolean press = false;
OnCheckListener onCheckListener;
public Switch(Context context, AttributeSet attrs) {
super(context, attrs);
setAttributes(attrs);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (check)
setChecked(false);
else
setChecked(true);
}
});
}
// Set atributtes of XML to View
protected void setAttributes(AttributeSet attrs) {
setBackgroundResource(R.drawable.background_transparent);
// Set size of view
setMinimumHeight(Utils.dpToPx(48, getResources()));
setMinimumWidth(Utils.dpToPx(80, getResources()));
// Set background Color
// Color by resource
int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML,
"background", -1);
if (bacgroundColor != -1) {
setBackgroundColor(getResources().getColor(bacgroundColor));
} else {
// Color by hexadecimal
int background = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
if (background != -1)
setBackgroundColor(background);
}
check = attrs.getAttributeBooleanValue(MATERIALDESIGNXML, "check",
false);
eventCheck = check;
ball = new Ball(getContext());
RelativeLayout.LayoutParams params = new LayoutParams(Utils.dpToPx(20,
getResources()), Utils.dpToPx(20, getResources()));
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
ball.setLayoutParams(params);
addView(ball);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isEnabled()) {
isLastTouch = true;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
press = true;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float x = event.getX();
x = (x < ball.xIni) ? ball.xIni : x;
x = (x > ball.xFin) ? ball.xFin : x;
if (x > ball.xCen) {
eventCheck = true;
} else {
eventCheck = false;
}
ViewHelper.setX(ball, x);
ball.changeBackground();
if ((event.getX() <= getWidth() && event.getX() >= 0)) {
isLastTouch = false;
press = false;
}
} else if (event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
press = false;
isLastTouch = false;
if (eventCheck != check) {
check = eventCheck;
if (onCheckListener != null)
onCheckListener.onCheck(check);
}
if ((event.getX() <= getWidth() && event.getX() >= 0)) {
ball.animateCheck();
}
}
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!placedBall)
placeBall();
// Crop line to transparent effect
Bitmap bitmap = Bitmap.createBitmap(canvas.getWidth(),
canvas.getHeight(), Bitmap.Config.ARGB_8888);
Canvas temp = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor((eventCheck) ? backgroundColor : Color.parseColor("#B0B0B0"));
paint.setStrokeWidth(Utils.dpToPx(2, getResources()));
temp.drawLine(getHeight() / 2, getHeight() / 2, getWidth()
- getHeight() / 2, getHeight() / 2, paint);
Paint transparentPaint = new Paint();
transparentPaint.setAntiAlias(true);
transparentPaint.setColor(getResources().getColor(
android.R.color.transparent));
transparentPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
temp.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
ViewHelper.getY(ball) + ball.getHeight() / 2,
ball.getWidth() / 2, transparentPaint);
canvas.drawBitmap(bitmap, 0, 0, new Paint());
if (press) {
paint.setColor((check) ? makePressColor() : Color
.parseColor("#446D6D6D"));
canvas.drawCircle(ViewHelper.getX(ball) + ball.getWidth() / 2,
getHeight() / 2, getHeight() / 2, paint);
}
invalidate();
}
/**
* Make a dark color to press effect
*
* @return
*/
protected int makePressColor() {
int r = (this.backgroundColor >> 16) & 0xFF;
int g = (this.backgroundColor >> 8) & 0xFF;
int b = (this.backgroundColor >> 0) & 0xFF;
r = (r - 30 < 0) ? 0 : r - 30;
g = (g - 30 < 0) ? 0 : g - 30;
b = (b - 30 < 0) ? 0 : b - 30;
return Color.argb(70, r, g, b);
}
// Move ball to first position in view
boolean placedBall = false;
private void placeBall() {
ViewHelper.setX(ball, getHeight() / 2 - ball.getWidth() / 2);
ball.xIni = ViewHelper.getX(ball);
ball.xFin = getWidth() - getHeight() / 2 - ball.getWidth() / 2;
ball.xCen = getWidth() / 2 - ball.getWidth() / 2;
placedBall = true;
ball.animateCheck();
}
// SETTERS
@Override
public void setBackgroundColor(int color) {
backgroundColor = color;
if (isEnabled())
beforeBackground = backgroundColor;
}
public void setChecked(boolean check) {
invalidate();
this.check = check;
this.eventCheck = check;
ball.animateCheck();
}
public boolean isCheck() {
return check;
}
class Ball extends View {
float xIni, xFin, xCen;
public Ball(Context context) {
super(context);
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
public void changeBackground() {
if (eventCheck) {
setBackgroundResource(R.drawable.background_checkbox);
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);
} else {
setBackgroundResource(R.drawable.background_switch_ball_uncheck);
}
}
public void animateCheck() {
changeBackground();
ObjectAnimator objectAnimator;
if (eventCheck) {
objectAnimator = ObjectAnimator.ofFloat(this, "x", ball.xFin);
} else {
objectAnimator = ObjectAnimator.ofFloat(this, "x", ball.xIni);
}
objectAnimator.setDuration(300);
objectAnimator.start();
}
}
public void setOncheckListener(OnCheckListener onCheckListener) {
this.onCheckListener = onCheckListener;
}
public interface OnCheckListener {
public void onCheck(boolean check);
}
}
|
package ch.openech.mj.model;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import ch.openech.mj.util.IdUtils;
public class Reference<T> implements Serializable {
private final Map<Object, Object> values;
private long referencedId;
public Reference(Object... keys) {
if (keys.length > 0) {
values = new HashMap<>(keys.length * 2);
for (Object key : keys) {
values.put(key, null);
}
} else {
values = Collections.emptyMap();
}
}
public long getReferencedId() {
return referencedId;
}
public void setReferencedId(long referencedId) {
this.referencedId = referencedId;
}
public boolean isEmpty() {
return referencedId == 0;
}
public Object get(Object key) {
if (!values.containsKey(key)) throw new IllegalArgumentException("Not declared: " + key);
return values.get(key);
}
public void set(Object key, Object value) {
if (!values.containsKey(key)) throw new IllegalArgumentException("Not declared: " + key);
values.put(key, value);
}
public void set(Object value) {
if (value != null) {
referencedId = IdUtils.getId(value);
for (Object key : values.keySet()) {
PropertyInterface property = Keys.getProperty(key);
Object v = property.getValue(value);
values.put(key, v);
}
} else {
referencedId = 0;
for (Object key : values.keySet()) {
values.put(key, null);
}
}
}
public Map<String, PropertyInterface> getProperties() {
Map<String, PropertyInterface> properties = new HashMap<>();
for (Object key : values.keySet()) {
PropertyInterface property = new ReferenceProperty(key);
properties.put(property.getFieldName(), property);
}
return properties;
}
public static class ReferenceProperty implements PropertyInterface {
private final Object key;
private final PropertyInterface property;
public ReferenceProperty(Object key) {
this.key = key;
this.property = Keys.getProperty(key);
}
public Class<?> getDeclaringClass() {
return property.getDeclaringClass();
}
public String getFieldName() {
return "^" + property.getFieldName();
}
public String getFieldPath() {
return "^" + property.getFieldPath();
}
public Class<?> getFieldClazz() {
return property.getFieldClazz();
}
public Type getType() {
return property.getType();
}
public <S extends Annotation> S getAnnotation(Class<S> annotationClass) {
return property.getAnnotation(annotationClass);
}
public Object getValue(Object object) {
return ((Reference<?>) object).get(key);
}
public void setValue(Object object, Object value) {
((Reference<?>) object).set(key, value);
}
public boolean isFinal() {
return false;
}
}
}
|
package ru.matevosyan.start;
public class StartUI {
/**
* Instance variable for set the range of user enters action
*/
private int[] range = new int[] {1, 2, 3};
/**
* Input instance variable input.
*/
private Input input;
/**
* Input instance variable tracker.
*/
private Tracker tracker;
/**
* Constructor for StartUI.
* @param input for assign ot enter data to the program.
* @param tracker for take the Tracker state.
*/
public StartUI(Input input, Tracker tracker) {
this.input = input;
this.tracker = tracker;
}
/**
* Method for initialization program menu and interaction with user.
*/
public void init() {
/**
* variables for user check.
*/
final String exit = "y";
MenuTracker menu = new MenuTracker(this.input, this.tracker);
menu.fillAction();
do {
menu.show();
menu.select(input.ask("Select: ", range));
} while (!exit.equals(this.input.ask("Esit? (y) ")));
}
/**
* The static main method which is starting our program.
* @param args is the array argument that pass to main method
*/
public static void main(String[] args) {
/**
* Instance variable StartUI and call the method init.
*/
Input input = new ValidateInput();
new StartUI(input, new Tracker()).init();
}
}
|
package ru.matevosyan.start;
import ru.matevosyan.models.Item;
import java.util.Random;
public class Tracker {
/**
* final variable int ITEMS_CAP is items array capacity.
*/
private static final int ITEMS_CAP = 3;
/**
* Instance variable items which is array types is hold all created items.
*/
private Item[] items = new Item[ITEMS_CAP];
/**
* int variable position is hold position elements in array items.
*/
private int position = 0;
/**
*Instance variable RM is created for value for items id.
*/
private Random rm = new Random();
/**
* Method add created for add new item to array items.
* it's may the specific type of item, for example: new Task or new Bug.
* @param item which is the new item.
* @return item that added to the items array
*/
public Item add(Item item) {
item.setId(this.generateId());
this.items[position] = item;
position++;
return item;
}
/**
* Method deleteItem created for deleted exist item from array of items.
* it's may remove the specific type of item: Task or Bug.
* @param id it is for determine which of this specific item must be deleted.
* @return itemsDelete array without deleted item
*/
public Item[] deleteItem(String id) {
Item[] itemsDelete = new Item[items.length - 1];
for (int i = 0; i < items.length; i++) {
if (items[i] != null && items[i].getId().equals(id)) {
for (int j = 0; j < items.length - 1; j++) {
items[j] = items[j + 1];
}
}
}
for (int i = 0; i < items.length - 1; i++) {
itemsDelete[i] = items[i];
}
return itemsDelete;
}
/**
* Method editItem created for edit exist item from array of items.
* it's may edit the specific type of item: Task or Bug.
* @param fresh it is specific item that you want to edit.
*/
public void editItem(Item fresh) {
for (int index = 0; index < items.length; index++) {
Item item = items[index];
if (item != null && item.getId().equals(fresh.getId())) {
items[index] = fresh;
break;
}
}
}
/**
* Method findById created for find exist item from array of items passing through method item's id.
* @param id it is specific item's id that item's would you like to find out.
* @return resultFindById it's concrete item that you find out
*/
public Item findById(String id) {
Item resultFindById = null;
for (Item item : items) {
if (item != null && item.getId().equals(id)) {
resultFindById = item;
break;
}
}
return resultFindById;
}
/**
* Method findByName created for find exist item from array of items passing through method item's name.
* @param name it is specific item's id that item's would you like to find out.
* @return resultFindByName it's concrete item that you find out
*/
public Item findByName(String name) {
Item resultFindByName = null;
for (Item item : items) {
if (item != null && item.getName().equals(name)) {
resultFindByName = item;
}
}
return resultFindByName;
}
/**
* Method findByyDate created for find exist item from array of items passing through method item's created date.
* @param create it is concrete item's created date that item's would you like to find out.
* @return resultFindByyDate it's concrete item that you find out
*/
public Item findByDate(long create) {
Item resultFindByDate = null;
for (Item item : items) {
if (item != null && item.getCreate() == (create)) {
resultFindByDate = item;
}
}
return resultFindByDate;
}
/**
* Method generateId created for generate items id.
* @return generated id number
*/
private String generateId() {
final int idDev = 1_000_000;
return String.valueOf(Math.abs(rm.nextInt() / idDev));
}
/**
* Method getAll created for getting all of exist item from array of items.
* @return itemsDelete array without deleted item
*/
public Item[] getAll() {
Item[] result = new Item[this.position];
for (int index = 0; index != this.position; index++) {
result[index] = this.items[index];
}
return result;
}
/**
* Method addComment using for adding comment to the item.
* @param item it is item that you want to comment
* @param comment it is comment that you passing to the method to add to your item
*/
public void addComment(Item item, String comment) {
item.addComment(comment);
}
/**
* method fillRangeOfId to return concrete id from item.
* @return itemIdRange array of all items id
*/
public String[] fillRangeOfId() {
int countIdRange = 0;
String[] itemIdRange = new String[ITEMS_CAP];
for (int i = 0; this.items[i] != null; i++) {
itemIdRange[countIdRange] = items[i].getId();
countIdRange++;
}
return itemIdRange;
}
}
|
package com.osmbonuspackdemo;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.clustering.GridMarkerClusterer;
import org.osmdroid.bonuspack.kml.KmlFeature;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.kml.KmlFolder;
import org.osmdroid.bonuspack.kml.KmlPlacemark;
import org.osmdroid.bonuspack.kml.Style;
import org.osmdroid.bonuspack.location.FlickrPOIProvider;
import org.osmdroid.bonuspack.location.GeoNamesPOIProvider;
import org.osmdroid.bonuspack.location.GeocoderNominatim;
import org.osmdroid.bonuspack.location.NominatimPOIProvider;
import org.osmdroid.bonuspack.location.POI;
import org.osmdroid.bonuspack.location.PicasaPOIProvider;
import org.osmdroid.bonuspack.overlays.FolderOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.bonuspack.overlays.Marker.OnMarkerDragListener;
import org.osmdroid.bonuspack.overlays.MarkerInfoWindow;
import org.osmdroid.bonuspack.overlays.Polygon;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.routing.GoogleRoadManager;
import org.osmdroid.bonuspack.routing.MapQuestRoadManager;
import org.osmdroid.bonuspack.routing.OSRMRoadManager;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.MapTileProviderBase;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.MapBoxTileSource;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.NetworkLocationIgnorer;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.DirectedLocationOverlay;
import org.osmdroid.views.overlay.Overlay;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Address;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MapActivity extends Activity implements MapEventsReceiver, LocationListener, SensorEventListener {
protected MapView map;
protected GeoPoint startPoint, destinationPoint;
protected ArrayList<GeoPoint> viaPoints;
protected static int START_INDEX=-2, DEST_INDEX=-1;
protected FolderOverlay itineraryMarkers;
//for departure, destination and viapoints
protected Marker markerStart, markerDestination;
protected ViaPointInfoWindow mViaPointInfoWindow;
protected DirectedLocationOverlay myLocationOverlay;
//MyLocationNewOverlay myLocationNewOverlay;
protected LocationManager locationManager;
//protected SensorManager mSensorManager;
//protected Sensor mOrientation;
protected boolean mTrackingMode;
Button mTrackingModeButton;
float mAzimuthAngleSpeed = 0.0f;
protected Polygon mDestinationPolygon; //enclosing polygon of destination location
public static Road mRoad; //made static to pass between activities
protected Polyline roadOverlay;
protected FolderOverlay roadNodeMarkers;
protected static final int ROUTE_REQUEST = 1;
static final int OSRM=0, MAPQUEST_FASTEST=1, MAPQUEST_BICYCLE=2, MAPQUEST_PEDESTRIAN=3, GOOGLE_FASTEST=4;
int whichRouteProvider;
public static ArrayList<POI> mPOIs; //made static to pass between activities
GridMarkerClusterer poiMarkers;
AutoCompleteTextView poiTagText;
protected static final int POIS_REQUEST = 2;
protected FolderOverlay mKmlOverlay; //root container of overlays from KML reading
protected static final int KML_TREE_REQUEST = 3;
public static KmlDocument mKmlDocument; //made static to pass between activities
public static Stack<KmlFeature> mKmlStack; //passed between activities, top is the current KmlFeature to edit.
public static KmlFolder mKmlClipboard; //passed between activities. Folder for multiple items selection.
static String SHARED_PREFS_APPKEY = "OSMNavigator";
static String PREF_LOCATIONS_KEY = "PREF_LOCATIONS";
OnlineTileSourceBase MAPBOXSATELLITELABELLED;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE);
MapBoxTileSource.retrieveMapBoxMapId(this);
MAPBOXSATELLITELABELLED = new MapBoxTileSource("MapBoxSatelliteLabelled", ResourceProxy.string.mapquest_aerial, 1, 19, 256, ".png");
TileSourceFactory.addTileSource(MAPBOXSATELLITELABELLED);
map = (MapView) findViewById(R.id.map);
String tileProviderName = prefs.getString("TILE_PROVIDER", "Mapnik");
try {
ITileSource tileSource = TileSourceFactory.getTileSource(tileProviderName);
map.setTileSource(tileSource);
} catch (IllegalArgumentException e) {
map.setTileSource(TileSourceFactory.MAPNIK);
}
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
IMapController mapController = map.getController();
//To use MapEventsReceiver methods, we add a MapEventsOverlay:
MapEventsOverlay overlay = new MapEventsOverlay(this, this);
map.getOverlays().add(overlay);
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
//mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
//map prefs:
mapController.setZoom(prefs.getInt("MAP_ZOOM_LEVEL", 5));
mapController.setCenter(new GeoPoint((double)prefs.getFloat("MAP_CENTER_LAT", 48.5f),
(double)prefs.getFloat("MAP_CENTER_LON", 2.5f)));
myLocationOverlay = new DirectedLocationOverlay(this);
map.getOverlays().add(myLocationOverlay);
if (savedInstanceState == null){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
//location known:
onLocationChanged(location);
} else {
//no location known: hide myLocationOverlay
myLocationOverlay.setEnabled(false);
}
startPoint = null;
destinationPoint = null;
viaPoints = new ArrayList<GeoPoint>();
} else {
myLocationOverlay.setLocation((GeoPoint)savedInstanceState.getParcelable("location"));
//TODO: restore other aspects of myLocationOverlay...
startPoint = savedInstanceState.getParcelable("start");
destinationPoint = savedInstanceState.getParcelable("destination");
viaPoints = savedInstanceState.getParcelableArrayList("viapoints");
}
//ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(this);
//map.getOverlays().add(scaleBarOverlay);
// Itinerary markers:
itineraryMarkers = new FolderOverlay(this);
map.getOverlays().add(itineraryMarkers);
mViaPointInfoWindow = new ViaPointInfoWindow(R.layout.itinerary_bubble, map);
updateUIWithItineraryMarkers();
//Tracking system:
mTrackingModeButton = (Button)findViewById(R.id.buttonTrackingMode);
mTrackingModeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mTrackingMode = !mTrackingMode;
updateUIWithTrackingMode();
}
});
if (savedInstanceState != null){
mTrackingMode = savedInstanceState.getBoolean("tracking_mode");
updateUIWithTrackingMode();
} else
mTrackingMode = false;
AutoCompleteOnPreferences departureText = (AutoCompleteOnPreferences) findViewById(R.id.editDeparture);
departureText.setPrefKeys(SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY);
Button searchDepButton = (Button)findViewById(R.id.buttonSearchDep);
searchDepButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
handleSearchButton(START_INDEX, R.id.editDeparture);
}
});
AutoCompleteOnPreferences destinationText = (AutoCompleteOnPreferences) findViewById(R.id.editDestination);
destinationText.setPrefKeys(SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY);
Button searchDestButton = (Button)findViewById(R.id.buttonSearchDest);
searchDestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
handleSearchButton(DEST_INDEX, R.id.editDestination);
}
});
View expander = (View)findViewById(R.id.expander);
expander.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
View searchPanel = (View)findViewById(R.id.search_panel);
if (searchPanel.getVisibility() == View.VISIBLE){
searchPanel.setVisibility(View.GONE);
} else {
searchPanel.setVisibility(View.VISIBLE);
}
}
});
View searchPanel = (View)findViewById(R.id.search_panel);
searchPanel.setVisibility(prefs.getInt("PANEL_VISIBILITY", View.VISIBLE));
registerForContextMenu(searchDestButton);
//context menu for clicking on the map is registered on this button.
//(a little bit strange, but if we register it on mapView, it will catch map drag events)
//Route and Directions
whichRouteProvider = prefs.getInt("ROUTE_PROVIDER", OSRM);
roadNodeMarkers = new FolderOverlay(this);
map.getOverlays().add(roadNodeMarkers);
if (savedInstanceState != null){
//STATIC mRoad = savedInstanceState.getParcelable("road");
updateUIWithRoad(mRoad);
}
//POIs:
//POI search interface:
String[] poiTags = getResources().getStringArray(R.array.poi_tags);
poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
ArrayAdapter<String> poiAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, poiTags);
poiTagText.setAdapter(poiAdapter);
Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
setPOITagButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Hide the soft keyboard:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
//Start search:
String feature = poiTagText.getText().toString();
if (!feature.equals(""))
Toast.makeText(v.getContext(), "Searching:\n"+feature, Toast.LENGTH_LONG).show();
getPOIAsync(feature);
}
});
//POI markers:
poiMarkers = new GridMarkerClusterer(this);
Drawable clusterIconD = getResources().getDrawable(R.drawable.marker_poi_cluster);
Bitmap clusterIcon = ((BitmapDrawable)clusterIconD).getBitmap();
poiMarkers.setIcon(clusterIcon);
poiMarkers.mAnchorV = Marker.ANCHOR_BOTTOM;
poiMarkers.mTextAnchorU = 0.70f;
poiMarkers.mTextAnchorV = 0.27f;
poiMarkers.getTextPaint().setTextSize(12.0f);
map.getOverlays().add(poiMarkers);
if (savedInstanceState != null){
//STATIC - mPOIs = savedInstanceState.getParcelableArrayList("poi");
updateUIWithPOI(mPOIs);
}
//KML handling:
mKmlOverlay = null;
if (savedInstanceState != null){
//STATIC - mKmlDocument = savedInstanceState.getParcelable("kml");
updateUIWithKml();
} else { //first launch:
mKmlDocument = new KmlDocument();
mKmlStack = new Stack<KmlFeature>();
mKmlClipboard = new KmlFolder();
//check if intent has been passed with a kml URI to load (url or file)
Intent onCreateIntent = getIntent();
if (onCreateIntent.getAction().equals(Intent.ACTION_VIEW)){
String uri = onCreateIntent.getDataString();
openFile(uri, true);
}
}
}
void setViewOn(BoundingBoxE6 bb){
if (bb != null){
map.zoomToBoundingBox(bb);
}
}
void savePrefs(){
SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putInt("MAP_ZOOM_LEVEL", map.getZoomLevel());
GeoPoint c = (GeoPoint) map.getMapCenter();
ed.putFloat("MAP_CENTER_LAT", c.getLatitudeE6()*1E-6f);
ed.putFloat("MAP_CENTER_LON", c.getLongitudeE6()*1E-6f);
MapTileProviderBase tileProvider = map.getTileProvider();
String tileProviderName = tileProvider.getTileSource().name();
View searchPanel = (View)findViewById(R.id.search_panel);
ed.putInt("PANEL_VISIBILITY", searchPanel.getVisibility());
ed.putString("TILE_PROVIDER", tileProviderName);
ed.putInt("ROUTE_PROVIDER", whichRouteProvider);
ed.commit();
}
/**
* callback to store activity status before a restart (orientation change for instance)
*/
@Override protected void onSaveInstanceState (Bundle outState){
outState.putParcelable("location", myLocationOverlay.getLocation());
outState.putBoolean("tracking_mode", mTrackingMode);
outState.putParcelable("start", startPoint);
outState.putParcelable("destination", destinationPoint);
outState.putParcelableArrayList("viapoints", viaPoints);
//STATIC - outState.putParcelable("road", mRoad);
//STATIC - outState.putParcelableArrayList("poi", mPOIs);
//STATIC - outState.putParcelable("kml", mKmlDocument);
savePrefs();
}
@Override protected void onActivityResult (int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case ROUTE_REQUEST :
if (resultCode == RESULT_OK) {
int nodeId = intent.getIntExtra("NODE_ID", 0);
map.getController().setCenter(mRoad.mNodes.get(nodeId).mLocation);
Marker roadMarker = (Marker)roadNodeMarkers.getItems().get(nodeId);
roadMarker.showInfoWindow();
}
break;
case POIS_REQUEST:
if (resultCode == RESULT_OK) {
int id = intent.getIntExtra("ID", 0);
map.getController().setCenter(mPOIs.get(id).mLocation);
Marker poiMarker = (Marker)poiMarkers.getItem(id);
poiMarker.showInfoWindow();
}
break;
case KML_TREE_REQUEST:
KmlFolder result = (KmlFolder)mKmlStack.pop();
if (resultCode == RESULT_OK) {
//use the object which has been modified in KmlTreeActivity:
mKmlDocument.mKmlRoot = result; //intent.getParcelableExtra("KML");
updateUIWithKml();
}
break;
default:
break;
}
}
/* String getBestProvider(){
String bestProvider = null;
//bestProvider = locationManager.getBestProvider(new Criteria(), true); // => returns "Network Provider"!
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
bestProvider = LocationManager.GPS_PROVIDER;
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
bestProvider = LocationManager.NETWORK_PROVIDER;
return bestProvider;
} */
boolean startLocationUpdates(){
boolean result = false;
for (final String provider : locationManager.getProviders(true)) {
locationManager.requestLocationUpdates(provider, 2*1000, 0.0f, this);
result = true;
}
return result;
}
@Override protected void onResume() {
super.onResume();
boolean isOneProviderEnabled = startLocationUpdates();
myLocationOverlay.setEnabled(isOneProviderEnabled);
//TODO: not used currently
//mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL);
//sensor listener is causing a high CPU consumption...
}
@Override protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
//TODO: mSensorManager.unregisterListener(this);
savePrefs();
}
void updateUIWithTrackingMode(){
if (mTrackingMode){
mTrackingModeButton.setBackgroundResource(R.drawable.btn_tracking_on);
if (myLocationOverlay.isEnabled()&& myLocationOverlay.getLocation() != null){
map.getController().animateTo(myLocationOverlay.getLocation());
}
map.setMapOrientation(-mAzimuthAngleSpeed);
mTrackingModeButton.setKeepScreenOn(true);
} else {
mTrackingModeButton.setBackgroundResource(R.drawable.btn_tracking_off);
map.setMapOrientation(0.0f);
mTrackingModeButton.setKeepScreenOn(false);
}
}
/**
* Reverse Geocoding
*/
public String getAddress(GeoPoint p){
GeocoderNominatim geocoder = new GeocoderNominatim(this);
String theAddress;
try {
double dLatitude = p.getLatitudeE6() * 1E-6;
double dLongitude = p.getLongitudeE6() * 1E-6;
List<Address> addresses = geocoder.getFromLocation(dLatitude, dLongitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int n = address.getMaxAddressLineIndex();
for (int i=0; i<=n; i++) {
if (i!=0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
theAddress = new String(sb.toString());
} else {
theAddress = null;
}
} catch (IOException e) {
theAddress = null;
}
if (theAddress != null) {
return theAddress;
} else {
return "";
}
}
/**
* Geocoding of the departure or destination address
*/
public void handleSearchButton(int index, int editResId){
EditText locationEdit = (EditText)findViewById(editResId);
//Hide the soft keyboard:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(locationEdit.getWindowToken(), 0);
String locationAddress = locationEdit.getText().toString();
if (locationAddress.equals("")){
removePoint(index);
map.invalidate();
return;
}
Toast.makeText(this, "Searching:\n"+locationAddress, Toast.LENGTH_LONG).show();
AutoCompleteOnPreferences.storePreference(this, locationAddress, SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY);
GeocoderNominatim geocoder = new GeocoderNominatim(this);
geocoder.setOptions(true); //ask for enclosing polygon (if any)
try {
List<Address> foundAdresses = geocoder.getFromLocationName(locationAddress, 1);
if (foundAdresses.size() == 0) { //if no address found, display an error
Toast.makeText(this, "Address not found.", Toast.LENGTH_SHORT).show();
} else {
Address address = foundAdresses.get(0); //get first address
if (index == START_INDEX){
startPoint = new GeoPoint(address.getLatitude(), address.getLongitude());
markerStart = updateItineraryMarker(markerStart, startPoint, START_INDEX,
R.string.departure, R.drawable.marker_departure, -1);
map.getController().setCenter(startPoint);
} else if (index == DEST_INDEX){
destinationPoint = new GeoPoint(address.getLatitude(), address.getLongitude());
markerDestination = updateItineraryMarker(markerDestination, destinationPoint, DEST_INDEX,
R.string.destination, R.drawable.marker_destination, -1);
map.getController().setCenter(destinationPoint);
}
getRoadAsync();
//get and display enclosing polygon:
Bundle extras = address.getExtras();
if (extras != null && extras.containsKey("polygonpoints")){
ArrayList<GeoPoint> polygon = extras.getParcelableArrayList("polygonpoints");
//Log.d("DEBUG", "polygon:"+polygon.size());
updateUIWithPolygon(polygon);
} else {
updateUIWithPolygon(null);
}
}
} catch (Exception e) {
Toast.makeText(this, "Geocoding error", Toast.LENGTH_SHORT).show();
}
}
//add or replace the polygon overlay
public void updateUIWithPolygon(ArrayList<GeoPoint> polygon){
List<Overlay> mapOverlays = map.getOverlays();
int location = -1;
if (mDestinationPolygon != null)
location = mapOverlays.indexOf(mDestinationPolygon);
mDestinationPolygon = new Polygon(this);
mDestinationPolygon.setFillColor(0x30FF0080);
mDestinationPolygon.setStrokeColor(0x800000FF);
mDestinationPolygon.setStrokeWidth(5.0f);
BoundingBoxE6 bb = null;
if (polygon != null){
mDestinationPolygon.setPoints(polygon);
bb = BoundingBoxE6.fromGeoPoints(polygon);
}
if (location != -1)
mapOverlays.set(location, mDestinationPolygon);
else
mapOverlays.add(mDestinationPolygon);
if (bb != null)
setViewOn(bb);
map.invalidate();
}
//Async task to reverse-geocode the marker position in a separate thread:
private class GeocodingTask extends AsyncTask<Object, Void, String> {
Marker marker;
protected String doInBackground(Object... params) {
marker = (Marker)params[0];
return getAddress(marker.getPosition());
}
protected void onPostExecute(String result) {
marker.setSnippet(result);
marker.showInfoWindow();
}
}
class OnItineraryMarkerDragListener implements OnMarkerDragListener {
@Override public void onMarkerDrag(Marker marker) {}
@Override public void onMarkerDragEnd(Marker marker) {
int index = (Integer)marker.getRelatedObject();
if (index == START_INDEX)
startPoint = marker.getPosition();
else if (index == DEST_INDEX)
destinationPoint = marker.getPosition();
else
viaPoints.set(index, marker.getPosition());
//update location:
new GeocodingTask().execute(marker);
//update route:
getRoadAsync();
}
@Override public void onMarkerDragStart(Marker marker) {}
}
final OnItineraryMarkerDragListener mItineraryListener = new OnItineraryMarkerDragListener();
/** Update (or create if null) a marker in itineraryMarkers. */
public Marker updateItineraryMarker(Marker item, GeoPoint p, int index,
int titleResId, int markerResId, int imageResId) {
Drawable icon = getResources().getDrawable(markerResId);
String title = getResources().getString(titleResId);
if (item == null){
item = new Marker(map);
item.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
item.setInfoWindow(mViaPointInfoWindow);
item.setDraggable(true);
item.setOnMarkerDragListener(mItineraryListener);
itineraryMarkers.add(item);
}
item.setTitle(title);
item.setPosition(p);
item.setIcon(icon);
if (imageResId != -1)
item.setImage(getResources().getDrawable(imageResId));
item.setRelatedObject(index);
map.invalidate();
//Start geocoding task to update the description of the marker with its address:
new GeocodingTask().execute(item);
return item;
}
public void addViaPoint(GeoPoint p){
viaPoints.add(p);
updateItineraryMarker(null, p, viaPoints.size()-1,
R.string.viapoint, R.drawable.marker_via, -1);
}
public void removePoint(int index){
if (index == START_INDEX){
startPoint = null;
if (markerStart != null){
itineraryMarkers.remove(markerStart);
markerStart = null;
}
} else if (index == DEST_INDEX){
destinationPoint = null;
if (markerDestination != null){
itineraryMarkers.remove(markerDestination);
markerDestination = null;
}
} else {
viaPoints.remove(index);
updateUIWithItineraryMarkers();
}
getRoadAsync();
}
public void updateUIWithItineraryMarkers(){
itineraryMarkers.getItems().clear();
//Start marker:
if (startPoint != null){
markerStart = updateItineraryMarker(null, startPoint, START_INDEX,
R.string.departure, R.drawable.marker_departure, -1);
}
//Via-points markers if any:
for (int index=0; index<viaPoints.size(); index++){
updateItineraryMarker(null, viaPoints.get(index), index,
R.string.viapoint, R.drawable.marker_via, -1);
}
//Destination marker if any:
if (destinationPoint != null){
markerDestination = updateItineraryMarker(null, destinationPoint, DEST_INDEX,
R.string.destination, R.drawable.marker_destination, -1);
}
}
private void putRoadNodes(Road road){
roadNodeMarkers.getItems().clear();
Drawable icon = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
MarkerInfoWindow infoWindow = new MarkerInfoWindow(R.layout.bonuspack_bubble, map);
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
Marker nodeMarker = new Marker(map);
nodeMarker.setTitle("Step " + (i+1));
nodeMarker.setSnippet(instructions);
nodeMarker.setSubDescription(Road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setPosition(node.mLocation);
nodeMarker.setIcon(icon);
nodeMarker.setInfoWindow(infoWindow); //use a shared infowindow.
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable image = getResources().getDrawable(iconId);
nodeMarker.setImage(image);
}
roadNodeMarkers.add(nodeMarker);
}
iconIds.recycle();
}
void updateUIWithRoad(Road road){
roadNodeMarkers.getItems().clear();
TextView textView = (TextView)findViewById(R.id.routeInfo);
textView.setText("");
List<Overlay> mapOverlays = map.getOverlays();
if (roadOverlay != null){
mapOverlays.remove(roadOverlay);
}
if (road == null)
return;
if (road.mStatus == Road.STATUS_DEFAULT)
Toast.makeText(map.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show();
roadOverlay = RoadManager.buildRoadOverlay(road, map.getContext());
Overlay removedOverlay = mapOverlays.set(1, roadOverlay);
//we set the road overlay at the "bottom", just above the MapEventsOverlay,
//to avoid covering the other overlays.
mapOverlays.add(removedOverlay);
putRoadNodes(road);
map.invalidate();
//Set route info in the text view:
textView.setText(road.getLengthDurationText(-1));
}
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
@SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
RoadManager roadManager = null;
Locale locale = Locale.getDefault();
switch (whichRouteProvider){
case OSRM:
roadManager = new OSRMRoadManager();
break;
case MAPQUEST_FASTEST:
roadManager = new MapQuestRoadManager("Fmjtd%7Cluubn10zn9%2C8s%3Do5-90rnq6");
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
break;
case MAPQUEST_BICYCLE:
roadManager = new MapQuestRoadManager("Fmjtd%7Cluubn10zn9%2C8s%3Do5-90rnq6");
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
roadManager.addRequestOption("routeType=bicycle");
break;
case MAPQUEST_PEDESTRIAN:
roadManager = new MapQuestRoadManager("Fmjtd%7Cluubn10zn9%2C8s%3Do5-90rnq6");
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
roadManager.addRequestOption("routeType=pedestrian");
break;
case GOOGLE_FASTEST:
roadManager = new GoogleRoadManager();
//roadManager.addRequestOption("mode=driving"); //default
break;
default:
return null;
}
return roadManager.getRoad(waypoints);
}
protected void onPostExecute(Road result) {
mRoad = result;
updateUIWithRoad(result);
getPOIAsync(poiTagText.getText().toString());
}
}
public void getRoadAsync(){
mRoad = null;
GeoPoint roadStartPoint = null;
if (startPoint != null){
roadStartPoint = startPoint;
} else if (myLocationOverlay.isEnabled() && myLocationOverlay.getLocation() != null){
//use my current location as itinerary start point:
roadStartPoint = myLocationOverlay.getLocation();
}
if (roadStartPoint == null || destinationPoint == null){
updateUIWithRoad(mRoad);
return;
}
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2);
waypoints.add(roadStartPoint);
//add intermediate via points:
for (GeoPoint p:viaPoints){
waypoints.add(p);
}
waypoints.add(destinationPoint);
new UpdateRoadTask().execute(waypoints);
}
void updateUIWithPOI(ArrayList<POI> pois){
if (pois != null){
POIInfoWindow poiInfoWindow = new POIInfoWindow(map);
for (POI poi:pois){
Marker poiMarker = new Marker(map);
poiMarker.setTitle(poi.mType);
poiMarker.setSnippet(poi.mDescription);
poiMarker.setPosition(poi.mLocation);
Drawable icon = null;
if (poi.mServiceId == POI.POI_SERVICE_NOMINATIM){
icon = getResources().getDrawable(R.drawable.marker_poi);
} else if (poi.mServiceId == POI.POI_SERVICE_GEONAMES_WIKIPEDIA){
if (poi.mRank < 90)
icon = getResources().getDrawable(R.drawable.marker_poi_wikipedia_16);
else
icon = getResources().getDrawable(R.drawable.marker_poi_wikipedia_32);
} else if (poi.mServiceId == POI.POI_SERVICE_FLICKR){
icon = getResources().getDrawable(R.drawable.marker_poi_flickr);
} else if (poi.mServiceId == POI.POI_SERVICE_PICASA){
icon = getResources().getDrawable(R.drawable.marker_poi_picasa_24);
poiMarker.setSubDescription(poi.mCategory);
}
poiMarker.setIcon(icon);
if (poi.mServiceId == POI.POI_SERVICE_NOMINATIM){
poiMarker.setAnchor(Marker.ANCHOR_CENTER, 1.0f);
}
poiMarker.setRelatedObject(poi);
poiMarker.setInfoWindow(poiInfoWindow);
//thumbnail loading moved in async task for better performances.
poiMarkers.add(poiMarker);
}
}
poiMarkers.invalidate();
map.invalidate();
}
void setMarkerIconAsPhoto(Marker marker, Bitmap thumbnail){
int borderSize = 2;
thumbnail = Bitmap.createScaledBitmap(thumbnail, 48, 48, true);
Bitmap withBorder = Bitmap.createBitmap(thumbnail.getWidth() + borderSize * 2, thumbnail.getHeight() + borderSize * 2, thumbnail.getConfig());
Canvas canvas = new Canvas(withBorder);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(thumbnail, borderSize, borderSize, null);
BitmapDrawable icon = new BitmapDrawable(getResources(), withBorder);
marker.setIcon(icon);
}
ExecutorService mThreadPool = Executors.newFixedThreadPool(3);
class ThumbnailLoaderTask implements Runnable {
POI mPoi; Marker mMarker;
ThumbnailLoaderTask(POI poi, Marker marker){
mPoi = poi; mMarker = marker;
}
@Override public void run(){
Bitmap thumbnail = mPoi.getThumbnail();
if (thumbnail != null){
setMarkerIconAsPhoto(mMarker, thumbnail);
}
}
}
/** Loads all thumbnails in background */
void startAsyncThumbnailsLoading(ArrayList<POI> pois){
if (pois == null)
return;
//Try to stop existing threads:
mThreadPool.shutdownNow();
mThreadPool = Executors.newFixedThreadPool(3);
for (int i=0; i<pois.size(); i++){
final POI poi = pois.get(i);
final Marker marker = (Marker)poiMarkers.getItem(i);
mThreadPool.submit(new ThumbnailLoaderTask(poi, marker));
}
}
private class POILoadingTask extends AsyncTask<Object, Void, ArrayList<POI>> {
String mTag;
protected ArrayList<POI> doInBackground(Object... params) {
mTag = (String)params[0];
if (mTag == null || mTag.equals("")){
return null;
} else if (mTag.equals("wikipedia")){
GeoNamesPOIProvider poiProvider = new GeoNamesPOIProvider("mkergall");
//Get POI inside the bounding box of the current map view:
BoundingBoxE6 bb = map.getBoundingBox();
ArrayList<POI> pois = poiProvider.getPOIInside(bb, 30);
return pois;
} else if (mTag.equals("flickr")){
FlickrPOIProvider poiProvider = new FlickrPOIProvider("c39be46304a6c6efda8bc066c185cd7e");
BoundingBoxE6 bb = map.getBoundingBox();
ArrayList<POI> pois = poiProvider.getPOIInside(bb, 30);
return pois;
} else if (mTag.startsWith("picasa")){
PicasaPOIProvider poiProvider = new PicasaPOIProvider(null);
BoundingBoxE6 bb = map.getBoundingBox();
//allow to search for keywords among picasa photos:
String q = mTag.substring("picasa".length());
ArrayList<POI> pois = poiProvider.getPOIInside(bb, 50, q);
return pois;
} else {
NominatimPOIProvider poiProvider = new NominatimPOIProvider();
//poiProvider.setService(NominatimPOIProvider.MAPQUEST_POI_SERVICE);
ArrayList<POI> pois;
if (mRoad == null){
BoundingBoxE6 bb = map.getBoundingBox();
pois = poiProvider.getPOIInside(bb, mTag, 100);
} else {
pois = poiProvider.getPOIAlong(mRoad.getRouteLow(), mTag, 100, 2.0);
}
return pois;
}
}
protected void onPostExecute(ArrayList<POI> pois) {
mPOIs = pois;
if (mTag.equals("")){
//no search, no message
} else if (mPOIs == null){
Toast.makeText(getApplicationContext(), "Technical issue when getting "+mTag+ " POI.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), ""+mPOIs.size()+" "+mTag+ " entries found", Toast.LENGTH_LONG).show();
}
updateUIWithPOI(mPOIs);
if (mTag.equals("flickr")||mTag.startsWith("picasa")||mTag.equals("wikipedia"))
startAsyncThumbnailsLoading(mPOIs);
}
}
void getPOIAsync(String tag){
poiMarkers.getItems().clear();
new POILoadingTask().execute(tag);
}
boolean mDialogForOpen;
String mLocalFileName = "current.kml";
void openLocalFileDialog(boolean open){
mDialogForOpen = open;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("File (.kml or .json)");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setText(mLocalFileName);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
mLocalFileName = input.getText().toString();
dialog.cancel();
if (mDialogForOpen){
File file = mKmlDocument.getDefaultPathForAndroid(mLocalFileName);
openFile("file:/"+file.toString(), false);
} else
saveFile(mLocalFileName);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
void openUrlDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("KML url");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
String defaultUri = "http://mapsengine.google.com/map/kml?mid=z6IJfj90QEd4.kUUY9FoHFRdE";
SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE);
String uri = prefs.getString("KML_URI", defaultUri);
input.setText(uri);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
String uri = input.getText().toString();
SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putString("KML_URI", uri);
ed.commit();
dialog.cancel();
openFile(uri, false);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
ProgressDialog createSpinningDialog(String title){
ProgressDialog pd = new ProgressDialog(map.getContext());
pd.setTitle(title);
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
return pd;
}
class KmlLoadingTask extends AsyncTask<Object, Void, Boolean>{
String mUri;
boolean mOnCreate;
ProgressDialog mPD;
String mMessage;
KmlLoadingTask(String message){
super();
mMessage = message;
}
@Override protected void onPreExecute() {
mPD = createSpinningDialog(mMessage);
mPD.show();
}
@Override protected Boolean doInBackground(Object... params) {
mUri = (String)params[0];
mOnCreate = (Boolean)params[1];
mKmlDocument = new KmlDocument();
boolean ok = false;
if (mUri.startsWith("file:/")){
mUri = mUri.substring("file:/".length());
File file = new File(mUri);
if (mUri.endsWith(".json"))
ok = mKmlDocument.parseGeoJSON(file);
else //assume KML
ok = mKmlDocument.parseFile(file);
} else if (mUri.startsWith("http")) {
ok = mKmlDocument.parseUrl(mUri);
}
return ok;
}
@Override protected void onPostExecute(Boolean ok) {
if (mPD != null)
mPD.dismiss();
if (!ok)
Toast.makeText(getApplicationContext(), "Sorry, unable to read "+mUri, Toast.LENGTH_SHORT).show();
updateUIWithKml();
if (mKmlDocument.mKmlRoot != null && mKmlDocument.mKmlRoot.mBB != null){
if (!mOnCreate)
setViewOn(mKmlDocument.mKmlRoot.mBB);
else //KO in onCreate - Workaround:
map.getController().setCenter(new GeoPoint(
mKmlDocument.mKmlRoot.mBB.getLatSouthE6()+mKmlDocument.mKmlRoot.mBB.getLatitudeSpanE6()/2,
mKmlDocument.mKmlRoot.mBB.getLonWestE6()+mKmlDocument.mKmlRoot.mBB.getLongitudeSpanE6()/2));
}
}
}
void openFile(String uri, boolean onCreate){
//Toast.makeText(this, "Loading "+uri, Toast.LENGTH_SHORT).show();
new KmlLoadingTask("Loading "+uri).execute(uri, onCreate);
}
/** save fileName locally, as KML or GeoJSON depending on the extension */
void saveFile(String fileName){
boolean result;
File file = mKmlDocument.getDefaultPathForAndroid(fileName);
if (fileName.endsWith(".json"))
result = mKmlDocument.saveAsGeoJSON(file);
else
result = mKmlDocument.saveAsKML(file);
if (result)
Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Unable to save "+fileName, Toast.LENGTH_SHORT).show();
}
Style buildDefaultStyle(){
Drawable defaultKmlMarker = getResources().getDrawable(R.drawable.marker_kml_point);
Bitmap bitmap = ((BitmapDrawable)defaultKmlMarker).getBitmap();
Style defaultStyle = new Style(bitmap, 0x901010AA, 3.0f, 0x20AA1010);
return defaultStyle;
}
void updateUIWithKml(){
if (mKmlOverlay != null)
map.getOverlays().remove(mKmlOverlay);
if (mKmlDocument.mKmlRoot != null){
mKmlOverlay = (FolderOverlay)mKmlDocument.mKmlRoot.buildOverlay(map, buildDefaultStyle(), null, mKmlDocument);
map.getOverlays().add(mKmlOverlay);
}
map.invalidate();
}
void insertOverlaysInKml(){
//Ensure the root exist:
if (mKmlDocument.mKmlRoot == null){
mKmlDocument.mKmlRoot = new KmlFolder();
}
KmlFolder root = mKmlDocument.mKmlRoot;
//Insert relevant overlays inside:
if (itineraryMarkers.getItems().size()>0)
root.addOverlay(itineraryMarkers, mKmlDocument);
root.addOverlay(roadOverlay, mKmlDocument);
if (roadNodeMarkers.getItems().size()>0)
root.addOverlay(roadNodeMarkers, mKmlDocument);
root.addOverlay(mDestinationPolygon, mKmlDocument);
if (poiMarkers.getItems().size()>0)
root.addOverlay(poiMarkers, mKmlDocument);
}
void addKmlPoint(GeoPoint position){
//Ensure the root exist:
if (mKmlDocument.mKmlRoot == null){
mKmlDocument.mKmlRoot = new KmlFolder();
}
KmlFeature kmlPoint = new KmlPlacemark(position);
mKmlDocument.mKmlRoot.add(kmlPoint);
updateUIWithKml();
}
GeoPoint mClickedGeoPoint; //any other way to pass the position to the menu ???
@Override public boolean longPressHelper(GeoPoint p) {
mClickedGeoPoint = p;
Button searchButton = (Button)findViewById(R.id.buttonSearchDest);
openContextMenu(searchButton);
//menu is hooked on the "Search Destination" button, as it must be hooked somewhere.
return true;
}
@Override public boolean singleTapConfirmedHelper(GeoPoint p) {
return false;
}
@Override public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_menu, menu);
}
@Override public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_departure:
startPoint = new GeoPoint(mClickedGeoPoint);
markerStart = updateItineraryMarker(markerStart, startPoint, START_INDEX,
R.string.departure, R.drawable.marker_departure, -1);
getRoadAsync();
return true;
case R.id.menu_destination:
destinationPoint = new GeoPoint(mClickedGeoPoint);
markerDestination = updateItineraryMarker(markerDestination, destinationPoint, DEST_INDEX,
R.string.destination, R.drawable.marker_destination, -1);
getRoadAsync();
return true;
case R.id.menu_viapoint:
GeoPoint viaPoint = new GeoPoint(mClickedGeoPoint);
addViaPoint(viaPoint);
getRoadAsync();
return true;
case R.id.menu_kmlpoint:
GeoPoint kmlPoint = new GeoPoint(mClickedGeoPoint);
addKmlPoint(kmlPoint);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
switch (whichRouteProvider){
case OSRM:
menu.findItem(R.id.menu_route_osrm).setChecked(true);
break;
case MAPQUEST_FASTEST:
menu.findItem(R.id.menu_route_mapquest_fastest).setChecked(true);
break;
case MAPQUEST_BICYCLE:
menu.findItem(R.id.menu_route_mapquest_bicycle).setChecked(true);
break;
case MAPQUEST_PEDESTRIAN:
menu.findItem(R.id.menu_route_mapquest_pedestrian).setChecked(true);
break;
case GOOGLE_FASTEST:
menu.findItem(R.id.menu_route_google).setChecked(true);
break;
}
if (map.getTileProvider().getTileSource() == TileSourceFactory.MAPNIK)
menu.findItem(R.id.menu_tile_mapnik).setChecked(true);
else if (map.getTileProvider().getTileSource() == TileSourceFactory.MAPQUESTOSM)
menu.findItem(R.id.menu_tile_mapquest_osm).setChecked(true);
else if (map.getTileProvider().getTileSource() == MAPBOXSATELLITELABELLED)
menu.findItem(R.id.menu_tile_mapbox_satellite).setChecked(true);
return true;
}
@Override public boolean onPrepareOptionsMenu(Menu menu) {
if (mRoad != null && mRoad.mNodes.size()>0)
menu.findItem(R.id.menu_itinerary).setEnabled(true);
else
menu.findItem(R.id.menu_itinerary).setEnabled(false);
if (mPOIs != null && mPOIs.size()>0)
menu.findItem(R.id.menu_pois).setEnabled(true);
else
menu.findItem(R.id.menu_pois).setEnabled(false);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent;
switch (item.getItemId()) {
case R.id.menu_itinerary:
myIntent = new Intent(this, RouteActivity.class);
myIntent.putExtra("NODE_ID", -1 /*TODO - default to roadNodeMarkers.getBubbledItemId()*/);
startActivityForResult(myIntent, ROUTE_REQUEST);
return true;
case R.id.menu_pois:
myIntent = new Intent(this, POIActivity.class);
myIntent.putExtra("ID", -1 /*TODO - default to poiMarkers.getBubbledItemId()*/);
startActivityForResult(myIntent, POIS_REQUEST);
return true;
case R.id.menu_kml_url:
openUrlDialog();
return true;
case R.id.menu_open_file:
openLocalFileDialog(true);
return true;
case R.id.menu_kml_get_overlays:
insertOverlaysInKml();
updateUIWithKml();
return true;
case R.id.menu_kml_tree:
if (mKmlDocument.mKmlRoot==null)
return false;
myIntent = new Intent(this, KmlTreeActivity.class);
//myIntent.putExtra("KML", mKmlDocument.kmlRoot);
mKmlStack.push(mKmlDocument.mKmlRoot.clone());
startActivityForResult(myIntent, KML_TREE_REQUEST);
return true;
case R.id.menu_save_file:
openLocalFileDialog(false);
return true;
case R.id.menu_kml_clear:
mKmlDocument = new KmlDocument();
updateUIWithKml();
return true;
case R.id.menu_route_osrm:
whichRouteProvider = OSRM;
item.setChecked(true);
getRoadAsync();
return true;
case R.id.menu_route_mapquest_fastest:
whichRouteProvider = MAPQUEST_FASTEST;
item.setChecked(true);
getRoadAsync();
return true;
case R.id.menu_route_mapquest_bicycle:
whichRouteProvider = MAPQUEST_BICYCLE;
item.setChecked(true);
getRoadAsync();
return true;
case R.id.menu_route_mapquest_pedestrian:
whichRouteProvider = MAPQUEST_PEDESTRIAN;
item.setChecked(true);
getRoadAsync();
return true;
case R.id.menu_route_google:
whichRouteProvider = GOOGLE_FASTEST;
item.setChecked(true);
getRoadAsync();
return true;
case R.id.menu_tile_mapnik:
map.setTileSource(TileSourceFactory.MAPNIK);
item.setChecked(true);
return true;
case R.id.menu_tile_mapquest_osm:
map.setTileSource(TileSourceFactory.MAPQUESTOSM);
item.setChecked(true);
return true;
case R.id.menu_tile_mapbox_satellite:
map.setTileSource(MAPBOXSATELLITELABELLED);
item.setChecked(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private final NetworkLocationIgnorer mIgnorer = new NetworkLocationIgnorer();
long mLastTime = 0; // milliseconds
double mSpeed = 0.0; // km/h
@Override public void onLocationChanged(final Location pLoc) {
long currentTime = System.currentTimeMillis();
if (mIgnorer.shouldIgnore(pLoc.getProvider(), currentTime))
return;
double dT = currentTime - mLastTime;
if (dT < 100.0){
//Toast.makeText(this, pLoc.getProvider()+" dT="+dT, Toast.LENGTH_SHORT).show();
return;
}
mLastTime = currentTime;
GeoPoint newLocation = new GeoPoint(pLoc);
if (!myLocationOverlay.isEnabled()){
//we get the location for the first time:
myLocationOverlay.setEnabled(true);
map.getController().animateTo(newLocation);
}
GeoPoint prevLocation = myLocationOverlay.getLocation();
myLocationOverlay.setLocation(newLocation);
myLocationOverlay.setAccuracy((int)pLoc.getAccuracy());
if (prevLocation != null && pLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
/*
double d = prevLocation.distanceTo(newLocation);
mSpeed = d/dT*1000.0; // m/s
mSpeed = mSpeed * 3.6; //km/h
*/
mSpeed = pLoc.getSpeed() * 3.6;
long speedInt = Math.round(mSpeed);
TextView speedTxt = (TextView)findViewById(R.id.speed);
speedTxt.setText(speedInt + " km/h");
//TODO: check if speed is not too small
if (mSpeed >= 0.1){
//mAzimuthAngleSpeed = (float)prevLocation.bearingTo(newLocation);
mAzimuthAngleSpeed = (float)pLoc.getBearing();
myLocationOverlay.setBearing(mAzimuthAngleSpeed);
}
}
if (mTrackingMode){
//keep the map view centered on current location:
map.getController().animateTo(newLocation);
map.setMapOrientation(-mAzimuthAngleSpeed);
} else {
//just redraw the location overlay:
map.invalidate();
}
}
@Override public void onProviderDisabled(String provider) {}
@Override public void onProviderEnabled(String provider) {}
@Override public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override public void onAccuracyChanged(Sensor sensor, int accuracy) {
myLocationOverlay.setAccuracy(accuracy);
map.invalidate();
}
static float mAzimuthOrientation = 0.0f;
@Override public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()){
case Sensor.TYPE_ORIENTATION:
if (mSpeed < 0.1){
/* TODO Filter to implement...
float azimuth = event.values[0];
if (Math.abs(azimuth-mAzimuthOrientation)>2.0f){
mAzimuthOrientation = azimuth;
myLocationOverlay.setBearing(mAzimuthOrientation);
if (mTrackingMode)
map.setMapOrientation(-mAzimuthOrientation);
else
map.invalidate();
}
*/
}
//at higher speed, we use speed vector, not phone orientation.
break;
default:
break;
}
}
}
|
package owltools.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import org.apache.log4j.Logger;
import org.coode.owlapi.obo.parser.OBOOntologyFormat;
import org.obolibrary.obo2owl.Obo2Owl;
import org.obolibrary.obo2owl.Owl2Obo;
import org.obolibrary.oboformat.model.Frame;
import org.obolibrary.oboformat.model.FrameMergeException;
import org.obolibrary.oboformat.model.OBODoc;
import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag;
import org.obolibrary.oboformat.parser.OBOFormatConstants;
import org.obolibrary.oboformat.parser.OBOFormatParser;
import org.obolibrary.oboformat.parser.OBOFormatParserException;
import org.obolibrary.oboformat.writer.OBOFormatWriter;
import org.obolibrary.oboformat.writer.OBOFormatWriter.NameProvider;
import org.obolibrary.oboformat.writer.OBOFormatWriter.OBODocNameProvider;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyDocumentAlreadyExistsException;
import org.semanticweb.owlapi.model.OWLOntologyFormat;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.semanticweb.owlapi.model.OWLOntologyIRIMapper;
import org.semanticweb.owlapi.model.OWLOntologyLoaderListener;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import owltools.graph.OWLGraphWrapper;
/**
* Convenience class wrapping org.oboformat that abstracts away underlying details of ontology format or location
* @author cjm
*
*/
public class ParserWrapper {
private static Logger LOG = Logger.getLogger(ParserWrapper.class);
OWLOntologyManager manager;
OBODoc obodoc;
boolean isCheckOboDoc = true;
public ParserWrapper() {
manager = OWLManager.createOWLOntologyManager(); // persist?
OWLOntologyLoaderListener listener = new OWLOntologyLoaderListener() {
@Override
public void startedLoadingOntology(LoadingStartedEvent event) {
IRI id = event.getOntologyID().getOntologyIRI();
IRI source = event.getDocumentIRI();
LOG.info("Start loading ontology: "+id+" from: "+source);
}
@Override
public void finishedLoadingOntology(LoadingFinishedEvent event) {
IRI id = event.getOntologyID().getOntologyIRI();
IRI source = event.getDocumentIRI();
LOG.info("Finished loading ontology: "+id+" from: "+source);
}
};
manager.addOntologyLoaderListener(listener);
}
public OWLOntologyManager getManager() {
return manager;
}
public void setManager(OWLOntologyManager manager) {
this.manager = manager;
}
public boolean isCheckOboDoc() {
return isCheckOboDoc;
}
public void setCheckOboDoc(boolean isCheckOboDoc) {
this.isCheckOboDoc = isCheckOboDoc;
}
public void addIRIMapper(OWLOntologyIRIMapper mapper) {
manager.addIRIMapper(mapper);
}
public void removeIRIMapper(OWLOntologyIRIMapper mapper) {
manager.removeIRIMapper(mapper);
}
public OWLGraphWrapper parseToOWLGraph(String iriString) throws OWLOntologyCreationException, IOException, OBOFormatParserException {
return new OWLGraphWrapper(parse(iriString));
}
public OWLGraphWrapper parseToOWLGraph(String iriString, boolean isMergeImportClosure) throws OWLOntologyCreationException, IOException, OBOFormatParserException {
return new OWLGraphWrapper(parse(iriString), isMergeImportClosure);
}
public OWLOntology parse(String iriString) throws OWLOntologyCreationException, IOException, OBOFormatParserException {
if (iriString.endsWith(".obo"))
return parseOBO(iriString);
if (iriString.endsWith(".owl") || iriString.endsWith(".omn") || iriString.endsWith(".ofn") || iriString.endsWith(".owx"))
return parseOWL(iriString);
if (isOboFile(iriString))
return parseOBO(iriString);
return parseOWL(iriString);
}
public boolean isOboFile(String source) throws IOException, OWLOntologyCreationException, OBOFormatParserException {
if (isIRI(source))
return false; // assume anything from web is owl by default
BufferedReader in =
new BufferedReader(new InputStreamReader(new FileInputStream(source)));
//new BufferedReader(new InputStreamReader(url.openStream(), OBOFormatConstants.DEFAULT_CHARACTER_ENCODING));
boolean isOboFile = false;
for (int i=0; i<100; i++) {
String line = in.readLine();
if (line.startsWith("format-version:"))
isOboFile = true;
}
return isOboFile;
}
public OWLOntology parseOBO(String source) throws IOException, OWLOntologyCreationException, OBOFormatParserException {
OBOFormatParser p = new OBOFormatParser();
LOG.info("Parsing: "+source);
final String id;
if (isIRI(source)) {
obodoc = p.parse(IRI.create(source).toURI().toURL());
id = source;
}
else {
final File file = new File(source);
obodoc = p.parse(file);
String fileName = file.getName();
if (fileName.endsWith(".obo") || fileName.endsWith(".owl")) {
fileName = fileName.substring(0, fileName.length() - 4);
}
id = fileName;
}
if (obodoc == null) {
throw new IOException("Loading of ontology failed: "+source);
}
/*
* This fixes an exception for ontologies without an declared id.
* Only by URL encoding the path it is guaranteed that a valid
* ontology id is generated.
*/
obodoc.addDefaultOntologyHeader(URLEncoder.encode(id, "UTF-8"));
Obo2Owl bridge = new Obo2Owl(manager);
OWLOntology ontology = bridge.convert(obodoc);
return ontology;
}
public OWLOntology parseOBOFiles(List<String> files) throws IOException, OWLOntologyCreationException, OBOFormatParserException, FrameMergeException {
OBOFormatParser p = new OBOFormatParser();
OBODoc obodoc = null;
for (String f : files) {
LOG.info("Parsing file " +f);
if (obodoc == null)
obodoc = p.parse(f);
else {
OBODoc obodoc2 = p.parse(f);
obodoc.mergeContents(obodoc2);
}
}
Obo2Owl bridge = new Obo2Owl();
OWLOntology ontology = bridge.convert(obodoc);
return ontology;
}
public OWLOntology parseOWL(String iriString) throws OWLOntologyCreationException {
IRI iri;
LOG.info("parsing: "+iriString);
if (isIRI(iriString)) {
iri = IRI.create(iriString);
}
else {
iri = IRI.create(new File(iriString));
}
return parseOWL(iri);
}
private boolean isIRI(String iriString) {
return iriString.startsWith("file:") || iriString.startsWith("http:") || iriString.startsWith("https:");
}
public OWLOntology parseOWL(IRI iri) throws OWLOntologyCreationException {
LOG.info("parsing: "+iri.toString()+" using "+manager);
OWLOntology ont;
try {
ont = manager.loadOntology(iri);
} catch (OWLOntologyAlreadyExistsException e) {
// Trying to recover from exception
OWLOntologyID ontologyID = e.getOntologyID();
ont = manager.getOntology(ontologyID);
if (ont == null) {
// throw original exception, if no ontology could be found
// never return null ontology
throw e;
}
else {
LOG.info("Skip already loaded ontology: "+iri);
}
} catch (OWLOntologyDocumentAlreadyExistsException e) {
// Trying to recover from exception
IRI duplicate = e.getOntologyDocumentIRI();
ont = manager.getOntology(duplicate);
if (ont == null) {
for(OWLOntology managed : manager.getOntologies()) {
if(duplicate.equals(managed.getOntologyID().getOntologyIRI())) {
LOG.info("Skip already loaded ontology: "+iri);
ont = managed;
break;
}
}
}
if (ont == null) {
// throw original exception, if no ontology could be found
// never return null ontology
throw e;
}
}
return ont;
}
public void saveOWL(OWLOntology ont, String file, OWLGraphWrapper graph) throws OWLOntologyStorageException {
OWLOntologyFormat owlFormat = new RDFXMLOntologyFormat();
saveOWL(ont, owlFormat, file, graph);
}
public void saveOWL(OWLOntology ont, OWLOntologyFormat owlFormat, String file, OWLGraphWrapper graph) throws OWLOntologyStorageException {
if ((owlFormat instanceof OBOOntologyFormat) || (owlFormat instanceof OWLJSONFormat)) {
try {
FileOutputStream os = new FileOutputStream(new File(file));
saveOWL(ont, owlFormat, os, graph);
} catch (FileNotFoundException e) {
throw new OWLOntologyStorageException("Could not open file: "+file, e);
}
}
else {
manager.saveOntology(ont, owlFormat, IRI.create(file));
}
}
public void saveOWL(OWLOntology ont, OWLOntologyFormat owlFormat,
OutputStream outputStream, OWLGraphWrapper graph) throws OWLOntologyStorageException {
if (owlFormat instanceof OBOOntologyFormat) {
Owl2Obo bridge = new Owl2Obo();
OBODoc doc;
BufferedWriter bw = null;
try {
doc = bridge.convert(ont);
OBOFormatWriter oboWriter = new OBOFormatWriter();
oboWriter.setCheckStructure(isCheckOboDoc);
bw = new BufferedWriter(new OutputStreamWriter(outputStream));
if (graph != null) {
oboWriter.write(doc, bw, new OboAndOwlNameProvider(doc, graph));
}
else {
oboWriter.write(doc, bw);
}
} catch (OWLOntologyCreationException e) {
throw new OWLOntologyStorageException("Could not create temporary OBO ontology.", e);
} catch (IOException e) {
throw new OWLOntologyStorageException("Could not write ontology to output stream.", e);
}
finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
LOG.warn("Could not close writer.", e);
}
}
}
}
else if (owlFormat instanceof OWLJSONFormat) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(outputStream));
//OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))));
OWLGsonRenderer gr = new OWLGsonRenderer(new PrintWriter(outputStream));
gr.render(ont);
gr.flush();
}
finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
LOG.warn("Could not close writer.", e);
}
}
}
}
else {
manager.saveOntology(ont, owlFormat, outputStream);
}
}
public OBODoc getOBOdoc() {
return obodoc;
}
/**
* Provide names for the {@link OBOFormatWriter} using an
* {@link OWLGraphWrapper}.
*
* @see OboAndOwlNameProvider use the {@link OboAndOwlNameProvider}, the
* pure OWL lookup is problematic for relations.
*/
public static class OWLGraphWrapperNameProvider implements NameProvider {
private final OWLGraphWrapper graph;
private final String defaultOboNamespace;
/**
* @param graph
*/
public OWLGraphWrapperNameProvider(OWLGraphWrapper graph) {
super();
this.graph = graph;
this.defaultOboNamespace = null;
}
/**
* @param graph
* @param defaultOboNamespace
*/
public OWLGraphWrapperNameProvider(OWLGraphWrapper graph, String defaultOboNamespace) {
super();
this.graph = graph;
this.defaultOboNamespace = defaultOboNamespace;
}
/**
* @param graph
* @param oboDoc
*
* If an {@link OBODoc} is available use {@link OboAndOwlNameProvider}.
*/
@Deprecated
public OWLGraphWrapperNameProvider(OWLGraphWrapper graph, OBODoc oboDoc) {
super();
this.graph = graph;
String defaultOboNamespace = null;
if (oboDoc != null) {
Frame headerFrame = oboDoc.getHeaderFrame();
if (headerFrame != null) {
defaultOboNamespace = headerFrame.getTagValue(OboFormatTag.TAG_DEFAULT_NAMESPACE, String.class);
}
}
this.defaultOboNamespace = defaultOboNamespace;
}
public String getName(String id) {
String name = null;
OWLObject obj = graph.getOWLObjectByIdentifier(id);
if (obj != null) {
name = graph.getLabel(obj);
}
return name;
}
public String getDefaultOboNamespace() {
return defaultOboNamespace;
}
}
/**
* Provide names for the {@link OBOFormatWriter} using an {@link OBODoc}
* first and an {@link OWLGraphWrapper} as secondary.
*/
public static class OboAndOwlNameProvider extends OBODocNameProvider {
private final OWLGraphWrapper graph;
public OboAndOwlNameProvider(OBODoc oboDoc, OWLGraphWrapper wrapper) {
super(oboDoc);
this.graph = wrapper;
}
@Override
public String getName(String id) {
String name = super.getName(id);
if (name != null) {
return name;
}
OWLObject owlObject = graph.getOWLObjectByIdentifier(id);
if (owlObject != null) {
name = graph.getLabel(owlObject);
}
return name;
}
}
public static void main(String[] args) throws Exception {
ParserWrapper pw = new ParserWrapper();
OWLOntologyIRIMapper mapper = new CatalogXmlIRIMapper("/Users/cjm/cvs/uberon/phenoscape-vocab/homology/catalog-v001.xml");
pw.addIRIMapper(mapper);
OWLOntology o = pw.parse("/Users/cjm/cvs/uberon/phenoscape-vocab/homology/test2.owl");
}
}
|
package ch.openech.xml.read;
import static ch.openech.model.XmlConstants.*;
import static ch.openech.xml.read.StaxEch.*;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import ch.openech.model.common.CountryIdentification;
public class StaxEch0072 {
private static StaxEch0072 instance;
private final List<CountryIdentification> countryIdentifications = new ArrayList<CountryIdentification>(300);
private final List<CountryIdentification> countriesUnmodifiable;
private StaxEch0072() {
InputStream inputStream = this.getClass().getResourceAsStream("eCH0072.xml");
try {
process(inputStream);
} catch (Exception x) {
throw new RuntimeException("Read of Countries failed", x);
}
countriesUnmodifiable = Collections.unmodifiableList(countryIdentifications);
}
public static synchronized StaxEch0072 getInstance() {
if (instance == null) {
instance = new StaxEch0072();
}
return instance;
}
public List<CountryIdentification> getCountryIdentifications() {
return countriesUnmodifiable;
}
private void country(XMLEventReader xml) throws XMLStreamException, SQLException {
CountryIdentification countryIdentification = new CountryIdentification();
while (true) {
XMLEvent event = xml.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
String startName = startElement.getName().getLocalPart();
if (ID.equals(startName)) countryIdentification.countryId = integer(xml);
else if (ISO2_ID.equals(startName)) countryIdentification.countryIdISO2 = token(xml);
else if (SHORT_NAME_DE.equals(startName)) countryIdentification.countryNameShort = token(xml);
else skip(xml);
} else if (event.isEndElement()) {
countryIdentifications.add(countryIdentification);
break;
} // else skip
}
}
private void countries(XMLEventReader xml) throws XMLStreamException, SQLException {
while (xml.hasNext()) {
XMLEvent event = xml.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
String startName = startElement.getName().getLocalPart();
if (startName.equals(COUNTRY)) country(xml);
else skip(xml);
} else if (event.isEndElement()) {
break;
}
}
}
private void process(InputStream inputStream) throws XMLStreamException, SQLException {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLEventReader xml = inputFactory.createXMLEventReader(inputStream);
while (xml.hasNext()) {
XMLEvent event = xml.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
String startName = startElement.getName().getLocalPart();
if (startName.equals(COUNTRIES))countries(xml);
else skip(xml);
} else if (event.isEndElement()) {
break;
}
}
}
public static void main(String... args){
System.out.println(getInstance().countryIdentifications.size());
}
}
|
package dk.aau.sw402F15.CodeGenerator;
import dk.aau.sw402F15.parser.analysis.DepthFirstAdapter;
import dk.aau.sw402F15.parser.node.*;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class CodeGenerator extends DepthFirstAdapter {
int jumpLabel = 0;
PrintWriter instructionWriter;
PrintWriter symbolWriter;
public CodeGenerator() {
try {
instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8");
symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8");
Emit("LD P_First_Cycle", true);
Emit("SSET(630) W0 5", true);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void outStart(Start node){
instructionWriter.close();
symbolWriter.close();
}
@Override
public void caseAArrayDefinition(AArrayDefinition node){
//throw new NotImplementedException();
}
@Override
public void caseAArrayExpr(AArrayExpr node){
//throw new NotImplementedException();
}
@Override
public void caseADeclaration(ADeclaration node){
super.caseADeclaration(node);
}
@Override
public void outABreakStatement(ABreakStatement node){
//throw new NotImplementedException();
}
@Override
public void outACaseStatement(ACaseStatement node){
//throw new NotImplementedException();
}
@Override
public void outACompareAndExpr(ACompareAndExpr node){
super.outACompareAndExpr(node);
PopFromStack();
Emit("LD b1", true);
Emit("AND b2", true);
Emit("SET b1", true);
}
@Override
public void outACompareEqualExpr(ACompareEqualExpr node){
super.outACompareEqualExpr(node);
PopFromStack();
Emit("=(300) r1 r2", true);
}
@Override
public void outACompareGreaterExpr(ACompareGreaterExpr node){
super.outACompareGreaterExpr(node);
PopFromStack();
Emit(">(320) r1 r2", true);
}
@Override
public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){
super.outACompareGreaterOrEqualExpr(node);
PopFromStack();
Emit(">=(325) r1 r2", true);
}
@Override
public void outACompareLessExpr(ACompareLessExpr node){
super.outACompareLessExpr(node);
PopFromStack();
Emit("<(310) r1 r2", true);
}
@Override
public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node){
super.outACompareLessOrEqualExpr(node);
PopFromStack();
Emit("<=(315) r1 r2", true);
}
@Override
public void outACompareNotEqualExpr(ACompareNotEqualExpr node){
super.outACompareNotEqualExpr(node);
PopFromStack();
Emit("<>(305) r1 r2", true);
}
@Override
public void outACompareOrExpr(ACompareOrExpr node){
super.outACompareOrExpr(node);
PopFromStack();
Emit("LD b1", true);
Emit("OR b2", true);
Emit("SET b1", true);
}
@Override
public void outAContinueStatement(AContinueStatement node){
//throw new NotImplementedException();
}
@Override
public void outADeclaration(ADeclaration node){
//throw new NotImplementedException();
}
@Override
public void outADefaultStatement(ADefaultStatement node){
//throw new NotImplementedException();
}
@Override
public void outAFalseExpr(AFalseExpr node){
//throw new NotImplementedException();
}
@Override
public void outAFunctionCallExpr(AFunctionCallExpr node){
//throw new NotImplementedException();
}
@Override
public void outAFunctionRootDeclaration(AFunctionRootDeclaration node){
//throw new NotImplementedException();
}
@Override
public void outAIdentifierExpr(AIdentifierExpr node){
//throw new NotImplementedException();
}
@Override
public void outAMemberExpr(AMemberExpr node){
//throw new NotImplementedException();
}
@Override
public void outANegationExpr(ANegationExpr node){
super.outANegationExpr(node);
PopFromStack();
Emit("NOT r1", true);
}
@Override
public void outAPortAnalogInputExpr(APortAnalogInputExpr node){
//throw new NotImplementedException();
}
@Override
public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){
//throw new NotImplementedException();
}
@Override
public void outAPortInputExpr(APortInputExpr node){
//throw new NotImplementedException();
}
@Override
public void outAPortMemoryExpr(APortMemoryExpr node){
//throw new NotImplementedException();
}
@Override
public void outAPortOutputExpr(APortOutputExpr node){
//throw new NotImplementedException();
}
@Override
public void outAReturnStatement(AReturnStatement node){
//throw new NotImplementedException();
}
@Override
public void outASwitchStatement(ASwitchStatement node){
//throw new NotImplementedException();
}
@Override
public void outATrueExpr(ATrueExpr node){
//throw new NotImplementedException();
}
@Override
public void outATypeCastExpr(ATypeCastExpr node){
//throw new NotImplementedException();
}
@Override
public void outAWhileStatement(AWhileStatement node) {
//throw new NotImplementedException();
}
@Override
public void caseABranchStatement(ABranchStatement node) {
super.caseABranchStatement(node);
if (node.getRight() != null) {
// If - else statement
int ifLabel = getNextJump();
int elseLabel = getNextJump();
node.getCondition().apply(this);
Emit("CJP(510) #" + ifLabel, true);
node.getRight().apply(this);
Emit("JMP(004) #" + elseLabel, true);
Emit("JME(005) #" + ifLabel, true);
node.getLeft().apply(this);
Emit("JME(005) #" + elseLabel, true);
}
else {
// If statement
int label = getNextJump();
node.getCondition().apply(this);
Emit("CJPN(511) #" + label, true);
node.getLeft().apply(this);
Emit("JME(005) #" + label, true);
}
}
@Override
public void caseAForStatement(AForStatement node){
int jumpLabel = getNextJump();
int loopLabel = getNextJump();
{
List<PExpr> copy = new ArrayList<PExpr>(node.getInitilizer());
for(PExpr e : copy)
{
e.apply(this);
}
}
Emit("JMP(004) #" + jumpLabel, true);
Emit("JME(005) #" + loopLabel, true);
node.getStatement().apply(this);
{
List<PExpr> copy = new ArrayList<PExpr>(node.getIterator());
for(PExpr e : copy)
{
e.apply(this);
}
}
Emit("JME(005) #" + jumpLabel, true);
node.getCondition().apply(this);
Emit("CJP(510) #" + loopLabel, true);
}
@Override
public void caseASwitchStatement(ASwitchStatement node){
//throw new NotImplementedException();
}
@Override
public void caseAWhileStatement(AWhileStatement node){
int jumpLabel = getNextJump();
int loopLabel = getNextJump();
Emit("JMP(004) #" + jumpLabel, true);
Emit("JME(005) #" + loopLabel, true);
node.getStatement().apply(this);
Emit("JME(005) #" + jumpLabel, true);
node.getCondition().apply(this);
Emit("CJP(510) #" + loopLabel, true);
}
@Override
public void outAIntegerExpr(AIntegerExpr node) {
super.outAIntegerExpr(node);
Emit("PUSH(632) W0 #" + node.getIntegerLiteral().getText(), true);
}
@Override
public void outADecimalExpr(ADecimalExpr node) {
super.outADecimalExpr(node);
Emit("PUSH(632) W0 #" + node.getDecimalLiteral().getText(), true);
}
@Override
public void outAAddExpr(AAddExpr node) {
super.outAAddExpr(node);
PopFromStack();
Emit("+(400) r1 r2 r1", true);
}
@Override
public void outADivExpr(ADivExpr node) {
super.outADivExpr(node);
PopFromStack();
Emit("/(430) r1 r2 r1", true);
}
@Override
public void outAMultiExpr(AMultiExpr node) {
super.outAMultiExpr(node);
PopFromStack();
Emit("*(420) r1 r2 r1", true);
}
@Override
public void outASubExpr(ASubExpr node) {
super.outASubExpr(node);
PopFromStack();
Emit("-(410) r1 r2 r1", true);
}
private void PopFromStack(){
Emit("r1\tINT\tW4\t\t0", false);
Emit("r2\tINT\tW5\t\t0", false);
Emit("LIFO(634) W0 r1", true);
Emit("LIFO(634) W0 r2", true);
}
private int getNextJump(){
jumpLabel = jumpLabel + 1;
if(jumpLabel > 255)
throw new IndexOutOfBoundsException();
return jumpLabel;
}
protected void Emit(String s, boolean inst){
if (inst == true) {
instructionWriter.println(s);
} else {
symbolWriter.println(s);
}
}
}
|
package motocitizen.startup;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import motocitizen.Activity.AboutActivity;
import motocitizen.Activity.AuthActivity;
import motocitizen.Activity.CreateAccActivity;
import motocitizen.Activity.SettingsActivity;
import motocitizen.app.mc.MCAccidents;
import motocitizen.app.mc.MCLocation;
import motocitizen.app.mc.gcm.GcmBroadcastReceiver;
import motocitizen.app.mc.user.MCRole;
import motocitizen.main.R;
import motocitizen.maps.general.MCMap;
import motocitizen.maps.google.MCGoogleMap;
import motocitizen.maps.osm.MCOSMMap;
import motocitizen.network.IncidentRequest;
import motocitizen.network.JsonRequest;
import motocitizen.utils.Const;
import motocitizen.utils.Keyboard;
import motocitizen.utils.MCUtils;
import motocitizen.utils.Props;
import motocitizen.utils.Show;
public class Startup extends ActionBarActivity implements View.OnClickListener {
public static Props props;
public static Context context;
public static MCPreferences prefs;
public static MCMap map;
public static boolean fromDetails;
private ImageButton dialButton;
private ImageButton createAccButton;
private RadioGroup mainTabsGroup;
private View accListView;
private View mapContainer;
private Menu mMenu;
private static ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
context = this;
actionBar = getSupportActionBar();
//prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs = new MCPreferences(this);
prefs.setDoNotDistrub(false);
new Const();
checkUpdate();
dialButton = (ImageButton) findViewById(R.id.dial_button);
dialButton.setOnClickListener(this);
createAccButton = (ImageButton) findViewById(R.id.mc_add_point_button);
createAccButton.setOnClickListener(this);
mainTabsGroup = (RadioGroup) findViewById(R.id.main_tabs_group);
mainTabsGroup.setOnCheckedChangeListener(mainTabsListener);
accListView = findViewById(R.id.mc_acc_list);
mapContainer = findViewById(R.id.map_container);
mapContainer.setTranslationX(Const.getWidth(context));
//prefs = getSharedPreferences("motocitizen.startup", MODE_PRIVATE);
//prefs.edit().clear().commit();
props = new Props();
new MCAccidents(this);
createMap(prefs.getMapProvider());
// new SettingsMenu();
if (MCAccidents.auth.isFirstRun()) {
//Show.show(R.id.main_frame, R.id.first_auth_screen);
Intent i = new Intent(Startup.context, AuthActivity.class);
Startup.context.startActivity(i);
}
new GcmBroadcastReceiver();
}
private void checkUpdate(){
PackageManager manager = this.getPackageManager();
String version;
try {
PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
version = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
version = getString(R.string.unknown_code_version);
}
if(!prefs.getCurrentVersion().equals(version)){
ChangeLog.getDialog(this, true).show();
}
prefs.setCurrentVersion(version);
}
@Override
protected void onPause() {
super.onPause();
MCLocation.sleep();
}
@Override
protected void onResume() {
super.onResume();
// Show.show(R.id.main_frame, R.id.main_screen_fragment);
MCLocation.wakeup(this);
Intent intent = getIntent();
Integer toMap = intent.getIntExtra("toMap", 0);
Integer toDetails = intent.getIntExtra("toDetails", 0);
context = this;
//MCAccidents.refresh(this);
if (MCRole.isStandart()) {
createAccButton.setVisibility(View.VISIBLE);
} else {
createAccButton.setVisibility(View.INVISIBLE);
}
if (isOnline()) {
JsonRequest request = MCAccidents.getLoadPointsRequest();
if (request != null) {
(new IncidentRequest(this)).execute(request);
}
catchIntent(intent);
} else {
Toast.makeText(Startup.context, Startup.context.getString(R.string.inet_not_available), Toast.LENGTH_LONG).show();
}
if(toMap != 0){
intent.removeExtra("toMap");
mainTabsGroup.check(R.id.tab_map_button);
fromDetails = intent.getBooleanExtra("fromDetails", false);
} else if(toDetails != 0){
intent.removeExtra("toDetails");
MCAccidents.refresh(this);
MCAccidents.toDetails(this, toDetails);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
public boolean onKeyUp(int keycode, @NonNull KeyEvent e) {
switch (keycode) {
case KeyEvent.KEYCODE_BACK:
if(fromDetails){
MCAccidents.toDetails(this);
}
// FragmentManager fm = getFragmentManager();
// Fragment pf = fm.findFragmentByTag("settings");
// if(pf != null && pf.isVisible()){
// Fragment mf = fm.findFragmentByTag("main_screen");
// fm.beginTransaction().show(mf).hide(pf).commit();
MCAccidents.redraw(this);
Keyboard.hide();
return true;
}
return super.onKeyUp(keycode, e);
}
private void catchIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null) {
return;
}
String type = extras.getString("type");
String idString = extras.getString("id");
if (type == null || idString == null || !MCUtils.isInteger(idString)) {
return;
}
int id = Integer.parseInt(idString);
if (type.equals("acc") && id != 0) {
MCAccidents.points.setSelected(this, id);
}
}
public static boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) Startup.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public static void createMap(String name) {
if (map != null && !map.getName().equals(name))
map = null;
if (name.equals(MCMap.OSM)) {
map = new MCOSMMap(context);
} else if (name.equals(MCMap.GOOGLE)) {
map = new MCGoogleMap(context);
}
Location location = MCLocation.getLocation(context);
//if(location != null)
map.jumpToPoint(location);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.dial_button:
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+74957447350"));
Startup.context.startActivity(intent);
break;
case R.id.mc_add_point_button:
startActivity(new Intent(Startup.context, CreateAccActivity.class));
break;
default:
Log.e("Startup", "Unknown button pressed");
break;
}
}
private final RadioGroup.OnCheckedChangeListener mainTabsListener = new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
int id = group.getCheckedRadioButtonId();
fromDetails = false;
accListView.setVisibility(View.VISIBLE);
mapContainer.setVisibility(View.VISIBLE);
if (Show.currentGeneral == null) {
Show.currentGeneral = R.id.tab_accidents_button;
}
if (id == R.id.tab_accidents_button) {
accListView.animate().translationX(0);
mapContainer.animate().translationX(Const.getWidth(context) * 2);
} else if (id == R.id.tab_map_button) {
accListView.animate().translationX(-Const.getWidth(context) * 2);
mapContainer.animate().translationX(0);
}
Show.currentGeneral = id;
}
};
public static void updateStatusBar(String address) {
actionBar.setTitle(address);
// Text.set(context, R.id.statusBarText, name + address);
map.placeUser(context);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.small_settings_menu, menu);
mMenu = menu;
MenuItem itemMenuNotDistrub = mMenu.findItem(R.id.do_not_distrub);
if(prefs.getDoNotDistrub())
itemMenuNotDistrub.setIcon(R.drawable.ic_lock_ringer_on_alpha);
else
itemMenuNotDistrub.setIcon(R.drawable.ic_lock_ringer_off_alpha);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.small_menu_refresh:
MCAccidents.refresh(context);
if (Startup.isOnline()) {
JsonRequest request = MCAccidents.getLoadPointsRequest();
if (request != null) {
(new IncidentRequest(context)).execute(request);
}
} else {
Toast.makeText(context, Startup.context.getString(R.string.inet_not_available), Toast.LENGTH_LONG).show();
}
return true;
case R.id.small_menu_settings:
Intent intentSettings = new Intent(this, SettingsActivity.class);
Startup.context.startActivity(intentSettings);
return true;
case R.id.small_menu_about:
Intent intentAbout = new Intent(this, AboutActivity.class);
context.startActivity(intentAbout);
return true;
case R.id.small_menu_exit:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
context.startActivity(intent);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
return true;
case R.id.do_not_distrub:
MCPreferences prefs = new MCPreferences(Startup.context);
MenuItem menuItemActionDistrub = mMenu.findItem(R.id.do_not_distrub);
if(prefs.getDoNotDistrub()){
item.setIcon(R.drawable.ic_lock_ringer_on_alpha);
prefs.setDoNotDistrub(false);
} else {
item.setIcon(R.drawable.ic_lock_ringer_off_alpha);
prefs.setDoNotDistrub(true);
}
return true;
}
return false;
}
}
|
package nl.tue.apom.l3;
import java.util.Scanner;
import nl.tue.apom.l3.ai.AutomaticPlayer;
import nl.tue.apom.l3.ai.AutomaticPlayerV1;
import nl.tue.apom.l3.items.*;
/**
* Very basic support for the rock/paper/scissors game: taking two player inputs
* and indicating whether someone has one, continue doing so until you have a
* winner.
*
* @author pvgorp
*
*/
public class GameV2 {
private enum GameResult {
UNDECIDED, P1WON, P2WON, TIE
}
public static void main(String[] args) {
String howto = "Please enter once one of {paper,rock,scissors} to play"; // CHANGED
System.out.println(howto);
Scanner s = new Scanner(System.in);
Item i1 = null;
Item i2 = null;
AutomaticPlayer player2= new AutomaticPlayerV1(); // NEW
GameResult result = GameResult.UNDECIDED;
int round= 1;
do {
System.out.println("Round "+round++);
do {
try {
System.out.println("Player 1: please enter your choice");
i1 = ItemFactory.toItem(s.next());
i2 = player2.play(); // CHANGED
} catch (InvalidInputException e) {
System.out.println(e);
System.out.println(howto);
}
} while (i1 == null || i2 == null);
System.out.println("You selected " + i1); // CHANGED
System.out.println("Your computer opponent selected " + i2); // CHANGED
if (i1.beats(i2)) {
System.out.println("You win"); // CHANGED
result = GameResult.P1WON;
} else if (i2.beats(i1)) {
System.out.println("You loose");
result = GameResult.P2WON;
} else {
System.out.println("Nobody wins");
result = GameResult.TIE;
}
} while (result != GameResult.P1WON && result != GameResult.P2WON);
}
}
|
package persistlayer;
/**
* This class contains information needed to connect to the database.
*
* @author Connor Kirk
*
*/
public abstract class DbAccessConfiguration {
static final String DRIVER_NAME = "com.mysql.jdbc.Driver"; //name of jdb driver
static final String CONNECT_URL = "jdbc:mysql://localhost:3306/ryde"; //mysql url
static final String USER = "root"; //mysql username
static final String PASS = "root"; //mysql password
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private final Color alphaZero = new Color(0x0, true);
private final Color color = new Color(255, 0, 0, 50);
private MainPanel() {
super(new BorderLayout());
String[] columnNames = {"String", "Integer", "Boolean"};
Object[][] data = {
{"aaa", 12, true}, {"bbb", 5, false},
{"CCC", 92, true}, {"DDD", 0, false}
};
TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model) {
@Override public void updateUI() {
// [JDK-6788475] Changing to Nimbus LAF and back doesn't reset look and feel of JTable completely - Java Bug System
// XXX: set dummy ColorUIResource
setSelectionForeground(new ColorUIResource(Color.RED));
setSelectionBackground(new ColorUIResource(Color.RED));
super.updateUI();
setAutoCreateRowSorter(true);
setRowSelectionAllowed(true);
setFillsViewportHeight(true);
setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
setDefaultRenderer(Boolean.class, new TranslucentBooleanRenderer());
setOpaque(false);
setBackground(alphaZero);
TableModel m = getModel();
for (int i = 0; i < m.getColumnCount(); i++) {
TableCellRenderer r = getDefaultRenderer(m.getColumnClass(i));
if (r instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component) r);
}
}
}
@Override public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JTextField) {
JTextField tf = (JTextField) c;
tf.setOpaque(false);
} else if (c instanceof JCheckBox) {
JCheckBox cb = (JCheckBox) c;
cb.setBackground(getSelectionBackground());
}
return c;
}
};
TexturePaint texture = makeImageTexture();
JScrollPane scroll = new JScrollPane(table) {
@Override protected JViewport createViewport() {
return new JViewport() {
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(texture);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
};
}
};
scroll.getViewport().setOpaque(false);
scroll.getViewport().setBackground(alphaZero);
JCheckBox check = new JCheckBox("setBackground(new Color(255, 0, 0, 50))");
check.addActionListener(e -> table.setBackground(((JCheckBox) e.getSource()).isSelected() ? color : alphaZero));
add(check, BorderLayout.NORTH);
add(scroll);
setPreferredSize(new Dimension(320, 240));
}
private static TexturePaint makeImageTexture() {
BufferedImage bi = Optional.ofNullable(MainPanel.class.getResource("unkaku_w.png"))
.map(url -> {
try {
return ImageIO.read(url);
} catch (IOException ex) {
return makeMissingImage();
}
}).orElseGet(() -> makeMissingImage());
return new TexturePaint(bi, new Rectangle(bi.getWidth(), bi.getHeight()));
}
private static BufferedImage makeMissingImage() {
Icon missingIcon = UIManager.getIcon("OptionPane.errorIcon");
int w = missingIcon.getIconWidth();
int h = missingIcon.getIconHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
missingIcon.paintIcon(null, g2, 0, 0);
g2.dispose();
return bi;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGui();
}
});
}
public static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TranslucentBooleanRenderer implements TableCellRenderer {
private final JCheckBox renderer = new JCheckBox() {
@Override public void updateUI() {
super.updateUI();
// NG???: setHorizontalAlignment(SwingConstants.CENTER);
setBorderPainted(true);
setBorderPaintedFlat(true);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setOpaque(false);
}
@Override protected void paintComponent(Graphics g) {
if (!isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
};
protected TranslucentBooleanRenderer() {
renderer.setHorizontalAlignment(SwingConstants.CENTER);
}
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
renderer.setOpaque(true);
renderer.setForeground(table.getSelectionForeground());
renderer.setBackground(table.getSelectionBackground());
} else {
renderer.setOpaque(false);
renderer.setForeground(table.getForeground());
renderer.setBackground(table.getBackground());
}
renderer.setSelected(Objects.equals(value, Boolean.TRUE));
return renderer;
}
}
|
package controllers;
import models.Account;
import models.Friendship;
import models.enums.CustomContentType;
import net.hamnaberg.funclite.Predicate;
import net.hamnaberg.json.Collection;
import net.hamnaberg.json.Item;
import play.db.jpa.Transactional;
import play.mvc.Result;
import play.mvc.Security;
import util.JsonCollectionUtil;
import java.util.LinkedList;
import java.util.List;
@Transactional
@Security.Authenticated(SecuredWithToken.class)
public class APIUserController extends BaseController {
/**
* Fetches the requested user(s) and returns Collection+JSON representation of the user(s).
* @param id the id of the requested use, -1 for all uses visible for the current user (determined by access token)
* @return ok with Collection+Json of requested user(s), bad request with received collection with errors or not acceptable
* if the client does not accept Collection+JSON
*/
public static Result get(final long id) {
if (request().getHeader("Accept").contains(CustomContentType.JSON_COLLECTION.getIdentifier())) {
response().setContentType(CustomContentType.JSON_COLLECTION.getIdentifier());
Collection collection = JsonCollectionUtil.getRequestedCollection(Account.class, id, "Account");
Collection filterdCollection = new Collection.Builder().addItems(collection.filterItems(new Predicate<Item>() {
@Override
public boolean apply(Item item) {
long tokenUser = Long.parseLong(session().get("token_user"));
Account tokenUserAccount = Account.findById(tokenUser);
boolean isFriend = false;
List<Long> friendsOfTokenUser = new LinkedList<Long>();
for (Friendship f : tokenUserAccount.friends) {
friendsOfTokenUser.add(f.friend.id);
}
long candidate = item.getData().getDataAsMap().get("id").getValue().get().asNumber().longValue();
if (friendsOfTokenUser.contains(candidate)) {
List<Long> candidates = new LinkedList<Long>();
for (Friendship cf : Account.findById(candidate).friends) {
if (cf.friend.id == tokenUser) {
isFriend = true;
}
}
}
return isFriend;
}
})).withHref(collection.getHref().get())
.withError(collection.getError().get())
.withTemplate(collection.getTemplate().get())
.addLinks(collection.getLinks())
.addQueries(collection.getQueries())
.build();
return ok(filterdCollection.toString());
} else {
return statusWithWarning(NOT_ACCEPTABLE, CustomContentType.JSON_COLLECTION.getAcceptHeaderMessage());
}
}
}
|
/*
* $Log: XmlIf.java,v $
* Revision 1.2 2005-08-25 15:49:49 europe\L190409
* improved logging
*
* Revision 1.1 2005/08/24 15:54:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* introduction of XmlIf
*
*/
package nl.nn.adapterframework.pipes;
import javax.xml.transform.TransformerConfigurationException;
import org.apache.commons.lang.StringUtils;
import nl.nn.adapterframework.configuration.ConfigurationException;
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.util.TransformerPool;
/**
* Selects an exitState, based on the content of a sessionkey.
*
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>{@link #setSessionKey(String) sessionKey}</td><td>name of the key in the <code>PipeLineSession</code> to retrieve the input-message from. If not set, the current input message of the Pipe is taken</td><td> </td></tr>
* <tr><td>{@link #setXpathExpression(String) xpathExpression}</td><td>XPath expression to be applied to the input-message. If not set, no transformation is done</td><td> </td></tr>
* <tr><td>{@link #setExpressionValue(String) expressionValue}</td><td>a string to compare the result of the xpathExpression (or the input-message itself) to. If not specified, a non-empty result leads to the 'then'-forward, an empty result to 'else'-forward</td><td> </td></tr>
* <tr><td>{@link #setThenForwardName(String) thenForwardName(String)}</td><td>forward returned when 'true'</code></td><td>then</td></tr>
* <tr><td>{@link #setElseForwardName(String) elseForwardName(String)}</td><td>forward returned when 'false'</td><td>else</td></tr>
* </table>
* </p>
*
* @version Id
* @author Peter Leeuwenburgh
* @since 4.3
*/
public class XmlIf extends AbstractPipe {
public static final String version="$RCSfile: XmlIf.java,v $ $Revision: 1.2 $ $Date: 2005-08-25 15:49:49 $";
private String sessionKey = null;
private String xpathExpression = null;
private String expressionValue = null;
private String thenForwardName = "then";
private String elseForwardName = "else";
private TransformerPool tp = null;
protected String makeStylesheet(String xpathExpression, String resultVal) {
String result =
// "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<xsl:stylesheet xmlns:xsl=\"http:
"<xsl:output method=\"text\" omit-xml-declaration=\"yes\"/>" +
"<xsl:strip-space elements=\"*\"/>" +
"<xsl:template match=\"/\">" +
"<xsl:choose>" +
"<xsl:when test=\"" +xpathExpression +
(StringUtils.isEmpty(resultVal)?"":"='"+resultVal+"'")+
"\">" +getThenForwardName()+"</xsl:when>"+
"<xsl:otherwise>" +getElseForwardName()+"</xsl:otherwise>" +
"</xsl:choose>" +
"</xsl:template>" +
"</xsl:stylesheet>";
log.debug(getLogPrefix(null)+"created stylesheet ["+result+"]");
return result;
}
public void configure() throws ConfigurationException {
super.configure();
if (StringUtils.isNotEmpty(getXpathExpression())) {
try {
tp = new TransformerPool(makeStylesheet(getXpathExpression(), getExpressionValue()));
} catch (TransformerConfigurationException e) {
throw new ConfigurationException(getLogPrefix(null)+"could not create transformer from xpathExpression ["+getXpathExpression()+"], target expressionValue ["+getExpressionValue()+"]",e);
}
}
}
public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException {
String forward = "";
PipeForward pipeForward = null;
String sInput;
if (StringUtils.isEmpty(getSessionKey())) {
sInput = input.toString();
} else {
log.debug(getLogPrefix(session)+"taking input from sessionKey ["+getSessionKey()+"]");
sInput=(String) session.get(getSessionKey());
}
log.debug(getLogPrefix(session) + "input value is [" + sInput + "]");
if (tp!=null) {
try {
forward = tp.transform(sInput,null);
} catch (Exception e) {
throw new PipeRunException(this,getLogPrefix(session)+"cannot evaluate expression",e);
}
} else {
if (sInput.equals(expressionValue)) {
forward = thenForwardName;
}
else {
forward = elseForwardName;
}
}
log.debug(getLogPrefix(session)+ "determined forward [" + forward + "]");
pipeForward=findForward(forward);
if (pipeForward == null) {
throw new PipeRunException (this, getLogPrefix(null)+"cannot find forward or pipe named [" + forward + "]");
}
log.debug(getLogPrefix(session)+ "resolved forward [" + forward + "] to path ["+pipeForward.getPath()+"]");
return new PipeRunResult(pipeForward, input);
}
public void setSessionKey(String sessionKey){
this.sessionKey = sessionKey;
}
public String getSessionKey(){
return sessionKey;
}
public void setExpressionValue(String expressionValue){
this.expressionValue = expressionValue;
}
public String getExpressionValue(){
return expressionValue;
}
public void setThenForwardName(String thenForwardName){
this.thenForwardName = thenForwardName;
}
public String getThenForwardName(){
return thenForwardName;
}
public void setElseForwardName(String elseForwardName){
this.elseForwardName = elseForwardName;
}
public String getElseForwardName(){
return elseForwardName;
}
public void setXpathExpression(String string) {
xpathExpression = string;
}
public String getXpathExpression() {
return xpathExpression;
}
}
|
package net.gangelov.orm;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
public class Query<T extends Model> implements Cloneable {
static final boolean VERBOSE = true;
enum Type {
SELECT,
INSERT,
UPDATE,
DELETE
}
private Type type;
private final Connection connection;
private String table = null,
returning = null,
select = null;
private Class<T> modelClass = null;
protected final LinkedHashMap<String, Object> values = new LinkedHashMap<>();
protected final LinkedHashMap<String, List<Object>> wheres = new LinkedHashMap<>();
public Query(Connection connection) {
this.connection = connection;
}
public Query<T> clone() {
Query<T> obj = null;
try {
obj = (Query<T>)super.clone();
} catch (CloneNotSupportedException e) {
// This cannot happen
e.printStackTrace();
}
obj.values.putAll(values);
obj.wheres.putAll(wheres);
return obj;
}
public Query<T> forModel(Class<T> klass) {
Query<T> q = select("*").from(ModelReflection.get(klass).tableName);
q.modelClass = klass;
return q;
}
public Query<T> select() {
return select("*");
}
public Query<T> select(String select) {
Query<T> q = clone();
q.type = Type.SELECT;
q.select = select;
return q;
}
public Query<T> insert() {
Query<T> q = clone();
q.type = Type.INSERT;
return q;
}
public Query<T> update() {
Query<T> q = clone();
q.type = Type.UPDATE;
return q;
}
public Query<T> delete() {
Query<T> q = clone();
q.type = Type.DELETE;
return q;
}
public Query<T> table(String table) {
Query<T> q = clone();
q.table = table;
return q;
}
public Query<T> from(String table) {
return table(table);
}
public Query<T> into(String table) {
return table(table);
}
public Query<T> set(String column, Object object) {
Query<T> q = clone();
q.values.put(column, object);
return q;
}
public Query<T> set(Map<String, Object> values) {
Query<T> q = clone();
q.values.putAll(values);
return q;
}
public Query<T> where(String column, Object value) {
return whereSql("\"" + column + "\" = ?", value);
}
public Query<T> whereNot(String column, Object value) {
return whereSql("\"" + column + "\" != ?", value);
}
public Query<T> whereSql(String where, Object... args) {
Query<T> q = clone();
q.wheres.put(where, Arrays.asList(args));
return q;
}
public Query<T> returning(String column) {
Query<T> q = clone();
q.returning = column;
return q;
}
public String toSQL() {
StringBuilder sql = new StringBuilder();
switch(type) {
case SELECT:
sql.append("select ");
sql.append(select);
sql.append(" from ");
sql.append("\"").append(table).append("\"");
if (wheres.size() > 0) {
sql.append(" where ");
sql.append(buildWhereClause());
}
break;
case DELETE:
sql.append("delete from ");
sql.append("\"").append(table).append("\"");
if (wheres.size() > 0) {
sql.append(" where ");
sql.append(buildWhereClause());
}
break;
case INSERT:
sql.append("insert into \"").append(table).append("\"");
sql.append(" (");
sql.append(
values.keySet().stream()
.map(key -> "\"" + key + "\"")
.collect(Collectors.joining(", "))
);
sql.append(")");
sql.append(" values (");
sql.append(String.join(", ", Collections.nCopies(values.size(), "?")));
sql.append(")");
if (returning != null) {
sql.append(" returning \"").append(returning).append("\"");
}
break;
case UPDATE:
sql.append("update \"").append(table).append("\"");
if (values.size() > 0) {
sql.append(" set ");
sql.append(
values.keySet().stream()
.map(key -> "\"" + key + "\" = ?")
.collect(Collectors.joining(", "))
);
}
if (wheres.size() > 0) {
sql.append(" where ");
sql.append(buildWhereClause());
}
if (returning != null) {
sql.append(" returning \"").append(returning).append("\"");
}
break;
default:
throw new RuntimeException("Unsupported query type");
}
return sql.toString();
}
private String buildWhereClause() {
return this.wheres.keySet().stream()
.map(clause -> "(" + clause + ")")
.collect(Collectors.joining(" and "));
}
public QueryResult<T> execute() throws SQLException {
String sql = toSQL();
List<Object> params = buildParameters();
if (VERBOSE) {
System.out.println("ORM QUERY: " + toSQL());
if (params.size() > 0) {
System.out.println(
"ORM DATA: [" +
params.stream().map(o -> {
if (o instanceof Integer) {
return o.toString();
} else {
return "'" + o.toString() + "'";
}
}).collect(Collectors.joining(", ")) +
"]"
);
}
}
PreparedStatement statement = statement(sql, params);
statement.execute();
if (modelClass != null) {
return new QueryResult<T>(statement, modelClass);
} else {
return new QueryResult<T>(statement);
}
}
public List<T> results() throws SQLException {
return execute().results();
}
public T first() throws SQLException {
return (T)execute().first();
}
public boolean exists() throws SQLException {
return count() > 0;
}
public int count() throws SQLException {
QueryResult result = clone().select("count(*)").execute();
return result.getInt();
}
private List<Object> buildParameters() {
List<Object> params = new ArrayList<>();
for (Object value : values.values()) {
if (value instanceof Instant) {
params.add(Timestamp.from((Instant)value));
} else {
params.add(value);
}
}
for (List<Object> whereValues : wheres.values()) {
for (Object value : whereValues) {
if (value instanceof Instant) {
params.add(Timestamp.from((Instant)value));
} else {
params.add(value);
}
}
}
return params;
}
private PreparedStatement statement(String sql, List<Object> params) throws SQLException {
PreparedStatement statement = connection.prepareStatement(sql);
for (int i = 0; i < params.size(); i++) {
statement.setObject(i + 1, params.get(i));
}
return statement;
}
}
|
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Random;
import javax.swing.SwingUtilities;
import netscape.javascript.JSObject;
/**
* Pings client. Connects to the Pings server, retrieves addresses
* to be pinged, pings them and submits the results back to the server.
*
* To use, embed in a thread object, then start the thread. If you want
* to be notified when the source geoip info or ping destination change, you
* can register yourself with addNotifier().
*
* We give up (and stop the thread) after a total of MAX_ERROR_COUNT errors
* has occurred. We also do exponential backoff on consecutive errors,
* to avoid overloading the servers if they have a problem. There is a
* maximum wait time of MAX_WAIT_TIME. This is set to wait for 5 days before
* stopping to work without user intervention if we need to reboot the server.
*
* We will wait at least MIN_ROUND_TIME seconds in average before contacting
* the server to get new ip to pings. As we have a queue of pings address to
* get, each pings slot in the queue need to wait MIN_ROUND_TIME*pings_queue_size.
* We also add a random number of up to 10% of the server MIN_ROUND_TIME to
* help spread the users in case they all start at the same time.
* We also multiple the wait_time by WAIT_TIME_BOOST to help load testing
* wait_time is the time we should wait normally.
* @author Christian Hudon <chrish@pianocktail.org>
*/
public class PingsClient extends Observable implements Runnable {
public final int MAX_WAIT_TIME = 15 * 60; //Max wait time in seconds
public final int MAX_ERROR_COUNT = 10 + //It take 10 tries to wait 15 minutes
5*24*60/(MAX_WAIT_TIME/60); //We will try for 5 days before stopping!
public final long MIN_ROUND_TIME = 1 * 60; //In seconds.
public double WAIT_TIME_BOOST = 1; //default to 1, no change.
// These variables are initialized in the constructor and then
// only accessed by the subClients thread. No need for locking, etc.
private ClientInfo m_client_info;
private ServerProxy m_server_proxy;
private final static Logger LOGGER = Logger.getLogger(PingsClient.class.getName());
// These variables are accessed both by the PingsClient thread and
// by other threads using this class. They need to use something
// like the Java Atomic types or other to prevent fun multithreading
// bugs!
protected AtomicReference<GeoipInfo> m_source_geoip;
protected AtomicBoolean m_is_running;
protected AtomicReference<String> m_nick;
protected AtomicInteger m_total_error_count;
protected AtomicInteger m_total_submited_pings;
// For analysis
protected AtomicInteger m_measurements_failed;
int num_measurements = 0;
String measurements = "";
boolean shown_analysis = false;
//The number of subClient(s) to run simultaneously
protected int subClient_number = 6;
//The subClients
protected subClient[] subClients_pool;
protected Thread[] subClients_threads_pool;
//The queue of ServerProxy.Pings
private int pings_queue_size = 1;
private ServerProxy.Pings[] pings_queue;
//The index in the queue of the next Pings to look into to find new addresses
//to be pinged. This is only used as an indication to allow pings to be
//filled one after an other so that there are as much free addresses as
//possible
private int next_pings_with_addresses = 0;
//The number of addresses we didn't store result about for each Pings in the
//queue
private int remaining_addresses[];
//The index of the next available address for each Pings, please note that
//there is a difference between available/free addresses -which were not
//given to a subClient yet- and remaining addresses which might have been
//given to a subClient but didn't return result yet
private int next_available_address[];
//Variables used to notify the applet that there was a connection problem with
//the server. The error_reason is also set when there is a problem,
//but this is not yet an error.
public boolean connect_error;
public String error_reason;
/**
A reference to the applet. This is needed to set the cookie.
*/
private PingsApplet applet;
private long start_time;
/**
The prefix of cookies
The name is hardcoded in the index.html file too.
*/
public final static String m_cookie_name="udem_ping";
public PingsClient(String server_hostname, int server_port, PingsApplet applet,
String uuid, String nick, int nb_submited_pings) {
m_client_info = new ClientInfo(uuid, nick);
this.applet = applet;
m_server_proxy = new ServerProxy(server_hostname, server_port);
m_nick = new AtomicReference<String>(m_client_info.getNickname());
m_source_geoip = new AtomicReference<GeoipInfo>();
m_total_error_count = new AtomicInteger();
m_total_submited_pings = new AtomicInteger(nb_submited_pings);
m_measurements_failed = new AtomicInteger();
m_is_running = new AtomicBoolean(false);
//Initialize the pings_queue
pings_queue = new ServerProxy.Pings[pings_queue_size];
next_available_address = new int[pings_queue_size];
remaining_addresses= new int[pings_queue_size];
for (int pings_index = 0; pings_index < pings_queue_size; pings_index++) {
pings_queue[pings_index] = null;
next_available_address[pings_index] = -1;
remaining_addresses[pings_index] = 0;
}
//Initialize the subClients pool
subClients_pool = new subClient[subClient_number];
subClients_threads_pool = new Thread[subClient_number];
for (int i = 0; i < subClient_number; i++) {
subClients_pool[i] = new subClient();
subClients_threads_pool[i] = new Thread(subClients_pool[i]);
subClients_threads_pool[i].setName("SubClient "+ i);
}
resetErrorCount();
}
/**
* This constructor in only for simulation and test purpose
*/
public PingsClient() {
m_client_info = new ClientInfo("", "");
m_nick = new AtomicReference<String>("");
m_source_geoip = new AtomicReference<GeoipInfo>();
m_total_error_count = new AtomicInteger();
m_total_submited_pings = new AtomicInteger();
m_measurements_failed = new AtomicInteger();
m_is_running = new AtomicBoolean(false);
pings_queue = new ServerProxy.Pings[pings_queue_size];
}
public void run() {
LOGGER.info("PingsClient starting.");
resetErrorCount();
m_is_running.set(true);
this.start_time = System.currentTimeMillis();
for (int pings_index = 0; pings_index < pings_queue_size; pings_index++) {
sendResultsGetNewAddress(pings_index);
}
for (int pings_index = 0; pings_index < subClient_number; pings_index++) {
subClients_threads_pool[pings_index].start();
}
}
/**
* Launched as a thread this class get new addresses using setNewAddress and
* pings them (the same method report them to the server) .
* Used as an Observable it provides an interface for the GUI.
*/
class subClient extends Observable implements Runnable {
//The class that actually do the pings
private Prober prober;
//The information on the current ping, they are mainly used by the GUI
//observers
protected InetAddress current_ping_dest = null;
protected GeoipInfo current_dest_geoip = null;
protected String current_ping_result = null;
//The position of the current address/geoip in the pings_queue
private int current_pings_index;
private int current_address_index;
//The number of consecutive errors that occurred in this thread.
private int consecutive_error_count = 0;
private boolean sucide;
protected boolean last_pings_succeded = true;
public subClient () {
prober = new CompositeProber(m_client_info);
}
public subClient (Prober p) {
prober = p;
}
public void run() {
while (!sucide) {
try {
//Get a new Address (and send the result of the previous one)
setNewAddress (this, current_ping_result,
current_pings_index, current_address_index);
if (sucide) break;
notifyObserversOfChange();
//Ping this address
prober.probe(current_ping_dest);
current_ping_result = prober.getLastProbe();
LOGGER.log(Level.INFO, "Ping result: {0}.",current_ping_result);
//Extract relevant info for analysis
last_pings_succeded = addMeasurement(current_ping_result, current_ping_dest);
notifyObserversOfChange();
//In case the thread is paused here
if (!m_is_running.get()) {
while (!m_is_running.get()) {
synchronized(pings_queue) {pings_queue.wait();}
}
}
// Clear consecutive error count.
consecutive_error_count = 0;
}
catch (InterruptedException _) {break;}
catch (Exception e) {
final int total_error_count = m_total_error_count.incrementAndGet();
consecutive_error_count++;
LOGGER.log(Level.WARNING, "Exception caught in subClient thread.", e);
// Exponential backoff for consecutive errors
int wait_time = (int)Math.pow(2, consecutive_error_count);
wait_time = Math.min(wait_time, MAX_WAIT_TIME);
if (consecutive_error_count > MAX_ERROR_COUNT) {
LOGGER.log(Level.SEVERE, "Too many errors; stopping the subClient thread.");
PingsClient.this.errorConnectingToServer(
"Too many problem happened." +
"Click try to retry or reload this page to possibly get a newer clients version."
);
break;
}
else {
try {
Thread.sleep(1000 * wait_time);
} catch (InterruptedException _) {break;}
}
}
}
}
/**
* Set the parameters for a new ping, so that changes might be notified
* to the GUI.
*
* @param add the address of the new target to ping
* @param geo the geoip of the new target to ping
* @param pings_index the index of the current Pings in the pings_queue
* @param address_index the index of the address in the current Pings
*/
public void setCurrentAddressProperty (InetAddress add, GeoipInfo geo,
int pings_index, int address_index) {
current_ping_dest = add;
current_dest_geoip = geo;
current_ping_result = null;
current_pings_index = pings_index;
current_address_index = address_index;
}
/**
* Combines java.util.Observable's setChanged() and notifyObservers()
* to notify the GUI
*/
protected void notifyObserversOfChange() {
setChanged();
notifyObservers();
}
public InetAddress getCurrentPingDest() {
return current_ping_dest;
}
public GeoipInfo getCurrentDestGeoip() {
return current_dest_geoip;
}
public String getCurrentPingResult() {
return current_ping_result;
}
public GeoipInfo getSourceGeoip() {
return PingsClient.this.getSourceGeoip();
}
public InetAddress getSourceAddress() {
return PingsClient.this.getSourceAddress();
}
public InetAddress getSourceExternalAddress() {
return PingsClient.this.getSourceExternalAddress();
}
public void destroy() {
sucide = true;
}
}
/**
* Invoked by a subClient this method store its last result and give him a
* new address to ping.
* <p>
* If there are no more addresses available on the current Pings it calls
* sendResultGetNewAddress to get new ones and proceed to the next Pings in
* the queue. If there are no more address anywhere it waits to be wake up by
* the thread receiving new address.
*
*/
protected void setNewAddress (subClient sub, String last_result,
int current_pings_index, int current_address_index) {
synchronized(pings_queue) {
//Store the result of the subClient in the corresponding Pings
if (last_result != null) {
ServerProxy.Pings pings = pings_queue[current_pings_index];
pings.results[current_address_index] = last_result;
remaining_addresses[current_pings_index] -= 1;
//If it was the last address to get result from on the current Pings then
//send the results an get a new address list
if (remaining_addresses[current_pings_index] == 0 ) {
sendResultsGetNewAddress(current_pings_index);
}
}
//Get a new address to ping
int pings_index = next_pings_with_addresses;
//Loop thought pings_queue to find a free address and give it to sub
// index_to_wait allow to decide if we have cycle or not
int index_to_wait = next_pings_with_addresses;
while (true) {
ServerProxy.Pings local_pings = pings_queue[pings_index];
if (next_available_address[pings_index] != -1 && local_pings != null) {
//If the Pings at address pings_index have some free address we
//take one
int address_index = next_available_address[pings_index];
next_available_address[pings_index]++;
if (next_available_address[pings_index] == local_pings.addresses.length) {
next_available_address[pings_index] = -1;
next_pings_with_addresses = (next_pings_with_addresses +1) % pings_queue_size;
}
sub.setCurrentAddressProperty(local_pings.addresses[address_index],
local_pings.geoip_info[address_index],
pings_index,
address_index);
break;
}
//Otherwise we change next_pings_with_addresses and proceed to the
//next ping if we didn't loop
next_pings_with_addresses = (next_pings_with_addresses +1) % pings_queue_size;
pings_index = (pings_index +1) % pings_queue_size;
if (pings_index == index_to_wait && next_available_address[index_to_wait] == -1 ) {
try {
pings_queue.wait(100);
} catch (InterruptedException e) {
sub.destroy();
break;
}
}
}
}
}
/**
* Send the results of a Pings to the server and get a new list of addresses
* to ping.
* <p>
* When the list is obtained it set the index and next_address parameters
* correctly then wake up the methods potentially waiting for new addresses lists.
* <p>
* Doesn't need to be synchronized as only one instance can execute at a time
* over a given pings_index.
* <p>
* If the Pings at the current index is null then it get replaced by a fresh
* Pings
* It die after having submited/fetch new results once.
*/
private class SendResultsGetNewAddress extends Thread {
private int pings_index;
private int consecutive_error_count = 0;
private Random rand = new Random();
public SendResultsGetNewAddress(int pings_index) {
this.pings_index = pings_index;
this.setName("SendResultsGetNewAddress " + pings_index);
}
public void run() {
while (true) {
String catched = "";
String err_msg = "";
try {
// Submit results to server.
if (pings_queue[pings_index] != null) {
//elapsed_time are in mili-seconds.
long elapsed_time = System.currentTimeMillis() - pings_queue[pings_index].time_fetched;
LOGGER.info("Submitting results to server for pings_index=" +
pings_index +
". Round took " + elapsed_time/1000 + "s.");
m_server_proxy.submitResults(m_client_info,
pings_queue[pings_index]);
// Save the number of submitted ip in a cookie:
synchronized(m_total_submited_pings) {
int n = m_total_submited_pings.addAndGet(pings_queue[pings_index].addresses.length);
setCookieNbPings(n);
}
//Wait if needed
long min_round_time = Math.max(MIN_ROUND_TIME, pings_queue[pings_index].min_round_time);
min_round_time += 0.1 * this.rand.nextInt((int)min_round_time);
//wait_time are in mili-seconds.
long wait_time = (min_round_time * pings_queue_size * 1000) - elapsed_time ;
wait_time = (long)(wait_time * WAIT_TIME_BOOST);
// In case the submit succeed, but the get fail, if we don't null it, it will get resubmitted.
pings_queue[pings_index] = null;
if (wait_time > 0){
LOGGER.info("\nWaiting before the next round for pings_index=" + pings_index +
" elapsed_time(ms)=" + elapsed_time +
" min_round_time(s)=" + min_round_time +
" pings_queue_size=" + pings_queue_size +
" wait_time(ms)=" + wait_time);
try {
Thread.sleep(wait_time);
} catch (InterruptedException e1) {}
}
if(consecutive_error_count >= 6)
PingsClient.this.displayProblem("");
}
// Get source geoip data and list of addresses to ping.
pings_queue[pings_index] = m_server_proxy.getPings(m_client_info);
m_source_geoip.set(m_client_info.getGeoipInfo());
//Setting the remaining_address and next
remaining_addresses[pings_index] = pings_queue[pings_index].addresses.length;
next_available_address[pings_index] = 0;
//Wake up threads that might wait for new addresses
synchronized(pings_queue){
pings_queue.notify();
}
if(consecutive_error_count >= 6)
PingsClient.this.displayProblem("");
//consecutive_error_count = 0; useless as a new thread will be created for the next fetch.
break;
}
catch (UnknownHostException _) {
catched = "UnknownHostException";
err_msg = "A problem happened while trying to connect to the server. The most probable causes are :\n" +
"_ you are not connected to the internet\n" +
"_ you have a DNS problem\n" +
"_ the server you are trying to join is not correctly configured";
}
catch (ConnectException e) {
catched = "ConnectException";
err_msg = "A problem happened while trying to connect to the server. The most probable causes are :\n" +
"_ a firewall is blocking the connection\n" +
"_ you lost your connection to internet\n"+
"_ the server you are trying to join reject the connection";
}
catch(SocketTimeoutException e) {
catched = "SocketTimeoutException";
err_msg = "A problem happened while trying to connect to the server . The most probable causes are :\n" +
"_ a firewall is blocking the connection\n" +
"_ the server is overloaded\n" +
"_ the connection is taking too long";
}
catch (IOException e) {
catched = "IOException";
err_msg = "Exception caught in PingsClient thread " + pings_index +
" when contacting the server.\n" + e;
} // catch IOException
if (catched != ""){
consecutive_error_count++;
int wait_time = (int)Math.pow(2, consecutive_error_count);
wait_time = Math.min(wait_time, MAX_WAIT_TIME);
err_msg += "\n This is the " + consecutive_error_count +
" consecutive error count. We will wait " + wait_time +
" seconds before recontacting it again.";
LOGGER.log(Level.WARNING, err_msg);
if (consecutive_error_count > MAX_ERROR_COUNT) {
LOGGER.log(Level.SEVERE,
"Too many errors; stopping PingsClient thread " + pings_index);
PingsClient.this.errorConnectingToServer(
"Too many problem happened while trying to connect to the server." +
"Click try to retry or reload this page to possibly get a newer clients version."
);
break;
}
else {
//If we wait for more then 1 minutes, display the error messages.
//subClient thread will remove this when fixed.
if (wait_time >= 60)
PingsClient.this.displayProblem(err_msg);
// Exponential backoff for consecutive errors. Also
// avoid thread busy-loop if IOException keeps getting
// raised in call to getPings.
try {
Thread.sleep(1000 * wait_time);
} catch (InterruptedException e1) {
LOGGER.log(Level.SEVERE,
"SendResultsGetNewAddress got interrupted while waiting after an errors. pings_index=" +
pings_index, e1);
PingsClient.this.errorConnectingToServer(
"Interupted while a thread was sleeping.");
break;
}
}
}
}
}
}
/**
* A function that launch the thread class sendResultsGetNewAddress
* @see SendResultsGetNewAddress
*/
private void sendResultsGetNewAddress(int pings_index) {
new SendResultsGetNewAddress(pings_index).start();
}
public void errorConnectingToServer(String reason) {
this.connect_error = true;
this.error_reason = reason;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PingsClient.this.setChanged();
notifyObservers();
}
});
}
public void displayProblem(String prob){
this.error_reason = prob;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PingsClient.this.setChanged();
notifyObservers();
}
});
}
public subClient[] getSubClientsPoolCopy() {
subClient[] copy = new subClient[subClient_number];
for (int i = 0; i < subClient_number; i++) {
copy[i] = subClients_pool[i];
}
return copy;
}
public void setNickname(String nick) {
m_nick.set(nick);
m_client_info.setNickname(nick);
this.setCookie();
}
public String getNickname() {
return m_nick.get();
}
public GeoipInfo getSourceGeoip() {
return m_source_geoip.get();
}
public InetAddress getSourceAddress() {
return m_client_info.getAddress();
}
public InetAddress getSourceExternalAddress() {
return m_client_info.getExternalAddress();
}
public int getErrorCount() {
return m_total_error_count.get();
}
public int getSubmitedPingsCount() {
return m_total_submited_pings.get();
}
private void resetErrorCount() {
m_total_error_count.set(0);
}
public void pause() {
synchronized(pings_queue) {
m_is_running.set(false);
}
}
public void resume() {
this.setCookie();
m_is_running.set(true);
for (int i = 0; i < subClient_number; i++) {
synchronized(pings_queue) {
pings_queue.notify();
}
}
}
public void destroy() {
for (int i = 0; i < subClient_number; i++) {
subClients_threads_pool[i].interrupt();
}
this.m_is_running.set(false);
}
public boolean isRunning() {
return m_is_running.get();
}
// Return if the last ICMP pings succeded of not
// This add the measurement to the list for the feedback as show it when needed.
public boolean addMeasurement(String current_ping_result, InetAddress current_ping_dest) {
String[] icmp_result = current_ping_result.split(";")[0].split(" ");
String last = icmp_result[icmp_result.length - 1];
boolean ok = current_ping_result.indexOf("ICMP") != -1 &&
last.length() > 2 &&
last.substring(last.length() - 2).equals("ms");
float value = -999f;
if(shown_analysis)
return ok;
if(!ok){
LOGGER.log(Level.INFO, "Bad measurements: " + current_ping_result);
}else{
try{
last = last.substring(0, last.length() - 2);
value = Float.parseFloat(last);
ok &= value >= 10 && value < 1900;
}catch(NumberFormatException e){
ok = false;
LOGGER.log(Level.INFO, "addMeasurement: Bad parsing of new ICMP ping: " + current_ping_result);
}
}
synchronized(measurements) {
if (ok) {
String measurement = current_ping_dest.getHostAddress() + "," + last;
if (num_measurements > 0) measurements += "-";
measurements += measurement;
num_measurements++;
LOGGER.log(Level.INFO, "Measurement #" + Integer.toString(num_measurements) + ": " + measurement);
// If the applet is started for more then 15 minutes and we have at least 5 ip,
// request the repport.
if (num_measurements >= 5 && (System.currentTimeMillis() - start_time) > 1000*60*15){ // 15 minutes
LOGGER.log(Level.INFO, "\n\nTry to print the feedback");
LOGGER.log(Level.INFO, "javascript:get_analysis('" + measurements + "')");
JSObject.getWindow(applet).eval("javascript:get_analysis('" + measurements + "')");
shown_analysis = true;
}
}
}
return ok;
}
private void setOneCookie(String name, String value){
System.out.println("setCookie " + name + " " + value);
// The try..catch work around some browser bugs. This could make some cookie not saved
// but having something working without cookie is better then nothing working!
try{
JSObject.getWindow(this.applet).eval("javascript:set_cookie('" + name +
"', '" + value + "')");
}catch(NullPointerException e){
LOGGER.log(Level.INFO, "Cannot set cookie due to NullPointerException");
}
}
public void setCookie() {
setOneCookie(m_cookie_name + "_uuid", this.m_client_info.m_uuid);
setOneCookie(m_cookie_name + "_nickname", this.m_client_info.getNickname());
}
public void setCookieNbPings(int n) {
setOneCookie(m_cookie_name + "_nb_pings", Integer.toString(n));
}
/*
* This make sure we can put into a cookie the following string by removing caractere that aren't safe.
*/
public static String sanitize_string(String str) {
//{a-zA-Z0-9 .@}
if (str != null)
str = str.replaceAll("[^a-zA-Z0-9 .@]", "");
return str;
}
public static void main(String args[]) throws InterruptedException {
String hostname = "iconnect.iro.umontreal.ca";
int port = 6543;
boolean null_prober = false;
boolean icmp_prober = false;
int nb_clients = 1;
//Parse input
for (int i = 0 ; i < args.length ; i++) {
if (args[i].equals("--null")) {
null_prober = true;
} else if (args[i].equals("--icmp")) {
icmp_prober = true;
} else if (args[i].startsWith("-n=")) {
try {
nb_clients = Integer.parseInt(args[i].substring(3));
}
catch (NumberFormatException e) {
System.err.println("Error: port argument must be an integer.");
System.exit(2);
}
} else if ((args.length - i) > 2) {
System.err.println("Usage: PingsClient [-n=N] [--{null,icmp}] [hostname [port]]");
System.exit(1);
} else {
hostname = args[i];
if ((i + 1) < args.length){
try {
port = Integer.parseInt(args[i + 1]);
}
catch (NumberFormatException e) {
System.err.println("Error: port argument must be an integer.");
System.exit(2);
}
}
break;
}
}
System.out.println("Hostname: " + hostname);
System.out.println("Port:" + port);
System.out.println("Nb clients:" + nb_clients);
if (null_prober && icmp_prober) {
System.err.println("Can only use one of --null and --icmp parameter");
System.exit(1);
}
// 1 clients 4587M virtual 34M real
// 10 clients 6497M virtual 60M real
// 20 clients 6645M virtual 99M real
// 20 clients 6800M virtual 146M real
// 50 clients 6993M virtual 124M real
// 50 clients Out of memory on 8G computers. even with ulimit -v unlimited
PingsClient[] clients = new PingsClient[nb_clients];
for (int i = 0 ; i < nb_clients ; i++) {
clients[i] = new PingsClient(hostname, port, null, "", "", 0);
//Do only the ICMP ping as this is faster
for(int j = 0 ; j < clients[i].subClients_pool.length ; j++){
PingsClient c = clients[i];
if (null_prober)
c.subClients_pool[j].prober = new NullProber();
if (icmp_prober)
c.subClients_pool[j].prober = new IcmpPinger(c.m_client_info);
}
clients[i].setNickname("yoda");
clients[i].run();
}
if (false)
for (int idx_client = 0 ; idx_client < nb_clients ; idx_client++) {
PingsClient client = clients[idx_client];
subClient[] copy = client.getSubClientsPoolCopy();
for (int i = 0 ; i < copy.length ; i++ ) {
copy[i].addObserver(new Observer() {
public void update(Observable o, Object arg) {
subClient client = (subClient)o;
InetAddress current_ping_dest = client.getCurrentPingDest();
if (current_ping_dest != null)
System.out.printf("Current ping dest: %s\n",
current_ping_dest.toString());
GeoipInfo dest_geoip_info = client.getCurrentDestGeoip();
if (dest_geoip_info != null) {
System.out.printf("Long: %f; lat: %f; city: %s; country: %s\n",
dest_geoip_info.longitude,
dest_geoip_info.latitude,
dest_geoip_info.city,
dest_geoip_info.country);
}
}
});
}
}
}
}
|
package org.intermine.api.mines;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Represents an instance of an InterMine. Contains generic data structures to populate with
* queryable values.
*
* @author Julie Sullivan
*/
public class Mine
{
// private static final Logger LOG = Logger.getLogger(Mine.class);
protected String name = null;
protected String url = null;
protected String logo = null;
protected String bgcolor, frontcolor;
protected Set<String> defaultValues = new HashSet<String>();
protected String releaseVersion = null;
// holds a set of values available to query for this mine
private Set<String> mineValues;
// holds a map of values available to query for this mine, eg. dept --> employee,gene --> ortho
private Map<String, Set<String>> mineMap;
/**
* Constructor
*
* @param name name of mine, eg FlyMine
*/
public Mine(String name) {
this.name = name;
}
/**
* @return the name of the mine
*/
public String getName() {
return name;
}
/**
* @return the url to the mine
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the logo
*/
public String getLogo() {
return logo;
}
/**
* @param logo the logo to set
*/
public void setLogo(String logo) {
this.logo = logo;
}
/**
* @return bgcolor
*/
public String getBgcolor() {
return bgcolor;
}
/**
* @param bgcolor background color
*/
public void setBgcolor(String bgcolor) {
this.bgcolor = bgcolor;
}
/**
* @return frontcolor
*/
public String getFrontcolor() {
return frontcolor;
}
/**
* @param frontcolor front color
*/
public void setFrontcolor(String frontcolor) {
this.frontcolor = frontcolor;
}
/**
* @return the mineValues
*/
public Set<String> getMineValues() {
return mineValues;
}
/**
* @param mineValues the mineValues to set
*/
public void setMineValues(Set<String> mineValues) {
this.mineValues = mineValues;
}
/**
* @return true if this mine has queryable values
*/
public boolean hasValues() {
return mineValues != null && !mineValues.isEmpty();
}
/**
* @return the mineMap
*/
public Map<String, Set<String>> getMineMap() {
return mineMap;
}
/**
* @param mineMap the mineMap to set
*/
public void setMineMap(Map<String, Set<String>> mineMap) {
this.mineMap = mineMap;
}
/**
* @return the releaseVersion
*/
public String getReleaseVersion() {
return releaseVersion;
}
/**
* @param releaseVersion the releaseVersion to set
*/
public void setReleaseVersion(String releaseVersion) {
this.releaseVersion = releaseVersion;
}
/**
* @return the defaultValue
*/
public Set<String> getDefaultValues() {
return defaultValues;
}
/**
* @return the defaultValue
*/
public String getDefaultValue() {
if (defaultValues.isEmpty()) {
return null;
}
Object[] values = defaultValues.toArray();
return values[0].toString();
}
/**
* @param defaultValue the defaultValues to set, comma delim
*/
public void setDefaultValues(String defaultValue) {
String[] bits = defaultValue.split(",");
for (String bit : bits) {
defaultValues.add(bit);
}
}
/**
* Search through the map held by this mine for matching values. eg. look in the map for
* entries with values equal to the organism name provided.
*
* For a Dmel list, finds in this mine:
*
* D. rerio --> Dmel
*
* @param remoteKeys keys from other mine
* @param values values to query for
* @return list of keys for values provided
*/
public Set<String> getMatchingMapKeys(Set<String> remoteKeys, List<String> values) {
if (mineMap != null && !mineMap.isEmpty()) {
Set<String> results = new HashSet<String>();
for (Map.Entry<String, Set<String>> entry : mineMap.entrySet()) {
String key = entry.getKey();
Set<String> currentMineValues = entry.getValue();
for (String otherMineValue : values) {
if (currentMineValues.contains(otherMineValue)) {
if (remoteKeys == null || remoteKeys.contains(key)) {
results.add(key);
}
}
}
}
return results;
}
return Collections.emptySet();
}
/**
* finds Dmel (organism in list) --> D. rerio (organism for remote mine)
*
* @param remoteKeys keys for remote mine
* @param values values to test for
* @return list of values (organisms)
*/
public Set<String> getMatchingMapValues(Set<String> remoteKeys, List<String> values) {
if (mineMap != null && !mineMap.isEmpty()) {
Set<String> results = new HashSet<String>();
for (String value : values) {
Set<String> localValues = mineMap.get(value);
if (localValues != null) {
for (String key : remoteKeys) {
if (localValues.contains(key)) {
results.add(key);
}
}
}
}
return results;
}
return Collections.emptySet();
}
}
|
package org.intermine.web;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.upload.FormFile;
/**
* An action that makes a bag from text.
*
* @author Kim Rutherford
*/
public class BuildBagAction extends LookupDispatchAction
{
/**
* Action for creating a bag of Strings from a text field.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
*
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward makeStringBag(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
BuildBagForm buildBagForm = (BuildBagForm) form;
InterMineBag bag = new InterMineBag();
String trimmedText = buildBagForm.getText().trim();
if (trimmedText.length() == 0) {
FormFile formFile = buildBagForm.getFormFile();
if (formFile.getFileName() == null || formFile.getFileName().length() == 0) {
ActionMessages actionMessages = new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionError("bagBuild.noBagToSave"));
saveMessages(request, actionMessages);
return mapping.findForward("buildBag");
} else {
BufferedReader reader =
new BufferedReader(new InputStreamReader(formFile.getInputStream()));
StringBuffer buffer = new StringBuffer();
String thisLine;
while ((thisLine = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(thisLine, " \t");
while (st.hasMoreTokens()) {
String token = st.nextToken();
bag.add(token);
}
}
}
} else {
StringTokenizer st = new StringTokenizer(trimmedText, " \t");
while (st.hasMoreTokens()) {
String token = st.nextToken();
bag.add(token);
}
}
String newBagName = buildBagForm.getBagName();
profile.saveBag(newBagName, bag);
ActionMessages actionMessages = new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionError("bagBuild.saved", newBagName));
saveMessages(request, actionMessages);
request.setAttribute("bagName", newBagName);
return mapping.findForward("buildBag");
}
/**
* Distributes the actions to the necessary methods, by providing a Map from action to
* the name of a method.
*
* @return a Map
*/
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("bagBuild.makeStringBag", "makeStringBag");
return map;
}
}
|
package com.intellij.psi.util;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.JavaVersionService;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.infos.ClassCandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.infos.MethodCandidateInfo.ApplicabilityLevel;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.meta.PsiMetaOwner;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.EmptyIterable;
import com.intellij.util.containers.JBIterable;
import gnu.trove.THashSet;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public final class PsiUtil extends PsiUtilCore {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.util.PsiUtil");
public static final int ACCESS_LEVEL_PUBLIC = 4;
public static final int ACCESS_LEVEL_PROTECTED = 3;
public static final int ACCESS_LEVEL_PACKAGE_LOCAL = 2;
public static final int ACCESS_LEVEL_PRIVATE = 1;
public static final Key<Boolean> VALID_VOID_TYPE_IN_CODE_FRAGMENT = Key.create("VALID_VOID_TYPE_IN_CODE_FRAGMENT");
private static final Set<String> IGNORED_NAMES = ContainerUtil.newTroveSet(
"ignore", "ignore1", "ignore2", "ignore3", "ignore4", "ignore5",
"ignored", "ignored1", "ignored2", "ignored3", "ignored4", "ignored5");
private PsiUtil() {}
public static boolean isOnAssignmentLeftHand(@NotNull PsiExpression expr) {
PsiElement parent = PsiTreeUtil.skipParentsOfType(expr, PsiParenthesizedExpression.class);
return parent instanceof PsiAssignmentExpression &&
PsiTreeUtil.isAncestor(((PsiAssignmentExpression)parent).getLExpression(), expr, false);
}
public static boolean isAccessibleFromPackage(@NotNull PsiModifierListOwner element, @NotNull PsiPackage aPackage) {
if (element.hasModifierProperty(PsiModifier.PUBLIC)) return true;
return !element.hasModifierProperty(PsiModifier.PRIVATE) &&
JavaPsiFacade.getInstance(element.getProject()).isInPackage(element, aPackage);
}
public static boolean isAccessedForWriting(@NotNull PsiExpression expr) {
if (isOnAssignmentLeftHand(expr)) return true;
PsiElement parent = skipParenthesizedExprUp(expr.getParent());
return isIncrementDecrementOperation(parent);
}
public static boolean isAccessedForReading(@NotNull PsiExpression expr) {
PsiElement parent = PsiTreeUtil.skipParentsOfType(expr, PsiParenthesizedExpression.class);
return !(parent instanceof PsiAssignmentExpression) ||
!PsiTreeUtil.isAncestor(((PsiAssignmentExpression)parent).getLExpression(), expr, false) ||
((PsiAssignmentExpression)parent).getOperationTokenType() != JavaTokenType.EQ;
}
public static boolean isAccessible(@NotNull PsiMember member, @NotNull PsiElement place, @Nullable PsiClass accessObjectClass) {
return isAccessible(place.getProject(), member, place, accessObjectClass);
}
/**
* Checks that a *resolved* to {@code member} reference at {@code place} is accessible: it's visible by visibility rules as well as
* by module (java) rules.
*
* <p>NOTE:</p>
* If there is no module (IDEA's) dependency from module with {@code place} on a module with {@code member},
* then reference won't be resolved and this method will return {@code true}.
*
* Please use {@link #isMemberAccessibleAt(PsiMember, PsiElement)} to catch these cases as well
*/
public static boolean isAccessible(@NotNull Project project, @NotNull PsiMember member,
@NotNull PsiElement place, @Nullable PsiClass accessObjectClass) {
return JavaPsiFacade.getInstance(project).getResolveHelper().isAccessible(member, place, accessObjectClass);
}
/**
* Checks that reference on {@code member} inserted at {@code place} will be resolved and accessible
*/
public static boolean isMemberAccessibleAt(@NotNull PsiMember member, @NotNull PsiElement place) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(member);
if (virtualFile != null && !place.getResolveScope().contains(virtualFile)) {
return false;
}
return isAccessible(member, place, null);
}
@NotNull
public static JavaResolveResult getAccessObjectClass(@NotNull PsiExpression expression) {
if (expression instanceof PsiSuperExpression) return JavaResolveResult.EMPTY;
PsiType type = expression.getType();
final JavaResolveResult accessObject = getAccessObjectClass(type, expression.getProject());
if (accessObject != null) return accessObject;
if (type == null && expression instanceof PsiReferenceExpression) {
JavaResolveResult resolveResult = ((PsiReferenceExpression)expression).advancedResolve(false);
if (resolveResult.getElement() instanceof PsiClass) {
return resolveResult;
}
}
return JavaResolveResult.EMPTY;
}
private static JavaResolveResult getAccessObjectClass(PsiType type, Project project) {
if (type instanceof PsiClassType) {
return ((PsiClassType)type).resolveGenerics();
}
if (type instanceof PsiDisjunctionType) {
final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound();
if (lub instanceof PsiClassType) {
return ((PsiClassType)lub).resolveGenerics();
}
}
if (type instanceof PsiCapturedWildcardType) {
final PsiType upperBound = ((PsiCapturedWildcardType)type).getUpperBound();
if (upperBound instanceof PsiClassType) {
final PsiClass resolved = ((PsiClassType)upperBound).resolve();
final PsiFile containingFile = resolved != null ? resolved.getContainingFile() : null;
final String packageName = containingFile instanceof PsiClassOwner ? ((PsiClassOwner)containingFile).getPackageName() : null;
String classText = StringUtil.isEmptyOrSpaces(packageName) ? "" : "package " + packageName + ";\n ";
classText += "class I<T extends " + upperBound.getCanonicalText() + "> {}";
final PsiJavaFile file =
(PsiJavaFile)PsiFileFactory.getInstance(project).createFileFromText("inference_dummy.java", JavaLanguage.INSTANCE, classText);
final PsiTypeParameter freshParameter = file.getClasses()[0].getTypeParameters()[0];
return new ClassCandidateInfo(freshParameter, PsiSubstitutor.EMPTY);
}
}
if (type instanceof PsiArrayType) {
return getAccessObjectClass(((PsiArrayType)type).getComponentType(), project);
}
return null;
}
public static boolean isConstantExpression(@Nullable PsiExpression expression) {
return expression != null && JavaPsiFacade.getInstance(expression.getProject()).isConstantExpression(expression);
}
// todo: move to PsiThrowsList?
public static void addException(@NotNull PsiMethod method, @NotNull @NonNls String exceptionFQName) throws IncorrectOperationException {
PsiClass exceptionClass = JavaPsiFacade.getInstance(method.getProject()).findClass(exceptionFQName, method.getResolveScope());
addException(method, exceptionClass, exceptionFQName);
}
public static void addException(@NotNull PsiMethod method, @NotNull PsiClass exceptionClass) throws IncorrectOperationException {
addException(method, exceptionClass, exceptionClass.getQualifiedName());
}
private static void addException(@NotNull PsiMethod method, @Nullable PsiClass exceptionClass, @Nullable String exceptionName) throws IncorrectOperationException {
assert exceptionClass != null || exceptionName != null : "One of exceptionName, exceptionClass must be not null";
PsiReferenceList throwsList = method.getThrowsList();
PsiJavaCodeReferenceElement[] refs = throwsList.getReferenceElements();
boolean replaced = false;
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(exceptionClass)) return;
PsiClass aClass = (PsiClass)ref.resolve();
if (exceptionClass == null || aClass == null) {
continue;
}
if (aClass.isInheritor(exceptionClass, true)) {
if (replaced) {
ref.delete();
}
else {
PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
PsiJavaCodeReferenceElement ref1;
if (exceptionName != null) {
ref1 = factory.createReferenceElementByFQClassName(exceptionName, method.getResolveScope());
}
else {
PsiClassType type = factory.createType(exceptionClass);
ref1 = factory.createReferenceElementByType(type);
}
ref.replace(ref1);
replaced = true;
}
}
else if (exceptionClass.isInheritor(aClass, true)) {
return;
}
}
if (replaced) return;
PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
PsiJavaCodeReferenceElement ref;
if (exceptionName != null) {
ref = factory.createReferenceElementByFQClassName(exceptionName, method.getResolveScope());
}
else {
PsiClass superClass = exceptionClass.getSuperClass();
while (superClass != null && isLocalOrAnonymousClass(superClass)) {
superClass = superClass.getSuperClass();
}
PsiClassType type = factory.createType(superClass != null ? superClass : exceptionClass);
ref = factory.createReferenceElementByType(type);
}
throwsList.add(ref);
}
// todo: move to PsiThrowsList?
public static void removeException(@NotNull PsiMethod method, @NonNls String exceptionClass) throws IncorrectOperationException {
PsiJavaCodeReferenceElement[] refs = method.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.getCanonicalText().equals(exceptionClass)) {
ref.delete();
}
}
}
public static boolean isVariableNameUnique(@NotNull String name, @NotNull PsiElement place) {
PsiResolveHelper helper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
return helper.resolveAccessibleReferencedVariable(name, place) == null;
}
/**
* @return enclosing outermost (method or class initializer) body but not higher than scope
*/
@Nullable
public static PsiElement getTopLevelEnclosingCodeBlock(@Nullable PsiElement element, PsiElement scope) {
PsiElement blockSoFar = null;
while (element != null) {
// variable can be defined in for loop initializer
PsiElement parent = element.getParent();
if (!(parent instanceof PsiExpression) || parent instanceof PsiLambdaExpression) {
if (element instanceof PsiCodeBlock || element instanceof PsiForStatement || element instanceof PsiForeachStatement) {
blockSoFar = element;
}
if (parent instanceof PsiMethod
&& parent.getParent() instanceof PsiClass
&& !isLocalOrAnonymousClass((PsiClass)parent.getParent()))
break;
if (parent instanceof PsiClassInitializer && !(parent.getParent() instanceof PsiAnonymousClass)) break;
if (parent instanceof PsiField && ((PsiField) parent).getInitializer() == element) {
blockSoFar = element;
}
if (parent instanceof PsiClassLevelDeclarationStatement) {
parent = parent.getParent();
}
if (element instanceof PsiClass && !isLocalOrAnonymousClass((PsiClass)element)) {
break;
}
if (element instanceof PsiFile && PsiUtilCore.getTemplateLanguageFile(element) != null) {
return element;
}
}
if (element == scope) break;
element = parent;
}
return blockSoFar;
}
public static boolean isLocalOrAnonymousClass(@NotNull PsiClass psiClass) {
return psiClass instanceof PsiAnonymousClass || isLocalClass(psiClass);
}
public static boolean isLocalClass(@NotNull PsiClass psiClass) {
PsiElement parent = psiClass.getParent();
if (parent instanceof PsiDeclarationStatement && parent.getParent() instanceof PsiCodeBlock) {
return true;
}
if (parent instanceof PsiClass) {
return isLocalOrAnonymousClass((PsiClass)parent);
}
return false;
}
public static boolean isAbstractClass(@NotNull PsiClass clazz) {
PsiModifierList modifierList = clazz.getModifierList();
return modifierList != null && modifierList.hasModifierProperty(PsiModifier.ABSTRACT);
}
/**
* @return topmost code block where variable makes sense
*/
@Nullable
public static PsiElement getVariableCodeBlock(@NotNull PsiVariable variable, @Nullable PsiElement context) {
PsiElement codeBlock = null;
if (variable instanceof PsiParameter) {
PsiElement declarationScope = ((PsiParameter)variable).getDeclarationScope();
if (declarationScope instanceof PsiCatchSection) {
codeBlock = ((PsiCatchSection)declarationScope).getCatchBlock();
}
else if (declarationScope instanceof PsiForeachStatement) {
codeBlock = ((PsiForeachStatement)declarationScope).getBody();
}
else if (declarationScope instanceof PsiMethod) {
codeBlock = ((PsiMethod)declarationScope).getBody();
} else if (declarationScope instanceof PsiLambdaExpression) {
codeBlock = ((PsiLambdaExpression)declarationScope).getBody();
}
}
else if (variable instanceof PsiResourceVariable) {
final PsiElement resourceList = variable.getParent();
return resourceList != null ? resourceList.getParent() : null; // use try statement as topmost
}
else if (variable instanceof PsiLocalVariable && variable.getParent() instanceof PsiForStatement) {
return variable.getParent();
}
else if (variable instanceof PsiField && context != null) {
final PsiClass aClass = ((PsiField) variable).getContainingClass();
while (context != null && context.getParent() != aClass) {
context = context.getParent();
if (context instanceof PsiClassLevelDeclarationStatement) return null;
}
return context instanceof PsiMethod ?
((PsiMethod) context).getBody() :
context instanceof PsiClassInitializer ? ((PsiClassInitializer) context).getBody() : null;
}
else {
final PsiElement scope = variable.getParent() == null ? null : variable.getParent().getParent();
codeBlock = getTopLevelEnclosingCodeBlock(variable, scope);
if (codeBlock != null && codeBlock.getParent() instanceof PsiSwitchStatement) codeBlock = codeBlock.getParent().getParent();
}
return codeBlock;
}
@Contract("null -> false")
public static boolean isIncrementDecrementOperation(@Nullable PsiElement element) {
if (element instanceof PsiUnaryExpression) {
final IElementType sign = ((PsiUnaryExpression)element).getOperationTokenType();
return sign == JavaTokenType.PLUSPLUS || sign == JavaTokenType.MINUSMINUS;
}
return false;
}
@MagicConstant(intValues = {ACCESS_LEVEL_PUBLIC, ACCESS_LEVEL_PROTECTED, ACCESS_LEVEL_PACKAGE_LOCAL, ACCESS_LEVEL_PRIVATE})
public @interface AccessLevel {}
@AccessLevel
public static int getAccessLevel(@NotNull PsiModifierList modifierList) {
if (modifierList.hasModifierProperty(PsiModifier.PRIVATE)) {
return ACCESS_LEVEL_PRIVATE;
}
if (modifierList.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
return ACCESS_LEVEL_PACKAGE_LOCAL;
}
if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) {
return ACCESS_LEVEL_PROTECTED;
}
return ACCESS_LEVEL_PUBLIC;
}
@PsiModifier.ModifierConstant
@NotNull
public static String getAccessModifier(@AccessLevel int accessLevel) {
assert accessLevel > 0 && accessLevel <= accessModifiers.length : accessLevel;
@SuppressWarnings("UnnecessaryLocalVariable") @PsiModifier.ModifierConstant
final String modifier = accessModifiers[accessLevel - 1];
return modifier;
}
private static final String[] accessModifiers = {
PsiModifier.PRIVATE, PsiModifier.PACKAGE_LOCAL, PsiModifier.PROTECTED, PsiModifier.PUBLIC
};
/**
* @return true if element specified is statement or expression statement. see JLS 14.5-14.8
*/
public static boolean isStatement(@NotNull PsiElement element) {
PsiElement parent = element.getParent();
if (element instanceof PsiExpressionListStatement) {
// statement list allowed in for() init or update only
if (!(parent instanceof PsiForStatement)) return false;
final PsiForStatement forStatement = (PsiForStatement)parent;
if (!(element == forStatement.getInitialization() || element == forStatement.getUpdate())) return false;
final PsiExpressionList expressionList = ((PsiExpressionListStatement) element).getExpressionList();
final PsiExpression[] expressions = expressionList.getExpressions();
for (PsiExpression expression : expressions) {
if (!isStatement(expression)) return false;
}
return true;
}
if (element instanceof PsiExpressionStatement) {
return isStatement(((PsiExpressionStatement) element).getExpression());
}
if (element instanceof PsiDeclarationStatement) {
if (parent instanceof PsiCodeBlock) return true;
if (parent instanceof PsiCodeFragment) return true;
if (!(parent instanceof PsiForStatement) || ((PsiForStatement)parent).getBody() == element) {
return false;
}
}
if (element instanceof PsiStatement) return true;
if (element instanceof PsiAssignmentExpression) return true;
if (isIncrementDecrementOperation(element)) return true;
if (element instanceof PsiMethodCallExpression) return true;
if (element instanceof PsiNewExpression) {
return !(((PsiNewExpression) element).getType() instanceof PsiArrayType);
}
return element instanceof PsiCodeBlock;
}
@Nullable
public static PsiElement getEnclosingStatement(PsiElement element) {
while (element != null) {
if (element.getParent() instanceof PsiCodeBlock) return element;
element = element.getParent();
}
return null;
}
@Nullable
public static PsiElement getElementInclusiveRange(@NotNull PsiElement scope, @NotNull TextRange range) {
PsiElement psiElement = scope.findElementAt(range.getStartOffset());
while (psiElement != null && !psiElement.getTextRange().contains(range)) {
if (psiElement == scope) return null;
psiElement = psiElement.getParent();
}
return psiElement;
}
@Nullable
public static PsiClass resolveClassInType(@Nullable PsiType type) {
if (type instanceof PsiClassType) {
return ((PsiClassType) type).resolve();
}
if (type instanceof PsiArrayType) {
return resolveClassInType(((PsiArrayType) type).getComponentType());
}
if (type instanceof PsiDisjunctionType) {
final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound();
if (lub instanceof PsiClassType) {
return ((PsiClassType)lub).resolve();
}
}
return null;
}
@Nullable
public static PsiClass resolveClassInClassTypeOnly(@Nullable PsiType type) {
return type instanceof PsiClassType ? ((PsiClassType)type).resolve() : null;
}
@NotNull
public static PsiClassType.ClassResolveResult resolveGenericsClassInType(@Nullable PsiType type) {
if (type instanceof PsiClassType) {
final PsiClassType classType = (PsiClassType) type;
return classType.resolveGenerics();
}
if (type instanceof PsiArrayType) {
return resolveGenericsClassInType(((PsiArrayType) type).getComponentType());
}
if (type instanceof PsiDisjunctionType) {
final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound();
if (lub instanceof PsiClassType) {
return ((PsiClassType)lub).resolveGenerics();
}
}
return PsiClassType.ClassResolveResult.EMPTY;
}
@NotNull
public static PsiType convertAnonymousToBaseType(@NotNull PsiType type) {
PsiClass psiClass = resolveClassInType(type);
if (psiClass instanceof PsiAnonymousClass) {
type = PsiTypesUtil.createArrayType(((PsiAnonymousClass) psiClass).getBaseClassType(), type.getArrayDimensions());
}
return type;
}
public static boolean isApplicable(@NotNull PsiMethod method, @NotNull PsiSubstitutor substitutorForMethod, @NotNull PsiExpressionList argList) {
return getApplicabilityLevel(method, substitutorForMethod, argList) != ApplicabilityLevel.NOT_APPLICABLE;
}
public static boolean isApplicable(@NotNull PsiMethod method, @NotNull PsiSubstitutor substitutorForMethod, @NotNull PsiExpression[] argList) {
final PsiType[] types = ContainerUtil.map2Array(argList, PsiType.class, PsiExpression.EXPRESSION_TO_TYPE);
return getApplicabilityLevel(method, substitutorForMethod, types, getLanguageLevel(method)) != ApplicabilityLevel.NOT_APPLICABLE;
}
@MethodCandidateInfo.ApplicabilityLevelConstant
public static int getApplicabilityLevel(@NotNull PsiMethod method, @NotNull PsiSubstitutor substitutorForMethod, @NotNull PsiExpressionList argList) {
return getApplicabilityLevel(method, substitutorForMethod, argList.getExpressionTypes(), getLanguageLevel(argList));
}
@MethodCandidateInfo.ApplicabilityLevelConstant
public static int getApplicabilityLevel(@NotNull final PsiMethod method,
@NotNull final PsiSubstitutor substitutorForMethod,
@NotNull final PsiType[] args,
@NotNull final LanguageLevel languageLevel) {
return getApplicabilityLevel(method, substitutorForMethod, args, languageLevel, true, true);
}
@FunctionalInterface
public interface ApplicabilityChecker {
ApplicabilityChecker ASSIGNABILITY_CHECKER =
(left, right, allowUncheckedConversion, argId) -> TypeConversionUtil.isAssignable(left, right, allowUncheckedConversion);
boolean isApplicable(PsiType left, PsiType right, boolean allowUncheckedConversion, int argId);
}
@MethodCandidateInfo.ApplicabilityLevelConstant
public static int getApplicabilityLevel(@NotNull final PsiMethod method,
@NotNull final PsiSubstitutor substitutorForMethod,
@NotNull final PsiType[] args,
@NotNull final LanguageLevel languageLevel,
final boolean allowUncheckedConversion,
final boolean checkVarargs) {
return getApplicabilityLevel(method, substitutorForMethod, args, languageLevel,
allowUncheckedConversion, checkVarargs, ApplicabilityChecker.ASSIGNABILITY_CHECKER);
}
@MethodCandidateInfo.ApplicabilityLevelConstant
public static int getApplicabilityLevel(@NotNull final PsiMethod method,
@NotNull final PsiSubstitutor substitutorForMethod,
@NotNull final PsiType[] args,
@NotNull final LanguageLevel languageLevel,
final boolean allowUncheckedConversion,
final boolean checkVarargs,
@NotNull final ApplicabilityChecker function) {
final PsiParameter[] parms = method.getParameterList().getParameters();
if (args.length < parms.length - 1) return ApplicabilityLevel.NOT_APPLICABLE;
final PsiClass containingClass = method.getContainingClass();
final boolean isRaw = containingClass != null && isRawSubstitutor(method, substitutorForMethod) && isRawSubstitutor(containingClass, substitutorForMethod);
if (!areFirstArgumentsApplicable(args, parms, languageLevel, substitutorForMethod, isRaw, allowUncheckedConversion, function)) return ApplicabilityLevel.NOT_APPLICABLE;
if (args.length == parms.length) {
if (parms.length == 0) return ApplicabilityLevel.FIXED_ARITY;
PsiType parmType = getParameterType(parms[parms.length - 1], languageLevel, substitutorForMethod);
PsiType argType = args[args.length - 1];
if (argType == null) return ApplicabilityLevel.NOT_APPLICABLE;
if (function.isApplicable(parmType, argType, allowUncheckedConversion, parms.length - 1)) return ApplicabilityLevel.FIXED_ARITY;
if (isRaw) {
final PsiType erasedParamType = TypeConversionUtil.erasure(parmType);
if (erasedParamType != null && function.isApplicable(erasedParamType, argType, allowUncheckedConversion, parms.length - 1)) {
return ApplicabilityLevel.FIXED_ARITY;
}
}
}
if (checkVarargs && method.isVarArgs() && languageLevel.compareTo(LanguageLevel.JDK_1_5) >= 0) {
if (args.length < parms.length) return ApplicabilityLevel.VARARGS;
PsiParameter lastParameter = parms.length == 0 ? null : parms[parms.length - 1];
if (lastParameter == null || !lastParameter.isVarArgs()) return ApplicabilityLevel.NOT_APPLICABLE;
PsiType lastParmType = getParameterType(lastParameter, languageLevel, substitutorForMethod);
if (!(lastParmType instanceof PsiArrayType)) return ApplicabilityLevel.NOT_APPLICABLE;
lastParmType = ((PsiArrayType)lastParmType).getComponentType();
if (lastParmType instanceof PsiCapturedWildcardType &&
!JavaVersionService.getInstance().isAtLeast(((PsiCapturedWildcardType)lastParmType).getContext(), JavaSdkVersion.JDK_1_8)) {
lastParmType = ((PsiCapturedWildcardType)lastParmType).getWildcard();
}
if (lastParmType instanceof PsiClassType) {
lastParmType = ((PsiClassType)lastParmType).setLanguageLevel(languageLevel);
}
for (int i = parms.length - 1; i < args.length; i++) {
PsiType argType = args[i];
if (argType == null || !function.isApplicable(lastParmType, argType, allowUncheckedConversion, i)) {
return ApplicabilityLevel.NOT_APPLICABLE;
}
}
return ApplicabilityLevel.VARARGS;
}
return ApplicabilityLevel.NOT_APPLICABLE;
}
private static boolean areFirstArgumentsApplicable(@NotNull PsiType[] args,
@NotNull final PsiParameter[] parms,
@NotNull LanguageLevel languageLevel,
@NotNull final PsiSubstitutor substitutorForMethod,
boolean isRaw,
boolean allowUncheckedConversion, ApplicabilityChecker function) {
for (int i = 0; i < parms.length - 1; i++) {
final PsiType type = args[i];
if (type == null) return false;
final PsiParameter parameter = parms[i];
final PsiType substitutedParmType = getParameterType(parameter, languageLevel, substitutorForMethod);
if (isRaw) {
final PsiType substErasure = TypeConversionUtil.erasure(substitutedParmType);
if (substErasure != null && !function.isApplicable(substErasure, type, allowUncheckedConversion, i)) {
return false;
}
}
else if (!function.isApplicable(substitutedParmType, type, allowUncheckedConversion, i)) {
return false;
}
}
return true;
}
private static PsiType getParameterType(@NotNull final PsiParameter parameter,
@NotNull LanguageLevel languageLevel,
@NotNull final PsiSubstitutor substitutor) {
PsiType parmType = parameter.getType();
if (parmType instanceof PsiClassType) {
parmType = ((PsiClassType)parmType).setLanguageLevel(languageLevel);
}
return substitutor.substitute(parmType);
}
/**
* Compares types with respect to type parameter bounds: e.g. for
* {@code class Foo<T extends Number>{}} types Foo<?> and Foo<? extends Number>
* would be equivalent
*/
public static boolean equalOnEquivalentClasses(PsiClassType thisClassType,
@NotNull PsiClass aClass,
PsiClassType otherClassType,
@NotNull PsiClass bClass) {
final PsiClassType capture1 = !PsiCapturedWildcardType.isCapture()
? thisClassType : (PsiClassType)captureToplevelWildcards(thisClassType, aClass);
final PsiClassType capture2 = !PsiCapturedWildcardType.isCapture()
? otherClassType : (PsiClassType)captureToplevelWildcards(otherClassType, bClass);
final PsiClassType.ClassResolveResult result1 = capture1.resolveGenerics();
final PsiClassType.ClassResolveResult result2 = capture2.resolveGenerics();
return equalOnEquivalentClasses(result1.getSubstitutor(), aClass, result2.getSubstitutor(), bClass);
}
private static boolean equalOnEquivalentClasses(@NotNull PsiSubstitutor s1,
@NotNull PsiClass aClass,
@NotNull PsiSubstitutor s2,
@NotNull PsiClass bClass) {
// assume generic class equals to non-generic
if (aClass.hasTypeParameters() != bClass.hasTypeParameters()) return true;
final PsiTypeParameter[] typeParameters1 = aClass.getTypeParameters();
final PsiTypeParameter[] typeParameters2 = bClass.getTypeParameters();
if (typeParameters1.length != typeParameters2.length) return false;
for (int i = 0; i < typeParameters1.length; i++) {
final PsiType substituted2 = s2.substitute(typeParameters2[i]);
final PsiType substituted1 = s1.substitute(typeParameters1[i]);
if (!Comparing.equal(substituted1, substituted2)) return false;
}
if (aClass.hasModifierProperty(PsiModifier.STATIC)) return true;
final PsiClass containingClass1 = aClass.getContainingClass();
final PsiClass containingClass2 = bClass.getContainingClass();
if (containingClass1 != null && containingClass2 != null) {
return equalOnEquivalentClasses(s1, containingClass1, s2, containingClass2);
}
return containingClass1 == null && containingClass2 == null;
}
/** @deprecated use more generic {@link #isCompileTimeConstant(PsiVariable)} instead */
public static boolean isCompileTimeConstant(@NotNull final PsiField field) {
return isCompileTimeConstant((PsiVariable)field);
}
/**
* JLS 15.28
*/
public static boolean isCompileTimeConstant(@NotNull final PsiVariable field) {
return field.hasModifierProperty(PsiModifier.FINAL)
&& (TypeConversionUtil.isPrimitiveAndNotNull(field.getType()) || field.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING))
&& field.hasInitializer()
&& isConstantExpression(field.getInitializer());
}
public static boolean allMethodsHaveSameSignature(@NotNull PsiMethod[] methods) {
if (methods.length == 0) return true;
final MethodSignature methodSignature = methods[0].getSignature(PsiSubstitutor.EMPTY);
for (int i = 1; i < methods.length; i++) {
PsiMethod method = methods[i];
if (!methodSignature.equals(method.getSignature(PsiSubstitutor.EMPTY))) return false;
}
return true;
}
@Nullable
public static PsiExpression deparenthesizeExpression(PsiExpression expression) {
while (true) {
if (expression instanceof PsiParenthesizedExpression) {
expression = ((PsiParenthesizedExpression)expression).getExpression();
continue;
}
if (expression instanceof PsiTypeCastExpression) {
expression = ((PsiTypeCastExpression)expression).getOperand();
continue;
}
return expression;
}
}
/**
* Checks whether given class is inner (as opposed to nested)
*
*/
public static boolean isInnerClass(@NotNull PsiClass aClass) {
return !aClass.hasModifierProperty(PsiModifier.STATIC) && aClass.getContainingClass() != null;
}
@Nullable
public static PsiElement findModifierInList(@NotNull final PsiModifierList modifierList, @NonNls String modifier) {
final PsiElement[] children = modifierList.getChildren();
for (PsiElement child : children) {
if (child.getText().equals(modifier)) return child;
}
return null;
}
@Nullable
public static PsiClass getTopLevelClass(@NotNull PsiElement element) {
PsiClass topClass = JBIterable.generate(element, PsiElement::getParent).takeWhile(e -> !(e instanceof PsiFile)).filter(PsiClass.class).last();
return topClass instanceof PsiTypeParameter ? null : topClass;
}
@Nullable
public static String getPackageName(@NotNull PsiClass aClass) {
PsiClass topClass = getTopLevelClass(aClass);
if (topClass != null) {
String fqName = topClass.getQualifiedName();
if (fqName != null) {
return StringUtil.getPackageName(fqName);
}
}
PsiFile file = aClass.getContainingFile();
if (file instanceof PsiClassOwner) {
return ((PsiClassOwner)file).getPackageName();
}
return null;
}
/**
* @param place place to start traversal
* @param aClass level to stop traversal
* @return element with static modifier enclosing place and enclosed by aClass (if not null)
*/
@Nullable
public static PsiModifierListOwner getEnclosingStaticElement(@NotNull PsiElement place, @Nullable PsiClass aClass) {
LOG.assertTrue(aClass == null || !place.isPhysical() || PsiTreeUtil.isContextAncestor(aClass, place, false));
PsiElement parent = place;
while (parent != aClass) {
if (parent instanceof PsiFile) break;
if (parent instanceof PsiModifierListOwner && ((PsiModifierListOwner)parent).hasModifierProperty(PsiModifier.STATIC)) {
return (PsiModifierListOwner)parent;
}
parent = parent.getParent();
}
return null;
}
@Nullable
public static PsiType getTypeByPsiElement(@NotNull final PsiElement element) {
if (element instanceof PsiVariable) {
return ((PsiVariable)element).getType();
}
if (element instanceof PsiMethod) return ((PsiMethod)element).getReturnType();
return null;
}
/**
* Applies capture conversion to the type in context
*/
@NotNull
public static PsiType captureToplevelWildcards(@NotNull final PsiType type, @NotNull final PsiElement context) {
if (type instanceof PsiClassType) {
final PsiClassType.ClassResolveResult result = ((PsiClassType)type).resolveGenerics();
final PsiClass aClass = result.getElement();
if (aClass != null) {
final PsiSubstitutor substitutor = result.getSubstitutor();
PsiSubstitutor captureSubstitutor = substitutor;
for (PsiTypeParameter typeParameter : typeParametersIterable(aClass)) {
final PsiType substituted = substitutor.substitute(typeParameter);
if (substituted instanceof PsiWildcardType) {
captureSubstitutor = captureSubstitutor.put(typeParameter, PsiCapturedWildcardType.create((PsiWildcardType)substituted, context, typeParameter));
}
}
if (captureSubstitutor != substitutor) {
Map<PsiTypeParameter, PsiType> substitutionMap = null;
for (PsiTypeParameter typeParameter : typeParametersIterable(aClass)) {
final PsiType substituted = substitutor.substitute(typeParameter);
if (substituted instanceof PsiWildcardType) {
if (substitutionMap == null) substitutionMap = new HashMap<>(substitutor.getSubstitutionMap());
final PsiCapturedWildcardType capturedWildcard = (PsiCapturedWildcardType)captureSubstitutor.substitute(typeParameter);
LOG.assertTrue(capturedWildcard != null);
final PsiType upperBound = PsiCapturedWildcardType.captureUpperBound(typeParameter, (PsiWildcardType)substituted, captureSubstitutor);
if (upperBound != null) {
capturedWildcard.setUpperBound(upperBound);
}
substitutionMap.put(typeParameter, capturedWildcard);
}
}
if (substitutionMap != null) {
final PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
final PsiSubstitutor newSubstitutor = factory.createSubstitutor(substitutionMap);
return factory.createType(aClass, newSubstitutor);
}
}
}
}
return type;
}
/**
* Opens top level captured wildcards and remap them according to the context.
* The only valid purpose: allow to speculate on non-physical expressions about types, e.g. to detect redundant casts with 'wildcards'
*/
static PsiType recaptureWildcards(PsiType type, PsiElement context) {
if (type instanceof PsiClassType) {
final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)type).resolveGenerics();
final PsiClass aClass = resolveResult.getElement();
if (aClass != null) {
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
PsiSubstitutor resultSubstitution = null;
for (PsiTypeParameter parameter : substitutor.getSubstitutionMap().keySet()) {
final PsiType substitute = substitutor.substitute(parameter);
if (substitute instanceof PsiCapturedWildcardType) {
if (resultSubstitution == null) resultSubstitution = substitutor;
resultSubstitution = resultSubstitution.put(parameter, ((PsiCapturedWildcardType)substitute).getWildcard());
}
}
if (resultSubstitution != null) {
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
return captureToplevelWildcards(factory.createType(aClass, resultSubstitution), context);
}
}
}
else if (type instanceof PsiArrayType) {
return recaptureWildcards(((PsiArrayType)type).getComponentType(), context).createArrayType();
}
return type;
}
public static boolean isInsideJavadocComment(PsiElement element) {
return PsiTreeUtil.getParentOfType(element, PsiDocComment.class, true) != null;
}
@NotNull
public static List<PsiTypeElement> getParameterTypeElements(@NotNull PsiParameter parameter) {
PsiTypeElement typeElement = parameter.getTypeElement();
return typeElement != null && typeElement.getType() instanceof PsiDisjunctionType
? PsiTreeUtil.getChildrenOfTypeAsList(typeElement, PsiTypeElement.class)
: Collections.singletonList(typeElement);
}
public static void checkIsIdentifier(@NotNull PsiManager manager, String text) throws IncorrectOperationException{
if (!PsiNameHelper.getInstance(manager.getProject()).isIdentifier(text)){
throw new IncorrectOperationException(PsiBundle.message("0.is.not.an.identifier", text) );
}
}
@Nullable
public static VirtualFile getJarFile(@NotNull PsiElement candidate) {
VirtualFile file = candidate.getContainingFile().getVirtualFile();
if (file != null && file.getFileSystem().getProtocol().equals("jar")) {
return VfsUtilCore.getVirtualFileForJar(file);
}
return file;
}
public static boolean isAnnotationMethod(PsiElement element) {
if (!(element instanceof PsiAnnotationMethod)) return false;
PsiClass psiClass = ((PsiAnnotationMethod)element).getContainingClass();
return psiClass != null && psiClass.isAnnotationType();
}
@PsiModifier.ModifierConstant
public static String getMaximumModifierForMember(final PsiClass aClass, boolean allowPublicAbstract) {
String modifier = PsiModifier.PUBLIC;
if (!allowPublicAbstract && aClass.hasModifierProperty(PsiModifier.ABSTRACT) && !aClass.isEnum()) {
modifier = PsiModifier.PROTECTED;
}
else if (aClass.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || aClass.isEnum()) {
modifier = PsiModifier.PACKAGE_LOCAL;
}
else if (aClass.hasModifierProperty(PsiModifier.PRIVATE)) {
modifier = PsiModifier.PRIVATE;
}
return modifier;
}
/*
* Returns iterator of type parameters visible in owner. Type parameters are iterated in
* inner-to-outer, right-to-left order.
*/
@NotNull
public static Iterator<PsiTypeParameter> typeParametersIterator(@NotNull PsiTypeParameterListOwner owner) {
return typeParametersIterable(owner).iterator();
}
@NotNull
public static Iterable<PsiTypeParameter> typeParametersIterable(@NotNull final PsiTypeParameterListOwner owner) {
List<PsiTypeParameter> result = null;
PsiTypeParameterListOwner currentOwner = owner;
while (currentOwner != null) {
PsiTypeParameter[] typeParameters = currentOwner.getTypeParameters();
if (typeParameters.length > 0) {
if (result == null) result = new ArrayList<>(typeParameters.length);
for (int i = typeParameters.length - 1; i >= 0; i
result.add(typeParameters[i]);
}
}
if (currentOwner.hasModifierProperty(PsiModifier.STATIC)) break;
currentOwner = currentOwner.getContainingClass();
}
if (result == null) return EmptyIterable.getInstance();
return result;
}
public static boolean canBeOverridden(@NotNull PsiMethod method) {
PsiClass parentClass = method.getContainingClass();
return parentClass != null &&
!method.isConstructor() &&
!method.hasModifierProperty(PsiModifier.STATIC) &&
!method.hasModifierProperty(PsiModifier.FINAL) &&
!method.hasModifierProperty(PsiModifier.PRIVATE) &&
!(parentClass instanceof PsiAnonymousClass) &&
!parentClass.hasModifierProperty(PsiModifier.FINAL);
}
/**
* @deprecated Use {@link #canBeOverridden(PsiMethod)} instead
*/
public static boolean canBeOverriden(@NotNull PsiMethod method) {
return canBeOverridden(method);
}
@NotNull
public static PsiElement[] mapElements(@NotNull ResolveResult[] candidates) {
PsiElement[] result = new PsiElement[candidates.length];
for (int i = 0; i < candidates.length; i++) {
result[i] = candidates[i].getElement();
}
return result;
}
@Nullable
public static PsiMember findEnclosingConstructorOrInitializer(PsiElement expression) {
PsiMember parent = PsiTreeUtil.getParentOfType(expression, PsiClassInitializer.class, PsiEnumConstantInitializer.class, PsiMethod.class, PsiField.class);
if (parent instanceof PsiMethod && !((PsiMethod)parent).isConstructor()) return null;
if (parent instanceof PsiField && parent.hasModifierProperty(PsiModifier.STATIC)) return null;
return parent;
}
public static boolean checkName(@NotNull PsiElement element, @NotNull String name, final PsiElement context) {
if (element instanceof PsiMetaOwner) {
final PsiMetaData data = ((PsiMetaOwner) element).getMetaData();
if (data != null) return name.equals(data.getName(context));
}
return element instanceof PsiNamedElement && name.equals(((PsiNamedElement)element).getName());
}
public static boolean isRawSubstitutor(@NotNull PsiTypeParameterListOwner owner, @NotNull PsiSubstitutor substitutor) {
if (substitutor == PsiSubstitutor.EMPTY) return false;
for (PsiTypeParameter parameter : typeParametersIterable(owner)) {
if (substitutor.substitute(parameter) == null) return true;
}
return false;
}
public static final Key<LanguageLevel> FILE_LANGUAGE_LEVEL_KEY = Key.create("FORCE_LANGUAGE_LEVEL");
public static boolean isLanguageLevel5OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_5);
}
public static boolean isLanguageLevel6OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_6);
}
public static boolean isLanguageLevel7OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_7);
}
public static boolean isLanguageLevel8OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_8);
}
public static boolean isLanguageLevel9OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_1_9);
}
public static boolean isLanguageLevel10OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_10);
}
public static boolean isLanguageLevel11OrHigher(@NotNull final PsiElement element) {
return getLanguageLevel(element).isAtLeast(LanguageLevel.JDK_11);
}
@NotNull
public static LanguageLevel getLanguageLevel(@NotNull PsiElement element) {
if (element instanceof PsiDirectory) {
return JavaDirectoryService.getInstance().getLanguageLevel((PsiDirectory)element);
}
PsiFile file = element.getContainingFile();
if (file instanceof PsiJavaFile) {
return ((PsiJavaFile)file).getLanguageLevel();
}
if (file != null) {
PsiElement context = file.getContext();
if (context != null) {
if (!context.isValid()) {
throw new PsiInvalidElementAccessException(context, "Invalid context in " + file + " of " + file.getClass());
}
return getLanguageLevel(context);
}
}
PsiResolveHelper instance = PsiResolveHelper.SERVICE.getInstance(element.getProject());
return instance != null ? instance.getEffectiveLanguageLevel(getVirtualFile(file)) : LanguageLevel.HIGHEST;
}
@NotNull
public static LanguageLevel getLanguageLevel(@NotNull Project project) {
LanguageLevelProjectExtension instance = LanguageLevelProjectExtension.getInstance(project);
return instance != null ? instance.getLanguageLevel() : LanguageLevel.HIGHEST;
}
public static boolean isInstantiatable(@NotNull PsiClass clazz) {
return !clazz.hasModifierProperty(PsiModifier.ABSTRACT) &&
clazz.hasModifierProperty(PsiModifier.PUBLIC) &&
hasDefaultConstructor(clazz);
}
public static boolean hasDefaultConstructor(@NotNull PsiClass clazz) {
return hasDefaultConstructor(clazz, false);
}
public static boolean hasDefaultConstructor(@NotNull PsiClass clazz, boolean allowProtected) {
return hasDefaultConstructor(clazz, allowProtected, true);
}
public static boolean hasDefaultConstructor(@NotNull PsiClass clazz, boolean allowProtected, boolean checkModifiers) {
return hasDefaultCtrInHierarchy(clazz, allowProtected, checkModifiers, null);
}
private static boolean hasDefaultCtrInHierarchy(@NotNull PsiClass clazz, boolean allowProtected, boolean checkModifiers, @Nullable Set<PsiClass> visited) {
final PsiMethod[] constructors = clazz.getConstructors();
if (constructors.length > 0) {
for (PsiMethod cls: constructors) {
if ((!checkModifiers || cls.hasModifierProperty(PsiModifier.PUBLIC) ||
allowProtected && cls.hasModifierProperty(PsiModifier.PROTECTED)) &&
cls.getParameterList().isEmpty()) {
return true;
}
}
}
else {
final PsiClass superClass = clazz.getSuperClass();
if (superClass == null) {
return true;
}
if (visited == null) visited = new THashSet<>();
if (!visited.add(clazz)) return false;
return hasDefaultCtrInHierarchy(superClass, true, true, visited);
}
return false;
}
@Contract("null, _ -> null")
@Nullable
public static PsiType extractIterableTypeParameter(@Nullable PsiType psiType, final boolean eraseTypeParameter) {
final PsiType type = substituteTypeParameter(psiType, CommonClassNames.JAVA_LANG_ITERABLE, 0, eraseTypeParameter);
return type != null ? type : substituteTypeParameter(psiType, CommonClassNames.JAVA_UTIL_COLLECTION, 0, eraseTypeParameter);
}
@Contract("null, _, _, _ -> null")
@Nullable
public static PsiType substituteTypeParameter(@Nullable final PsiType psiType, @NotNull final String superClass, final int typeParamIndex,
final boolean eraseTypeParameter) {
if (psiType == null) return null;
if (!(psiType instanceof PsiClassType)) return null;
final PsiClassType classType = (PsiClassType)psiType;
final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
if (psiClass == null) return null;
final PsiClass baseClass = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(superClass, psiClass.getResolveScope());
if (baseClass == null) return null;
return substituteType(typeParamIndex, eraseTypeParameter, classResolveResult, psiClass, baseClass);
}
@Contract("null, _, _, _ -> null")
@Nullable
public static PsiType substituteTypeParameter(@Nullable final PsiType psiType, @NotNull final PsiClass superClass, final int typeParamIndex,
final boolean eraseTypeParameter) {
if (psiType == null) return null;
if (!(psiType instanceof PsiClassType)) return null;
final PsiClassType classType = (PsiClassType)psiType;
final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
if (psiClass == null) return null;
return substituteType(typeParamIndex, eraseTypeParameter, classResolveResult, psiClass, superClass);
}
@Nullable
private static PsiType substituteType(int typeParamIndex,
boolean eraseTypeParameter,
PsiClassType.ClassResolveResult classResolveResult,
PsiClass psiClass, PsiClass baseClass) {
if (!psiClass.isEquivalentTo(baseClass) && !psiClass.isInheritor(baseClass, true)) return null;
final PsiTypeParameter[] parameters = baseClass.getTypeParameters();
if (parameters.length <= typeParamIndex) return PsiType.getJavaLangObject(psiClass.getManager(), psiClass.getResolveScope());
final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, psiClass, classResolveResult.getSubstitutor());
final PsiType type = substitutor.substitute(parameters[typeParamIndex]);
if (type == null && eraseTypeParameter) {
return TypeConversionUtil.typeParameterErasure(parameters[typeParamIndex]);
}
return type;
}
public static final Comparator<PsiElement> BY_POSITION = (o1, o2) -> compareElementsByPosition(o1, o2);
public static void setModifierProperty(@NotNull PsiModifierListOwner owner, @NotNull @PsiModifier.ModifierConstant String property, boolean value) {
final PsiModifierList modifierList = owner.getModifierList();
assert modifierList != null : owner;
modifierList.setModifierProperty(property, value);
}
public static boolean isTryBlock(@Nullable final PsiElement element) {
if (element == null) return false;
final PsiElement parent = element.getParent();
return parent instanceof PsiTryStatement && element == ((PsiTryStatement)parent).getTryBlock();
}
public static boolean isElseBlock(@Nullable final PsiElement element) {
if (element == null) return false;
final PsiElement parent = element.getParent();
return parent instanceof PsiIfStatement && element == ((PsiIfStatement)parent).getElseBranch();
}
public static boolean isJavaToken(@Nullable PsiElement element, IElementType type) {
return element instanceof PsiJavaToken && ((PsiJavaToken)element).getTokenType() == type;
}
public static boolean isJavaToken(@Nullable PsiElement element, @NotNull TokenSet types) {
return element instanceof PsiJavaToken && types.contains(((PsiJavaToken)element).getTokenType());
}
public static boolean isCatchParameter(@Nullable final PsiElement element) {
return element instanceof PsiParameter && element.getParent() instanceof PsiCatchSection;
}
public static boolean isIgnoredName(@Nullable String name) {
return name != null && IGNORED_NAMES.contains(name);
}
@Nullable
public static PsiMethod[] getResourceCloserMethodsForType(@NotNull final PsiClassType resourceType) {
final PsiClass resourceClass = resourceType.resolve();
if (resourceClass == null) return null;
final Project project = resourceClass.getProject();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
final PsiClass autoCloseable = facade.findClass(CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE, ProjectScope.getLibrariesScope(project));
if (autoCloseable == null) return null;
if (JavaClassSupers.getInstance().getSuperClassSubstitutor(autoCloseable, resourceClass, resourceType.getResolveScope(), PsiSubstitutor.EMPTY) == null) return null;
final PsiMethod[] closes = autoCloseable.findMethodsByName("close", false);
if (closes.length == 1) {
return resourceClass.findMethodsBySignature(closes[0], true);
}
return null;
}
@Nullable
public static PsiExpression skipParenthesizedExprDown(PsiExpression expression) {
while (expression instanceof PsiParenthesizedExpression) {
expression = ((PsiParenthesizedExpression)expression).getExpression();
}
return expression;
}
public static PsiElement skipParenthesizedExprUp(PsiElement parent) {
while (parent instanceof PsiParenthesizedExpression) {
parent = parent.getParent();
}
return parent;
}
public static void ensureValidType(@NotNull PsiType type) {
ensureValidType(type, null);
}
public static void ensureValidType(@NotNull PsiType type, @Nullable String customMessage) {
if (!type.isValid()) {
TimeoutUtil.sleep(1); // to see if processing in another thread suddenly makes the type valid again (which is a bug)
if (type.isValid()) {
LOG.error("PsiType resurrected: " + type + " of " + type.getClass() + " " + customMessage);
return;
}
if (type instanceof PsiClassType) {
try {
PsiClass psiClass = ((PsiClassType)type).resolve(); // should throw exception
if (psiClass != null) {
ensureValid(psiClass);
}
}
catch (PsiInvalidElementAccessException e) {
throw customMessage == null? e : new RuntimeException(customMessage, e);
}
}
throw new AssertionError("Invalid type: " + type + " of class " + type.getClass() + " " + customMessage);
}
}
@Nullable
public static String getMemberQualifiedName(@NotNull PsiMember member) {
if (member instanceof PsiClass) {
return ((PsiClass)member).getQualifiedName();
}
PsiClass containingClass = member.getContainingClass();
if (containingClass == null) return null;
String className = containingClass.getQualifiedName();
if (className == null) return null;
return className + "." + member.getName();
}
public static boolean isFromDefaultPackage(PsiClass aClass) {
return isFromDefaultPackage((PsiElement)aClass);
}
public static boolean isFromDefaultPackage(PsiElement element) {
final PsiFile containingFile = element.getContainingFile();
return containingFile instanceof PsiClassOwner && StringUtil.isEmpty(((PsiClassOwner)containingFile).getPackageName());
}
static boolean checkSameExpression(PsiElement templateExpr, final PsiExpression expression) {
return templateExpr.equals(skipParenthesizedExprDown(expression));
}
public static boolean isCondition(PsiElement expr, PsiElement parent) {
if (parent instanceof PsiIfStatement) {
return checkSameExpression(expr, ((PsiIfStatement)parent).getCondition());
}
if (parent instanceof PsiWhileStatement) {
return checkSameExpression(expr, ((PsiWhileStatement)parent).getCondition());
}
if (parent instanceof PsiForStatement) {
return checkSameExpression(expr, ((PsiForStatement)parent).getCondition());
}
if (parent instanceof PsiDoWhileStatement) {
return checkSameExpression(expr, ((PsiDoWhileStatement)parent).getCondition());
}
if (parent instanceof PsiConditionalExpression) {
return checkSameExpression(expr, ((PsiConditionalExpression)parent).getCondition());
}
return false;
}
@NotNull
public static PsiReturnStatement[] findReturnStatements(@NotNull PsiMethod method) {
return findReturnStatements(method.getBody());
}
@NotNull
public static PsiReturnStatement[] findReturnStatements(@Nullable PsiCodeBlock body) {
ArrayList<PsiReturnStatement> vector = new ArrayList<>();
if (body != null) {
addReturnStatements(vector, body);
}
return vector.toArray(PsiReturnStatement.EMPTY_ARRAY);
}
private static void addReturnStatements(List<? super PsiReturnStatement> vector, PsiElement element) {
if (element instanceof PsiReturnStatement) {
vector.add((PsiReturnStatement)element);
}
else if (!(element instanceof PsiClass) && !(element instanceof PsiLambdaExpression)) {
PsiElement[] children = element.getChildren();
for (PsiElement child : children) {
addReturnStatements(vector, child);
}
}
}
public static boolean isModuleFile(@NotNull PsiFile file) {
return file instanceof PsiJavaFile && ((PsiJavaFile)file).getModuleDeclaration() != null;
}
public static boolean isPackageEmpty(@NotNull PsiDirectory[] directories, @NotNull String packageName) {
for (PsiDirectory directory : directories) {
for (PsiFile file : directory.getFiles()) {
if (file instanceof PsiClassOwner &&
packageName.equals(((PsiClassOwner)file).getPackageName()) &&
((PsiClassOwner)file).getClasses().length > 0) {
return false;
}
}
}
return true;
}
@NotNull
public static PsiModifierListOwner preferCompiledElement(@NotNull PsiModifierListOwner element) {
PsiElement original = element.getOriginalElement();
return original instanceof PsiModifierListOwner ? (PsiModifierListOwner)original : element;
}
public static PsiElement addModuleStatement(@NotNull PsiJavaModule module, @NotNull String text) {
PsiJavaParserFacade facade = JavaPsiFacade.getInstance(module.getProject()).getParserFacade();
PsiStatement statement = facade.createModuleStatementFromText(text);
PsiElement anchor = SyntaxTraverser.psiTraverser().children(module).filter(statement.getClass()).last();
if (anchor == null) {
anchor = SyntaxTraverser.psiTraverser().children(module).filter(e -> isJavaToken(e, JavaTokenType.LBRACE)).first();
}
if (anchor == null) {
throw new IllegalStateException("No anchor in " + Arrays.toString(module.getChildren()));
}
return module.addAfter(statement, anchor);
}
}
|
package edu.umd.cs.findbugs;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.meta.TypeQualifier;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.FieldSummary;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.ch.Subtypes2;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.IAnalysisCache;
import edu.umd.cs.findbugs.classfile.MethodDescriptor;
import edu.umd.cs.findbugs.classfile.analysis.MethodInfo;
import edu.umd.cs.findbugs.classfile.engine.bcel.AnalysisFactory;
import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.util.Util;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand
* stack throughout the execution of method. To use, a detector should
* instantiate one for each method, and call
* <p>
* stack.sawOpcode(this,seen);
* </p>
* at the bottom of their sawOpcode method. at any point you can then inspect
* the stack and see what the types of objects are on the stack, including
* constant values if they were pushed. The types described are of course, only
* the static types. There are some outstanding opcodes that have yet to be
* implemented, I couldn't find any code that actually generated these, so i
* didn't put them in because I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2 {
/** You can put this annotation on a OpcodeStack detector
* to indicate that it uses {@link OpcodeStack.Item#userValue},
* and thus should not reuse generic OpcodeStack information
* from an iterative evaluation of the opcode stack. Such detectors
* will not use iterative opcode stack evaluation.
*
* This is primarily for detectors that need to be backwards compatible with
* versions of FindBugs that do not support {@link OpcodeStackDetector.WithCustomJumpInfo }}
*/
@Documented
@Target({ElementType.TYPE, ElementType.PACKAGE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomUserValue {
}
private static final String JAVA_UTIL_ARRAYS_ARRAY_LIST = "Ljava/util/Arrays$ArrayList;";
private static final boolean DEBUG = SystemProperties.getBoolean("ocstack.debug");
private static final boolean DEBUG2 = DEBUG;
private List<Item> stack;
private List<Item> lvValues;
private final List<Integer> lastUpdate;
private boolean top;
static class HttpParameterInjection {
HttpParameterInjection(String parameterName, int pc) {
this.parameterName = parameterName;
this.pc = pc;
}
String parameterName;
int pc;
}
private boolean seenTransferOfControl = false;
private final boolean useIterativeAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(
AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class Item {
@Documented
@TypeQualifier(applicableTo = Integer.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface SpecialKind {
}
public static final @SpecialKind
int NOT_SPECIAL = 0;
public static final @SpecialKind
int SIGNED_BYTE = 1;
public static final @SpecialKind
int RANDOM_INT = 2;
public static final @SpecialKind
int LOW_8_BITS_CLEAR = 3;
public static final @SpecialKind
int HASHCODE_INT = 4;
public static final @SpecialKind
int INTEGER_SUM = 5;
public static final @SpecialKind
int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final @SpecialKind
int FLOAT_MATH = 7;
public static final @SpecialKind
int RANDOM_INT_REMAINDER = 8;
public static final @SpecialKind
int HASHCODE_INT_REMAINDER = 9;
public static final @SpecialKind
int FILE_SEPARATOR_STRING = 10;
public static final @SpecialKind
int MATH_ABS = 11;
public static final @SpecialKind
int MATH_ABS_OF_RANDOM = 12;
public static final @SpecialKind
int MATH_ABS_OF_HASHCODE = 13;
public static final @SpecialKind
int NON_NEGATIVE = 14;
public static final @SpecialKind
int NASTY_FLOAT_MATH = 15;
public static final @SpecialKind
int FILE_OPENED_IN_APPEND_MODE = 16;
public static final @SpecialKind
int SERVLET_REQUEST_TAINTED = 17;
public static final @SpecialKind
int NEWLY_ALLOCATED = 18;
public static final @SpecialKind
int ZERO_MEANS_NULL = 19;
public static final @SpecialKind
int NONZERO_MEANS_NULL = 20;
public static final @SpecialKind
int RESULT_OF_I2L = 21;
public static final @SpecialKind
int RESULT_OF_L2I = 22;
public static final @SpecialKind
int SERVLET_OUTPUT = 23;
public static HashMap<Integer, String> specialKindNames = new HashMap<Integer, String>();
private static int nextSpecialKind = SERVLET_OUTPUT + 1;
public static @SpecialKind
int defineNewSpecialKind(String name) {
specialKindNames.put(nextSpecialKind, name);
return nextSpecialKind++;
}
private static final int IS_INITIAL_PARAMETER_FLAG = 1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private @SpecialKind
int specialKind = NOT_SPECIAL;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull
ClassMember source;
private int pc = -1;
private int flags;
private int registerNumber = -1;
private Object userValue = null;
private HttpParameterInjection injection = null;
private int fieldLoadedFromRegister = -1;
public void makeCrossMethod() {
pc = -1;
registerNumber = -1;
fieldLoadedFromRegister = -1;
}
public int getSize() {
if (signature.equals("J") || signature.equals("D"))
return 2;
return 1;
}
public int getPC() {
return pc;
}
public void setPC(int pc) {
this.pc = pc;
}
public boolean isWide() {
return getSize() == 2;
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r += signature.hashCode();
r *= 31;
if (constValue != null)
r += constValue.hashCode();
r *= 31;
if (source != null)
r += source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item))
return false;
Item that = (Item) o;
return Util.nullSafeEquals(this.signature, that.signature) && Util.nullSafeEquals(this.constValue, that.constValue)
&& Util.nullSafeEquals(this.source, that.source) && Util.nullSafeEquals(this.userValue, that.userValue)
&& Util.nullSafeEquals(this.injection, that.injection) && this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber && this.flags == that.flags
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("< ");
buf.append(signature);
switch (specialKind) {
case SIGNED_BYTE:
buf.append(", signed_byte");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case MATH_ABS_OF_RANDOM:
buf.append(", abs_of_random");
break;
case MATH_ABS_OF_HASHCODE:
buf.append(", abs_of_hashcode");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case NON_NEGATIVE:
buf.append(", non_negative");
break;
case FILE_OPENED_IN_APPEND_MODE:
buf.append(", file opened in append mode");
break;
case SERVLET_REQUEST_TAINTED:
buf.append(", servlet request tainted");
break;
case NEWLY_ALLOCATED:
buf.append(", new");
break;
case ZERO_MEANS_NULL:
buf.append(", zero means null");
break;
case NONZERO_MEANS_NULL:
buf.append(", nonzero means null");
break;
case SERVLET_OUTPUT:
buf.append(", servlet_output");
break;
case NOT_SPECIAL:
break;
default:
buf.append(", #" + specialKind);
buf.append("(" + specialKindNames.get(specialKind) + ")");
break;
}
if (constValue != UNKNOWN) {
if (constValue instanceof String) {
buf.append(", \"");
buf.append(constValue);
buf.append("\"");
} else {
buf.append(", ");
buf.append(constValue);
}
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1 && fieldLoadedFromRegister != Integer.MAX_VALUE)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero())
buf.append(", cbz");
if (userValue != null) {
buf.append(", uv: ");
buf.append(userValue.toString());
}
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null)
return i2;
if (i2 == null)
return i1;
if (i1.equals(i2))
return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (i1.pc == i2.pc)
m.pc = i1.pc;
if (Util.nullSafeEquals(i1.signature, i2.signature))
m.signature = i1.signature;
else if (i1.isNull())
m.signature = i2.signature;
else if (i2.isNull())
m.signature = i1.signature;
if (Util.nullSafeEquals(i1.constValue, i2.constValue))
m.constValue = i1.constValue;
if (Util.nullSafeEquals(i1.source, i2.source)) {
m.source = i1.source;
} else if ("".equals(i1.constValue))
m.source = i2.source;
else if ("".equals(i2.constValue))
m.source = i1.source;
if (Util.nullSafeEquals(i1.userValue, i2.userValue))
m.userValue = i1.userValue;
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == SERVLET_REQUEST_TAINTED) {
m.specialKind = SERVLET_REQUEST_TAINTED;
m.injection = i1.injection;
} else if (i2.specialKind == SERVLET_REQUEST_TAINTED) {
m.specialKind = SERVLET_REQUEST_TAINTED;
m.injection = i2.injection;
} else if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG)
System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, Integer.valueOf(constValue));
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.injection = it.injection;
this.flags = it.flags;
this.specialKind = it.specialKind;
this.pc = it.pc;
}
public Item(Item it, String signature) {
this(it);
this.signature = DescriptorFactory.canonicalizeString(signature);
if (constValue instanceof Number) {
Number constantNumericValue = (Number) constValue;
if (signature.equals("B"))
this.constValue = constantNumericValue.byteValue();
else if (signature.equals("S"))
this.constValue = constantNumericValue.shortValue();
else if (signature.equals("C"))
this.constValue = (char) constantNumericValue.intValue();
else if (signature.equals("I"))
this.constValue = constantNumericValue.intValue();
}
setSpecialKindFromSignature();
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.signature = DescriptorFactory.canonicalizeString(signature);
setSpecialKindFromSignature();
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.signature = DescriptorFactory.canonicalizeString(signature);
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
/**
* If this value was loaded from an instance field,
* give the register number containing the object that the field was loaded from.
* If Integer.MAX value, the value was loaded from a static field
* If -1, we don't know or don't have the register containing the object that
* the field was loaded from.
* @return
*
*/
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public void setLoadedFromField(XField f, int fieldLoadedFromRegister) {
source = f;
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
this.registerNumber = -1;
}
public @CheckForNull
String getHttpParameterName() {
if (!isServletParameterTainted())
throw new IllegalStateException();
if (injection == null)
return null;
return injection.parameterName;
}
public int getInjectionPC() {
if (!isServletParameterTainted())
throw new IllegalStateException();
if (injection == null)
return -1;
return injection.pc;
}
public Item(String signature, Object constantValue) {
this.signature = DescriptorFactory.canonicalizeString(signature);
setSpecialKindFromSignature();
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = ((Integer) constantValue).intValue();
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0)
setCouldBeZero(true);
} else if (constantValue instanceof Long) {
long value = ((Long) constantValue).longValue();
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0)
setCouldBeZero(true);
}
}
private void setSpecialKindFromSignature() {
if (false && specialKind != NOT_SPECIAL)
return;
if (signature.equals("B"))
specialKind = SIGNED_BYTE;
else if (signature.equals("C"))
specialKind = NON_NEGATIVE;
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
setNull(true);
}
public static Item nullItem(String signature) {
Item item = new Item(signature);
item.constValue = null;
item.setNull(true);
return item;
}
/** Returns null for primitive and arrays */
public @CheckForNull
JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive() || isArray())
return null;
baseSig = signature;
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
@Deprecated
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == NON_NEGATIVE)
return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !signature.startsWith("L") && !signature.startsWith("[");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known. NOTE: if the value
* is a constant Class object, the constant value returned is the name
* of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField)
return (XField) source;
return null;
}
/**
* @param specialKind
* The specialKind to set.
*/
public void setSpecialKind(@SpecialKind int specialKind) {
this.specialKind = specialKind;
}
public Item cloneAndSetSpecialKind(@SpecialKind int specialKind) {
Item that = new Item(this);
that.specialKind = specialKind;
return that;
}
/**
* @return Returns the specialKind.
*/
public @SpecialKind
int getSpecialKind() {
return specialKind;
}
/**
* @return Returns the specialKind.
*/
public boolean isBooleanNullnessValue() {
return specialKind == ZERO_MEANS_NULL || specialKind == NONZERO_MEANS_NULL;
}
/**
* attaches a detector specified value to this item
*
* @param value
* the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the
* method invoked
*/
public @CheckForNull
XMethod getReturnValueOf() {
if (source instanceof XMethod)
return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number) value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean isServletParameterTainted() {
return getSpecialKind() == Item.SERVLET_REQUEST_TAINTED;
}
public void setServletParameterTainted() {
setSpecialKind(Item.SERVLET_REQUEST_TAINTED);
}
public void setIsServletWriter() {
setSpecialKind(Item.SERVLET_OUTPUT);
}
public boolean isServletWriter() {
if (getSpecialKind() == Item.SERVLET_OUTPUT)
return true;
if (getSignature().equals("Ljavax/servlet/ServletOutputStream;"))
return true;
XMethod writingToSource = getReturnValueOf();
return writingToSource != null && writingToSource.getClassName().equals("javax.servlet.http.HttpServletResponse")
&& (writingToSource.getName().equals("getWriter") || writingToSource.getName().equals("getOutputStream"));
}
public boolean valueCouldBeNegative() {
return !isNonNegative()
&& (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT || getSpecialKind() == Item.RANDOM_INT_REMAINDER
|| getSpecialKind() == Item.HASHCODE_INT_REMAINDER || getSpecialKind() == Item.MATH_ABS_OF_RANDOM || getSpecialKind() == Item.MATH_ABS_OF_HASHCODE);
}
public @SpecialKind int getSpecialKindForAbs() {
switch (getSpecialKind()) {
case Item.HASHCODE_INT:
return Item.MATH_ABS_OF_HASHCODE;
case Item.RANDOM_INT:
return Item.MATH_ABS_OF_RANDOM;
default:
return Item.MATH_ABS;
}
}
public @SpecialKind int getSpecialKindForRemainder() {
switch (getSpecialKind()) {
case Item.HASHCODE_INT:
return Item.HASHCODE_INT_REMAINDER;
case Item.RANDOM_INT:
return Item.RANDOM_INT_REMAINDER;
default:
return Item.NOT_SPECIAL;
}
}
/** Value could be Integer.MIN_VALUE */
public boolean checkForIntegerMinValue() {
return !isNonNegative() && (getSpecialKind() == Item.RANDOM_INT || getSpecialKind() == Item.HASHCODE_INT);
}
/** The result of applying Math.abs to a checkForIntegerMinValue() value */
public boolean mightRarelyBeNegative() {
return !isNonNegative()
&& (getSpecialKind() == Item.MATH_ABS_OF_RANDOM || getSpecialKind() == Item.MATH_ABS_OF_HASHCODE);
}
/**
* @param isInitialParameter
* The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero
* The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull
* The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
public void clearNewlyAllocated() {
if (specialKind == NEWLY_ALLOCATED) {
if (signature.startsWith("Ljava/lang/StringB"))
constValue = null;
specialKind = NOT_SPECIAL;
}
}
public boolean isNewlyAllocated() {
return specialKind == NEWLY_ALLOCATED;
}
/**
* @param i
* @return
*/
public boolean hasConstantValue(int value) {
if (constValue instanceof Number)
return ((Number) constValue).intValue() == value;
return false;
}
public boolean hasConstantValue(long value) {
if (constValue instanceof Number)
return ((Number) constValue).longValue() == value;
return false;
}
}
@Override
public String toString() {
if (isTop())
return "TOP";
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack() {
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
public boolean hasIncomingBranches(int pc) {
return jumpEntryLocations.get(pc) && jumpEntries.get(pc) != null;
}
boolean needToMerge = true;
private boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0)
return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L" + ((ConstantClass) c).getBytes(dbc.getConstantPool()) + ";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge)
return;
needToMerge = false;
if (dbc.getPC() == zeroOneComing) {
pop();
top = false;
OpcodeStack.Item item = new Item("I");
if (oneMeansNull)
item.setSpecialKind(Item.NONZERO_MEANS_NULL);
else
item.setSpecialKind(Item.ZERO_MEANS_NULL);
item.setPC(dbc.getPC() - 8);
item.setCouldBeZero(true);
push(item);
zeroOneComing = -1;
if (DEBUG)
System.out.println("Updated to " + this);
return;
}
boolean stackUpdated = false;
if (!isTop() && (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3)) {
pop();
Item topItem = new Item("I");
topItem.setCouldBeZero(true);
push(topItem);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(Integer.valueOf(dbc.getPC()));
if (jumpEntry != null) {
setReachOnlyByBranch(false);
List<Item> jumpStackEntry = jumpStackEntries.get(Integer.valueOf(dbc.getPC()));
if (DEBUG2) {
System.out.println("XXXXXXX " + isReachOnlyByBranch());
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
System.out.println(" merging stack entry " + jumpStackEntry);
System.out.println(" current stack values " + stack);
}
if (isTop()) {
lvValues = new ArrayList<Item>(jumpEntry);
if (jumpStackEntry != null)
stack = new ArrayList<Item>(jumpStackEntry);
else
stack.clear();
setTop(false);
return;
}
if (isReachOnlyByBranch()) {
setTop(false);
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null)
stack = new ArrayList<Item>(jumpStackEntry);
else
stack.clear();
}
} else {
setTop(false);
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null)
mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
} else if (isReachOnlyByBranch() && !stackUpdated) {
stack.clear();
for (CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
setReachOnlyByBranch(false);
setTop(false);
return;
}
}
setTop(true);
}
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
int registerTestedFoundToBeNonnegative = -1;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg)
lastUpdate.add(Integer.valueOf(0));
lastUpdate.set(reg, Integer.valueOf(pc));
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg)
return 0;
return lastUpdate.get(reg).intValue();
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
int zeroOneComing = -1;
boolean oneMeansNull;
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2;
Constant cons;
// System.out.printf("%3d %12s%s%n", dbc.getPC(), OPCODE_NAMES[seen],
// this);
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
precomputation(dbc);
needToMerge = true;
try {
if (isTop()) {
encountedTop = true;
return;
}
if (seen == GOTO) {
int nextPC = dbc.getPC() + 3;
if (nextPC <= dbc.getMaxPC()) {
int prevOpcode1 = dbc.getPrevOpcode(1);
int prevOpcode2 = dbc.getPrevOpcode(2);
try {
int nextOpcode = dbc.getCodeByte(dbc.getPC() + 3);
if ((prevOpcode1 == ICONST_0 || prevOpcode1 == ICONST_1)
&& (prevOpcode2 == IFNULL || prevOpcode2 == IFNONNULL)
&& (nextOpcode == ICONST_0 || nextOpcode == ICONST_1) && prevOpcode1 != nextOpcode) {
oneMeansNull = prevOpcode1 == ICONST_0;
if (prevOpcode2 != IFNULL)
oneMeansNull = !oneMeansNull;
zeroOneComing = nextPC + 1;
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw e; // throw new
// ArrayIndexOutOfBoundsException(nextPC + " "
// + dbc.getMaxPC());
}
}
}
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else
convertJumpToOneZeroState = 0;
break;
default:
convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else
convertJumpToZeroOneState = 0;
break;
default:
convertJumpToZeroOneState = 0;
}
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC: {
FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
XField fieldOperand = dbc.getXFieldOperand();
if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) {
OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand);
if (item != null) {
Item itm = new Item(item);
itm.setLoadedFromField(fieldOperand, Integer.MAX_VALUE);
push(itm);
break;
}
}
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFNONNULL:
case IFNULL:
// Item topItem = pop();
// if (seen == IFNONNULL && topItem.isNull())
// break;
// seenTransferOfControl = true;
// addJumpValue(dbc.getPC(), dbc.getBranchTarget());
// break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
seenTransferOfControl = true;
{
Item topItem = pop();
// System.out.printf("%4d %10s %s%n",
// dbc.getPC(),OPCODE_NAMES[seen], topItem);
if (seen == IFLT || seen == IFLE) {
registerTestedFoundToBeNonnegative = topItem.registerNumber;
}
// if we see a test comparing a special negative value with
// reset all other such values on the opcode stack
if (topItem.valueCouldBeNegative() && (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = topItem.getSpecialKind();
for (Item item : stack)
if (item != null && item.getSpecialKind() == specialKind)
item.setSpecialKind(Item.NOT_SPECIAL);
for (Item item : lvValues)
if (item != null && item.getSpecialKind() == specialKind)
item.setSpecialKind(Item.NOT_SPECIAL);
}
}
addJumpValue(dbc.getPC(), dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
addJumpValue(dbc.getPC(), dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for (int offset : dbc.getSwitchOffsets())
addJumpValue(dbc.getPC(), offset + pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
{
seenTransferOfControl = true;
Item right = pop();
Item left = pop();
Object lConstant = left.getConstant();
Object rConstant = right.getConstant();
if (lConstant instanceof Integer && rConstant instanceof Integer) {
boolean takeJump = false;
boolean handled = false;
int lC = ((Integer)lConstant).intValue();
int rC = ((Integer)rConstant).intValue();
switch(seen) {
case IF_ICMPEQ:
takeJump = lC == rC;
handled = true;
break;
case IF_ICMPNE:
takeJump = lC != rC;
handled = true;
break;
case IF_ICMPGE:
takeJump = lC >= rC;
handled = true;
break;
case IF_ICMPGT:
takeJump = lC > rC;
handled = true;
break;
case IF_ICMPLE:
takeJump = lC <= rC;
handled = true;
break;
case IF_ICMPLT:
takeJump = lC < rC;
handled = true;
break;
}
if (handled) {
if (takeJump) {
int branchTarget = dbc.getBranchTarget();
addJumpValue(dbc.getPC(), branchTarget);
setTop(true);
break;
} else {
break;
}
}
}
if (right.hasConstantValue(Integer.MIN_VALUE) && left.mightRarelyBeNegative()
|| left.hasConstantValue(Integer.MIN_VALUE) && right.mightRarelyBeNegative()) {
for (Item i : stack)
if (i != null && i.mightRarelyBeNegative())
i.setSpecialKind(Item.NOT_SPECIAL);
for (Item i : lvValues)
if (i != null && i.mightRarelyBeNegative())
i.setSpecialKind(Item.NOT_SPECIAL);
}
int branchTarget = dbc.getBranchTarget();
addJumpValue(dbc.getPC(), branchTarget);
break;
}
case POP2:
it = pop();
if (it.getSize() == 1)
pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case DUP2_X2:
handleDup2X2();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue(register);
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath(dbc, IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
setReachOnlyByBranch(true);
setTop(true);
break;
case CHECKCAST: {
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[')
castTo = "L" + castTo + ";";
it = pop();
if (!it.signature.equals(castTo)) {
it = new Item(it, castTo);
}
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
break;
case GOTO:
case GOTO_W:
seenTransferOfControl = true;
setReachOnlyByBranch(true);
addJumpValue(dbc.getPC(), dbc.getBranchTarget());
stack.clear();
setTop(true);
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen - ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", Long.valueOf(seen - LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", Double.valueOf(seen - DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", Float.valueOf(seen - FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD: {
FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
XField fieldOperand = dbc.getXFieldOperand();
if (fieldOperand != null && fieldSummary.isComplete() && !fieldOperand.isPublic()) {
OpcodeStack.Item item = fieldSummary.getSummary(fieldOperand);
if (item != null) {
Item addr = pop();
Item itm = new Item(item);
itm.setLoadedFromField(fieldOperand, addr.getRegisterNumber());
push(itm);
break;
}
}
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(), FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH: {
pop();
Item newItem = new Item("I");
newItem.setSpecialKind(Item.NON_NEGATIVE);
push(newItem);
}
break;
case BALOAD: {
pop(2);
Item newItem = new Item("I");
newItem.setSpecialKind(Item.SIGNED_BYTE);
push(newItem);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", Integer.valueOf(dbc.getIntConstant())));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(dbc, seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() instanceof Integer) {
push(new Item("I", Integer.valueOf(-constantToInt(it))));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() instanceof Long) {
push(new Item("J", Long.valueOf(-constantToLong(it))));
} else {
push(new Item("J"));
}
break;
case FNEG:
it = pop();
if (it.getConstant() instanceof Float) {
push(new Item("F", Float.valueOf(-constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() instanceof Double) {
push(new Item("D", Double.valueOf(-constantToDouble(it))));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL:
handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
case FREM:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B: {
it = pop();
Item newValue = new Item(it, "B");
push(newValue);
}
break;
case I2C: {
it = pop();
Item newValue = new Item(it, "C");
push(newValue);
}
break;
case I2L:
case D2L:
case F2L: {
it = pop();
Item newValue = new Item(it, "J");
int specialKind = it.getSpecialKind();
if (specialKind != Item.SIGNED_BYTE && seen == I2L)
newValue.setSpecialKind(Item.RESULT_OF_I2L);
push(newValue);
}
break;
case I2S:
changeSignatureOfTopElement("S");
break;
case L2I:
case D2I:
case F2I:
it = pop();
int oldSpecialKind = it.getSpecialKind();
it = new Item(it, "I");
if (oldSpecialKind == Item.NOT_SPECIAL)
it.setSpecialKind(Item.RESULT_OF_L2I);
push(it);
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", Float.valueOf(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", Double.valueOf(constantToDouble(it))));
} else {
push(new Item("D"));
}
break;
case NEW: {
Item item = new Item("L" + dbc.getClassConstantOperand() + ";", (Object) null);
item.setSpecialKind(Item.NEWLY_ALLOCATED);
push(item);
}
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte) dbc.getIntConstant()).getSignature();
pushBySignature(signature, dbc);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (signature.charAt(0) == '[')
signature = "[" + signature;
else
signature = "[L" + signature + ";";
pushBySignature(signature, dbc);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
for (int i = 0; i < dims; i++)
pop();
signature = dbc.getClassConstantOperand();
pushBySignature(signature, dbc);
break;
case AALOAD: {
pop();
it = pop();
String arraySig = it.getSignature();
if (arraySig.charAt(0) == '[')
pushBySignature(arraySig.substring(1), dbc);
else
push(new Item());
}
break;
case JSR:
seenTransferOfControl = true;
setReachOnlyByBranch(false);
push(new Item("")); // push return address on stack
addJumpValue(dbc.getPC(), dbc.getBranchTarget());
pop();
if (dbc.getBranchOffset() < 0) {
// OK, backwards JSRs are weird; reset the stack.
int stackSize = stack.size();
stack.clear();
for (int i = 0; i < stackSize; i++)
stack.add(new Item());
}
setTop(false);
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported ");
}
}
catch (RuntimeException e) {
// If an error occurs, we clear the stack and locals. one of two
// things will occur.
// Either the client will expect more stack items than really exist,
// and so they're condition check will fail,
// or the stack will resync with the code. But hopefully not false
// positives
String msg = "Error processing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in "
+ dbc.getFullyQualifiedMethodName();
AnalysisContext.logError(msg, e);
if (DEBUG)
e.printStackTrace();
clear();
} finally {
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
private void changeSignatureOfTopElement(String newSignature) {
{
Item item = pop();
Item newValue = new Item(item, newSignature);
push(newValue);
}
}
public void precomputation(DismantleBytecode dbc) {
if (registerTestedFoundToBeNonnegative >= 0) {
for (int i = 0; i < stack.size(); i++) {
Item item = stack.get(i);
if (item != null && item.registerNumber == registerTestedFoundToBeNonnegative)
stack.set(i, item.cloneAndSetSpecialKind(Item.NON_NEGATIVE));
}
for (int i = 0; i < lvValues.size(); i++) {
Item item = lvValues.get(i);
if (item != null && item.registerNumber == registerTestedFoundToBeNonnegative)
lvValues.set(i, item.cloneAndSetSpecialKind(Item.NON_NEGATIVE));
}
}
registerTestedFoundToBeNonnegative = -1;
mergeJumps(dbc);
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
Object constant = it.getConstant();
if (constant instanceof Number) {
return ((Number) constant).intValue();
}
if (constant instanceof Character) {
return ((Character) constant).charValue();
}
throw new IllegalArgumentException(String.valueOf(constant));
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number) it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number) it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number) it.getConstant()).longValue();
}
/**
* handle dcmp
*
*/
private void handleDcmp(int opcode) {
Item it = pop();
Item it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = constantToDouble(it);
double d2 = constantToDouble(it2);
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", Integer.valueOf(1)));
else
push(new Item("I", Integer.valueOf(-1)));
}
if (d2 < d)
push(new Item("I", Integer.valueOf(-1)));
else if (d2 > d)
push(new Item("I", Integer.valueOf(1)));
else
push(new Item("I", Integer.valueOf(0)));
} else {
push(new Item("I"));
}
}
/**
* handle fcmp
*
*/
private void handleFcmp(int opcode) {
Item it = pop();
Item it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = constantToFloat(it);
float f2 = constantToFloat(it2);
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", Integer.valueOf(1)));
else
push(new Item("I", Integer.valueOf(-1)));
}
if (f2 < f)
push(new Item("I", Integer.valueOf(-1)));
else if (f2 > f)
push(new Item("I", Integer.valueOf(1)));
else
push(new Item("I", Integer.valueOf(0)));
} else {
push(new Item("I"));
}
}
/**
* handle lcmp
*/
private void handleLcmp() {
Item it = pop();
Item it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = constantToLong(it);
long l2 = constantToLong(it2);
if (l2 < l)
push(new Item("I", Integer.valueOf(-1)));
else if (l2 > l)
push(new Item("I", Integer.valueOf(1)));
else
push(new Item("I", Integer.valueOf(0)));
} else {
push(new Item("I"));
}
}
/**
* handle swap
*/
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
/**
* handleDup
*/
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
/**
* handle dupX1
*/
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
/**
* handle dup2
*/
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
} else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
/**
* handle Dup2x1
*/
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDup2X2() {
Item it = pop();
Item it2 = pop();
if (it.isWide()) {
if (it2.isWide()) {
push(it);
push(it2);
push(it);
} else {
Item it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
} else {
Item it3 = pop();
if (it3.isWide()) {
push(it2);
push(it);
push(it3);
push(it2);
push(it);
} else {
Item it4 = pop();
push(it2);
push(it);
push(it4);
push(it3);
push(it2);
push(it);
}
}
}
/**
* Handle DupX2
*/
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
static final HashMap<String, String> boxedTypes = new HashMap<String, String>();
static private void addBoxedType(Class<?>... clss) {
for (Class<?> c : clss) {
Class<?> primitiveType;
try {
primitiveType = (Class<?>) c.getField("TYPE").get(null);
boxedTypes.put(ClassName.toSlashedClassName(c.getName()), primitiveType.getName());
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
static {
addBoxedType(Integer.class, Long.class, Double.class, Short.class, Float.class, Boolean.class, Character.class,
Byte.class);
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
@SlashedClassName String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
boolean servletRequestParameterTainted = false;
boolean sawUnknownAppend = false;
Item sbItem = null;
Item topItem = null;
if (getStackDepth() > 0)
topItem = getStackItem(0);
int numberArguments = PreorderVisitor.getNumberArguments(signature);
if (boxedTypes.containsKey(clsName)
&& topItem != null
&& (methodName.equals("valueOf") && !signature.contains("String") || methodName.equals(boxedTypes.get(clsName)
+ "Value"))) {
// boxing/unboxing conversion
Item value = pop();
String newSignature = Type.getReturnType(signature).getSignature();
Item newValue = new Item(value, newSignature);
if (newValue.source == null)
newValue.source = XFactory.createReferencedXMethod(dbc);
if (newValue.specialKind == Item.NOT_SPECIAL) {
if (newSignature.equals("B") || newSignature.equals("Ljava/lang/Boolean;"))
newValue.specialKind = Item.SIGNED_BYTE;
else if (newSignature.equals("C") || newSignature.equals("Ljava/lang/Character;"))
newValue.specialKind = Item.NON_NEGATIVE;
}
push(newValue);
return;
}
int firstArgument = seen == INVOKESTATIC ? 0 : 1;
for (int i = firstArgument; i < firstArgument + numberArguments; i++) {
if (i >= getStackDepth())
break;
Item item = getStackItem(i);
String itemSignature = item.getSignature();
if (itemSignature.equals("Ljava/lang/StringBuilder;") || itemSignature.equals("Ljava/lang/StringBuffer;"))
item.constValue = null;
}
boolean initializingServletWriter = false;
if (seen == INVOKESPECIAL && methodName.equals("<init>") && clsName.startsWith("java/io") && clsName.endsWith("Writer")
&& numberArguments > 0) {
Item firstArg = getStackItem(numberArguments-1);
if (firstArg.isServletWriter())
initializingServletWriter = true;
}
boolean topIsTainted = topItem != null && topItem.isServletParameterTainted();
HttpParameterInjection injection = null;
if (topIsTainted)
injection = topItem.injection;
// TODO: stack merging for trinaries kills the constant.. would be nice
// to maintain.
if ("java/lang/StringBuffer".equals(clsName) || "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String) i.getConstant();
if (i.isServletParameterTainted())
servletRequestParameterTainted = true;
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String) i.getConstant();
if (i.isServletParameterTainted())
servletRequestParameterTainted = true;
} else if ("append".equals(methodName)) {
if (signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
if (i.isServletParameterTainted() || sbItem.isServletParameterTainted())
servletRequestParameterTainted = true;
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
} else if (signature.startsWith("([CII)")) {
sawUnknownAppend = true;
sbItem = getStackItem(3);
if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
} else {
sawUnknownAppend = true;
}
}
} else if (seen == INVOKESPECIAL && clsName.equals("java/io/FileOutputStream") && methodName.equals("<init>")
&& (signature.equals("(Ljava/io/File;Z)V") || signature.equals("(Ljava/lang/String;Z)V")) && stack.size() > 3) {
OpcodeStack.Item item = getStackItem(0);
Object value = item.getConstant();
if (value instanceof Integer && ((Integer) value).intValue() == 1) {
pop(3);
Item newTop = getStackItem(0);
if (newTop.signature.equals("Ljava/io/FileOutputStream;")) {
newTop.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE);
newTop.source = XFactory.createReferencedXMethod(dbc);
newTop.setPC(dbc.getPC());
}
return;
}
} else if (seen == INVOKESPECIAL && clsName.equals("java/io/BufferedOutputStream") && methodName.equals("<init>")
&& signature.equals("(Ljava/io/OutputStream;)V")) {
if (getStackItem(0).getSpecialKind() == Item.FILE_OPENED_IN_APPEND_MODE
&& getStackItem(2).signature.equals("Ljava/io/BufferedOutputStream;")) {
pop(2);
Item newTop = getStackItem(0);
newTop.setSpecialKind(Item.FILE_OPENED_IN_APPEND_MODE);
newTop.source = XFactory.createReferencedXMethod(dbc);
newTop.setPC(dbc.getPC());
return;
}
} else if (seen == INVOKEINTERFACE && methodName.equals("getParameter")
&& clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) {
Item requestParameter = pop();
pop();
Item result = new Item("Ljava/lang/String;");
result.setServletParameterTainted();
result.source = XFactory.createReferencedXMethod(dbc);
String parameterName = null;
if (requestParameter.getConstant() instanceof String)
parameterName = (String) requestParameter.getConstant();
result.injection = new HttpParameterInjection(parameterName, dbc.getPC());
result.setPC(dbc.getPC());
push(result);
return;
} else if (seen == INVOKEINTERFACE && methodName.equals("getQueryString")
&& clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) {
pop();
Item result = new Item("Ljava/lang/String;");
result.setServletParameterTainted();
result.source = XFactory.createReferencedXMethod(dbc);
result.setPC(dbc.getPC());
push(result);
return;
} else if (seen == INVOKEINTERFACE && methodName.equals("getHeader")
&& clsName.equals("javax/servlet/http/HttpServletRequest") || clsName.equals("javax/servlet/http/ServletRequest")) {
/* Item requestParameter = */pop();
pop();
Item result = new Item("Ljava/lang/String;");
result.setServletParameterTainted();
result.source = XFactory.createReferencedXMethod(dbc);
result.setPC(dbc.getPC());
push(result);
return;
} else if (seen == INVOKESTATIC && methodName.equals("asList") && clsName.equals("java/util/Arrays")) {
/* Item requestParameter = */pop();
Item result = new Item(JAVA_UTIL_ARRAYS_ARRAY_LIST);
push(result);
return;
} else if (seen == INVOKESTATIC && signature.equals("(Ljava/util/List;)Ljava/util/List;")
&& clsName.equals("java/util/Collections")) {
Item requestParameter = pop();
if (requestParameter.getSignature().equals(JAVA_UTIL_ARRAYS_ARRAY_LIST)) {
Item result = new Item(JAVA_UTIL_ARRAYS_ARRAY_LIST);
push(result);
return;
}
push(requestParameter); // fall back to standard logic
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (initializingServletWriter)
this.getStackItem(0).setIsServletWriter();
if ((sawUnknownAppend || appenderValue != null || servletRequestParameterTainted) && getStackDepth() > 0) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (!sawUnknownAppend && servletRequestParameterTainted) {
i.injection = topItem.injection;
i.setServletParameterTainted();
}
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
if (i.injection == null)
i.injection = sbItem.injection;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i);
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) &&
(methodName.equals("nextInt") && signature.equals("()I")
|| methodName.equals("nextLong") && signature.equals("()J"))
) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
push(i);
} else if (methodName.equals("size") && signature.equals("()I")
&& Subtypes2.instanceOf(ClassName.toDottedClassName(clsName), "java.util.Collection")) {
Item i = pop();
if (i.getSpecialKind() == Item.NOT_SPECIAL)
i.setSpecialKind(Item.NON_NEGATIVE);
push(i);
} else if (ClassName.isMathClass(clsName) && methodName.equals("abs")) {
Item i = pop();
if (i.getSpecialKind() == Item.HASHCODE_INT)
i.setSpecialKind(Item.MATH_ABS_OF_HASHCODE);
else if (i.getSpecialKind() == Item.RANDOM_INT)
i.setSpecialKind(Item.MATH_ABS_OF_RANDOM);
else
i.setSpecialKind(Item.MATH_ABS);
push(i);
} else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I") || seen == INVOKESTATIC
&& clsName.equals("java/lang/System") && methodName.equals("identityHashCode")
&& signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
push(i);
} else if (topIsTainted
&& (methodName.startsWith("encode") && clsName.equals("javax/servlet/http/HttpServletResponse") || methodName
.equals("trim") && clsName.equals("java/lang/String"))) {
Item i = pop();
i.setSpecialKind(Item.SERVLET_REQUEST_TAINTED);
i.injection = injection;
push(i);
}
if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG2) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG2) {
if (intoSize == fromSize)
System.out.println("Merging items");
else
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG2) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
boolean encountedTop;
boolean backwardsBranch;
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
public static class JumpInfo {
final Map<Integer, List<Item>> jumpEntries;
final Map<Integer, List<Item>> jumpStackEntries;
final BitSet jumpEntryLocations;
JumpInfo(Map<Integer, List<Item>> jumpEntries, Map<Integer, List<Item>> jumpStackEntries, BitSet jumpEntryLocations) {
this.jumpEntries = jumpEntries;
this.jumpStackEntries = jumpStackEntries;
this.jumpEntryLocations = jumpEntryLocations;
}
public int getNextJump(int pc) {
return jumpEntryLocations.nextSetBit(pc);
}
}
public static class JumpInfoFactory extends AnalysisFactory<JumpInfo> {
public JumpInfoFactory() {
super("Jump info for opcode stack", JumpInfo.class);
}
public JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);
JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
Code code = method.getCode();
if (code == null) {
return null;
}
final OpcodeStack stack = new OpcodeStack();
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
stack.sawOpcode(this, seen);
}
};
return computeJumpInfo(jclass, method, stack, branchAnalysis);
}
/**
* @param jclass
* @param method
* @param stack
* @param branchAnalysis
* @return
*/
public static JumpInfo computeJumpInfo(JavaClass jclass, Method method, final OpcodeStack stack,
DismantleBytecode branchAnalysis) {
branchAnalysis.setupVisitorForClass(jclass);
MethodInfo xMethod = (MethodInfo) XFactory.createXMethod(jclass, method);
int oldCount = 0;
while (true) {
stack.resetForMethodEntry0(ClassName.toSlashedClassName(jclass.getClassName()), method);
branchAnalysis.doVisitMethod(method);
int newCount = stack.jumpEntries.size();
if (xMethod.hasBackBranch() != stack.backwardsBranch) {
AnalysisContext.logError(
String.format("For %s, mismatch on existence of backedge: %s for precomputation, %s for bytecode analysis",
xMethod, xMethod.hasBackBranch(), stack.backwardsBranch));
}
if (newCount == oldCount || !stack.encountedTop || !stack.backwardsBranch)
break;
oldCount = newCount;
}
return new JumpInfo(stack.jumpEntries, stack.jumpStackEntries, stack.jumpEntryLocations);
}
}
public boolean isJumpTarget(int pc) {
return jumpEntryLocations.get(pc);
}
private void addJumpValue(int from, int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues);
if (from >= target)
backwardsBranch = true;
List<Item> atTarget = jumpEntries.get(Integer.valueOf(target));
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(Integer.valueOf(target), new ArrayList<Item>(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(Integer.valueOf(target), new ArrayList<Item>(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(Integer.valueOf(target));
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
DismantleBytecode v;
public void learnFrom(JumpInfo info) {
jumpEntries = new HashMap<Integer, List<Item>>(info.jumpEntries);
jumpStackEntries = new HashMap<Integer, List<Item>>(info.jumpStackEntries);
jumpEntryLocations = (BitSet) info.jumpEntryLocations.clone();
}
public void initialize() {
setTop(false);
jumpEntries.clear();
jumpStackEntries.clear();
jumpEntryLocations.clear();
encountedTop = false;
backwardsBranch = false;
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
zeroOneComing = -1;
registerTestedFoundToBeNonnegative = -1;
setReachOnlyByBranch(false);
}
public int resetForMethodEntry(final DismantleBytecode visitor) {
this.v = visitor;
initialize();
int result = resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null)
return result;
if (useIterativeAnalysis) {
JumpInfo jump = null;
if (visitor instanceof OpcodeStackDetector.WithCustomJumpInfo) {
jump = ((OpcodeStackDetector.WithCustomJumpInfo) visitor).customJumpInfo();
} else if (!visitor.getClass().isAnnotationPresent(OpcodeStack.CustomUserValue.class))
jump = getJumpInfo();
if (jump != null) {
learnFrom(jump);
}
}
return result;
}
private JumpInfo getJumpInfo() {
IAnalysisCache analysisCache = Global.getAnalysisCache();
XMethod xMethod = XFactory.createXMethod(v.getThisClass(), v.getMethod());
if (xMethod instanceof MethodInfo) {
MethodInfo mi = (MethodInfo) xMethod;
if (!mi.hasBackBranch())
return null;
}
try {
return analysisCache.getMethodAnalysis(JumpInfo.class, xMethod.getMethodDescriptor());
} catch (CheckedAnalysisException e) {
AnalysisContext.logError("Error getting jump information", e);
return null;
}
}
private int resetForMethodEntry0(PreorderVisitor visitor) {
return resetForMethodEntry0(visitor.getClassName(), visitor.getMethod());
}
private int resetForMethodEntry0(@SlashedClassName String className, Method m) {
methodName = m.getName();
if (DEBUG)
System.out.println("
String signature = m.getSignature();
stack.clear();
lvValues.clear();
top = false;
encountedTop = false;
backwardsBranch = false;
setReachOnlyByBranch(false);
seenTransferOfControl = false;
exceptionHandlers.clear();
Code code = m.getCode();
if (code != null) {
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for (CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG)
System.out.println(" --- " + className + " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className + ";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue(reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
AnalysisContext.logError("Can't get stack offset " + stackOffset + " from " + stack.toString() + " @ " + v.getPC()
+ " in " + v.getFullyQualifiedMethodName(), new IllegalArgumentException(stackOffset
+ " is not a value stack offset"));
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("Requested item at offset " + stackOffset + " in a stack of size "
+ stack.size() + ", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size() - 1);
}
public void replaceTop(Item newTop) {
pop();
push(newTop);
}
private void pop(int count) {
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass) c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", Integer.valueOf(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
} else if (c instanceof ConstantFloat)
push(new Item("F", Float.valueOf(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", Double.valueOf(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", Long.valueOf(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected");
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("Ljava/lang/Object;", register);
}
private void pushByIntMath(DismantleBytecode dbc, int seen, Item lhs, Item rhs) {
Item newValue = new Item("I");
if (lhs == null || rhs == null) {
push(newValue);
return;
}
try {
if (DEBUG)
System.out.println("pushByIntMath " + dbc.getFullyQualifiedMethodName() + " @ " + dbc.getPC() + " : " + lhs
+ OPCODE_NAMES[seen] + rhs);
if (rhs.getConstant() != null && lhs.getConstant() != null) {
int lhsValue = constantToInt(lhs);
int rhsValue = constantToInt(rhs);
if ((seen == IDIV || seen == IREM) && rhsValue == 0) {
push(newValue);
return;
}
switch (seen) {
case IADD:
newValue = new Item("I", lhsValue + rhsValue);
break;
case ISUB:
newValue = new Item("I", lhsValue - rhsValue);
break;
case IMUL:
newValue = new Item("I", lhsValue * rhsValue);
break;
case IDIV:
newValue = new Item("I", lhsValue / rhsValue);
break;
case IREM:
newValue = new Item("I", lhsValue % rhsValue);
break;
case IAND:
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue & 0xff) == 0 && rhsValue != 0 || (lhsValue & 0xff) == 0 && lhsValue != 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
break;
case IOR:
newValue = new Item("I", lhsValue | rhsValue);
break;
case IXOR:
newValue = new Item("I", lhsValue ^ rhsValue);
break;
case ISHL:
newValue = new Item("I", lhsValue << rhsValue);
if (rhsValue >= 8)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
break;
case ISHR:
newValue = new Item("I", lhsValue >> rhsValue);
break;
case IUSHR:
newValue = new Item("I", lhsValue >>> rhsValue);
}
} else if ((seen == ISHL || seen == ISHR || seen == IUSHR)) {
if (rhs.getConstant() != null) {
int constant = constantToInt(rhs);
if ((constant & 0x1f) == 0)
newValue = new Item(lhs);
else if (seen == ISHL && (constant & 0x1f) >= 8)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
} else if (lhs.getConstant() != null) {
int constant = constantToInt(lhs);
if (constant == 0)
newValue = new Item("I", 0);
}
} else if (lhs.getConstant() != null && seen == IAND) {
int value = constantToInt(lhs);
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
else if (value >= 0)
newValue.setSpecialKind(Item.NON_NEGATIVE);
} else if (rhs.getConstant() != null && seen == IAND) {
int value = constantToInt(rhs);
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
else if (value >= 0)
newValue.setSpecialKind(Item.NON_NEGATIVE);
} else if (seen == IAND && lhs.getSpecialKind() == Item.ZERO_MEANS_NULL) {
newValue.setSpecialKind(Item.ZERO_MEANS_NULL);
newValue.setPC(lhs.getPC());
} else if (seen == IAND && rhs.getSpecialKind() == Item.ZERO_MEANS_NULL) {
newValue.setSpecialKind(Item.ZERO_MEANS_NULL);
newValue.setPC(rhs.getPC());
} else if (seen == IOR && lhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) {
newValue.setSpecialKind(Item.NONZERO_MEANS_NULL);
newValue.setPC(lhs.getPC());
} else if (seen == IOR && rhs.getSpecialKind() == Item.NONZERO_MEANS_NULL) {
newValue.setSpecialKind(Item.NONZERO_MEANS_NULL);
newValue.setPC(rhs.getPC());
}
} catch (ArithmeticException e) {
assert true; // ignore it
} catch (RuntimeException e) {
String msg = "Error processing2 " + lhs + OPCODE_NAMES[seen] + rhs + " @ " + dbc.getPC() + " in "
+ dbc.getFullyQualifiedMethodName();
AnalysisContext.logError(msg, e);
}
if (lhs.getSpecialKind() == Item.INTEGER_SUM && rhs.getConstant() != null) {
int rhsValue = constantToInt(rhs);
if (seen == IDIV && rhsValue == 2 || seen == ISHR && rhsValue == 1)
newValue.setSpecialKind(Item.AVERAGE_COMPUTED_USING_DIVISION);
}
if (seen == IADD && newValue.getSpecialKind() == Item.NOT_SPECIAL && lhs.getConstant() == null
&& rhs.getConstant() == null)
newValue.setSpecialKind(Item.INTEGER_SUM);
if (seen == IREM && lhs.getSpecialKind() == Item.HASHCODE_INT)
newValue.setSpecialKind(Item.HASHCODE_INT_REMAINDER);
if (seen == IREM && lhs.getSpecialKind() == Item.RANDOM_INT)
newValue.setSpecialKind(Item.RANDOM_INT_REMAINDER);
if (seen == IREM && lhs.checkForIntegerMinValue()) {
if (rhs.getConstant() != null) {
int rhsValue = constantToInt(rhs);
if (!Util.isPowerOfTwo(rhsValue))
newValue.setSpecialKind(lhs.getSpecialKindForRemainder());
} else
newValue.setSpecialKind(lhs.getSpecialKindForRemainder());
}
if (DEBUG)
System.out.println("push: " + newValue);
newValue.setPC(dbc.getPC());
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
long lhsValue = constantToLong(lhs);
if (seen == LSHL) {
newValue = new Item("J", Long.valueOf(lhsValue << constantToInt(rhs)));
if (constantToInt(rhs) >= 8)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
} else if (seen == LSHR)
newValue = new Item("J", Long.valueOf(lhsValue >> constantToInt(rhs)));
else if (seen == LUSHR)
newValue = new Item("J", Long.valueOf(lhsValue >>> constantToInt(rhs)));
else {
long rhsValue = constantToLong(rhs);
if (seen == LADD)
newValue = new Item("J", Long.valueOf(lhsValue + rhsValue));
else if (seen == LSUB)
newValue = new Item("J", Long.valueOf(lhsValue - rhsValue));
else if (seen == LMUL)
newValue = new Item("J", Long.valueOf(lhsValue * rhsValue));
else if (seen == LDIV)
newValue = new Item("J", Long.valueOf(lhsValue / rhsValue));
else if (seen == LAND) {
newValue = new Item("J", Long.valueOf(lhsValue & rhsValue));
if ((rhsValue & 0xff) == 0 && rhsValue != 0 || (lhsValue & 0xff) == 0 && lhsValue != 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
} else if (seen == LOR)
newValue = new Item("J", Long.valueOf(lhsValue | rhsValue));
else if (seen == LXOR)
newValue = new Item("J", Long.valueOf(lhsValue ^ rhsValue));
else if (seen == LREM)
newValue = new Item("J", Long.valueOf(lhsValue % rhsValue));
}
} else if (rhs.getConstant() != null && seen == LSHL && constantToInt(rhs) >= 8)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
else if (lhs.getConstant() != null && seen == LAND && (constantToLong(lhs) & 0xff) == 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
else if (rhs.getConstant() != null && seen == LAND && (constantToLong(rhs) & 0xff) == 0)
newValue.setSpecialKind(Item.LOW_8_BITS_CLEAR);
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) {
if (seen == FADD)
result = new Item("F", Float.valueOf(constantToFloat(it2) + constantToFloat(it)));
else if (seen == FSUB)
result = new Item("F", Float.valueOf(constantToFloat(it2) - constantToFloat(it)));
else if (seen == FMUL)
result = new Item("F", Float.valueOf(constantToFloat(it2) * constantToFloat(it)));
else if (seen == FDIV)
result = new Item("F", Float.valueOf(constantToFloat(it2) / constantToFloat(it)));
else if (seen == FREM)
result = new Item("F", Float.valueOf(constantToFloat(it2) % constantToFloat(it)));
else
result = new Item("F");
} else {
result = new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) {
if (seen == DADD)
result = new Item("D", Double.valueOf(constantToDouble(it2) + constantToDouble(it)));
else if (seen == DSUB)
result = new Item("D", Double.valueOf(constantToDouble(it2) - constantToDouble(it)));
else if (seen == DMUL)
result = new Item("D", Double.valueOf(constantToDouble(it2) * constantToDouble(it)));
else if (seen == DDIV)
result = new Item("D", Double.valueOf(constantToDouble(it2) / constantToDouble(it)));
else if (seen == DREM)
result = new Item("D", Double.valueOf(constantToDouble(it2) % constantToDouble(it)));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
if (dbc.getNameConstantOperand().equals("<init>") && signature.endsWith(")V") && popThis) {
pop(PreorderVisitor.getNumberArguments(signature));
Item constructed = pop();
if (getStackDepth() > 0) {
Item next = getStackItem(0);
if (constructed.equals(next)) {
next.source = XFactory.createReferencedXMethod(dbc);
next.pc = dbc.getPC();
}
}
return;
}
pop(PreorderVisitor.getNumberArguments(signature) + (popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature(), dbc);
}
public Item getItemMethodInvokedOn(DismantleBytecode dbc) {
int opcode = dbc.getOpcode();
switch (opcode) {
case INVOKEVIRTUAL:
case INVOKEINTERFACE:
case INVOKESPECIAL:
String signature = dbc.getSigConstantOperand();
int stackOffset = PreorderVisitor.getNumberArguments(signature);
return getStackItem(stackOffset);
}
throw new IllegalArgumentException("Not visiting an instance method call");
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s, DismantleBytecode dbc) {
if ("V".equals(s))
return;
Item item = new Item(s, (Object) null);
if (dbc != null)
item.setPC(dbc.getPC());
if ("B".equals(s))
item.setSpecialKind(Item.SIGNED_BYTE);
else if ("C".equals(s))
item.setSpecialKind(Item.NON_NEGATIVE);
push(item);
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for (Item i : lvValues)
if (i != null) {
if (i.registerNumber == register)
i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register)
i.fieldLoadedFromRegister = -1;
}
for (Item i : stack)
if (i != null) {
if (i.registerNumber == register)
i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register)
i.fieldLoadedFromRegister = -1;
}
}
setLVValue(register, it);
}
private void pushByLocalLoad(String signature, int register) {
Item oldItem = getLVValue(register);
Item newItem;
if (oldItem == null) {
newItem = new Item(signature);
newItem.registerNumber = register;
} else {
newItem = oldItem;
if (newItem.signature.equals("Ljava/lang/Object;") && !signature.equals("Ljava/lang/Object;")) {
newItem = new Item(oldItem);
newItem.signature = signature;
}
if (newItem.getRegisterNumber() < 0) {
if (newItem == oldItem)
newItem = new Item(oldItem);
newItem.registerNumber = register;
}
}
push(newItem);
}
private void setLVValue(int index, Item value) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index));
lvValues.set(index, value);
}
public Item getLVValue(int index) {
if (index >= lvValues.size())
return new Item();
Item item = lvValues.get(index);
if (item != null)
return item;
return new Item();
}
public int getNumLocalValues() {
return lvValues.size();
}
/**
* @param top
* The top to set.
*/
private void setTop(boolean top) {
if (top) {
if (!this.top)
this.top = true;
} else if (this.top)
this.top = false;
}
/**
* @return Returns the top.
*/
public boolean isTop() {
if (top)
return true;
return false;
}
/**
* @param reachOnlyByBranch
* The reachOnlyByBranch to set.
*/
void setReachOnlyByBranch(boolean reachOnlyByBranch) {
if (reachOnlyByBranch)
setTop(true);
this.reachOnlyByBranch = reachOnlyByBranch;
}
/**
* @return Returns the reachOnlyByBranch.
*/
boolean isReachOnlyByBranch() {
return reachOnlyByBranch;
}
}
// vim:ts=4
|
package com.wilutions.joa.outlook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javafx.application.Platform;
import com.wilutions.com.AsyncResult;
import com.wilutions.com.BackgTask;
import com.wilutions.com.ByRef;
import com.wilutions.com.CoClass;
import com.wilutions.com.ComException;
import com.wilutions.com.Dispatch;
import com.wilutions.com.IDispatch;
import com.wilutions.com.JoaDll;
import com.wilutions.com.WindowsUtil;
import com.wilutions.joa.OfficeAddin;
import com.wilutions.joa.OfficeAddinUtil;
import com.wilutions.joa.fx.ModalDialogFX;
import com.wilutions.mslib.outlook.ApplicationEvents_11;
import com.wilutions.mslib.outlook.FormRegion;
import com.wilutions.mslib.outlook.MAPIFolder;
import com.wilutions.mslib.outlook.OlFormRegionIcon;
import com.wilutions.mslib.outlook.OlFormRegionMode;
import com.wilutions.mslib.outlook.OlFormRegionSize;
import com.wilutions.mslib.outlook.PropertyPages;
import com.wilutions.mslib.outlook.Search;
import com.wilutions.mslib.outlook._Explorer;
import com.wilutions.mslib.outlook._FormRegionStartup;
import com.wilutions.mslib.outlook.impl._ExplorerImpl;
public abstract class OutlookAddin extends OfficeAddin<com.wilutions.mslib.outlook.Application> implements
ApplicationEvents_11, _FormRegionStartup {
public OutlookAddin() {
super(com.wilutions.mslib.outlook.Application.class);
}
public String toString() {
return "[OutlookAddin " + super.toString() + " ]";
}
public <T> void showModalDialogAsync(ModalDialogFX<T> dialog, AsyncResult<T> asyncResult) {
_Explorer _exp = getApplication().ActiveExplorer();
_ExplorerImpl explorer = Dispatch.as(_exp, _ExplorerImpl.class);
dialog.showAsync(explorer, asyncResult);
}
/**
* Check whether an item (ContactItem, MailItem, ...) is modified.
*
* @param item
* ContactItem, MailItem, ...
* @return true, if the item is modified (and not jet saved).
* @throws ComException
* @see http
* ://msdn.microsoft.com/en-us/library/office/gg583879(v=office.14).
* aspx
*/
public static boolean isItemModified(Dispatch item) throws ComException {
final int dispidModified = 0xF024;
Object ret = item._get(dispidModified);
return (Boolean) ret;
}
@Override
public Object GetFormRegionStorage(String FormRegionName, IDispatch Item, Integer LCID,
OlFormRegionMode FormRegionMode, OlFormRegionSize FormRegionSize) throws ComException {
try {
return OutlookFormRegion.getFormRegionOfs();
} catch (IOException e) {
throw new ComException(e.toString());
}
}
protected OutlookFormRegion createFormRegion(FormRegion formRegion) throws ComException {
OutlookFormRegion ret = null;
String formRegionClassName = "";
try {
// The internal name of the form region is its Java class name.
// This is ensured by the process of registration.
formRegionClassName = formRegion.getInternalName();
Class<?> formRegionClass = Class.forName(formRegionClassName);
ret = (OutlookFormRegion) formRegionClass.newInstance();
} catch (Throwable e) {
throw new ComException("Cannot create form region, internal name=" + formRegionClassName, e);
}
return ret;
}
@Override
public final void BeforeFormRegionShow(final FormRegion formRegion) throws ComException {
BackgTask.run(() -> {
final OutlookFormRegion myFormRegion = createFormRegion(formRegion);
myFormRegion.showAsync(formRegion, null);
});
}
@Override
public Object GetFormRegionManifest(String FormRegionName, Integer LCID) throws ComException {
String ret = null;
String resourceName = FormRegionName.replace('.', '/') + ".xml";
try {
ClassLoader classLoader = this.getClass().getClassLoader();
ret = OfficeAddinUtil.getResourceAsString(classLoader, resourceName);
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
@Override
public Object GetFormRegionIcon(String FormRegionName, Integer LCID, OlFormRegionIcon Icon) throws ComException {
return null;
}
@Override
public void onStartup() throws ComException {
}
@Override
public void onQuit() throws ComException {
//System.exit(0);
Platform.exit();
}
@Override
public void onItemSend(IDispatch Item, ByRef<Boolean> Cancel) throws ComException {
}
@Override
public void onNewMail() throws ComException {
}
@Override
public void onReminder(IDispatch Item) throws ComException {
}
@Override
public void onOptionsPagesAdd(PropertyPages Pages) throws ComException {
}
@Override
public void onAdvancedSearchComplete(Search SearchObject) throws ComException {
}
@Override
public void onAdvancedSearchStopped(Search SearchObject) throws ComException {
}
@Override
public void onMAPILogonComplete() throws ComException {
}
@Override
public void onNewMailEx(String EntryIDCollection) throws ComException {
}
@Override
public void onItemLoad(IDispatch Item) throws ComException {
}
@Override
public void onBeforeFolderSharingDialog(MAPIFolder FolderToShare, ByRef<Boolean> Cancel) throws ComException {
}
/**
* Assign the viewType as view for the folder.
*
* @param folder
* Outlook folder
* @param viewType
* FolderView class.
* @param title
* Folder view title. This title is displayed in the caption bar
* of Outlook.
* @param viewId
* Arbitrary string to be passed in
* {@link FolderView#setId(String)}.
* @throws IOException
*/
public void assignFolderView(MAPIFolder folder, Class<? extends FolderView> viewType, String title, String viewId)
throws IOException {
String webViewFile = createFolderViewHtml(viewType, title, viewId);
folder.setWebViewURL(webViewFile);
folder.setWebViewOn(true);
}
/**
* Create an HTML file to display the given view in a folder.
*
* @param viewType
* FolderView class. The explorer will call createWebView() to
* create an instance.
* @param title
* Folder view title. This title is displayed in the caption bar
* of Outlook.
* @param viewId
* Arbitrary string to be passed in
* {@link FolderView#setId(String)}.
* @return Temporary file that defines the folder's view.
* @throws ComException
*/
protected String createFolderViewHtml(Class<? extends FolderView> viewType, String title, String viewId)
throws ComException {
PrintWriter pr = null;
File webViewFile = null;
CoClass coclass = this.getClass().getAnnotation(CoClass.class);
if (coclass == null) {
throw new ComException("OfficeAddin misses annotation CoClass");
}
String progId = coclass.progId();
try {
File tempDir = JoaDll.getTempDir();
tempDir.mkdirs();
String fileName = viewType.getName() + "-" + viewId + ".htm";
fileName = WindowsUtil.replaceForbiddenFileNameCharsWithUnderscore(fileName);
webViewFile = new File(tempDir, fileName);
String html = OfficeAddinUtil.getResourceAsString(this.getClass().getClassLoader(),
"com/wilutions/joa/outlook/HomePage.html");
html = html.replace("__webview__title__", title);
html = html.replace("__addin__progid__", progId);
html = html.replace("__view__class__name__", viewType.getName());
html = html.replace("__view__id__", viewId);
pr = new PrintWriter(new OutputStreamWriter(new FileOutputStream(webViewFile), "UTF-8"));
pr.println(html);
} catch (Throwable e) {
throw new ComException(e.toString());
} finally {
if (pr != null) {
pr.close();
}
}
return webViewFile.getAbsolutePath();
}
@Deprecated
public void createWebView(final String hwndJoaCtrlStr, final String viewClassName, final String viewId) {
// Create the Java window as a child window of the JoaBridgeCtrl.
try {
final Class<?> viewClass = Class.forName(viewClassName);
final FolderView viewObject = (FolderView) viewClass.newInstance();
viewObject.setId(viewId);
long hwndJoaCtrl = Long.parseLong(hwndJoaCtrlStr);
viewObject.createAndShowEmbeddedWindowAsync(hwndJoaCtrl, null);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
package com.psddev.dari.db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.UuidUtils;
public class SqlVendor {
public enum ColumnType {
BYTES_LONG,
BYTES_SHORT,
DOUBLE,
INTEGER,
POINT,
SERIAL,
UUID;
}
public static final String RECORD_TABLE_NAME = "Record";
public static final String RECORD_UPDATE_TABLE_NAME = "RecordUpdate";
public static final String SYMBOL_TABLE_NAME = "Symbol";
public static final int MAX_BYTES_SHORT_LENGTH = 500;
private SqlDatabase database;
public SqlDatabase getDatabase() {
return database;
}
public void setDatabase(SqlDatabase database) {
this.database = database;
}
public Set<String> getTables(Connection connection) throws SQLException {
Set<String> tableNames = new HashSet<String>();
String catalog = connection.getCatalog();
DatabaseMetaData meta = connection.getMetaData();
ResultSet result = meta.getTables(catalog, null, null, null);
try {
while (result.next()) {
String name = result.getString("TABLE_NAME");
if (name != null) {
tableNames.add(name);
}
}
} finally {
result.close();
}
return tableNames;
}
public boolean hasInRowIndex(Connection connection, String recordTable) throws SQLException {
boolean newHasInRowIndex = false;
String catalog = connection.getCatalog();
DatabaseMetaData meta = connection.getMetaData();
ResultSet result = meta.getColumns(catalog, null, recordTable, null);
try {
while (result.next()) {
String name = result.getString("COLUMN_NAME");
if (name != null && name.equalsIgnoreCase(SqlDatabase.IN_ROW_INDEX_COLUMN)) {
newHasInRowIndex = true;
break;
}
}
} finally {
result.close();
}
return newHasInRowIndex;
}
public boolean supportsDistinctBlob() {
return true;
}
public void appendIdentifier(StringBuilder builder, String identifier) {
builder.append('"');
builder.append(identifier.replace("\"", "\"\""));
builder.append('"');
}
public void appendBindLocation(StringBuilder builder, Location location, List<Object> parameters) {
builder.append("GeomFromText(?)");
if (parameters != null) {
parameters.add(location == null ? null : "POINT(" + location.getX() + " " + location.getY() + ")");
}
}
public void appendBindUuid(StringBuilder builder, UUID uuid, List<Object> parameters) {
builder.append('?');
if (parameters != null) {
parameters.add(uuid == null ? null : UuidUtils.toBytes(uuid));
}
}
public void appendBindString(StringBuilder builder, String value, List<Object> parameters) {
builder.append('?');
if (parameters != null) {
parameters.add(value == null ? null : value.getBytes(StringUtils.UTF_8));
}
}
public void appendBindValue(StringBuilder builder, Object value, List<Object> parameters) {
if (value instanceof Location) {
appendBindLocation(builder, (Location) value, parameters);
} else if (value instanceof UUID) {
appendBindUuid(builder, (UUID) value, parameters);
} else if (value instanceof String) {
appendBindString(builder, (String) value, parameters);
} else {
builder.append('?');
if (parameters != null) {
parameters.add(value);
}
}
}
public void appendValue(StringBuilder builder, Object value) {
if (value == null) {
builder.append("NULL");
} else if (value instanceof Number) {
builder.append(value);
} else if (value instanceof UUID) {
appendUuid(builder, (UUID) value);
} else if (value instanceof byte[]) {
appendBytes(builder, (byte[]) value);
} else if (value instanceof Location) {
Location valueLocation = (Location) value;
builder.append("GeomFromText('POINT(");
builder.append(valueLocation.getX());
builder.append(' ');
builder.append(valueLocation.getY());
builder.append(")')");
} else {
appendBytes(builder, value.toString().getBytes(StringUtils.UTF_8));
}
}
protected void appendUuid(StringBuilder builder, UUID value) {
builder.append('{');
builder.append(value);
builder.append('}');
}
protected void appendBytes(StringBuilder builder, byte[] value) {
builder.append("X'");
builder.append(StringUtils.hex(value));
builder.append('\'');
}
protected void appendWhereRegion(StringBuilder builder, Region region, String field) {
List<Location> locations = region.getLocations();
builder.append("MBRCONTAINS(GEOMFROMTEXT('POLYGON((");
for (Location location : locations) {
builder.append(SqlDatabase.quoteValue(location.getX()));
builder.append(' ');
builder.append(SqlDatabase.quoteValue(location.getY()));
builder.append(", ");
}
builder.setLength(builder.length() - 2);
builder.append("))'), ");
builder.append(field);
builder.append(')');
}
protected void appendNearestLocation(
StringBuilder orderbyBuilder,
StringBuilder selectBuilder,
Location location, String field) {
StringBuilder builder = new StringBuilder();
builder.append("GLENGTH(LINESTRING(GEOMFROMTEXT('POINT(");
builder.append(location.getX());
builder.append(' ');
builder.append(location.getY());
builder.append(")'), ");
builder.append(field);
builder.append("))");
orderbyBuilder.append(builder);
selectBuilder.append(builder);
}
protected String rewriteQueryWithLimitClause(String query, int limit, long offset) {
return String.format("%s LIMIT %d OFFSET %d", query, limit, offset);
}
/** Creates a table using the given parameters. */
public void createTable(
SqlDatabase database,
String tableName,
Map<String, ColumnType> columns,
List<String> primaryKeyColumns)
throws SQLException {
if (database.hasTable(tableName)) {
return;
}
StringBuilder ddlBuilder = new StringBuilder();
appendTablePrefix(ddlBuilder, tableName, columns);
for (Map.Entry<String, ColumnType> entry : columns.entrySet()) {
appendColumn(ddlBuilder, entry.getKey(), entry.getValue());
ddlBuilder.append(", ");
}
if (primaryKeyColumns == null || primaryKeyColumns.isEmpty()) {
ddlBuilder.setLength(ddlBuilder.length() - 2);
} else {
appendPrimaryKey(ddlBuilder, primaryKeyColumns);
}
appendTableSuffix(ddlBuilder, tableName, columns);
executeDdl(database, ddlBuilder);
}
/** Creates an index using the given parameters. */
public void createIndex(
SqlDatabase database,
String tableName,
List<String> columns,
boolean isUnique)
throws SQLException {
StringBuilder ddlBuilder = new StringBuilder();
appendIndexPrefix(ddlBuilder, tableName, columns, isUnique);
appendIdentifier(ddlBuilder, columns.get(0));
for (int i = 1, size = columns.size(); i < size; ++ i) {
ddlBuilder.append(", ");
appendIdentifier(ddlBuilder, columns.get(i));
}
appendIndexSuffix(ddlBuilder, tableName, columns, isUnique);
executeDdl(database, ddlBuilder);
}
public void createRecord(SqlDatabase database) throws SQLException {
if (database.hasTable(RECORD_TABLE_NAME)) {
return;
}
Map<String, ColumnType> columns = new LinkedHashMap<String, ColumnType>();
columns.put(SqlDatabase.ID_COLUMN, ColumnType.UUID);
columns.put(SqlDatabase.TYPE_ID_COLUMN, ColumnType.UUID);
columns.put(SqlDatabase.DATA_COLUMN, ColumnType.BYTES_LONG);
createTable(database, RECORD_TABLE_NAME, columns, Arrays.asList(SqlDatabase.TYPE_ID_COLUMN, SqlDatabase.ID_COLUMN));
createIndex(database, RECORD_TABLE_NAME, Arrays.asList(SqlDatabase.ID_COLUMN), true);
}
private static final Map<SqlIndex, ColumnType> INDEX_TYPES; static {
Map<SqlIndex, ColumnType> m = new HashMap<SqlIndex, ColumnType>();
m.put(SqlIndex.LOCATION, ColumnType.POINT);
m.put(SqlIndex.NUMBER, ColumnType.DOUBLE);
m.put(SqlIndex.STRING, ColumnType.BYTES_SHORT);
m.put(SqlIndex.UUID, ColumnType.UUID);
INDEX_TYPES = m;
}
public void createRecordIndex(
SqlDatabase database,
String tableName,
SqlIndex... types)
throws SQLException {
if (database.hasTable(tableName)) {
return;
}
Map<String, ColumnType> columns = new LinkedHashMap<String, ColumnType>();
columns.put(SqlDatabase.ID_COLUMN, ColumnType.UUID);
columns.put(SqlDatabase.SYMBOL_ID_COLUMN, ColumnType.INTEGER);
for (int i = 0, length = types.length; i < length; ++ i) {
columns.put(SqlDatabase.VALUE_COLUMN + (i == 0 ? "" : i + 1), INDEX_TYPES.get(types[i]));
}
List<String> primaryKeyColumns = new ArrayList<String>(columns.keySet());
primaryKeyColumns.add(primaryKeyColumns.remove(0));
createTable(database, tableName, columns, primaryKeyColumns);
createIndex(database, tableName, Arrays.asList(SqlDatabase.ID_COLUMN), false);
}
public void createRecordUpdate(SqlDatabase database) throws SQLException {
if (database.hasTable(RECORD_UPDATE_TABLE_NAME)) {
return;
}
Map<String, ColumnType> columns = new LinkedHashMap<String, ColumnType>();
columns.put(SqlDatabase.ID_COLUMN, ColumnType.UUID);
columns.put(SqlDatabase.TYPE_ID_COLUMN, ColumnType.UUID);
columns.put(SqlDatabase.UPDATE_DATE_COLUMN, ColumnType.DOUBLE);
createTable(database, RECORD_UPDATE_TABLE_NAME, columns, Arrays.asList(SqlDatabase.ID_COLUMN));
createIndex(database, RECORD_UPDATE_TABLE_NAME, Arrays.asList(SqlDatabase.TYPE_ID_COLUMN, SqlDatabase.UPDATE_DATE_COLUMN), false);
createIndex(database, RECORD_UPDATE_TABLE_NAME, Arrays.asList(SqlDatabase.UPDATE_DATE_COLUMN), false);
}
public void createSymbol(SqlDatabase database) throws SQLException {
if (database.hasTable(SYMBOL_TABLE_NAME)) {
return;
}
Map<String, ColumnType> columns = new LinkedHashMap<String, ColumnType>();
columns.put(SqlDatabase.SYMBOL_ID_COLUMN, ColumnType.SERIAL);
columns.put(SqlDatabase.VALUE_COLUMN, ColumnType.BYTES_SHORT);
createTable(database, SYMBOL_TABLE_NAME, columns, Arrays.asList(SqlDatabase.SYMBOL_ID_COLUMN));
createIndex(database, SYMBOL_TABLE_NAME, Arrays.asList(SqlDatabase.VALUE_COLUMN), true);
}
protected void appendTablePrefix(
StringBuilder builder,
String name,
Map<String, ColumnType> columns) {
builder.append("CREATE TABLE ");
appendIdentifier(builder, name);
builder.append(" (");
}
protected void appendTableSuffix(
StringBuilder builder,
String name,
Map<String, ColumnType> columns) {
builder.append(')');
}
protected void appendColumn(StringBuilder builder, String name, ColumnType type) {
appendColumnPrefix(builder, name);
switch (type) {
case BYTES_LONG :
appendColumnTypeBytesLong(builder);
break;
case BYTES_SHORT :
appendColumnTypeBytesShort(builder);
break;
case DOUBLE :
appendColumnTypeDouble(builder);
break;
case INTEGER :
appendColumnTypeInteger(builder);
break;
case POINT :
appendColumnTypePoint(builder);
break;
case SERIAL :
appendColumnTypeSerial(builder);
break;
case UUID :
appendColumnTypeUuid(builder);
break;
}
}
protected void appendColumnPrefix(StringBuilder builder, String name) {
appendIdentifier(builder, name);
builder.append(' ');
}
protected void appendColumnTypeBytesLong(StringBuilder builder) {
builder.append("BIT VARYING NOT NULL");
}
protected void appendColumnTypeBytesShort(StringBuilder builder) {
builder.append("BIT VARYING(");
builder.append(MAX_BYTES_SHORT_LENGTH * 8);
builder.append(") NOT NULL");
}
protected void appendColumnTypeDouble(StringBuilder builder) {
builder.append("DOUBLE NOT NULL");
}
protected void appendColumnTypeInteger(StringBuilder builder) {
builder.append("INT NOT NULL");
}
protected void appendColumnTypePoint(StringBuilder builder) {
builder.append("POINT NOT NULL");
}
protected void appendColumnTypeSerial(StringBuilder builder) {
builder.append("SERIAL NOT NULL");
}
protected void appendColumnTypeUuid(StringBuilder builder) {
builder.append("UUID NOT NULL");
}
protected void appendPrimaryKey(StringBuilder builder, List<String> columns) {
builder.append("PRIMARY KEY (");
appendIdentifier(builder, columns.get(0));
for (int i = 1, size = columns.size(); i < size; ++ i) {
builder.append(", ");
appendIdentifier(builder, columns.get(i));
}
builder.append(')');
}
protected void appendIndexPrefix(
StringBuilder builder,
String tableName,
List<String> columns,
boolean isUnique) {
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.append("k_");
nameBuilder.append(tableName);
for (String column : columns) {
nameBuilder.append('_');
nameBuilder.append(column);
}
builder.append("CREATE");
if (isUnique) {
builder.append(" UNIQUE");
}
builder.append(" INDEX ");
appendIdentifier(builder, nameBuilder.toString());
builder.append(" ON ");
appendIdentifier(builder, tableName);
builder.append(" (");
}
protected void appendIndexSuffix(
StringBuilder builder,
String tableName,
List<String> columns,
boolean isUnique) {
builder.append(')');
}
private void executeDdl(SqlDatabase database, StringBuilder ddlBuilder) throws SQLException {
String ddl = ddlBuilder.toString();
ddlBuilder.setLength(0);
Connection connection = database.openConnection();
try {
Statement statement = connection.createStatement();
try {
statement.execute(ddl);
} finally {
statement.close();
}
} finally {
database.closeConnection(connection);
}
}
protected void appendSelectFields(StringBuilder builder, List<String> fields) {
appendIdentifier(builder, SqlDatabase.DATA_COLUMN);
}
public boolean isDuplicateKeyException(SQLException ex) {
return "23000".equals(ex.getSQLState());
}
public String convertRawToStringSql(String field) {
return "CONVERT(" + field + " USING utf8)";
}
public UUID getUuid(ResultSet result, int col) throws SQLException {
return UuidUtils.fromBytes(result.getBytes(col));
}
public String getSelectTimestampMillisSql() {
// This should return the entire select statement, including the SELECT and FROM clauses, if necessary.
throw new DatabaseException(this.getDatabase(), "getTimestampSelectSql is not implemented for this vendor.");
}
// These are all very vendor-specific.
public void appendMetricUpdateDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, double amount, long eventDate, boolean increment, boolean updateFuture) {
// This DOES shift the decimal place and round to 6 places.
// columnIdentifier is "`data`" - already quoted if it needs to be
throw new DatabaseException(this.getDatabase(), "appendMetricUpdateDataSql: Metrics is not fully implemented for this vendor.");
}
public void appendMetricFixDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, long eventDate, double cumulativeAmount, double amount) {
// This DOES shift the decimal place and round to 6 places.
// columnIdentifier is "`data`" - already quoted if it needs to be
throw new DatabaseException(this.getDatabase(), "appendMetricFixDataSql: Metrics is not fully implemented for this vendor.");
}
public void appendMetricSelectAmountSql(StringBuilder str, String columnIdentifier, int position) {
// This does NOT shift the decimal place or round to 6 places. Do it yourself AFTER any other arithmetic to avoid rounding errors.
// position is 1 or 2 (use the MetricDatabase.*_POSITION constants)
// columnIdentifier is "`data`" or "MAX(`data`)" - already quoted if it needs to be
throw new DatabaseException(this.getDatabase(), "appendMetricSelectAmountSql: Metrics is not fully implemented for this vendor.");
}
public void appendMetricSelectTimestampSql(StringBuilder str, String columnIdentifier) {
// This does NOT shift the decimal place - the result will need to be multiplied
// by MetricDatabase.DATE_DECIMAL_SHIFT to get a timestamp in milliseconds.
// columnIdentifier is "`data`" or "MAX(`data`)" - already escaped
throw new DatabaseException(this.getDatabase(), "appendMetricSelectTimestampSql: Metrics is not fully implemented for this vendor.");
}
public void appendMetricDateFormatTimestampSql(StringBuilder str, String columnIdentifier, MetricInterval metricInterval) {
// This DOES apply MetricDatabase.DATE_DECIMAL_SHIFT and returns SQL to provide a string formatted according to MetricInterval.getSqlTruncatedDateFormat(SqlVendor)
throw new DatabaseException(this.getDatabase(), "appendMetricDateFormatTimestampSql: Metrics is not fully implemented for this vendor.");
}
public void appendMetricEncodeTimestampSql(StringBuilder str, List<Object> parameters, long timestamp, Character rpadHexChar) {
// This accepts a normal timestamp and DOES apply MetricDatabase.DATE_DECIMAL_SHIFT
throw new DatabaseException(this.getDatabase(), "appendMetricEncodeTimestampSql: Metrics is not fully implemented for this vendor.");
}
public void appendBindMetricBytes(StringBuilder str, byte[] bytes, List<Object> parameters) {
appendBindValue(str, bytes, parameters);
}
public void appendMetricDataBytes(StringBuilder str, String columnIdentifier) {
// columnIdentifier is "`data`" or "MAX(`data`)" - already escaped
str.append(columnIdentifier);
}
public static class H2 extends SqlVendor {
@Override
protected void appendUuid(StringBuilder builder, UUID value) {
builder.append('\'');
builder.append(value);
builder.append('\'');
}
@Override
protected void appendColumnTypeBytesLong(StringBuilder builder) {
builder.append("LONGVARBINARY NOT NULL");
}
@Override
protected void appendColumnTypeBytesShort(StringBuilder builder) {
builder.append("VARBINARY(");
builder.append(MAX_BYTES_SHORT_LENGTH);
builder.append(") NOT NULL");
}
@Override
protected void appendColumnTypePoint(StringBuilder builder) {
builder.append("DOUBLE NOT NULL");
}
@Override
public boolean isDuplicateKeyException(SQLException ex) {
return "23001".equals(ex.getSQLState()) || "23505".equals(ex.getSQLState());
}
@Override
public String convertRawToStringSql(String field) {
return "UTF8TOSTRING(" + field + ")";
}
}
public static class MySQL extends SqlVendor {
private Boolean hasUdfGetFields;
private Boolean hasUdfIncrementMetric;
@Override
public void appendIdentifier(StringBuilder builder, String identifier) {
builder.append('`');
builder.append(identifier.replace("`", "``"));
builder.append('`');
}
@Override
protected void appendUuid(StringBuilder builder, UUID value) {
appendBytes(builder, UuidUtils.toBytes(value));
}
@Override
protected void appendTableSuffix(
StringBuilder builder,
String name,
Map<String, ColumnType> columns) {
builder.append(") ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_bin");
}
@Override
protected void appendColumnTypeBytesLong(StringBuilder builder) {
builder.append("LONGBLOB NOT NULL");
}
@Override
protected void appendColumnTypeBytesShort(StringBuilder builder) {
builder.append("VARBINARY(");
builder.append(MAX_BYTES_SHORT_LENGTH);
builder.append(") NOT NULL");
}
@Override
protected void appendColumnTypeSerial(StringBuilder builder) {
builder.append("INT NOT NULL AUTO_INCREMENT");
}
@Override
protected void appendColumnTypeUuid(StringBuilder builder) {
builder.append("BINARY(16) NOT NULL");
}
@Override
protected void appendSelectFields(StringBuilder builder, List<String> fields) {
SqlDatabase database = getDatabase();
if (hasUdfGetFields == null) {
Connection connection = database.openConnection();
try {
Statement statement = connection.createStatement();
try {
ResultSet result = statement.executeQuery("SELECT dari_get_fields('{}', 'test')");
try {
hasUdfGetFields = true;
} finally {
result.close();
}
} finally {
statement.close();
}
} catch (SQLException error) {
if ("42000".equals(error.getSQLState())) {
hasUdfGetFields = false;
}
} finally {
database.closeConnection(connection);
}
}
if (Boolean.TRUE.equals(hasUdfGetFields)) {
builder.append("dari_get_fields(r.");
appendIdentifier(builder, SqlDatabase.DATA_COLUMN);
for (ObjectField field : database.getEnvironment().getFields()) {
builder.append(", ");
appendValue(builder, field.getInternalName());
}
for (String field : fields) {
builder.append(", ");
appendValue(builder, field);
}
builder.append(')');
} else {
builder.append("r.");
appendIdentifier(builder, SqlDatabase.DATA_COLUMN);
}
}
@Override
public String getSelectTimestampMillisSql() {
return "SELECT UNIX_TIMESTAMP()*1000";
}
@Override
public void appendMetricUpdateDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, double amount, long eventDate, boolean increment, boolean updateFuture) {
SqlDatabase database = getDatabase();
if (hasUdfIncrementMetric == null) {
Connection connection = database.openConnection();
try {
Statement statement = connection.createStatement();
try {
ResultSet result = statement.executeQuery("SELECT dari_increment_metric(null, 0, 0)");
try {
hasUdfIncrementMetric = true;
} finally {
result.close();
}
} finally {
statement.close();
}
} catch (SQLException error) {
if ("42000".equals(error.getSQLState())) {
hasUdfIncrementMetric = false;
}
} finally {
database.closeConnection(connection);
}
}
if (hasUdfIncrementMetric) {
// dari_increment_metric() does NOT shift the decimal place for us.
long adjustedAmount = (long) (amount * MetricDatabase.AMOUNT_DECIMAL_SHIFT);
sql.append("dari_increment_metric(");
sql.append(columnIdentifier);
sql.append(',');
if (increment) { // increment
// cumulativeAmount should always be incremented
appendBindValue(sql, adjustedAmount, parameters);
sql.append(',');
if (updateFuture) {
// if we're updating future rows, only update the interval amount if it's the exact eventDate
sql.append("IF (");
appendIdentifier(sql, columnIdentifier);
sql.append(" <= ");
appendMetricEncodeTimestampSql(sql, parameters, eventDate, 'F');
sql.append(','); // if it's the exact date, then update the amount
appendBindValue(sql, adjustedAmount, parameters);
sql.append(','); // if it's a date in the future, leave the date alone
appendBindValue(sql, 0, parameters);
sql.append(')');
} else {
appendBindValue(sql, adjustedAmount, parameters);
}
} else { // only used for set, not increment
appendBindValue(sql, amount, parameters);
sql.append(',');
appendBindValue(sql, amount, parameters);
}
sql.append(')');
} else {
sql.append(" UNHEX(");
sql.append("CONCAT(");
// timestamp
appendHexEncodeExistingTimestampSql(sql, columnIdentifier);
sql.append(',');
// cumulativeAmount and amount
if (increment) {
// cumulativeAmount should always be incremented
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.CUMULATIVEAMOUNT_POSITION, amount);
sql.append(',');
if (updateFuture) {
// if we're updating future rows, only update the interval amount if it's the exact eventDate
sql.append("IF (");
appendIdentifier(sql, columnIdentifier);
sql.append(" <= ");
appendMetricEncodeTimestampSql(sql, parameters, eventDate, 'F');
sql.append(','); // if it's the exact date, then update the amount
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, amount);
sql.append(','); // if it's a date in the future, leave the date alone
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, 0);
sql.append(')');
} else {
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, amount);
}
} else {
appendHexEncodeSetAmountSql(sql, parameters, amount);
sql.append(',');
appendHexEncodeSetAmountSql(sql, parameters, amount);
}
sql.append(" )");
sql.append(" )");
}
}
@Override
public void appendMetricFixDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, long eventDate, double cumulativeAmount, double amount) {
sql.append(" UNHEX(");
sql.append("CONCAT(");
// timestamp
appendHexEncodeExistingTimestampSql(sql, columnIdentifier);
sql.append(',');
// cumulativeAmount
appendHexEncodeSetAmountSql(sql, parameters, cumulativeAmount);
sql.append(',');
// amount
appendHexEncodeSetAmountSql(sql, parameters, amount);
sql.append(" )");
sql.append(" )");
}
@Override
public void appendMetricSelectAmountSql(StringBuilder str, String columnIdentifier, int position) {
str.append("CONV(");
str.append("HEX(");
str.append("SUBSTR(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1+MetricDatabase.DATE_BYTE_SIZE + ((position-1)*MetricDatabase.AMOUNT_BYTE_SIZE));
str.append(',');
appendValue(str, MetricDatabase.AMOUNT_BYTE_SIZE);
str.append(')');
str.append(')');
str.append(", 16, 10)");
}
@Override
public void appendMetricEncodeTimestampSql(StringBuilder str, List<Object> parameters, long timestamp, Character rpadHexChar) {
str.append("UNHEX(");
appendHexEncodeTimestampSql(str, parameters, timestamp, rpadHexChar);
str.append(')');
}
@Override
public void appendMetricSelectTimestampSql(StringBuilder str, String columnIdentifier) {
str.append("CONV(");
str.append("HEX(");
str.append("SUBSTR(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1);
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE);
str.append(')');
str.append(')');
str.append(", 16, 10)");
}
@Override
public void appendMetricDateFormatTimestampSql(StringBuilder str, String columnIdentifier, MetricInterval metricInterval) {
str.append("DATE_FORMAT(FROM_UNIXTIME(");
appendMetricSelectTimestampSql(str, columnIdentifier);
str.append('*');
appendValue(str, (MetricDatabase.DATE_DECIMAL_SHIFT/1000L));
str.append("),");
appendValue(str, metricInterval.getSqlTruncatedDateFormat(this));
str.append(')');
}
private void appendHexEncodeSetAmountSql(StringBuilder str, List<Object> parameters, double amount) {
str.append("LPAD(");
str.append("HEX(");
appendBindValue(str, (long) (amount * MetricDatabase.AMOUNT_DECIMAL_SHIFT), parameters);
str.append(" )");
str.append(", "+(MetricDatabase.AMOUNT_BYTE_SIZE*2)+", '0')");
}
private void appendHexEncodeExistingTimestampSql(StringBuilder str, String columnIdentifier) {
// columnIdentifier is "data" or "max(`data`)" - already quoted
str.append("HEX(");
str.append("SUBSTR(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1);
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE);
str.append(')');
str.append(')');
}
private void appendHexEncodeTimestampSql(StringBuilder str, List<Object> parameters, long timestamp, Character rpadChar) {
if (rpadChar != null) {
str.append("RPAD(");
}
str.append("LPAD(");
str.append("HEX(");
if (parameters == null) {
appendValue(str, (int) (timestamp / MetricDatabase.DATE_DECIMAL_SHIFT));
} else {
appendBindValue(str, (int) (timestamp / MetricDatabase.DATE_DECIMAL_SHIFT), parameters);
}
str.append(')');
str.append(", "+(MetricDatabase.DATE_BYTE_SIZE*2)+", '0')");
if (rpadChar != null) {
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE*2+MetricDatabase.AMOUNT_BYTE_SIZE*2+MetricDatabase.AMOUNT_BYTE_SIZE*2);
str.append(", '");
str.append(rpadChar);
str.append("')");
}
}
private void appendHexEncodeIncrementAmountSql(StringBuilder str, List<Object> parameters, String columnIdentifier, int position, double amount) {
// position is 1 or 2
// columnIdentifier is "`data`" unless it is aliased - already quoted
str.append("LPAD(");
str.append("HEX(");
// conv(hex(substr(data, 1+4, 8)), 16, 10)
appendMetricSelectAmountSql(str, columnIdentifier, position);
str.append('+');
appendBindValue(str, (long)(amount * MetricDatabase.AMOUNT_DECIMAL_SHIFT), parameters);
str.append(" )");
str.append(", "+(MetricDatabase.AMOUNT_BYTE_SIZE*2)+", '0')");
}
}
public static class PostgreSQL extends SqlVendor {
@Override
public void appendIdentifier(StringBuilder builder, String identifier) {
builder.append(identifier);
}
@Override
protected void appendUuid(StringBuilder builder, UUID value) {
builder.append("'" + value.toString() + "'");
}
@Override
public void appendValue(StringBuilder builder, Object value) {
if (value instanceof String) {
builder.append("'" + value + "'");
} else if (value instanceof Location) {
Location valueLocation = (Location) value;
builder.append("ST_GeomFromText('POINT(");
builder.append(valueLocation.getX());
builder.append(' ');
builder.append(valueLocation.getY());
builder.append(")', 4326)");
} else {
super.appendValue(builder, value);
}
}
@Override
protected void appendBytes(StringBuilder builder, byte[] value) {
builder.append('\'');
builder.append(new String(value, StringUtils.UTF_8).replace("'", "''"));
builder.append('\'');
}
@Override
protected void appendWhereRegion(StringBuilder builder, Region region, String field) {
builder.append(field);
builder.append(" <-> ST_SetSRID(ST_MakePoint(");
builder.append(region.getX());
builder.append(", ");
builder.append(region.getY());
builder.append("), 4326) < ");
builder.append(region.getRadius());
}
@Override
protected void appendNearestLocation(
StringBuilder orderbyBuilder,
StringBuilder selectBuilder,
Location location, String field) {
StringBuilder builder = new StringBuilder();
builder.append(field);
builder.append(" <-> ST_SetSRID(ST_MakePoint(");
builder.append(location.getX());
builder.append(", ");
builder.append(location.getY());
builder.append("), 4326) ");
orderbyBuilder.append(builder);
selectBuilder.append(builder);
}
@Override
public void appendBindLocation(StringBuilder builder, Location location, List<Object> parameters) {
builder.append("ST_GeomFromText(?, 4326)");
if (location != null && parameters != null) {
parameters.add("POINT(" + location.getX() + " " + location.getY() + ")");
}
}
@Override
public void appendBindUuid(StringBuilder builder, UUID uuid, List<Object> parameters) {
builder.append('?');
if (uuid != null && parameters != null) {
parameters.add(uuid);
}
}
@Override
public String convertRawToStringSql(String field) {
return "CONVERT_FROM(" + field + ", 'UTF-8')";
}
@Override
public UUID getUuid(ResultSet result, int col) throws SQLException {
return UuidUtils.fromString(result.getString(col));
}
@Override
public String getSelectTimestampMillisSql() {
return "SELECT ROUND(EXTRACT(EPOCH FROM NOW())*1000)";
}
@Override
public void appendMetricUpdateDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, double amount, long eventDate, boolean increment, boolean updateFuture) {
sql.append("CONCAT(");
// timestamp
appendHexEncodeExistingTimestampSql(sql, columnIdentifier);
sql.append(',');
// cumulativeAmount and amount
if (increment) {
// cumulativeAmount should always be incremented
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.CUMULATIVEAMOUNT_POSITION, amount);
sql.append(',');
if (updateFuture) {
// if we're updating future rows, only update the interval amount if it's the exact eventDate
sql.append("CASE WHEN ");
appendIdentifier(sql, columnIdentifier);
sql.append(" <= ");
appendMetricEncodeTimestampSql(sql, parameters, eventDate, 'F');
sql.append(" THEN "); // if it's the exact date, then update the amount
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, amount);
sql.append(" ELSE "); // if it's a date in the future, leave the date alone
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, 0);
sql.append(" END ");
} else {
appendHexEncodeIncrementAmountSql(sql, parameters, columnIdentifier, MetricDatabase.AMOUNT_POSITION, amount);
}
} else {
appendHexEncodeSetAmountSql(sql, parameters, amount);
sql.append(',');
appendHexEncodeSetAmountSql(sql, parameters, amount);
}
sql.append(" )");
}
@Override
public void appendMetricFixDataSql(StringBuilder sql, String columnIdentifier, List<Object> parameters, long eventDate, double cumulativeAmount, double amount) {
sql.append("CONCAT(");
// timestamp
appendHexEncodeExistingTimestampSql(sql, columnIdentifier);
sql.append(',');
// cumulativeAmount
appendHexEncodeSetAmountSql(sql, parameters, cumulativeAmount);
sql.append(',');
// amount
appendHexEncodeSetAmountSql(sql, parameters, amount);
sql.append(" )");
}
@Override
public void appendMetricEncodeTimestampSql(StringBuilder str, List<Object> parameters, long timestamp, Character rpadHexChar) {
if (rpadHexChar != null) {
str.append("RPAD(");
}
str.append("LPAD(");
str.append("TO_HEX(");
if (parameters == null) {
appendValue(str, (int) (timestamp / MetricDatabase.DATE_DECIMAL_SHIFT));
} else {
appendBindValue(str, (int) (timestamp / MetricDatabase.DATE_DECIMAL_SHIFT), parameters);
}
str.append(')');
str.append(", "+(MetricDatabase.DATE_BYTE_SIZE*2)+", '0')");
if (rpadHexChar != null) {
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE*2+MetricDatabase.AMOUNT_BYTE_SIZE*2+MetricDatabase.AMOUNT_BYTE_SIZE*2);
str.append(", '");
str.append(rpadHexChar);
str.append("')");
}
}
@Override
public void appendMetricSelectAmountSql(StringBuilder str, String columnIdentifier, int position) {
str.append(" ('x'||");
str.append("SUBSTRING(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1+(MetricDatabase.DATE_BYTE_SIZE*2) + ((position-1)*MetricDatabase.AMOUNT_BYTE_SIZE*2));
str.append(',');
appendValue(str, MetricDatabase.AMOUNT_BYTE_SIZE*2);
str.append(')');
str.append(")::bit(");
str.append(MetricDatabase.AMOUNT_BYTE_SIZE*8);
str.append(")::bigint");
}
@Override
public void appendMetricSelectTimestampSql(StringBuilder str, String columnIdentifier) {
str.append(" ('x'||");
str.append("SUBSTRING(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1);
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE*2);
str.append(')');
str.append(")::bit(");
str.append(MetricDatabase.DATE_BYTE_SIZE*8);
str.append(")::bigint");
}
@Override
public void appendMetricDateFormatTimestampSql(StringBuilder str, String columnIdentifier, MetricInterval metricInterval) {
str.append("TO_CHAR(TO_TIMESTAMP(");
appendMetricSelectTimestampSql(str, columnIdentifier);
str.append('*');
appendValue(str, (MetricDatabase.DATE_DECIMAL_SHIFT/1000L));
str.append(")::TIMESTAMP,");
appendValue(str, metricInterval.getSqlTruncatedDateFormat(this));
str.append(')');
}
@Override
public void appendBindMetricBytes(StringBuilder str, byte[] bytes, List<Object> parameters) {
appendValue(str, StringUtils.hex(bytes));
}
@Override
public void appendMetricDataBytes(StringBuilder str, String columnIdentifier) {
str.append("DECODE(");
str.append(columnIdentifier);
str.append(", 'HEX')");
}
private void appendHexEncodeExistingTimestampSql(StringBuilder str, String columnIdentifier) {
// columnIdentifier is "data" or "max(`data`)" - already quoted
str.append("SUBSTRING(");
str.append(columnIdentifier);
str.append(',');
appendValue(str, 1);
str.append(',');
appendValue(str, MetricDatabase.DATE_BYTE_SIZE*2);
str.append(')');
}
private void appendHexEncodeIncrementAmountSql(StringBuilder str, List<Object> parameters, String columnIdentifier, int position, double amount) {
// position is 1 or 2
// columnIdentifier is "`data`" unless it is aliased - already quoted
str.append("LPAD(");
str.append("TO_HEX(");
// conv(hex(substr(data, 1+4, 8)), 16, 10)
appendMetricSelectAmountSql(str, columnIdentifier, position);
str.append('+');
appendBindValue(str, (long)(amount * MetricDatabase.AMOUNT_DECIMAL_SHIFT), parameters);
str.append(" )");
str.append(", "+(MetricDatabase.AMOUNT_BYTE_SIZE*2)+", '0')");
}
private void appendHexEncodeSetAmountSql(StringBuilder str, List<Object> parameters, double amount) {
str.append("LPAD(");
str.append("TO_HEX(");
appendBindValue(str, (long) (amount * MetricDatabase.AMOUNT_DECIMAL_SHIFT), parameters);
str.append(" )");
str.append(", "+(MetricDatabase.AMOUNT_BYTE_SIZE*2)+", '0')");
}
}
public static class Oracle extends SqlVendor {
@Override
public void appendIdentifier(StringBuilder builder, String identifier) {
builder.append(identifier.replace("\"", "\"\""));
}
@Override
protected void appendUuid(StringBuilder builder, UUID value) {
appendBytes(builder, UuidUtils.toBytes(value));
}
@Override
protected void appendBytes(StringBuilder builder, byte[] value) {
builder.append("HEXTORAW('");
builder.append(StringUtils.hex(value));
builder.append("')");
}
@Override
protected void appendWhereRegion(StringBuilder builder, Region region, String field) {
throw new UnsupportedIndexException(this, field);
}
@Override
protected void appendNearestLocation(
StringBuilder orderbyBuilder,
StringBuilder selectBuilder,
Location location, String field) {
throw new UnsupportedIndexException(this, field);
}
@Override
protected String rewriteQueryWithLimitClause(String query, int limit, long offset) {
return String.format(
"SELECT * FROM " +
" (SELECT a.*, ROWNUM rnum FROM " +
" (%s) a " +
" WHERE ROWNUM <= %d)" +
" WHERE rnum >= %d", query, offset + limit, offset);
}
@Override
public void appendBindLocation(StringBuilder builder, Location location, List<Object> parameters) {
builder.append("SDO_GEOMETRY(2001, 8307, SDO_POINT_TYPE(?, ?, NULL), NULL, NULL)");
if (location != null && parameters != null) {
parameters.add(location.getX());
parameters.add(location.getY());
}
}
@Override
public Set<String> getTables(Connection connection) throws SQLException {
Set<String> tableNames = new HashSet<String>();
Statement statement = connection.createStatement();
try {
ResultSet result = statement.executeQuery("SELECT TABLE_NAME FROM USER_TABLES");
try {
while (result.next()) {
String name = result.getString("TABLE_NAME");
if (name != null) {
tableNames.add(name);
}
}
} finally {
result.close();
}
} finally {
statement.close();
}
return tableNames;
}
@Override
public boolean hasInRowIndex(Connection connection, String recordTable) throws SQLException {
PreparedStatement statement = connection.prepareStatement(
"SELECT 1 FROM USER_TAB_COLS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?");
try {
statement.setString(1, recordTable);
statement.setString(2, SqlDatabase.IN_ROW_INDEX_COLUMN);
ResultSet result = statement.executeQuery();
try {
while (result.next()) {
return true;
}
} finally {
result.close();
}
} finally {
statement.close();
}
return false;
}
@Override
public boolean supportsDistinctBlob() {
return false;
}
// This is untested.
// @Override
// public String getSelectTimestampMillisSql() {
// return "SELECT ROUND((SYSTIMESTAMP - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000) FROM DUAL";
}
}
|
package org.ofbiz.base.util;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Cato: Randomization utilities.
*/
public class UtilRandom {
/**
* Method should generate random number that represents a time between two
* dates.
*
* @return
*/
private static long getRandomTimeBetweenTwoDates(Timestamp beginDate, Map<String, Object> context) {
long beginTime, endTime;
Calendar cal = Calendar.getInstance();
if (context.get("maxDate") != null) {
endTime = ((Timestamp) context.get("maxDate")).getTime();
} else {
endTime = cal.getTimeInMillis();
}
if (beginDate != null) {
beginTime = beginDate.getTime();
} else if (context.get("minDate") != null) {
beginTime = ((Timestamp) context.get("minDate")).getTime();
} else {
cal.add(Calendar.DATE, -180);
beginTime = cal.getTimeInMillis();
}
long diff = endTime - beginTime + 1;
beginTime = beginTime + (long) (Math.random() * diff);
return beginTime;
}
public static String generateRandomDate(Map<String, Object> context) {
return generateRandomDate(null, context);
}
public static String generateRandomDate(Date beginDate, Map<String, Object> context) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date randomDate;
if (UtilValidate.isNotEmpty(beginDate)) {
randomDate = new Date(getRandomTimeBetweenTwoDates(new Timestamp(beginDate.getTime()), context));
} else {
randomDate = new Date(getRandomTimeBetweenTwoDates(null, context));
}
return dateFormat.format(randomDate);
}
public static Timestamp generateRandomTimestamp(Map<String, Object> context) {
return generateRandomTimestamp(null, context);
}
public static Timestamp generateRandomTimestamp(Date beginDate, Map<String, Object> context) {
Timestamp randomDate;
if (UtilValidate.isNotEmpty(beginDate)) {
randomDate = new Timestamp(getRandomTimeBetweenTwoDates(new Timestamp(beginDate.getTime()), context));
} else {
randomDate = new Timestamp(getRandomTimeBetweenTwoDates(null, context));
}
return randomDate;
}
public static int random(List myList) {
int size = myList.size();
int index = new Random().nextInt(size);
return index;
}
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
}
public static int getRandomEvenInt(int min, int max) {
int x = getRandomInt(min, max);
while (x % 2 != 0) {
x = getRandomInt(min, max);
}
return x;
}
public static int getRandomInt(int min, int max) {
Random rand = new Random();
int x = rand.nextInt(max - min + 1) + min;
x = rand.nextInt(max - min + 1) + min;
return x;
}
}
|
package org.diirt.ui.tools;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Probe extends Application {
@Override
public void start(Stage stage) throws Exception {
stage.setTitle("diirt - Probe");
stage.setScene(createScene());
stage.show();
}
public static Scene createScene() throws Exception {
Parent root = FXMLLoader.load(Probe.class.getResource("/fxml/Probe.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add("/styles/Styles.css");
return scene;
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
|
package org.ccnx.ccn.config;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ccnx.ccn.impl.CCNNetworkManager.NetworkProtocol;
import org.ccnx.ccn.impl.encoding.BinaryXMLCodec;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
/**
* A class encapsulating a number of system-level default parameters as well as helper
* functionality for managing log output and printing debug data. Eventually will
* be supported by an external configuration file for controlling key parameters.
*
* The current basic logging infrastructure uses standard Java logging,
* controlled only by a system-wide Level value.
* That value, as well as other logging-related parameters are currently managed by the
* Log class, but should eventually migrate here. There is a facility for selective logging
* control, by turning on and off logging for individual named "modules"; though that has
* not yet been widely utilized. Eventually we should support separate log Level settings
* for each module when necessary.
*/
public class SystemConfiguration {
/**
* String constants, to define these in one place.
*/
public static final String STRING_FALSE = "false";
public static final String STRING_TRUE = "true";
/**
* System operation timeout. Very long timeout used to wait for system events
* such as stopping Daemons.
*/
public final static int SYSTEM_STOP_TIMEOUT = 30000;
/**
* Very long timeout for network operations, in msec..
*/
public final static int MAX_TIMEOUT = 10000;
/**
* Extra-long timeout, e.g. to get around reexpression timing issues.
*/
public final static int EXTRA_LONG_TIMEOUT = 6000;
/**
* Longer timeout, for e.g. waiting for a latest version and being sure you
* have anything available locally in msec.
*/
public final static int LONG_TIMEOUT = 3000;
/**
* Medium timeout, used as system default.
*/
public static final int MEDIUM_TIMEOUT = 1000;
/**
* Short timeout; for things you expect to exist or not exist locally.
*/
public static final int SHORT_TIMEOUT = 300;
protected static final String CCN_PROTOCOL_PROPERTY = "org.ccnx.protocol";
public static final String DEFAULT_PROTOCOL = "TCP"; // UDP or TCP allowed
public static NetworkProtocol AGENT_PROTOCOL = null; // Set up below
public static final String AGENT_PROTOCOL_PROPERTY = "org.ccnx.agent.protocol";
public static final String AGENT_PROTOCOL_ENVIRONMENT_VARIABLE = "CCN_AGENT_PROTOCOL";
/**
* Controls whether we should exit on severe errors in the network manager. This should only be
* set true in automated tests. In live running code, we hope to be able to recover instead.
*/
public static final boolean DEFAULT_EXIT_ON_NETWORK_ERROR = false;
public static boolean EXIT_ON_NETWORK_ERROR = DEFAULT_EXIT_ON_NETWORK_ERROR;
public static final String CCN_EXIT_ON_NETWORK_ERROR_PROPERTY = "org.ccnx.ExitOnNetworkError";
public static final String CCN_EXIT_ON_NETWORK_ERROR_ENVIRONMENT_VARIABLE = "CCN_EXIT_ON_NETERROR";
/**
* Interest reexpression period
* TODO - This is (currently) an architectual constant. Not all code has been changed to use it.
*/
public static final int INTEREST_REEXPRESSION_DEFAULT = 4000;
public enum DEBUGGING_FLAGS {DEBUG_SIGN, DEBUG_VERIFY, DUMP_DAEMONCMD, REPO_EXITDUMP};
protected static HashMap<DEBUGGING_FLAGS,Boolean> DEBUG_FLAG_VALUES = new HashMap<DEBUGGING_FLAGS,Boolean>();
/**
* Property to set debug flags.
*/
public static final String DEBUG_FLAG_PROPERTY = "com.parc.ccn.DebugFlags";
/**
* Property to set directory to dump debug data.
*/
public static final String DEBUG_DATA_DIRECTORY_PROPERTY = "com.parc.ccn.DebugDataDirectory";
protected static final String DEFAULT_DEBUG_DATA_DIRECTORY = "./CCN_DEBUG_DATA";
public static String DEBUG_DATA_DIRECTORY = null;
/**
* Tunable timeouts as well as timeout defaults.
*/
/**
* Enumerated Name List looping timeout in ms.
* Default is 300ms
*/
protected static final String CHILD_WAIT_INTERVAL_PROPERTY = "org.ccnx.EnumList.WaitInterval";
public final static int CHILD_WAIT_INTERVAL_DEFAULT = 300;
public static int CHILD_WAIT_INTERVAL = CHILD_WAIT_INTERVAL_DEFAULT;
/**
* Default timeout for the flow controller
*/
protected static final String FC_TIMEOUT_PROPERTY = "org.ccnx.fc.timeout";
public final static int FC_TIMEOUT_DEFAULT = MAX_TIMEOUT;
public static int FC_TIMEOUT = FC_TIMEOUT_DEFAULT;
/**
* Allow override to only save to a local repository
*/
protected static final String FC_LOCALREPOSITORY_PROPERTY = "org.ccnx.fc.localrepository";
protected final static String FC_LOCALREPOSITORY_ENV_VAR = "FC_LOCALREPOSITORY";
public final static boolean FC_LOCALREPOSITORY_DEFAULT = false;
public static boolean FC_LOCALREPOSITORY = FC_LOCALREPOSITORY_DEFAULT;
/**
* How long to wait for a service discovery timeout in CCNNetworkManager, in ms
*
* This should be longer than the interest timeout to permit at least one re-expression.
*/
protected static final String CCNDID_DISCOVERY_TIMEOUT_PROPERTY = "org.ccnx.ccndid.timeout";
public final static int CCNDID_DISCOVERY_TIMEOUT_DEFAULT = 4200;
public static int CCNDID_DISCOVERY_TIMEOUT = CCNDID_DISCOVERY_TIMEOUT_DEFAULT;
/**
* Pipeline size for pipeline in CCNAbstractInputStream
* Default is 4
*/
protected static final String PIPELINE_SIZE_PROPERTY = "org.ccnx.PipelineSize";
protected static final String PIPELINE_SIZE_ENV_VAR = "JAVA_PIPELINE_SIZE";
public static int PIPELINE_SIZE = 4;
/**
* Pipeline segment attempts for pipeline in CCNAbstractInputStream
* Default is 5
*/
protected static final String PIPELINE_ATTEMPTS_PROPERTY = "org.ccnx.PipelineAttempts";
protected static final String PIPELINE_ATTEMPTS_ENV_VAR = "JAVA_PIPELINE_ATTEMPTS";
public static int PIPELINE_SEGMENTATTEMPTS = 5;
/**
* Pipeline round trip time factor for pipeline in CCNAbstractInputStream
* Default is 2
*/
protected static final String PIPELINE_RTT_PROPERTY = "org.ccnx.PipelineRTTFactor";
protected static final String PIPELINE_RTT_ENV_VAR = "JAVA_PIPELINE_RTTFACTOR";
public static int PIPELINE_RTTFACTOR = 2;
/**
* Pipeline stat printouts in CCNAbstractInputStream
* Default is off
*/
protected static final String PIPELINE_STATS_PROPERTY = "org.ccnx.PipelineStats";
protected static final String PIPELINE_STATS_ENV_VAR = "JAVA_PIPELINE_STATS";
public static boolean PIPELINE_STATS = false;
/**
* Backwards-compatible handling of old header names.
* Current default is true; eventually will be false.
*/
protected static final String OLD_HEADER_NAMES_PROPERTY = "org.ccnx.OldHeaderNames";
protected static final String OLD_HEADER_NAMES_ENV_VAR = "CCNX_OLD_HEADER_NAMES";
public static boolean OLD_HEADER_NAMES = true;
/**
* Timeout used for communication with local 'ccnd' for control operations.
*
* An example is Face Creation and Prefix Registration.
* Should be longer than the interest timeout to permit at least one re-expression.
* TODO - ccnop would properly be spelled ccndop
*/
protected static final String CCND_OP_TIMEOUT_PROPERTY = "org.ccnx.ccnop.timeout";
protected final static String CCND_OP_TIMEOUT_ENV_VAR = "CCND_OP_TIMEOUT";
public final static int CCND_OP_TIMEOUT_DEFAULT = 4200;
public static int CCND_OP_TIMEOUT = CCND_OP_TIMEOUT_DEFAULT;
/**
* System default timeout
*/
protected static final String CCNX_TIMEOUT_PROPERTY = "org.ccnx.default.timeout";
protected final static String CCNX_TIMEOUT_ENV_VAR = "CCNX_TIMEOUT";
public final static int CCNX_TIMEOUT_DEFAULT = EXTRA_LONG_TIMEOUT;
/**
* GetLatestVersion attempt timeout.
* TODO This timeout is set to MEDIUM_TIMEOUT to work around the problem
* in ccnd where some interests take >300ms (and sometimes longer, have seen periodic delays >800ms)
* when that bug is found and fixed, this can be reduced back to the SHORT_TIMEOUT.
* long attemptTimeout = SystemConfiguration.SHORT_TIMEOUT;
*/
protected static final String GLV_ATTEMPT_TIMEOUT_PROPERTY = "org.ccnx.glv.attempt.timeout";
protected final static String GLV_ATTEMPT_TIMEOUT_ENV_VAR = "GLV_ATTEMPT_TIMEOUT";
public final static int GLV_ATTEMPT_TIMEOUT_DEFAULT = SHORT_TIMEOUT;
public static int GLV_ATTEMPT_TIMEOUT = GLV_ATTEMPT_TIMEOUT_DEFAULT;
/**
* "Short timeout" that can be set
*/
protected static final String SETTABLE_SHORT_TIMEOUT_PROPERTY = "org.ccnx.short.timeout";
protected final static String SETTABLE_SHORT_TIMEOUT_ENV_VAR = "SETTABLE_SHORT_TIMEOUT";
public static int SETTABLE_SHORT_TIMEOUT = SHORT_TIMEOUT;
/**
* Settable system default timeout.
*/
protected static int _defaultTimeout = CCNX_TIMEOUT_DEFAULT;
/**
* Get system default timeout.
* @return the default timeout.
*/
public static int getDefaultTimeout() { return _defaultTimeout; }
/**
* Set system default timeout.
*/
public static void setDefaultTimeout(int newTimeout) { _defaultTimeout = newTimeout; }
/**
* No timeout. Should be single value used in all places in the code where you
* want to block forever.
*/
public final static int NO_TIMEOUT = -1;
/**
* Set the maximum number of attempts that VersioningProfile.getLatestVersion will
* try to get a later version of an object.
*/
public static final int GET_LATEST_VERSION_ATTEMPTS = 10;
/**
* Can set compile-time default encoding here. Choices are
* currently "Text" and "Binary", or better yet
* BinaryXMLCodec.codecName() or TextXMLCodec.codecName().
*/
protected static final String SYSTEM_DEFAULT_ENCODING = BinaryXMLCodec.codecName();
/**
* Run-time default. Set to command line property if given, if not,
* the system default above.
*/
protected static String DEFAULT_ENCODING = null;
/**
* Command-line property to set default encoding
* @return
*/
protected static final String DEFAULT_ENCODING_PROPERTY =
"com.parc.ccn.data.DefaultEncoding";
public static final int DEBUG_RADIX = 34;
/**
* Obtain the management bean for this runtime if it is available.
* The class of the management bean is discovered at runtime and there
* should be no static dependency on any particular bean class.
* @return the bean or null if none available
*/
public static Object getManagementBean() {
// Check if we already have a management bean; retrieve only
// once per VM
if (null != runtimeMXBean) {
return runtimeMXBean;
}
ClassLoader cl = SystemConfiguration.class.getClassLoader();
try {
Class<?> mgmtclass = cl.loadClass("java.lang.management.ManagementFactory");
Method getRuntimeMXBean = mgmtclass.getDeclaredMethod("getRuntimeMXBean", (Class[])null);
runtimeMXBean = getRuntimeMXBean.invoke(mgmtclass, (Object[])null);
} catch (Exception ex) {
Log.log(Level.WARNING, "Management bean unavailable: {0}", ex.getMessage());
}
return runtimeMXBean;
}
static {
// Allow override of default debug information.
String debugFlags = System.getProperty(DEBUG_FLAG_PROPERTY);
if (null != debugFlags) {
String [] flags = debugFlags.split(":");
for (int i=0; i < flags.length; ++i) {
setDebugFlag(flags[i]);
}
}
DEBUG_DATA_DIRECTORY = System.getProperty(DEBUG_DATA_DIRECTORY_PROPERTY, DEFAULT_DEBUG_DATA_DIRECTORY);
}
static {
// Allow override of basic protocol
String proto = SystemConfiguration.retrievePropertyOrEnvironmentVariable(AGENT_PROTOCOL_PROPERTY, AGENT_PROTOCOL_ENVIRONMENT_VARIABLE, DEFAULT_PROTOCOL);
boolean found = false;
for (NetworkProtocol p : NetworkProtocol.values()) {
String pAsString = p.toString();
if (proto.equalsIgnoreCase(pAsString)) {
Log.warning("CCN agent protocol changed to " + pAsString + " per property");
AGENT_PROTOCOL = p;
found = true;
break;
}
}
if (!found) {
System.err.println("The protocol must be UDP(17) or TCP (6)");
throw new IllegalArgumentException("Invalid protocol '" + proto + "' specified in " + AGENT_PROTOCOL_PROPERTY);
}
// Allow override of exit on network error
try {
EXIT_ON_NETWORK_ERROR = Boolean.parseBoolean(retrievePropertyOrEnvironmentVariable(CCN_EXIT_ON_NETWORK_ERROR_PROPERTY, CCN_EXIT_ON_NETWORK_ERROR_ENVIRONMENT_VARIABLE,
Boolean.toString(DEFAULT_EXIT_ON_NETWORK_ERROR)));
// Log.fine("CCND_OP_TIMEOUT = " + CCND_OP_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The exit on network error must be an boolean.");
throw e;
}
// Allow override of default enumerated name list child wait timeout.
try {
CHILD_WAIT_INTERVAL = Integer.parseInt(System.getProperty(CHILD_WAIT_INTERVAL_PROPERTY, Integer.toString(CHILD_WAIT_INTERVAL_DEFAULT)));
// Log.fine("CHILD_WAIT_INTERVAL = " + CHILD_WAIT_INTERVAL);
} catch (NumberFormatException e) {
System.err.println("The ChildWaitInterval must be an integer.");
throw e;
}
// Allow override of default pipeline size for CCNAbstractInputStream
try {
PIPELINE_SIZE = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_SIZE_PROPERTY, PIPELINE_SIZE_ENV_VAR, "4"));
//PIPELINE_SIZE = Integer.parseInt(System.getProperty(PIPELINE_SIZE_PROPERTY, "4"));
} catch (NumberFormatException e) {
System.err.println("The PipelineSize must be an integer.");
throw e;
}
// Allow override of default pipeline size for CCNAbstractInputStream
try {
PIPELINE_SEGMENTATTEMPTS = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_ATTEMPTS_PROPERTY, PIPELINE_ATTEMPTS_ENV_VAR, "5"));
//PIPELINE_SIZE = Integer.parseInt(System.getProperty(PIPELINE_SIZE_PROPERTY, "4"));
} catch (NumberFormatException e) {
System.err.println("The PipelineAttempts must be an integer.");
}
// Allow override of default pipeline rtt multiplication factor for CCNAbstractInputStream
try {
PIPELINE_RTTFACTOR = Integer.parseInt(retrievePropertyOrEnvironmentVariable(PIPELINE_RTT_PROPERTY, PIPELINE_RTT_ENV_VAR, "2"));
} catch (NumberFormatException e) {
System.err.println("The PipelineRTTFactor must be an integer.");
}
// Allow printing of pipeline stats in CCNAbstractInputStream
PIPELINE_STATS = Boolean.parseBoolean(retrievePropertyOrEnvironmentVariable(PIPELINE_STATS_PROPERTY, PIPELINE_STATS_ENV_VAR, STRING_FALSE));
// Allow override of default ccndID discovery timeout.
try {
CCNDID_DISCOVERY_TIMEOUT = Integer.parseInt(System.getProperty(CCNDID_DISCOVERY_TIMEOUT_PROPERTY, Integer.toString(CCNDID_DISCOVERY_TIMEOUT_DEFAULT)));
// Log.fine("CCNDID_DISCOVERY_TIMEOUT = " + CCNDID_DISCOVERY_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The ccndID discovery timeout must be an integer.");
throw e;
}
// Allow override of default flow controller timeout.
try {
FC_TIMEOUT = Integer.parseInt(System.getProperty(FC_TIMEOUT_PROPERTY, Integer.toString(FC_TIMEOUT_DEFAULT)));
// Log.fine("FC_TIMEOUT = " + FC_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The default flow controller timeout must be an integer.");
throw e;
}
// Allow override for local repository override
try {
FC_LOCALREPOSITORY = Boolean.parseBoolean(retrievePropertyOrEnvironmentVariable(FC_LOCALREPOSITORY_PROPERTY, FC_LOCALREPOSITORY_ENV_VAR, Boolean.toString(FC_LOCALREPOSITORY_DEFAULT)));
} catch (NumberFormatException e) {
System.err.println("The local repository flow controller override must be a boolean.");
throw e;
}
// Allow override of ccn default timeout.
try {
_defaultTimeout = Integer.parseInt(retrievePropertyOrEnvironmentVariable(CCNX_TIMEOUT_PROPERTY, CCNX_TIMEOUT_ENV_VAR, Integer.toString(CCNX_TIMEOUT_DEFAULT)));
// Log.fine("CCNX_TIMEOUT = " + CCNX_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The ccnd default timeout must be an integer.");
throw e;
}
// Allow override of ccnd op timeout.
try {
CCND_OP_TIMEOUT = Integer.parseInt(System.getProperty(CCND_OP_TIMEOUT_PROPERTY, Integer.toString(CCND_OP_TIMEOUT_DEFAULT)));
// Log.fine("CCND_OP_TIMEOUT = " + CCND_OP_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The ccnd op timeout must be an integer.");
throw e;
}
// Allow override of getLatestVersion attempt timeout.
try {
GLV_ATTEMPT_TIMEOUT = Integer.parseInt(retrievePropertyOrEnvironmentVariable(GLV_ATTEMPT_TIMEOUT_PROPERTY, GLV_ATTEMPT_TIMEOUT_ENV_VAR, Integer.toString(GLV_ATTEMPT_TIMEOUT_DEFAULT)));
// Log.fine("GLV_ATTEMPT_TIMEOUT = " + GLV_ATTEMPT_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The getlatestversion attempt timeout must be an integer.");
throw e;
}
// Allow override of settable short timeout.
try {
SETTABLE_SHORT_TIMEOUT = Integer.parseInt(retrievePropertyOrEnvironmentVariable(SETTABLE_SHORT_TIMEOUT_PROPERTY, SETTABLE_SHORT_TIMEOUT_ENV_VAR, Integer.toString(SHORT_TIMEOUT)));
// Log.fine("SETTABLE_SHORT_TIMEOUT = " + SETTABLE_SHORT_TIMEOUT);
} catch (NumberFormatException e) {
System.err.println("The settable short timeout must be an integer.");
throw e;
}
// Handle old-style header names
OLD_HEADER_NAMES = Boolean.parseBoolean(
retrievePropertyOrEnvironmentVariable(OLD_HEADER_NAMES_PROPERTY, OLD_HEADER_NAMES_ENV_VAR, STRING_TRUE));
}
public static String getLocalHost() {
// InetAddress.getLocalHost().toString(),
return "127.0.0.1"; // using InetAddress.getLocalHost gives bad results
}
/**
* Order of precedence (highest to lowest):
*
* 1) dynamic setting on an individual encoder or decoder,
* or in a single encode or decode call
*
* 2) command-line property
*
* 3) compiled-in default
*
* The latter two are handled here, the former in the encoder/decoder
* machinery itself.
* @return
*/
public static String getDefaultEncoding() {
if (null == DEFAULT_ENCODING) {
// First time, check for argument
String commandLineProperty = System.getProperty(DEFAULT_ENCODING_PROPERTY);
if (null == commandLineProperty)
DEFAULT_ENCODING = SYSTEM_DEFAULT_ENCODING;
else
DEFAULT_ENCODING = commandLineProperty;
}
return DEFAULT_ENCODING;
}
public static void setDefaultEncoding(String encoding) {
DEFAULT_ENCODING = encoding;
}
public static boolean checkDebugFlag(DEBUGGING_FLAGS debugFlag) {
Boolean result = DEBUG_FLAG_VALUES.get(debugFlag);
if (null == result)
return false;
return result.booleanValue();
}
/**
* Management bean for this runtime, if available. This is not dependent
* upon availability of any particular class but discovered dynamically
* from what is available at runtime.
*/
private static Object runtimeMXBean = null;
public static void setDebugFlag(DEBUGGING_FLAGS debugFlag, boolean value) {
Log.info("Debug Flag {0} set to {1}", debugFlag.toString(), value);
DEBUG_FLAG_VALUES.put(debugFlag, Boolean.valueOf(value));
}
public static void setDebugFlag(String debugFlag, boolean value) {
try {
DEBUGGING_FLAGS df = DEBUGGING_FLAGS.valueOf(debugFlag);
setDebugFlag(df, value);
} catch (IllegalArgumentException ax) {
Log.info("Cannot set debugging flag, no known flag: " + debugFlag + ". Choices are: " + debugFlagList());
}
}
public static String debugFlagList() {
DEBUGGING_FLAGS [] availableFlags = DEBUGGING_FLAGS.values();
StringBuffer flags = new StringBuffer();
for (int i=0; i < availableFlags.length; ++i) {
if (i > 0)
flags.append(":");
flags.append(availableFlags);
}
return flags.toString();
}
public static void setDebugFlag(String debugFlag) {
setDebugFlag(debugFlag, true);
}
public static void setDebugDataDirectory(String dir) {
DEBUG_DATA_DIRECTORY=dir;
}
public static void outputDebugData(ContentName name, XMLEncodable data) {
try {
byte [] encoded = data.encode();
outputDebugData(name, encoded);
} catch (ContentEncodingException ex) {
Log.warning("Cannot encode object : " + name + " to output for debug.");
}
}
public static void outputDebugData(ContentName name, byte [] data) {
// Output debug data under a given name.
try {
File dataDir = new File(DEBUG_DATA_DIRECTORY);
if (!dataDir.exists()) {
if (!dataDir.mkdirs()) {
Log.warning("outputDebugData: Cannot create default debug data directory: " + dataDir.getAbsolutePath());
return;
}
}
File outputParent = new File(dataDir, name.toString());
if (!outputParent.exists()) {
if (!outputParent.mkdirs()) {
Log.warning("outputDebugData: cannot create data parent directory: " + outputParent);
}
}
byte [] contentDigest = CCNDigestHelper.digest(data);
String contentName = new BigInteger(1, contentDigest).toString(DEBUG_RADIX);
File outputFile = new File(outputParent, contentName);
Log.finest("Attempting to output debug data for name " + name.toString() + " to file " + outputFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(data);
fos.close();
} catch (Exception e) {
Log.warning("Exception attempting to log debug data for name: " + name.toString() + " " + e.getClass().getName() + ": " + e.getMessage());
}
}
public static void outputDebugObject(File dataDir, String postfix, ContentObject object) {
// Output debug data under a given name.
try {
if (!dataDir.exists()) {
if (!dataDir.mkdirs()) {
Log.warning("outputDebugData: Cannot create debug data directory: " + dataDir.getAbsolutePath());
return;
}
}
/*
File outputParent = new File(dataDir, object.name().toString());
if (!outputParent.exists()) {
if (!outputParent.mkdirs()) {
Log.warning("outputDebugData: cannot create data parent directory: " + outputParent);
}
}
*/
byte [] objectDigest = object.digest();
StringBuffer contentName = new StringBuffer(new BigInteger(1, objectDigest).toString(DEBUG_RADIX));
if (null != postfix) {
contentName = contentName.append(postfix);
}
contentName.append(".ccnb");
File outputFile = new File(dataDir, contentName.toString());
Log.finest("Attempting to output debug data for name " + object.name().toString() + " to file " + outputFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outputFile);
object.encode(fos);
fos.close();
} catch (Exception e) {
Log.warning("Exception attempting to log debug data for name: " + object.name().toString() + " " + e.getClass().getName() + ": " + e.getMessage());
}
}
public static void outputDebugObject(ContentObject object) {
outputDebugObject(new File(DEBUG_DATA_DIRECTORY), null, object);
}
/**
* Log information about an object at level Level.INFO. See logObject(Level, String, ContentObject) for details.
* @param message String to prefix output with
* @param co ContentObject to print debugging information about.
* @see logObject(Level, String, ContentObject)
*/
public static void logObject(String message, ContentObject co) {
logObject(Level.INFO, message, co);
}
/**
* Log the gory details of an object, including debugging information relevant to object signing.
* @param level log Level to control printing of log messages
* @param message message to prefix output with
* @param co ContentObject to print debugging information for
*/
public static void logObject(Level level, String message, ContentObject co) {
try {
byte [] coDigest = CCNDigestHelper.digest(co.encode());
byte [] tbsDigest = CCNDigestHelper.digest(ContentObject.prepareContent(co.name(), co.signedInfo(), co.content()));
Log.log(level, message + " name: {0} timestamp: {1} digest: {2} tbs: {3}.",
co.name(), co.signedInfo().getTimestamp(), CCNDigestHelper.printBytes(coDigest, DEBUG_RADIX),
CCNDigestHelper.printBytes(tbsDigest, DEBUG_RADIX));
} catch (ContentEncodingException xs) {
Log.log(level, "Cannot encode object for logging: {0}.", co.name());
}
}
protected static String _loggingConfiguration;
/**
* TODO: Fix this incorrect comment
* Property to turn off access control flags. Set it to any value and it will turn off
* access control; used for testing.
*/
public static final String LOGGING_CONFIGURATION_PROPERTY = "com.parc.ccn.LoggingConfiguration";
/**
* Strings of interest to be set in the logging configuration
*/
public static final String DETAILED_LOGGER = "DetailedLogger";
/**
* Configure logging itself. This is a set of concatenated strings set as a
* command line property; it can be used to set transparent properties read
* at various points in the code.
*/
public static String getLoggingConfiguration() {
if (null == _loggingConfiguration) {
_loggingConfiguration = System.getProperty(LOGGING_CONFIGURATION_PROPERTY, "");
}
return _loggingConfiguration;
}
public static boolean hasLoggingConfigurationProperty(String property) {
if (null == property)
return false;
return getLoggingConfiguration().contains(property);
}
public static String getPID() {
// We try the JVM mgmt bean if available, reported to work on variety
// of operating systems on the Sun JVM. The bean is obtained once per VM,
// the other work to get the ID is done here.
Object bean = getManagementBean();
if (null == getManagementBean()) {
return null;
}
try {
String pid = null;
String vmname = null;
Method getName = bean.getClass().getDeclaredMethod("getName", (Class[]) null);
if (null == getName) {
return null;
}
getName.setAccessible(true);
vmname = (String) getName.invoke(bean, (Object[]) null);
if (null == vmname) {
return null;
}
// Hopefully the string is in the form "60447@ice.local", where we can pull
// out the integer hoping it is identical to the OS PID
Pattern exp = Pattern.compile("^(\\d+)@\\S+$");
Matcher match = exp.matcher(vmname);
if (match.matches()) {
pid = match.group(1);
} else {
// We don't have a candidate to match the OS PID, but we have the JVM name
// from the mgmt bean itself so that will have to do, cleaned of spaces
pid = vmname.replaceAll("\\s+", "_");
}
return pid;
} catch (Exception e) {
return null;
}
}
protected static Boolean _accessControlDisabled;
/**
* Property to turn off access control flags. Set it to any value and it will turn off
* access control; used for testing.
*/
public static final String ACCESS_CONTROL_DISABLED_PROPERTY = "com.parc.ccn.DisableAccessControl";
/**
* Allow control of access control at the command line.
*/
public static boolean disableAccessControl() {
if (null == _accessControlDisabled) {
_accessControlDisabled = (null != System.getProperty(ACCESS_CONTROL_DISABLED_PROPERTY));
}
return _accessControlDisabled;
}
public static void setAccessControlDisabled(boolean accessControlDisabled) {
_accessControlDisabled = accessControlDisabled;
}
/**
* Retrieve a string that might be stored as an environment variable, or
* overridden on the command line. If the command line variable is set, return
* its (String) value; if not, return the environment variable value if available;
* Caller should synchronize as appropriate.
* @return The value in force for this variable, or null if unset.
*/
public static String retrievePropertyOrEnvironmentVariable(String javaPropertyName, String environmentVariableName, String defaultValue) {
// First try the command line property.
String value = null;
if (null != javaPropertyName) {
value = System.getProperty(javaPropertyName);
}
if ((null == value) && (null != environmentVariableName)) {
// Try for an environment variable.
value = System.getenv(environmentVariableName);
}
if (null == value)
value = defaultValue;
return value;
}
}
|
package org.ccnx.ccn.profiles;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.ContentVerifier;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.protocol.CCNTime;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.ExcludeAny;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* Versions, when present, usually occupy the penultimate component of the CCN name,
* not counting the digest component. A name may actually incorporate multiple
* versions, where the rightmost version is the version of "this" object, if it
* has one, and previous (parent) versions are the versions of the objects of
* which this object is a part. The most common location of a version, if present,
* is in the next to last component of the name, where the last component is a
* segment number (which is generally always present; versions themselves are
* optional). More complicated segmentation profiles occur, where a versioned
* object has components that are structured and named in ways other than segments --
* and may themselves have individual versions (e.g. if the components of such
* a composite object are written as CCNNetworkObjects and automatically pick
* up an (unnecessary) version in their own right). Versioning operations therefore
* take context from their caller about where to expect to find a version,
* and attempt to ignore other versions in the name.
*
* Versions may be chosen based on time.
* The first byte of the version component is 0xFD. The remaining bytes are a
* big-endian binary number. If based on time they are expressed in units of
* 2**(-12) seconds since the start of Unix time, using the minimum number of
* bytes. The time portion will thus take 48 bits until quite a few centuries
* from now (Sun, 20 Aug 4147 07:32:16 GMT). With 12 bits of precision, it allows
* for sub-millisecond resolution. The client generating the version stamp
* should try to avoid using a stamp earlier than (or the same as) any
* version of the file, to the extent that it knows about it. It should
* also avoid generating stamps that are unreasonably far in the future.
*/
public class VersioningProfile implements CCNProfile {
public static final byte VERSION_MARKER = (byte)0xFD;
public static final byte [] FIRST_VERSION_MARKER = new byte []{VERSION_MARKER};
public static final byte FF = (byte) 0xFF;
public static final byte OO = (byte) 0x00;
/**
* Add a version field to a ContentName.
* @return ContentName with a version appended. Does not affect previous versions.
*/
public static ContentName addVersion(ContentName name, long version) {
// Need a minimum-bytes big-endian representation of version.
byte [] vcomp = null;
if (0 == version) {
vcomp = FIRST_VERSION_MARKER;
} else {
byte [] varr = BigInteger.valueOf(version).toByteArray();
vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
}
return new ContentName(name, vcomp);
}
/**
* Converts a timestamp into a fixed point representation, with 12 bits in the fractional
* component, and adds this to the ContentName as a version field. The timestamp is rounded
* to the nearest value in the fixed point representation.
* <p>
* This allows versions to be recorded as a timestamp with a 1/4096 second accuracy.
* @see #addVersion(ContentName, long)
*/
public static ContentName addVersion(ContentName name, CCNTime version) {
if (null == version)
throw new IllegalArgumentException("Version cannot be null!");
byte [] vcomp = timeToVersionComponent(version);
return new ContentName(name, vcomp);
}
/**
* Add a version field based on the current time, accurate to 1/4096 second.
* @see #addVersion(ContentName, CCNTime)
*/
public static ContentName addVersion(ContentName name) {
return addVersion(name, CCNTime.now());
}
public static byte [] timeToVersionComponent(CCNTime version) {
byte [] varr = version.toBinaryTime();
byte [] vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
return vcomp;
}
public static String printAsVersionComponent(CCNTime version) {
byte [] vcomp = timeToVersionComponent(version);
return ContentName.componentPrintURI(vcomp);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, long version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, CCNTime version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Add updates the version field based on the current time, accurate to 1/4096 second.
* @see #updateVersion(ContentName, Timestamp)
*/
public static ContentName updateVersion(ContentName name) {
return updateVersion(name, CCNTime.now());
}
/**
* Finds the last component that looks like a version in name.
* @param name
* @return the index of the last version component in the name, or -1 if there is no version
* component in the name
*/
public static int findLastVersionComponent(ContentName name) {
int i = name.count();
for (;i >= 0; i
if (isVersionComponent(name.component(i)))
return i;
return -1;
}
/**
* Checks to see if this name has a validly formatted version field anywhere in it.
*/
public static boolean containsVersion(ContentName name) {
return findLastVersionComponent(name) != -1;
}
/**
* Checks to see if this name has a validly formatted version field either in final
* component or in next to last component with final component being a segment marker.
*/
public static boolean hasTerminalVersion(ContentName name) {
if ((name.count() > 0) &&
((isVersionComponent(name.lastComponent()) ||
((name.count() > 1) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2)))))) {
return true;
}
return false;
}
/**
* Check a name component to see if it is a valid version field
*/
public static boolean isVersionComponent(byte [] nameComponent) {
return (null != nameComponent) && (0 != nameComponent.length) &&
(VERSION_MARKER == nameComponent[0]) &&
((nameComponent.length == 1) || (nameComponent[1] != 0));
}
public static boolean isBaseVersionComponent(byte [] nameComponent) {
return (isVersionComponent(nameComponent) && (1 == nameComponent.length));
}
/**
* Remove a terminal version marker (one that is either the last component of name, or
* the next to last component of name followed by a segment marker) if one exists, otherwise
* return name as it was passed in.
* @param name
* @return
*/
public static Tuple<ContentName, byte[]> cutTerminalVersion(ContentName name) {
if (name.count() > 0) {
if (isVersionComponent(name.lastComponent())) {
return new Tuple<ContentName, byte []>(name.parent(), name.lastComponent());
} else if ((name.count() > 2) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2))) {
return new Tuple<ContentName, byte []>(name.cut(name.count()-2), name.component(name.count()-2));
}
}
return new Tuple<ContentName, byte []>(name, null);
}
/**
* Take a name which may have one or more version components in it,
* and strips the last one and all following components. If no version components
* present, returns the name as handed in.
*/
public static ContentName cutLastVersion(ContentName name) {
int offset = findLastVersionComponent(name);
return (offset == -1) ? name : new ContentName(offset, name.components());
}
/**
* Function to get the version field as a long. Starts from the end and checks each name component for the version marker.
* @param name
* @return long
* @throws VersionMissingException
*/
public static long getLastVersionAsLong(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return getVersionComponentAsLong(name.component(i));
}
public static byte [] getLastVersionComponent(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return name.component(i);
}
public static long getVersionComponentAsLong(byte [] versionComponent) {
byte [] versionData = new byte[versionComponent.length - 1];
System.arraycopy(versionComponent, 1, versionData, 0, versionComponent.length - 1);
if (versionData.length == 0)
return 0;
return new BigInteger(versionData).longValue();
}
public static CCNTime getVersionComponentAsTimestamp(byte [] versionComponent) {
if (null == versionComponent)
return null;
return versionLongToTimestamp(getVersionComponentAsLong(versionComponent));
}
/**
* Extract the version from this name as a Timestamp.
* @throws VersionMissingException
*/
public static CCNTime getLastVersionAsTimestamp(ContentName name) throws VersionMissingException {
long time = getLastVersionAsLong(name);
return CCNTime.fromBinaryTimeAsLong(time);
}
/**
* Returns null if no version, otherwise returns the last version in the name.
* @param name
* @return
*/
public static CCNTime getLastVersionAsTimestampIfVersioned(ContentName name) {
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime getTerminalVersionAsTimestampIfVersioned(ContentName name) {
if (!hasTerminalVersion(name))
return null;
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static CCNTime versionLongToTimestamp(long version) {
return CCNTime.fromBinaryTimeAsLong(version);
}
/**
* Control whether versions start at 0 or 1.
* @return
*/
public static final int baseVersion() { return 0; }
/**
* Compares terminal version (versions at the end of, or followed by only a segment
* marker) of a name to a given timestamp.
* @param left
* @param right
* @return
*/
public static int compareVersions(
CCNTime left,
ContentName right) {
if (!hasTerminalVersion(right)) {
throw new IllegalArgumentException("Both names to compare must be versioned!");
}
try {
return left.compareTo(getLastVersionAsTimestamp(right));
} catch (VersionMissingException e) {
throw new IllegalArgumentException("Name that isVersioned returns true for throws VersionMissingException!: " + right);
}
}
public static int compareVersionComponents(
byte [] left,
byte [] right) throws VersionMissingException {
// Propagate correct exception to callers.
if ((null == left) || (null == right))
throw new VersionMissingException("Must compare two versions!");
// DKS TODO -- should be able to just compare byte arrays, but would have to check version
return getVersionComponentAsTimestamp(left).compareTo(getVersionComponentAsTimestamp(right));
}
/**
* See if version is a version of parent (not commutative).
* @return
*/
public static boolean isVersionOf(ContentName version, ContentName parent) {
Tuple<ContentName, byte []>versionParts = cutTerminalVersion(version);
if (!parent.equals(versionParts.first())) {
return false; // not versions of the same thing
}
if (null == versionParts.second())
return false; // version isn't a version
return true;
}
/**
* This compares two names, with terminal versions, and determines whether one is later than the other.
* @param laterVersion
* @param earlierVersion
* @return
* @throws VersionMissingException
*/
public static boolean isLaterVersionOf(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
// TODO -- remove temporary warning
Log.warning("SEMANTICS CHANGED: if experiencing unexpected behavior, check to see if you want to call isLaterVerisionOf or startsWithLaterVersionOf");
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
return false; // not versions of the same thing
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()) > 0);
}
/**
* Finds out if you have a versioned name, and a ContentObject that might have a versioned name which is
* a later version of the given name, even if that CO name might not refer to a segment of the original name.
* For example, given a name /parc/foo.txt/<version1> or /parc/foo.txt/<version1>/<segment>
* and /parc/foo.txt/<version2>/<stuff>, return true, whether <stuff> is a segment marker, a whole
* bunch of repo write information, or whatever.
* @param newName Will check to see if this name begins with something which is a later version of previousVersion.
* @param previousVersion The name to compare to, must have a terminal version or be unversioned.
* @return
*/
public static boolean startsWithLaterVersionOf(ContentName newName, ContentName previousVersion) {
// If no version, treat whole name as prefix and any version as a later version.
Tuple<ContentName, byte []>previousVersionParts = cutTerminalVersion(previousVersion);
if (!previousVersionParts.first().isPrefixOf(newName))
return false;
if (null == previousVersionParts.second()) {
return ((newName.count() > previousVersionParts.first().count()) &&
VersioningProfile.isVersionComponent(newName.component(previousVersionParts.first().count())));
}
try {
return (compareVersionComponents(newName.component(previousVersionParts.first().count()), previousVersionParts.second()) > 0);
} catch (VersionMissingException e) {
return false; // newName doesn't have to have a version there...
}
}
public static int compareTerminalVersions(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
throw new IllegalArgumentException("Names not versions of the same name!");
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()));
}
/**
* Builds an Exclude filter that excludes components before or @ start, and components after
* the last valid version.
* @param startingVersionComponent The latest version component we know about. Can be null or
* VersioningProfile.isBaseVersionComponent() == true to indicate that we want to start
* from 0 (we don't have a known version we're trying to update). This exclude filter will
* find versions *after* the version represented in startingVersionComponent.
* @return An exclude filter.
*/
public static Exclude acceptVersions(byte [] startingVersionComponent) {
byte [] start = null;
// initially exclude name components just before the first version, whether that is the
// 0th version or the version passed in
if ((null == startingVersionComponent) || VersioningProfile.isBaseVersionComponent(startingVersionComponent)) {
start = new byte [] { VersioningProfile.VERSION_MARKER, VersioningProfile.OO, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF };
} else {
start = startingVersionComponent;
}
ArrayList<Exclude.Element> ees = new ArrayList<Exclude.Element>();
ees.add(new ExcludeAny());
ees.add(new ExcludeComponent(start));
ees.add(new ExcludeComponent(new byte [] {
VERSION_MARKER+1, OO, OO, OO, OO, OO, OO } ));
ees.add(new ExcludeAny());
return new Exclude(ees);
}
/**
* Active methods. Want to provide profile-specific methods that:
* - find the latest version without regard to what is below it
* - if no version given, gets the latest version
* - if a starting version given, gets the latest version available *after* that version;
* will time out if no such newer version exists
* Returns a content object, which may or may not be a segment of the latest version, but the
* latest version information is available from its name.
*
* - find the first segment of the latest version of a name
* - if no version given, gets the first segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
*
* - generate an interest designed to find the first segment of the latest version
* of a name, in the above form; caller is responsible for checking and re-issuing
*/
/**
* Generate an interest that will find the leftmost child of the latest version. It
* will ensure that the next to last segment is a version, and the last segment (excluding
* digest) is the leftmost child available. But it can't guarantee that the latter is
* a segment. Because most data is segmented, length constraints will make it very
* likely, however.
* @param startingVersion
* @return
*/
public static Interest firstBlockLatestVersionInterest(ContentName startingVersion, PublisherPublicKeyDigest publisher) {
// by the time we look for extra components we will have a version on our name if it
// doesn't have one already, so look for names with 2 extra components -- segment and digest.
return latestVersionInterest(startingVersion, 3, publisher);
}
/**
* Generate an interest that will find a descendant of the latest version of startingVersion,
* after any existing version component. If additionalNameComponents is non-null, it will
* find a descendant with exactly that many name components after the version (including
* the digest). The latest version is the rightmost child of the desired prefix, however,
* this interest will find leftmost descendants of that rightmost child. With appropriate
* length limitations, can be used to find segments of the latest version (though that
* will work more effectively with appropriate segment numbering).
*/
public static Interest latestVersionInterest(ContentName startingVersion, Integer additionalNameComponents, PublisherPublicKeyDigest publisher) {
if (hasTerminalVersion(startingVersion)) {
// Has a version. Make sure it doesn't have a segment; find a version after this one.
startingVersion = SegmentationProfile.segmentRoot(startingVersion);
} else {
// Doesn't have a version. Add the "0" version, so we are finding any version after that.
ContentName firstVersionName = addVersion(startingVersion, baseVersion());
startingVersion = firstVersionName;
}
byte [] versionComponent = startingVersion.lastComponent();
Interest constructedInterest = Interest.last(startingVersion, acceptVersions(versionComponent), startingVersion.count() - 1, additionalNameComponents,
additionalNameComponents, null);
if (null != publisher) {
constructedInterest.publisherID(new PublisherID(publisher));
}
constructedInterest.answerOriginKind(Interest.ANSWER_CONTENT_STORE);
return constructedInterest;
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects
* @param handle CCNHandle used to get the latest version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
public static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, null, false);
}
/**
* Function to (best effort) get the latest version. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait to retrieve any version. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects.
* @param handle CCNHandle used to get the latest version.
* @param startingSegmentNumber If we are requiring content to be a segment, what segment number
* do we want. If null, and findASegment is true, uses SegmentationProfile.baseSegment().
* @param findASegment are we requiring returned content to be a segment of this version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
private static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle,
Long startingSegmentNumber,
boolean findASegment) throws IOException {
if (Log.isLoggable(Level.FINE)){
Log.fine("getFirstBlockOfLatestVersion: getting version later than {0} called with timeout: {1}", startingVersion, timeout);
}
if (null == verifier) {
// TODO DKS normalize default behavior
verifier = handle.keyManager().getDefaultVerifier();
}
long startTime = System.currentTimeMillis();
long interestTime = 0;
long elapsedTime = 0;
long respondTime;
long remainingTime = timeout;
long attemptTimeout = SystemConfiguration.GLV_ATTEMPT_TIMEOUT;
boolean noTimeout = false;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//glv called with no timeout... should probably return what we have as soon as we have something
//to return and have suffered a timeout
Log.finest("gLV called with NO_TIMEOUT");
noTimeout = true;
//if something comes back, we should try for one more interest and then return what we have
} else if (timeout == 0) {
Log.finest("gLV called with timeout = 0, should just return the first thing we get");
}
ContentName prefix = startingVersion;
if (hasTerminalVersion(prefix)) {
prefix = startingVersion.parent();
}
int versionedLength = prefix.count() + 1;
ContentObject result = null;
ContentObject lastResult = null;
ArrayList<byte[]> excludeList = new ArrayList<byte[]>();
while ( (remainingTime > 0 && elapsedTime < timeout) || (noTimeout || timeout == 0)) {
Log.finer("gLV timeout: {0} remainingTime: {1} attemptTimeout: {2}", timeout, remainingTime, attemptTimeout);
lastResult = result;
//attempts++;
Interest getLatestInterest = null;
if (findASegment) {
getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
} else {
getLatestInterest = latestVersionInterest(startingVersion, null, publisher);
}
if (excludeList.size() > 0) {
//we have explicit excludes, add them to this interest
byte [][] e = new byte[excludeList.size()][];
excludeList.toArray(e);
getLatestInterest.exclude().add(e);
}
Log.finer("timeout {0} startTime: {1} elapsedTime: {2} remainingTime: {3} new elapsedTime = {4}", timeout, startTime, elapsedTime, remainingTime, (System.currentTimeMillis() - startTime));
interestTime = System.currentTimeMillis();
long tempT;
if (noTimeout) {
tempT = timeout;
} else if (timeout == 0) {
tempT = attemptTimeout;
} else {
if (remainingTime < timeout - elapsedTime) {
tempT = remainingTime;
} else {
tempT = timeout - elapsedTime;
}
}
result = handle.get(getLatestInterest, tempT);
elapsedTime = System.currentTimeMillis() - startTime;
respondTime = System.currentTimeMillis() - interestTime;
if (result == null && respondTime == 0) {
Log.warning("gLV: handle.get returned null and did not wait the full timeout time for the object (timeout: {0} responseTime: {1}", timeout, respondTime);
return null;
}
remainingTime = timeout - elapsedTime;
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV INTEREST: {0}", getLatestInterest);
Log.fine("gLV trying handle.get with timeout: {0}", tempT);
Log.fine("gLVTime sending Interest from gLV at {0} started at: {1}", System.currentTimeMillis(), startTime);
Log.fine("gLVTime returned from handle.get in {0} ms",respondTime);
Log.fine("gLV remaining time is now {0} ms", remainingTime);
}
if (null != result){
if (Log.isLoggable(Level.INFO))
Log.info("gLV getLatestVersion: retrieved latest version object {0} type: {1}", result.name(), result.signedInfo().getTypeName());
//did it verify?
//if it doesn't verify, we need to try harder to get a different content object (exclude this digest)
//make this a loop?
if (!verifier.verify(result)) {
//excludes = addVersionToExcludes(excludes, result.name());
Log.fine("gLV result did not verify, trying to find a verifiable answer");
excludeList = addVersionToExcludes(excludeList, result.name());
//note: need to use the full name, but want to exclude this particular digest. This means we can't cut off the segment marker.
//Interest retry = new Interest(SegmentationProfile.segmentRoot(result.name()), publisher);
//retry.maxSuffixComponents(1);
Interest retry = new Interest(result.name(), publisher);
boolean verifyDone = false;
while (!verifyDone) {
if (retry.exclude() == null)
retry.exclude(new Exclude());
retry.exclude().add(new byte[][] {result.digest()});
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV result did not verify! doing retry!! {0}", retry);
Log.fine("gLVTime sending retry interest at {0}", System.currentTimeMillis());
}
//try to send the interest with the response time the bad content object was returned with
//if (timeout == 0)
result = handle.get(retry, attemptTimeout);
//else
// result = handle.get(retry, respondTime);
if (result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV we got something back: {0}", result.name());
if (verifier.verify(result)) {
Log.fine("gLV the returned answer verifies");
verifyDone = true;
} else {
Log.fine("gLV this answer did not verify either... try again");
}
} else {
//result is null, we didn't find a verifiable answer
Log.fine("gLV did not get a verifiable answer back");
verifyDone = true;
}
}
//TODO if this is the latest version and we exclude it, we might not have anything to send back... we should reset the starting version
if (Log.isLoggable(Level.FINE)) {
Log.fine("the latest version did not verify and we might not have anything to send back...");
if (lastResult == null)
Log.fine("lastResult is null... we have nothing to send back");
else
Log.fine("lastResult is NOT null, we have something to send back!");
}
}
if (result!=null) {
//else {
//it verified! are we done?
//first check if we need to get the first segment...
if (findASegment) {
//yes, we need to have the first segment....
// Now we know the version. Did we luck out and get first block?
if (VersioningProfile.isVersionedFirstSegment(prefix, result, startingSegmentNumber)) {
if (Log.isLoggable(Level.FINE))
Log.fine("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
} else {
//not the first segment...
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
ContentName notFirstBlockVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
result = SegmentationProfile.getSegment(notFirstBlockVersion, startingSegmentNumber, null, timeout - elapsedTime, verifier, handle); // now that we have the latest version, go back for the first block.
//if this isn't the first segment... then we should exclude it. otherwise, we can use it!
if (result == null) {
//we couldn't get a new segment...
Log.fine("gLV could not get the first segment of the version we just found... should exclude the version");
//excludes = addVersionToExcludes(excludes, startingVersion);
excludeList = addVersionToExcludes(excludeList, notFirstBlockVersion);
}
}
} else {
//no need to get the first segment!
//this is already verified!
}
//if result is not null, we really have something to try since it also verified
if (result != null) {
//this could be our answer... set to lastResult and see if we have time to do better
lastResult = result;
if (noTimeout) {
//we want to keep trying for something new
//we don't want to wait forever... we have something to hand back. try one more time and then hand back what we have
timeout = attemptTimeout;
remainingTime = attemptTimeout;
} else if (timeout == 0) {
//caller just wants the first answer...
Log.fine("gLV we got an answer and the caller wants the first thing we found, returning");
return result;
} else if (remainingTime > 0) {
//we still have time to try for a better answer, but we shouldn't wait the full timeout
//The full timeout is the time to wait until there the answer is null.
//now we should wait the gLV attempt time.
if (remainingTime > attemptTimeout) {
//this is the first time we got something back
remainingTime = attemptTimeout;
}
else {
//we already tried again for a better answer... but we got something again... try again,
//since the remaining time is less than the attempt time, don't adjust
}
Log.fine("gLV we still have time to try for a better answer: remaining time = {0}", remainingTime);
} else {
Log.fine("gLV time is up, return what we have");
//attempts = SystemConfiguration.GET_LATEST_VERSION_ATTEMPTS;
}
} else {
//result is null
//will be handled below
}
}//the result verified
} //we got something back
if (result == null) {
//This check is added for the case where the underlying handle.get call did not respect the timeout.
//This should not happen in regular operation, but is a current behavior by an overridden handle
//for junit testing. For now, log at a warning and return the object to avoid slowing the test suite.
if (respondTime == 0) {
Log.warning("gLV: handle.get returned null and did not wait the full timeout time for the object (timeout: {0} responseTime: {1}", timeout, respondTime);
return null;
}
Log.fine("gLV we didn't get anything");
Log.info("getFirstBlockOfLatestVersion: no block available for later version of {0}", startingVersion);
//we didn't get a new version... we can return the last one we received if it isn't null.
if (lastResult!=null) {
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLV returning the last result that wasn't null... ");
Log.fine("gLV returning: {0}",lastResult.name());
}
return lastResult;
}
else {
Log.fine("gLV we didn't get anything, and we haven't had anything at all... try with remaining long timeout");
//if remaining time is done.. then we should return null
if (remainingTime > 0) {
Log.fine("we did not get anything back from our interest, but we still have time remaining. timeout: {0} elapsedTime {1} remainingTime {2}", timeout, elapsedTime, remainingTime);
timeout = remainingTime;
}
}
}
//Log.fine("gLV (after) attemptTimeout: {0} remainingTime: {1} (timeout: {2})", attemptTimeout, remainingTime, timeout);
if (result!=null)
startingVersion = SegmentationProfile.segmentRoot(result.name());
}
if(result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLV returning: {0}", result.name());
}
return result;
}
/**
* Find a particular segment of the latest version of a name
* - if no version given, gets the desired segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
* Also makes sure to return the latest version with a SegmentationProfile.baseSegment() marker.
* * @param desiredName The name of the object we are looking for the first segment of.
* If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can
* find of desiredName.
* If desiredName has a terminal version, will try to find the first block of content whose
* version is *after* desiredName (i.e. getLatestVersion starting from desiredName).
* @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment() if null.
* @param publisher, if one is specified.
* @param timeout
* @return The first block of a stream with a version later than desiredName, or null if timeout is reached.
* This block is verified.
* @throws IOException
*/
public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLatestVersion(startingVersion, publisher, timeout, verifier, handle, startingSegmentNumber, true);
}
/**
* Single-attempt function to get the first version found; and if there are multiple
* versions at the network point where that version is found, it will retrieve
* the latest of them. So if your ccnd cache has multiple versions, it will return
* the latest of those, but won't move past them to get a later one in the repository
* or one hop away. This should be used if you believe there is only a single version
* of a piece of content available, or if you care more about fast answers than ensuring
* you have the latest version available.
* if you ask again passing in the version found, you will find a version later than that
* if one is available (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout This is the time to wait until you get any response. If nothing is returned, this method will return null.
* @param verifier Used to verify the returned content objects
* @param handle CCNHandle used to get the latest version
* @return A ContentObject with the latest version, or null if the query timed out.
* @result Returns a matching ContentObject, verified.
* @throws IOException
*/
public static ContentObject getAnyLaterVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLocalLatestVersion(startingVersion, publisher, timeout, verifier, handle, null, false);
}
/**
* Find a particular segment of the closest version available of this object later than
* the version given. If there are multiple versions available at that point, will get
* the latest among them. See getAnyLaterVersion.
* - if no version given, gets the desired segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
* Also makes sure to return the latest version with a SegmentationProfile.baseSegment() marker.
* * @param desiredName The name of the object we are looking for the first segment of.
* If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can
* find of desiredName.
* If desiredName has a terminal version, will try to find the first block of content whose
* version is *after* desiredName (i.e. getLatestVersion starting from desiredName).
* @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment() if null.
* @param publisher, if one is specified.
* @param timeout
* @return The first block of a stream with a version later than desiredName, or null if timeout is reached.
* This block is verified.
* @throws IOException
*/
public static ContentObject getFirstBlockOfAnyLaterVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle) throws IOException {
return getLocalLatestVersion(startingVersion, publisher, timeout, verifier, handle, startingSegmentNumber, true);
}
protected static ContentObject getLocalLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle handle,
Long startingSegmentNumber,
boolean findASegment) throws IOException {
Log.info("getLocalLatestVersion: getting version later than {0} called with timeout: {1}", startingVersion, timeout);
if (null == verifier) {
// TODO DKS normalize default behavior
verifier = handle.keyManager().getDefaultVerifier();
}
//TODO This timeout is set to SystemConfiguration.MEDIUM_TIMEOUT to work around the problem
//in ccnd where some interests take >300ms (and sometimes longer, have seen periodic delays >800ms)
//when that bug is found and fixed, this can be reduced back to the SHORT_TIMEOUT.
//long attemptTimeout = SystemConfiguration.SHORT_TIMEOUT;
long attemptTimeout = SystemConfiguration.MEDIUM_TIMEOUT;
if (timeout == SystemConfiguration.NO_TIMEOUT) {
//the timeout sent in is equivalent to null... try till we don't hear something back
//we will reset the remaining time after each return...
} else if (timeout > 0 && timeout < attemptTimeout) {
attemptTimeout = timeout;
}
long stopTime = System.currentTimeMillis() + timeout;
ContentName prefix = startingVersion;
if (hasTerminalVersion(prefix)) {
prefix = startingVersion.parent();
}
int versionedLength = prefix.count() + 1;
ContentObject result = null;
ArrayList<byte[]> excludeList = new ArrayList<byte[]>();
while ((null == result) &&
((timeout == SystemConfiguration.NO_TIMEOUT) || (System.currentTimeMillis() < stopTime))) {
Interest getLatestInterest = null;
if (findASegment) {
getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
} else {
getLatestInterest = latestVersionInterest(startingVersion, null, publisher);
}
if (excludeList.size() > 0) {
//we have explicit excludes, add them to this interest
byte [][] e = new byte[excludeList.size()][];
excludeList.toArray(e);
getLatestInterest.exclude().add(e);
}
result = handle.get(getLatestInterest, timeout);
if (null != result) {
if (Log.isLoggable(Level.INFO))
Log.info("gLLV getLocalLatestVersion: retrieved latest version object {0} type: {1}", result.name(), result.signedInfo().getTypeName());
//did it verify?
//if it doesn't verify, we need to try harder to get a different content object (exclude this digest)
//make this a loop?
if (!verifier.verify(result)) {
// DKS TODO FIX -- this is incorrect; even if this one fails to verify it doesn't
// mean that the version is bad, if you do this attacker can shadow good versions with bad
//excludes = addVersionToExcludes(excludes, result.name());
Log.fine("gLLV result did not verify, trying to find a verifiable answer");
excludeList = addVersionToExcludes(excludeList, result.name());
//note: need to use the full name, but want to exclude this particular digest. This means we can't cut off the segment marker.
//Interest retry = new Interest(SegmentationProfile.segmentRoot(result.name()), publisher);
//retry.maxSuffixComponents(1);
Interest retry = new Interest(result.name(), publisher);
boolean verifyDone = false;
while (!verifyDone) {
if (retry.exclude() == null)
retry.exclude(new Exclude());
retry.exclude().add(new byte[][] {result.digest()});
if (Log.isLoggable(Level.FINE)) {
Log.fine("gLLV result did not verify! doing retry!! {0}", retry);
Log.fine("gLLVTime sending retry interest at {0}", System.currentTimeMillis());
}
result = handle.get(retry, attemptTimeout);
if (result!=null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLLV we got something back: {0}", result.name());
if(verifier.verify(result)) {
Log.fine("gLLV the returned answer verifies");
verifyDone = true;
} else {
Log.fine("gLLV this answer did not verify either... try again");
}
} else {
//result is null, we didn't find a verifiable answer
Log.fine("gLLV did not get a verifiable answer back");
verifyDone = true;
}
}
//TODO if this is the latest version and we exclude it, we might not have anything to send back... we should reset the starting version
}
if (result != null) {
//else {
//it verified! are we done?
//first check if we need to get the first segment...
if (findASegment) {
//yes, we need to have the first segment....
// Now we know the version. Did we luck out and get first block?
if (VersioningProfile.isVersionedFirstSegment(prefix, result, startingSegmentNumber)) {
if (Log.isLoggable(Level.FINE))
Log.fine("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
} else {
//not the first segment...
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
ContentName notFirstBlockVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
//don't count this against the gLV timeout.
result = SegmentationProfile.getSegment(notFirstBlockVersion, startingSegmentNumber, null, timeout, verifier, handle); // now that we have the latest version, go back for the first block.
//if this isn't the first segment... then we should exclude it. otherwise, we can use it!
if(result == null) {
//we couldn't get a new segment...
Log.fine("gLV could not get the first segment of the version we just found... should exclude the version");
//excludes = addVersionToExcludes(excludes, startingVersion);
excludeList = addVersionToExcludes(excludeList, notFirstBlockVersion);
}
}
} else {
//no need to get the first segment!
//this is already verified!
}
} //the result verified
} //we got something back
}
if (result != null) {
if (Log.isLoggable(Level.FINE))
Log.fine("gLLV returning: {0}", result.name());
}
return result;
}
/**
* Version of isFirstSegment that expects names to be versioned, and allows that desiredName
* won't know what version it wants but will want some version.
*/
public static boolean isVersionedFirstSegment(ContentName desiredName, ContentObject potentialFirstSegment, Long startingSegmentNumber) {
if ((null != potentialFirstSegment) && (SegmentationProfile.isSegment(potentialFirstSegment.name()))) {
if (Log.isLoggable(Level.FINER))
Log.finer("is " + potentialFirstSegment.name() + " a first segment of " + desiredName);
// In theory, the segment should be at most a versioning component different from desiredName.
// In the case of complex segmented objects (e.g. a KeyDirectory), where there is a version,
// then some name components, then a segment, desiredName should contain all of those other
// name components -- you can't use the usual versioning mechanisms to pull first segment anyway.
if (!desiredName.isPrefixOf(potentialFirstSegment.name())) {
if (Log.isLoggable(Level.FINE))
Log.fine("Desired name :" + desiredName + " is not a prefix of segment: " + potentialFirstSegment.name());
return false;
}
int difflen = potentialFirstSegment.name().count() - desiredName.count();
if (difflen > 2) {
if (Log.isLoggable(Level.FINE))
Log.fine("Have " + difflen + " extra components between " + potentialFirstSegment.name() + " and desired " + desiredName);
return false;
}
// Now need to make sure that if the difference is more than 1, that difference is
// a version component.
if ((difflen == 2) && (!isVersionComponent(potentialFirstSegment.name().component(potentialFirstSegment.name().count()-2)))) {
if (Log.isLoggable(Level.FINE))
Log.fine("The " + difflen + " extra component between " + potentialFirstSegment.name() + " and desired " + desiredName + " is not a version.");
}
if ((null != startingSegmentNumber) && (SegmentationProfile.baseSegment() != startingSegmentNumber)) {
return (startingSegmentNumber.longValue() == SegmentationProfile.getSegmentNumber(potentialFirstSegment.name()));
} else {
return SegmentationProfile.isFirstSegment(potentialFirstSegment.name());
}
}
return false;
}
/**
* Adds version components to the exclude list for the getLatestVersion method.
* @param excludeList current excludes
* @param name component to add to the exclude list
* @return updated exclude list
*/
private static ArrayList<byte[]> addVersionToExcludes(ArrayList<byte[]> excludeList, ContentName name) {
try {
excludeList.add(VersioningProfile.getLastVersionComponent(name));
} catch (VersionMissingException e) {
Log.warning("failed to exclude content object version that did not verify: {0}",name);
}
return excludeList;
}
public static byte[] versionComponentFromStripped(byte[] bs) {
if (null == bs)
return null;
byte [] versionComponent = new byte[bs.length + 1];
versionComponent[0] = VERSION_MARKER;
System.arraycopy(bs, 0, versionComponent, 1, bs.length);
return versionComponent;
}
public static byte[] stripVersionMarker(byte[] version) throws VersionMissingException {
if (null == version)
return null;
if (VERSION_MARKER != version[0]) {
throw new VersionMissingException("This is not a version component!");
}
byte [] stripped = new byte[version.length - 1];
System.arraycopy(version, 1, stripped, 0, stripped.length);
return stripped;
}
}
|
package com.marklogic.javaclient;
import java.io.IOException;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import com.marklogic.client.query.MatchDocumentSummary;
import com.marklogic.client.query.MatchLocation;
import com.marklogic.client.query.QueryManager;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.Transaction;
import com.marklogic.client.query.KeyValueQueryDefinition;
import com.marklogic.client.admin.NamespacesManager;
import com.marklogic.client.io.DOMHandle;
import com.marklogic.client.io.SearchHandle;
import static org.custommonkey.xmlunit.XMLAssert.assertXpathEvaluatesTo;
import static org.junit.Assert.*;
import org.custommonkey.xmlunit.exceptions.XpathException;
import org.junit.*;
public class TestKeyValueSearch extends BasicJavaClientREST {
private static String dbName = "TestKeyValueSearchDB";
private static String [] fNames = {"TestKeyValueSearchDB-1"};
private static String restServerName = "REST-Java-Client-API-Server";
private static int restPort=8011;
@BeforeClass
public static void setUp() throws Exception
{
System.out.println("In setup");
setupJavaRESTServer(dbName, fNames[0], restServerName,8011);
setupAppServicesConstraint(dbName);
}
@After
public void testCleanUp() throws Exception
{
clearDB(restPort);
System.out.println("Running clear script");
}
@SuppressWarnings("deprecation")
@Test
public void testKeyValueSearch() throws IOException, ParserConfigurationException, SAXException, XpathException
{
System.out.println("Running testKeyValueSearch");
String[] filenames = {"constraint1.xml", "constraint2.xml", "constraint3.xml", "constraint4.xml", "constraint5.xml"};
String queryOptionName = "valueConstraintWithoutIndexSettingsAndNSOpt.xml";
DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8011, "rest-admin", "x", Authentication.DIGEST);
// create transaction
Transaction transaction1 = client.openTransaction();
// write docs
for(String filename : filenames)
{
writeDocumentUsingInputStreamHandle(client, filename, "/key-value-search/", transaction1, "XML");
}
// commit transaction
transaction1.commit();
// create transaction
Transaction transaction2 = client.openTransaction();
setQueryOption(client, queryOptionName);
QueryManager queryMgr = client.newQueryManager();
// create a search definition
KeyValueQueryDefinition querydef = queryMgr.newKeyValueDefinition(queryOptionName);
querydef.put(queryMgr.newElementLocator(new QName("id")), "0012");
// create handle
DOMHandle resultsHandle = new DOMHandle();
queryMgr.search(querydef, resultsHandle, transaction2);
// commit transaction
transaction2.commit();
// get the result
Document resultDoc = resultsHandle.get();
|
package org.jpos.space;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.jpos.iso.ISOUtil;
import org.jpos.util.Profiler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
@SuppressWarnings("unchecked")
public class JDBMSpaceTestCase {
public static final int COUNT = 100;
JDBMSpace<String,Object> sp;
@BeforeEach
public void setUp (@TempDir Path filename) {
sp = (JDBMSpace<String,Object>) JDBMSpace.getSpace ("jdbm-space-test", filename.toString());
}
@Test
public void testSimpleOut() throws Exception {
Object o =Boolean.TRUE;
sp.out ("testSimpleOut_Key", o);
Object o1 = sp.in ("testSimpleOut_Key");
assertTrue (o.equals (o1));
}
@Test
public void testOutRdpInpRdp() throws Exception {
Object o = Boolean.TRUE;
String k = "testOutRdpInpRdp_Key";
sp.out (k, o);
assertTrue (o.equals (sp.rdp (k)));
assertTrue (o.equals (sp.rd (k)));
assertTrue (o.equals (sp.rd (k, 1000)));
assertTrue (o.equals (sp.inp (k)));
assertTrue (sp.rdp (k) == null);
assertTrue (sp.rd (k, 100) == null);
}
@Test
public void testMultiKeyLoad() throws Exception {
String s = "The quick brown fox jumped over the lazy dog";
Profiler prof = new Profiler ();
for (int i=0; i<COUNT; i++) {
sp.out ("testMultiKeyLoad_Key" + Integer.toString (i), s);
if (i % 100 == 0)
prof.checkPoint ("out " + i);
}
// prof.dump (System.err, "MultiKeyLoad out >");
prof = new Profiler ();
for (int i=0; i<COUNT; i++) {
assertTrue (s.equals (sp.in ("testMultiKeyLoad_Key" + Integer.toString (i))));
if (i % 100 == 0)
prof.checkPoint ("in " + i);
}
// prof.dump (System.err, "MultiKeyLoad in >");
}
@Test
public void testNoAutoCommit () throws Exception {
String s = "The quick brown fox jumped over the lazy dog";
Profiler prof = new Profiler ();
synchronized (sp) {
sp.setAutoCommit (false);
for (int i=0; i<COUNT; i++) {
sp.out ("testNoAutoCommit_Key" + Integer.toString (i), s);
if (i % 100 == 0)
prof.checkPoint ("out " + i);
}
prof.checkPoint ("pre-commit");
sp.commit();
sp.setAutoCommit (true);
prof.checkPoint ("commit");
}
// prof.dump (System.err, "NoAutoCommit out >");
prof = new Profiler ();
synchronized (sp) {
sp.setAutoCommit (false);
for (int i=0; i<COUNT; i++) {
assertTrue (s.equals (sp.in ("testNoAutoCommit_Key" + Integer.toString (i))));
if (i % 100 == 0)
prof.checkPoint ("in " + i);
}
prof.checkPoint ("pre-commit");
sp.commit();
sp.setAutoCommit (true);
prof.checkPoint ("commit");
}
// prof.dump (System.err, "NoAutoCommit in >");
}
@Test
public void testSingleKeyLoad() throws Exception {
String s = "The quick brown fox jumped over the lazy dog";
String k = "testSingleKeyLoad_Key";
Profiler prof = new Profiler ();
for (int i=0; i<COUNT; i++) {
sp.out (k, s);
if (i % 100 == 0)
prof.checkPoint ("out " + i);
}
// prof.dump (System.err, "SingleKeyLoad out >");
prof = new Profiler ();
for (int i=0; i<COUNT; i++) {
assertTrue (s.equals (sp.in (k)));
if (i % 100 == 0)
prof.checkPoint ("in " + i);
}
// prof.dump (System.err, "SingleKeyLoad in >");
assertTrue (sp.rdp (k) == null);
}
@Test
public void testTemplate () throws Exception {
String key = "TemplateTest_Key";
sp.out (key, "Value 1");
sp.out (key, "Value 2");
sp.out (key, "Value 3");
String k2r = (String)sp.rdp (new MD5Template (key, "Value 2"));
assertEquals (k2r, "Value 2");
String k2i = (String)sp.inp (new MD5Template (key, "Value 2"));
assertEquals (k2i, "Value 2");
assertEquals ("Value 1", (String) sp.inp (key));
assertEquals ("Value 3", (String) sp.inp (key));
}
@Test
public void testPush() {
sp.push ("PUSH", "ONE");
sp.push ("PUSH", "TWO");
sp.push ("PUSH", "THREE");
sp.out ("PUSH", "FOUR");
assertEquals ("THREE", sp.rdp ("PUSH"));
assertEquals ("THREE", sp.inp ("PUSH"));
assertEquals ("TWO", sp.inp ("PUSH"));
assertEquals ("ONE", sp.inp ("PUSH"));
assertEquals ("FOUR", sp.inp ("PUSH"));
assertNull (sp.rdp ("PUSH"));
}
@Test
public void testOutExpire() {
sp.out ("OUT", "ONE", 1000L);
sp.out ("OUT", "TWO", 2000L);
sp.out ("OUT", "THREE", 3000L);
sp.out ("OUT", "FOUR", 4000L);
assertEquals ("ONE", sp.rdp ("OUT"));
ISOUtil.sleep (1500L);
assertEquals ("TWO", sp.rdp ("OUT"));
ISOUtil.sleep (1000L);
assertEquals ("THREE", sp.rdp ("OUT"));
assertEquals ("THREE", sp.inp ("OUT"));
assertEquals ("FOUR", sp.inp ("OUT"));
assertNull (sp.rdp ("OUT"));
}
@Test
public void testPushExpire() {
sp.push ("PUSH", "FOUR", 4000L);
sp.push ("PUSH", "THREE", 3000L);
sp.push ("PUSH", "TWO", 2000L);
sp.push ("PUSH", "ONE", 1000L);
assertEquals ("ONE", sp.rdp ("PUSH"));
ISOUtil.sleep (1500L);
assertEquals ("TWO", sp.rdp ("PUSH"));
ISOUtil.sleep (1000L);
assertEquals ("THREE", sp.rdp ("PUSH"));
assertEquals ("THREE", sp.inp ("PUSH"));
assertEquals ("FOUR", sp.inp ("PUSH"));
assertNull (sp.rdp ("PUSH"));
}
@Test
public void testExist() {
sp.out ("KEYA", Boolean.TRUE);
sp.out ("KEYB", Boolean.TRUE);
assertTrue (
sp.existAny(new String[]{"KEYA"}),
"existAny ([KEYA])"
);
assertTrue (
sp.existAny(new String[]{"KEYB"}),
"existAny ([KEYB])"
);
assertTrue (
sp.existAny(new String[]{"KEYA", "KEYB"}),
"existAny ([KEYA,KEYB])"
);
assertFalse (
sp.existAny(new String[]{"KEYC", "KEYD"}),
"existAny ([KEYC,KEYD])"
);
}
@Test
public void testExistWithTimeout() {
assertFalse (
sp.existAny(new String[]{"KA", "KB"}),
"existAnyWithTimeout ([KA,KB])"
);
assertFalse (
sp.existAny(new String[]{"KA", "KB"}, 1000L),
"existAnyWithTimeout ([KA,KB], delay)"
);
new Thread() {
public void run() {
ISOUtil.sleep (1000L);
sp.out ("KA", Boolean.TRUE);
}
}.start();
long now = System.currentTimeMillis();
assertTrue (
sp.existAny(new String[]{"KA", "KB"}, 2000L),
"existAnyWithTimeout ([KA,KB], delay)"
);
long elapsed = System.currentTimeMillis() - now;
assertTrue (elapsed > 900L, "delay was > 1000");
assertNotNull (sp.inp("KA"), "Entry should not be null");
}
@Test
public void testPut () {
sp.out ("PUT", "ONE");
sp.out ("PUT", "TWO");
sp.put ("PUT", "ZERO");
assertEquals ("ZERO", sp.rdp ("PUT"));
assertEquals ("ZERO", sp.inp ("PUT"));
assertNull (sp.rdp ("PUT"));
}
}
|
package io.quarkus.test.common;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.configuration.ConfigUtils;
import io.quarkus.runtime.configuration.QuarkusConfigFactory;
import io.quarkus.test.common.http.TestHTTPResourceManager;
import io.smallrye.config.SmallRyeConfig;
public final class LauncherUtil {
private LauncherUtil() {
}
public static Config installAndGetSomeConfig() {
final SmallRyeConfig config = ConfigUtils.configBuilder(false, LaunchMode.NORMAL).build();
QuarkusConfigFactory.setConfig(config);
final ConfigProviderResolver cpr = ConfigProviderResolver.instance();
try {
final Config installed = cpr.getConfig();
if (installed != config) {
cpr.releaseConfig(installed);
}
} catch (IllegalStateException ignored) {
}
return config;
}
/**
* Launches a process using the supplied arguments and makes sure the process's output is drained to standard out
*/
static Process launchProcess(List<String> args) throws IOException {
Process process = Runtime.getRuntime().exec(args.toArray(new String[0]));
new Thread(new ProcessReader(process.getInputStream())).start();
new Thread(new ProcessReader(process.getErrorStream())).start();
return process;
}
static ListeningAddress waitForCapturedListeningData(Process quarkusProcess, Path logFile, long waitTimeSeconds) {
ensureProcessIsAlive(quarkusProcess);
CountDownLatch signal = new CountDownLatch(1);
AtomicReference<ListeningAddress> resultReference = new AtomicReference<>();
CaptureListeningDataReader captureListeningDataReader = new CaptureListeningDataReader(logFile,
Duration.ofSeconds(waitTimeSeconds), signal, resultReference);
new Thread(captureListeningDataReader, "capture-listening-data").start();
try {
signal.await(waitTimeSeconds + 2, TimeUnit.SECONDS); // wait enough for the signal to be given by the capturing thread
ListeningAddress result = resultReference.get();
if (result != null) {
return result;
}
// a null result means that we could not determine the status of the process so we need to abort testing
destroyProcess(quarkusProcess);
throw new IllegalStateException(
"Unable to determine the status of the running process. See the above logs for details");
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting to capture listening process port and protocol");
}
}
private static void ensureProcessIsAlive(Process quarkusProcess) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
throw new RuntimeException(
"Interrupted while waiting to determine the status of process '" + quarkusProcess.pid() + "'.");
}
if (!quarkusProcess.isAlive()) {
throw new RuntimeException("Unable to successfully launch process '" + quarkusProcess.pid() + "'. Exit code is: '"
+ quarkusProcess.exitValue() + "'.");
}
}
/**
* Try to destroy the process normally a few times
* and resort to forceful destruction if necessary
*/
private static void destroyProcess(Process quarkusProcess) {
quarkusProcess.destroy();
int i = 0;
while (i++ < 10) {
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
if (!quarkusProcess.isAlive()) {
break;
}
}
if (quarkusProcess.isAlive()) {
quarkusProcess.destroyForcibly();
}
}
static Function<IntegrationTestStartedNotifier.Context, IntegrationTestStartedNotifier.Result> createStartedFunction() {
List<IntegrationTestStartedNotifier> startedNotifiers = new ArrayList<>();
for (IntegrationTestStartedNotifier i : ServiceLoader.load(IntegrationTestStartedNotifier.class)) {
startedNotifiers.add(i);
}
if (startedNotifiers.isEmpty()) {
return null;
}
return (ctx) -> {
for (IntegrationTestStartedNotifier startedNotifier : startedNotifiers) {
IntegrationTestStartedNotifier.Result result = startedNotifier.check(ctx);
if (result.isStarted()) {
return result;
}
}
return IntegrationTestStartedNotifier.Result.NotStarted.INSTANCE;
};
}
/**
* Waits for {@param startedFunction} to indicate that the application has started.
*
* @return the {@link io.quarkus.test.common.IntegrationTestStartedNotifier.Result} indicating a successful start
* @throws RuntimeException if no successful start was indicated by {@param startedFunction}
*/
static IntegrationTestStartedNotifier.Result waitForStartedFunction(
Function<IntegrationTestStartedNotifier.Context, IntegrationTestStartedNotifier.Result> startedFunction,
Process quarkusProcess, long waitTimeSeconds, Path logFile) {
long bailout = System.currentTimeMillis() + waitTimeSeconds * 1000;
IntegrationTestStartedNotifier.Result result = null;
SimpleContext context = new SimpleContext(logFile);
while (System.currentTimeMillis() < bailout) {
if (!quarkusProcess.isAlive()) {
throw new RuntimeException("Failed to start target quarkus application, process has exited");
}
try {
Thread.sleep(100);
result = startedFunction.apply(context);
if (result.isStarted()) {
break;
}
} catch (Exception ignored) {
}
}
if (result == null) {
destroyProcess(quarkusProcess);
throw new RuntimeException("Unable to start target quarkus application " + waitTimeSeconds + "s");
}
return result;
}
/**
* Updates the configuration necessary to make all test systems knowledgeable about the port on which the launched
* process is listening
*/
static void updateConfigForPort(Integer effectivePort) {
System.setProperty("quarkus.http.port", effectivePort.toString()); //set the port as a system property in order to have it applied to Config
System.setProperty("quarkus.http.test-port", effectivePort.toString()); // needed for RestAssuredManager
installAndGetSomeConfig(); // reinitialize the configuration to make sure the actual port is used
System.clearProperty("test.url"); // make sure the old value does not interfere with setting the new one
System.setProperty("test.url", TestHTTPResourceManager.getUri());
}
/**
* Thread that reads a process output file looking for the line that indicates the address the application
* is listening on.
*/
private static class CaptureListeningDataReader implements Runnable {
private final Path processOutput;
private final Duration waitTime;
private final CountDownLatch signal;
private final AtomicReference<ListeningAddress> resultReference;
private final Pattern listeningRegex = Pattern.compile("Listening on:\\s+(https?):
public CaptureListeningDataReader(Path processOutput, Duration waitTime, CountDownLatch signal,
AtomicReference<ListeningAddress> resultReference) {
this.processOutput = processOutput;
this.waitTime = waitTime;
this.signal = signal;
this.resultReference = resultReference;
}
@Override
public void run() {
if (!ensureProcessOutputFileExists()) {
unableToDetermineData("Log file '" + processOutput.toAbsolutePath() + "' was not created.");
return;
}
long bailoutTime = System.currentTimeMillis() + waitTime.toMillis();
try (BufferedReader reader = new BufferedReader(new FileReader(processOutput.toFile()))) {
while (true) {
if (reader.ready()) { // avoid blocking as the input is a file which continually gets more data added
String line = reader.readLine();
Matcher regexMatcher = listeningRegex.matcher(line);
if (regexMatcher.find()) {
dataDetermined(regexMatcher.group(1), Integer.valueOf(regexMatcher.group(2)));
return;
} else {
if (line.contains("Failed to start application (with profile")) {
unableToDetermineData("Application was not started: " + line);
return;
}
}
} else {
//wait until there is more of the file for us to read
try {
Thread.sleep(500);
} catch (InterruptedException e) {
unableToDetermineData(
"Thread interrupted while waiting for more data to become available in proccess output file: "
+ processOutput.toAbsolutePath().toString());
return;
}
if (System.currentTimeMillis() > bailoutTime) {
unableToDetermineData("Waited " + waitTime.getSeconds() + "seconds for " + processOutput
+ " to contain info about the listening port and protocol but no such info was found");
return;
}
}
}
} catch (Exception e) {
unableToDetermineData("Exception occurred while reading process output from file " + processOutput);
e.printStackTrace();
}
}
private boolean ensureProcessOutputFileExists() {
long bailoutTime = System.currentTimeMillis() + waitTime.toMillis();
while (System.currentTimeMillis() < bailoutTime) {
if (Files.exists(processOutput)) {
return true;
} else {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
unableToDetermineData("Thread interrupted while waiting for process output file to be created");
return false;
}
}
}
return false;
}
private void dataDetermined(String protocolValue, Integer portValue) {
this.resultReference.set(new ListeningAddress(portValue, protocolValue));
signal.countDown();
}
private void unableToDetermineData(String errorMessage) {
System.err.println(errorMessage);
this.resultReference.set(null);
signal.countDown();
}
}
/**
* Used to drain the input of a launched process
*/
private static class ProcessReader implements Runnable {
private final InputStream inputStream;
private ProcessReader(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public void run() {
byte[] b = new byte[100];
int i;
try {
while ((i = inputStream.read(b)) > 0) {
System.out.print(new String(b, 0, i, StandardCharsets.UTF_8));
}
} catch (IOException e) {
//ignore
}
}
}
private static class SimpleContext implements IntegrationTestStartedNotifier.Context {
private final Path logFile;
public SimpleContext(Path logFile) {
this.logFile = logFile;
}
@Override
public Path logFile() {
return logFile;
}
}
}
|
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
/**
* Used to perform Monte-Carlo simulation upon N x N matrix
*/
public class PercolationStats {
// threshold factor
private static final double THRESHOLD_FACTOR = 1.96;
//array of the threshold values
private double[] threshold;
//number of experiments
private int numberOFExperiments;
/**
* performs independent experiments on an size-by-size grid
* @param size number of grid
* @param numberOfExperiments number of experiments
*/
public PercolationStats(int size, int numberOfExperiments) {
if (size <= 0 || numberOfExperiments <= 0) {
throw new IllegalArgumentException("Please check the size " +
"and number of experiments");
}
threshold = new double[numberOfExperiments];
this.numberOFExperiments = numberOfExperiments;
for (int i = 0; i < numberOfExperiments; i++) {
int openCounter = calculate(size);
threshold[i] = (double) openCounter / (size * size);
}
}
/**+
* calculates the percolation of the grid
* @param n size of the grid
* @return number of opened positions
*/
private int calculate(final int n) {
Percolation percolation = new Percolation(n);
int openCounter = 0;
while (!percolation.percolates()) {
int x = StdRandom.uniform(1, n + 1);
int y = StdRandom.uniform(1, n + 1);
if (!percolation.isOpen(x, y)) {
percolation.open(x, y);
openCounter++;
}
}
return openCounter;
}
/**
* calculates the percolation threshold
* @return value of the threshold
*/
public double mean() {
return StdStats.mean(threshold);
}
/**
* calculates the sample standard deviation of percolation threshold,
* sharpness of the threshold
* @return value of the sharpness of the threshold
*/
public double stddev() {
if (numberOFExperiments == 1) {
return Double.NaN;
}
return StdStats.stddev(threshold);
}
/**
* low endpoint of 95% confidence interval
* @return value of the low endpoint interval
*/
public double confidenceLo() {
return mean() - (THRESHOLD_FACTOR * stddev()
/ Math.sqrt(numberOFExperiments));
}
/**
* high endpoint of 95% confidence interval
* @return value of the high endpoint interval
*/
public double confidenceHi() {
return mean() + (THRESHOLD_FACTOR * stddev()
/ Math.sqrt(numberOFExperiments));
}
/**
* test client
* @param args values to enter
*/
public static void main(String[] args) {
StdOut.println("Please state the number of experiments ");
int numberOfExperiments = StdIn.readInt();
StdOut.println("Please state the size of area ");
int size = StdIn.readInt();
PercolationStats percolationStats = new PercolationStats(size, numberOfExperiments);
double mean = percolationStats.mean();
double stddev = percolationStats.stddev();
double min = percolationStats.confidenceLo();
double max = percolationStats.confidenceHi();
StdOut.println("mean " + mean);
StdOut.println("stddev " + stddev);
StdOut.println("95% confidence interval = " + min + " - " + max);
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package RebuildBot;
//imports:
import RebuildBot.Input.Attack3Joystick;
import RebuildBot.Listeners.MovementListener;
import edu.wpi.first.wpilibj.IterativeRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
private Attack3Joystick joystick1;
private Attack3Joystick joystick2;
private Driving driving;
private MovementListener movementlistener;
public static final int PORT1= 1;
public static final int PORT2= 2;
//TO-DO: create objects universally.
/*hint: Look in robotinit.
what do you need to: control the robot(what so we have in the code
to control this thing)? make the robot move? Control the driving functions?*/
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
joystick1 = new Attack3Joystick(1);
joystick2 = new Attack3Joystick(2);
driving = new Driving();
movementlistener = new MovementListener(driving);
//TO-DO: initialize variables in robotInit()
//joystick(s)
//create constants for ports 1 and/or 2 these ports are for the computer
//driving
//adding joystick listener(s)
/*TO-DO: look through Attack3Joystick at the comment descriptions above
each method, which one should be used to give the Attack3Joystick
something new to listen to? which listener do we need to add?*/
}
/**
* This function is called once when autonomous mode is first started
*/
public void autonomousInit(){
}
/**
* This function is called once when operator control is first started
*/
public void teleopInit() {
System.out.println("The robot has been enabled.");
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
/*TO-Do: tell the joystick to update values, look at Attack3Joustick methods.
Becasue this method is in the teleopPeriodic() method it gets called
/ver and over and over again,and will upsate values effectivley. */
joystick1.listen();
joystick2.listen();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
}
}
|
package verification.platu.logicAnalysis;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Stack;
import javax.swing.JOptionPane;
import lpn.parser.Abstraction;
import lpn.parser.ExprTree;
import lpn.parser.LhpnFile;
import lpn.parser.Place;
import lpn.parser.Transition;
import lpn.parser.LpnDecomposition.LpnProcess;
import main.Gui;
import verification.platu.MDD.MDT;
import verification.platu.MDD.Mdd;
import verification.platu.MDD.mddNode;
import verification.platu.common.IndexObjMap;
import verification.platu.lpn.LPNTranRelation;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Options;
import verification.platu.markovianAnalysis.ProbGlobalState;
import verification.platu.markovianAnalysis.ProbGlobalStateSet;
import verification.platu.markovianAnalysis.ProbLocalStateGraph;
import verification.platu.partialOrders.DependentSet;
import verification.platu.partialOrders.DependentSetComparator;
import verification.platu.partialOrders.ProbStaticDependencySets;
import verification.platu.partialOrders.StaticDependencySets;
import verification.platu.por1.AmpleSet;
import verification.platu.project.PrjState;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.octagon.Equivalence;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.TimedStateSet;
import verification.timed_state_exploration.zoneProject.Zone;
public class Analysis {
private LinkedList<Transition> traceCex;
protected Mdd mddMgr = null;
private HashMap<Transition, HashSet<Transition>> cachedNecessarySets = new HashMap<Transition, HashSet<Transition>>();
/*
* visitedTrans is used in computeNecessary for a disabled transition of interest, to keep track of all transitions visited during trace-back.
*/
private HashSet<Transition> visitedTrans;
HashMap<Transition, StaticDependencySets> staticDependency = new HashMap<Transition, StaticDependencySets>();
public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) {
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
if (method.equals("dfs")) {
//if (Options.getPOR().equals("off")) {
//this.search_dfs(lpnList, initStateArray);
//this.search_dfs_mdd_1(lpnList, initStateArray);
//this.search_dfs_mdd_2(lpnList, initStateArray);
//else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
}
else if (method.equals("bfs")==true)
this.search_bfs(lpnList, initStateArray);
else if (method == "dfs_noDisabling")
//this.search_dfs_noDisabling(lpnList, initStateArray);
this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* This constructor performs dfs.
* @param lpnList
*/
public Analysis(StateGraph[] lpnList){
traceCex = new LinkedList<Transition>();
mddMgr = new Mdd(lpnList.length);
// if (method.equals("dfs")) {
// if (Options.getPOR().equals("off")) {
// //this.search_dfs(lpnList, initStateArray);
// this.search_dfsNative(lpnList, initStateArray);
// //this.search_dfs_mdd_1(lpnList, initStateArray);
// //this.search_dfs_mdd_2(lpnList, initStateArray);
// else
// //behavior analysis
// boolean BA = true;
// if(BA==true)
// CompositionalAnalysis.searchCompositional(lpnList);
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state");
// else
// this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "lpn");
// else if (method.equals("bfs")==true)
// this.search_bfs(lpnList, initStateArray);
// else if (method == "dfs_noDisabling")
// //this.search_dfs_noDisabling(lpnList, initStateArray);
// this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray);
}
/**
* Recursively find all reachable project states.
*/
int iterations = 0;
int stack_depth = 0;
int max_stack_depth = 0;
public void search_recursive(final StateGraph[] lpnList,
final State[] curPrjState,
final ArrayList<LinkedList<Transition>> enabledList,
HashSet<PrjState> stateTrace) {
int lpnCnt = lpnList.length;
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
stack_depth++;
if (stack_depth > max_stack_depth)
max_stack_depth = stack_depth;
iterations++;
if (iterations % 50000 == 0)
System.out.println("iterations: " + iterations
+ ", # of prjStates found: " + prjStateSet.size()
+ ", max_stack_depth: " + max_stack_depth);
for (int index = 0; index < lpnCnt; index++) {
LinkedList<Transition> curEnabledSet = enabledList.get(index);
if (curEnabledSet == null)
continue;
for (Transition firedTran : curEnabledSet) {
// while(curEnabledSet.size() != 0) {
// LPNTran firedTran = curEnabledSet.removeFirst();
// TODO: (check) Not sure if lpnList[index] is correct
State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran);
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
PrjState nextPrjState = new PrjState(nextStateArray);
//if (stateTrace.contains(nextPrjState) == true)
// System.out.println("found a cycle");
if (prjStateSet.add(nextPrjState) == false) {
continue;
}
// Get the list of enabled transition sets, and call
// findsg_recursive.
ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>();
for (int i = 0; i < lpnCnt; i++) {
if (curPrjState[i] != nextStateArray[i]) {
StateGraph Lpn_tmp = lpnList[i];
nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran,
// enabledList.get(i),
// false));
} else {
nextEnabledList.add(i, enabledList.get(i));
}
}
stateTrace.add(nextPrjState);
search_recursive(lpnList, nextStateArray, nextEnabledList,
stateTrace);
stateTrace.remove(nextPrjState);
}
}
}
/**
* An iterative implement of findsg_recursive().
*
* @param sgList
* @param start
* @param curLocalStateArray
* @param enabledArray
*/
public StateSetInterface search_dfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("
System.out.println("---> calling function search_dfs");
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
Transition firedFailure = null;
//Stack<State[]> stateStack = new Stack<State[]>();
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
//HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// Set of PrjStates that have been seen before. Set class documentation
// for how it behaves. Timing Change.
// HashMap<PrjState, PrjState> prjStateSet = generateStateSet();
StateSetInterface prjStateSet = generateStateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not. Timing Change.
if(!Options.getTimingAnalysisFlag()){
// If not doing timing.
if (!Options.getMarkovianModelFlag())
initPrjState = new PrjState(initStateArray);
else
initPrjState = new ProbGlobalState(initStateArray);
}
else{
// If timing is enabled.
initPrjState = new TimedPrjState(initStateArray);
TimedPrjState.incTSCount();
// Set the initial values of the inequality variables.
//((TimedPrjState) initPrjState).updateInequalityVariables();
}
prjStateSet.add(initPrjState);
if(Options.getMarkovianModelFlag()) {
((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState);
}
PrjState stateStackTop;
stateStackTop = initPrjState;
if (Options.getDebugMode())
printStateArray(stateStackTop.toStateArray(), "~~~~ stateStackTop ~~~~");
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode())
printDstLpnList(sgList);
LpnTranList initEnabled;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
initEnabled = StateGraph.getEnabledFromTranVector(initStateArray[0]);
}
else
{
// When timing is enabled, it is the project state that will determine
// what is enabled since it contains the zone. This indicates the zeroth zone
// contained in the project and the zeroth LPN to get the transitions from.
initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0);
}
//lpnTranStack.push(initEnabled.clone());
lpnTranStack.push(initEnabled);
curIndexStack.push(0);
if (Options.getDebugMode()) {
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransList(initEnabled, "initEnabled");
}
main_while_loop: while (failure == false && stateStack.size() != 0) {
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~");
}
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
//if (failureTranIsEnabled(curEnabled)) {
firedFailure = failureTranIsEnabled(curEnabled); // Null means no failures.
if(firedFailure != null){
failure = true;
if(Options.getTimingAnalysisFlag()&& Options.getOutputSgFlag()){
// Add the failure transition to the graph.
TimedPrjState tps = (TimedPrjState) stateStackTop;
// To have a target state, clone the last state.
TimedPrjState lastState = new TimedPrjState(tps.getStateArray(), tps.get_zones());
TimedPrjState.incTSCount();
stateStackTop.addNextGlobalState(firedFailure, lastState);
}
break main_while_loop;
}
if (Options.getDebugMode()) {
printStateArray(curStateArray, "
printTransList(curEnabled, "+++++++ curEnabled trans ++++++++");
}
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
printTranStack(lpnTranStack, "***** lpnTranStack *****");
}
curIndexStack.pop();
curIndex++;
while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
if(!Options.getTimingAnalysisFlag()){ // Timing Change
curEnabled = StateGraph.getEnabledFromTranVector(curStateArray[curIndex]).clone();
}
else{
// Get the enabled transitions from the zone that are associated with
// the current LPN.
curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex);
}
if (curEnabled.size() > 0) {
if (Options.getDebugMode()) {
printTransList(curEnabled, "+++++++ Push trans onto lpnTranStack ++++++++");
}
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
}
curIndex++;
}
}
if (curIndex == numLpns) {
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "~~~~ Remove stateStackTop from stateStack ~~~~");
}
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
continue;
}
Transition firedTran = curEnabled.removeLast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired transition: " + firedTran.getFullLabel());
System.out.println("
}
State[] nextStateArray;
PrjState nextPrjState; // Moved this definition up. Timing Change.
// The next state depends on whether timing is in use or not.
// Timing Change.
if(!Options.getTimingAnalysisFlag()){
nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
if (!Options.getMarkovianModelFlag())
nextPrjState = new PrjState(nextStateArray);
else
nextPrjState = new ProbGlobalState(nextStateArray);
}
else{
// Get the next timed state and extract the next un-timed states.
nextPrjState = sgList[curIndex].fire(sgList, stateStackTop,
(EventSet) firedTran);
nextStateArray = nextPrjState.toStateArray();
}
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
//LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns];
//LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns];
//LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns];
//LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns];
List<LinkedList<Transition>> curEnabledArray = new ArrayList<LinkedList<Transition>>();
List<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>();
for (int i = 0; i < numLpns; i++) {
LinkedList<Transition> enabledList;
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = StateGraph.getEnabledFromTranVector(curStateArray[i]);
}
else{
// Get the enabled transitions from the Zone for the appropriate
// LPN.
//enabledList = ((TimedPrjState) stateStackTop).getEnabled(i);
enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i);
}
curEnabledArray.add(i,enabledList);
if(!Options.getTimingAnalysisFlag()){ // Timing Change.
enabledList = StateGraph.getEnabledFromTranVector(nextStateArray[i]);
}
else{
//enabledList = ((TimedPrjState) nextPrjState).getEnabled(i);
enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i);
}
nextEnabledArray.add(i,enabledList);
// TODO: (temp) Stochastic model does not need disabling error?
if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) {
Transition disabledTran = firedTran.disablingError(
curEnabledArray.get(i), nextEnabledArray.get(i));
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
if(!Options.getTimingAnalysisFlag()){
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
}
else{
if (Analysis.deadLock(nextEnabledArray)){
System.out.println("*** Verification failed: deadlock.");
failure = true;
if(Options.get_displayResults()){
JOptionPane.showMessageDialog(Gui.frame,
"The system deadlocked.", "Error",
JOptionPane.ERROR_MESSAGE);
}
break main_while_loop;
}
}
// Build transition rate map on global state.
if (Options.getMarkovianModelFlag()) {
for (State localSt : stateStackTop.toStateArray()) {
for (Transition t : localSt.getEnabledTransitions()) {
double tranRate = ((ProbLocalStateGraph) localSt.getLpn().getStateGraph()).getTranRate(localSt, t);
((ProbGlobalState) stateStackTop).addNextGlobalTranRate(t, tranRate);
}
}
}
//PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change.
boolean existingState;
existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState);
//existingState = prjStateSet.keySet().contains(nextPrjState); //|| stateStack.contains(nextPrjState);
if (existingState == false) {
prjStateSet.add(nextPrjState);
//prjStateSet.put(nextPrjState,nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getTimingAnalysisFlag()){
// Assign a new id.
TimedPrjState tpState = (TimedPrjState) nextPrjState;
tpState.setCurrentId();
TimedPrjState.incTSCount();
if(Options.getOutputSgFlag()){
// Add the current state as a previous state for the next state.
if(Zone.getSupersetFlag()){
tpState.addPreviousState((EventSet) firedTran, (TimedPrjState) stateStackTop);
}
}
}
if (Options.getMarkovianModelFlag() || Options.getOutputSgFlag()) {
stateStackTop.addNextGlobalState(firedTran, nextPrjState);
}
// else {
// if (Options.getDebugMode()) {
// printStateArray(curStateArray);
// printStateArray(nextStateArray);
// System.out.println("stateStackTop: ");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("firedTran = " + firedTran.getName());
// printNextStateMap(stateStackTop.getNextStateMap());
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
lpnTranStack.push((LpnTranList) nextEnabledArray.get(0).clone());
curIndexStack.push(0);
totalStates++;
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "~~~~~~~ Add global state to stateStack ~~~~~~~");
System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
printTransList(nextEnabledArray.get(0), "");
printTranStack(lpnTranStack, "******** lpnTranStack ***********");
}
}
else { // existingState == true
if (Options.getMarkovianModelFlag()) {
PrjState nextPrjStInStateSet = ((ProbGlobalStateSet) prjStateSet).get(nextPrjState);
stateStackTop.addNextGlobalState(firedTran, nextPrjStInStateSet);
}
else if (!Options.getMarkovianModelFlag() && Options.getOutputSgFlag()) { // non-stochastic model, but need to draw global state graph.
for (PrjState prjSt : prjStateSet) {
if(Options.getTimingAnalysisFlag() && Zone.getSubsetFlag()){
TimedPrjState nextTimed = (TimedPrjState) nextPrjState;
if(nextTimed.subset((TimedPrjState) prjSt)){
// If the subset flag is in effect, then a set can be considered
// 'previously seen' if the newly produced state is a subset of
// of the previous set and not just equal. In addition, we cannot
// break, since the current state could be a subset of more than
// one state.
stateStackTop.addNextGlobalState(firedTran, prjSt);
if(Zone.getSupersetFlag()){
// If supersets are in effect, add the previous states.
TimedPrjState tps = (TimedPrjState) prjSt;
tps.addPreviousState((EventSet) firedTran, (TimedPrjState) stateStackTop);
}
}
}
else if (prjSt.equals(nextPrjState)) {
stateStackTop.addNextGlobalState(firedTran, prjSt);
break;
}
}
}
else {
if (Options.getOutputSgFlag()) {
if (Options.getDebugMode()) {
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
printStateArray(stateStackTop.toStateArray(), "stateStackTop: ");
System.out.println("firedTran = " + firedTran.getFullLabel());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
}
}
}
}
}
double totalStateCnt =0;
totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if(Options.getTimingAnalysisFlag()){// && !failure){
if(!failure){
if(Options.get_displayResults()){
JOptionPane.showMessageDialog(Gui.frame,
"Verification was successful.", "Success",
JOptionPane.INFORMATION_MESSAGE);
}
System.out.println("Verification was successful");
}
else{
System.out.println("************ System failed. ***********");
if(firedFailure != null){
if(Options.get_displayResults()){
JOptionPane.showMessageDialog(Gui.frame,
"Failure transition " + firedFailure.getLabel() + " is enabled.", "Error",
JOptionPane.ERROR_MESSAGE);
}
System.out.println("The failure transition" + firedFailure.getLabel() + "fired.");
}
else{
if(Options.get_displayResults()){
JOptionPane.showMessageDialog(Gui.frame,
"System failed for reason other\nthan a failure transition.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
System.out.println(prjStateSet.toString());
}
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
System.out.println("outputSGPath = " + Options.getPrjSgPath());
//drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true);
drawGlobalStateGraph(initPrjState, prjStateSet);
}
// try{
// File stateFile = new File(Options.getPrjSgPath() + Options.getLogName() + ".txt");
// FileWriter fileWritter = new FileWriter(stateFile,true);
// BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
// // TODO: Need to merge variable vectors from different local states.
// ArrayList<Integer> vector;
// String curPrjStInfo = "";
// for (PrjState prjSt : prjStateSet) {
// // marking
// curPrjStInfo += "marking: ";
// for (State localSt : prjSt.toStateArray())
// curPrjStInfo += intArrayToString("markings", localSt) + "\n";
// // variable vector
// curPrjStInfo += "var values: ";
// for (State localSt : prjSt.toStateArray()) {
// localSt.getLpn().getAllVarsWithValuesAsInt(localSt.getVariableVector());
// //curPrjStInfo += intArrayToString("vars", localSt)+ "\n";
// // tranVector
// curPrjStInfo += "tran vector: ";
// for (State localSt : prjSt.toStateArray())
// curPrjStInfo += boolArrayToString("enabled trans", localSt)+ "\n";
// bufferWritter.write(curPrjStInfo);
// //bufferWritter.flush();
// bufferWritter.close();
// System.out.println("Done writing state file.");
// }catch(IOException e){
// e.printStackTrace();
return prjStateSet;
}
// private boolean failureCheck(LinkedList<Transition> curEnabled) {
// boolean failureTranIsEnabled = false;
// for (Transition tran : curEnabled) {
// if (tran.isFail()) {
// JOptionPane.showMessageDialog(Gui.frame,
// "Failure transition " + tran.getLabel() + " is enabled.", "Error",
// JOptionPane.ERROR_MESSAGE);
// failureTranIsEnabled = true;
// break;
// return failureTranIsEnabled;
// /**
// * Generates the appropriate version of a HashSet<PrjState> for storing
// * the "already seen" set of project states.
// * @return
// * Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet
// * depending on the type.
// */
// private HashSet<PrjState> generateStateSet(){
// boolean timed = Options.getTimingAnalysisFlag();
// boolean subsets = Zone.getSubsetFlag();
// boolean supersets = Zone.getSupersetFlag();
// if(Options.getMarkovianModelFlag()){
// return new ProbGlobalStateSet();
// else if(timed && (subsets || supersets)){
// return new TimedStateSet();
// return new HashSet<PrjState>();
/**
* Generates the appropriate version of a HashSet<PrjState> for storing
* the "already seen" set of project states.
* @return
* Returns a HashSet<PrjState>, a StateSet, or a ProbGlobalStateSet
* depending on the type.
*/
private static StateSetInterface generateStateSet(){
boolean timed = Options.getTimingAnalysisFlag();
boolean subsets = Zone.getSubsetFlag();
boolean supersets = Zone.getSupersetFlag();
if(Options.getMarkovianModelFlag()){
return new ProbGlobalStateSet();
}
else if(timed && (subsets || supersets)){
return new TimedStateSet();
}
return new HashSetWrapper();
}
private static Transition failureTranIsEnabled(LinkedList<Transition> enabledTrans) {
Transition failure = null;
for (Transition tran : enabledTrans) {
if (tran.isFail()) {
if(Zone.get_writeLogFile() != null){
try {
Zone.get_writeLogFile().write(tran.getLabel());
Zone.get_writeLogFile().newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
// JOptionPane.showMessageDialog(Gui.frame,
// "Failure transition " + tran.getLabel() + " is enabled.", "Error",
// JOptionPane.ERROR_MESSAGE);
return tran;
}
}
return failure;
}
/**
* Produces DOT files for visualizing the global state graph. <p>
* This method assumes that the global state graph exists.
* @param initGlobalState
* @param globalStateSet
*/
public static void drawGlobalStateGraph(PrjState initGlobalState, StateSetInterface globalStateSet) {
try {
String fileName = null;
if (Options.getPOR().toLowerCase().equals("off")) {
fileName = Options.getPrjSgPath() + "full_sg.dot";
}
else {
fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_"
+ Options.getCycleClosingMthd().toLowerCase() + "_"
+ Options.getCycleClosingStrongStubbornMethd().toLowerCase() + "_sg.dot";
}
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
NumberFormat num = NumberFormat.getNumberInstance();//NumberFormat.getInstance();
num.setMaximumFractionDigits(6);
num.setGroupingUsed(false);
out.write("digraph G {\n");
out.write("node [shape=box, style=rounded]");
for (PrjState curGlobalState : globalStateSet) {
// Build composite current global state.
String curVarNames = "";
String curVarValues = "";
String curMarkings = "";
String curEnabledTrans = "";
String curGlobalStateLabel = "";
String curGlobalStateProb = null;
String DBM = "";
HashMap<String, Integer> vars = new HashMap<String, Integer>();
for (State curLocalState : curGlobalState.toStateArray()) {
curGlobalStateLabel = curGlobalStateLabel + "_" + "S" + curLocalState.getIndex();
LhpnFile curLpn = curLocalState.getLpn();
for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) {
vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVariableVector()[i]);
}
curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState);
if (!boolArrayToString("enabled trans", curLocalState).equals(""))
curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState);
}
for (String vName : vars.keySet()) {
Integer vValue = vars.get(vName);
curVarValues = curVarValues + vValue + ", ";
curVarNames = curVarNames + vName + ", ";
}
if (!curVarNames.isEmpty() && !curVarValues.isEmpty()) {
curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(","));
curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(","));
}
curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length());
curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length());
if (Options.getMarkovianModelFlag()) {
// State probability after steady state analysis.
curGlobalStateProb = num.format(((ProbGlobalState) curGlobalState).getCurrentProb());
}
if(Options.getTimingAnalysisFlag()){
TimedPrjState timedState = (TimedPrjState) curGlobalState;
curGlobalStateLabel = "TS_" + timedState.getTSID();
if(Options.get_displayDBM()){
Equivalence[] dbm = timedState.get_zones();
DBM = "\\n" + dbm[0].toString().replace("\n", "\\n") + "\\n";
}
}
else{
curGlobalStateLabel = curGlobalStateLabel.substring(curGlobalStateLabel.indexOf("_")+1, curGlobalStateLabel.length());
}
if (curGlobalState.equals(initGlobalState)) {
String sgVector = ""; // sgVector is a vector of LPN labels. It shows the order of local state graph composition.
for (State s : initGlobalState.toStateArray()) {
sgVector = sgVector + s.getLpn().getLabel() + ", ";
}
out.write("Inits[shape=plaintext, label=\"variable vector:<" + curVarNames + ">\\n" + "LPN vector:<" +sgVector.substring(0, sgVector.lastIndexOf(",")) + ">\"]\n");
if (!Options.getMarkovianModelFlag()) {
out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\n" + DBM + "\\n" + "\", style=\"rounded, filled\"]\n");
}
else {
out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\", style=\"rounded, filled\"]\n");
}
}
else { // non-initial global state(s)
if (!Options.getMarkovianModelFlag()) {
out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\n" + DBM + "\\n" + "\"]\n");
}
else {
out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
+ "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\\nProb = " + curGlobalStateProb + "\"]\n");
}
}
for (Transition outTran : curGlobalState.getNextGlobalStateMap().keySet()) {
PrjState nextGlobalState = curGlobalState.getNextGlobalStateMap().get(outTran);
String nextGlobalStateLabel = "";
if(Options.getTimingAnalysisFlag()){
nextGlobalStateLabel = "TS_" + ((TimedPrjState)nextGlobalState).getTSID();
}else{
nextGlobalStateLabel = nextGlobalState.getLabel();
}
String outTranName = outTran.getLabel();
if (!Options.getMarkovianModelFlag()) {
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel + "[label=\"" + outTranName + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent()) {
// out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
// + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n");
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel + "[label=\"" + outTranName + "\", fontcolor=blue]\n");
}
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel + "[label=\"" + outTranName + "\", fontcolor=purple]\n");
else {
// out.write(curGlobalStateLabel + "[label=\"" + curGlobalStateLabel + "\\n<"+curVarValues+">"
// + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n");
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel + "[label=\"" + outTranName + "\"]\n");
}
}
else { // stochastic global state graph
//State localState = curGlobalState.toStateArray()[outTran.getLpn().getLpnIndex()];
//String outTranRate = num.format(((ProbLocalStateGraph) localState.getStateGraph()).getTranRate(localState, outTran));
String outTranRate = num.format(((ProbGlobalState) curGlobalState).getOutgoingTranRate(outTran));
if (outTran.isFail() && !outTran.isPersistent())
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=red]\n");
else if (!outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=blue]\n");
else if (outTran.isFail() && outTran.isPersistent())
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\", fontcolor=purple]\n");
else
out.write(curGlobalStateLabel + "->" + nextGlobalStateLabel
+ "[label=\"" + outTranName + "\\n" + outTranRate + "\"]\n");
}
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing global state graph as dot file.");
}
}
private void drawDependencyGraphs(LhpnFile[] lpnList) {
String fileName = Options.getPrjSgPath() + "dependencyGraph.dot";
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileName));
out.write("digraph G {\n");
for (Transition curTran : staticDependency.keySet()) {
String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel();
out.write(curTranStr + "[shape=\"box\"];");
out.newLine();
}
for (Transition curTran : staticDependency.keySet()) {
StaticDependencySets curStaticSets = staticDependency.get(curTran);
String curTranStr = curTran.getLpn().getLabel() + "_" + curTran.getLabel();
// TODO: getOtherTransDisableCurTranSet(false) or getOtherTransDisableCurTranSet(true)
for (Transition curTranInDisable : curStaticSets.getOtherTransDisableSeedTran(false)) {
String curTranInDisableStr = curTranInDisable.getLpn().getLabel() + "_" + curTranInDisable.getLabel();
out.write(curTranInDisableStr + "->" + curTranStr + "[color=\"chocolate\"];");
out.newLine();
}
// for (Transition curTranInDisable : curStaticSets.getCurTranDisableOtherTransSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"chocolate\"];");
// out.newLine();
// for (Transition curTranInDisable : curStaticSets.getDisableSet()) {
// String curTranInDisableStr = lpnList[curTranInDisable.getLpnIndex()].getLabel()
// + "_" + lpnList[curTranInDisable.getLpnIndex()].getTransition(curTranInDisable.getTranIndex()).getName();
// out.write(curTranStr + "->" + curTranInDisableStr + "[color=\"blue\"];");
// out.newLine();
HashSet<Transition> enableByBringingToken = new HashSet<Transition>();
for (Place p : curTran.getPreset()) {
for (Transition presetTran : p.getPreset()) {
enableByBringingToken.add(presetTran);
}
}
for (Transition curTranInCanEnable : enableByBringingToken) {
String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel();
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"mediumaquamarine\"];");
out.newLine();
}
for (HashSet<Transition> canEnableOneConjunctSet : curStaticSets.getOtherTransSetSeedTranEnablingTrue()) {
for (Transition curTranInCanEnable : canEnableOneConjunctSet) {
String curTranInCanEnableStr = curTranInCanEnable.getLpn().getLabel() + "_" + curTranInCanEnable.getLabel();
out.write(curTranStr + "->" + curTranInCanEnableStr + "[color=\"deepskyblue\"];");
out.newLine();
}
}
}
out.write("}");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVariableVector().length; i++) {
arrayStr = arrayStr + curState.getVariableVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private static String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabled trans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
//arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getFullLabel() + ", ";
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ", ";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private static void printStateArray(State[] stateArray, String title) {
if (title != null)
System.out.println(title);
for (int i=0; i<stateArray.length; i++) {
System.out.println("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +"): ");
System.out.println("\tmarkings: " + intArrayToString("markings", stateArray[i]));
System.out.println("\tvar values: " + intArrayToString("vars", stateArray[i]));
System.out.println("\tenabled trans: " + boolArrayToString("enabled trans", stateArray[i]));
}
System.out.println("
}
private static void printTransList(LinkedList<Transition> tranList, String title) {
if (title != null && !title.equals(""))
System.out.println("+++++++" + title + "+++++++");
for (int i=0; i< tranList.size(); i++)
System.out.println(tranList.get(i).getFullLabel() + ", ");
System.out.println("+++++++++++++");
}
// private void writeIntegerStackToDebugFile(Stack<Integer> curIndexStack, String title) {
// if (title != null)
// System.out.println(title);
// for (int i=0; i < curIndexStack.size(); i++) {
// System.out.println(title + "[" + i + "]" + curIndexStack.get(i));
private static void printDstLpnList(StateGraph[] lpnList) {
System.out.println("++++++ dstLpnList ++++++");
for (int i=0; i<lpnList.length; i++) {
LhpnFile curLPN = lpnList[i].getLpn();
System.out.println("LPN: " + curLPN.getLabel());
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j< allTrans.length; j++) {
System.out.println(allTrans[j].getLabel() + ": ");
for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) {
System.out.println(allTrans[j].getDstLpnList().get(k).getLabel() + ",");
}
System.out.print("\n");
}
System.out.println("
}
System.out.println("++++++++++++++++++++");
}
private static void constructDstLpnList(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
LhpnFile curLPN = sgList[i].getLpn();
Transition[] allTrans = curLPN.getAllTransitions();
for (int j=0; j<allTrans.length; j++) {
Transition curTran = allTrans[j];
for (int k=0; k<sgList.length; k++) {
curTran.setDstLpnList(sgList[k].getLpn());
}
}
}
}
/**
* This method performs first-depth search on an array of LPNs and applies partial order reduction technique with trace-back on LPNs.
* @param sgList
* @param initStateArray
* @param cycleClosingMthdIndex
* @return
*/
public StateSetInterface searchPOR_taceback(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> calling function searchPOR_traceback");
System.out.println("---> " + Options.getPOR());
System.out.println("---> " + Options.getCycleClosingMthd());
System.out.println("---> " + Options.getCycleClosingStrongStubbornMethd());
double peakUsedMem = 0;
double peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int numLpns = sgList.length;
Transition firedFailure = null;
LhpnFile[] lpnList = new LhpnFile[numLpns];
for (int i=0; i<numLpns; i++) {
lpnList[i] = sgList[i].getLpn();
}
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
StateSetInterface prjStateSet = generateStateSet();
PrjState initPrjState;
// Create the appropriate type for the PrjState depending on whether timing is
// being used or not.
if (!Options.getMarkovianModelFlag()) {
initPrjState = new PrjState(initStateArray);
}
else {
initPrjState = new ProbGlobalState(initStateArray);
}
prjStateSet.add(initPrjState);
if(Options.getMarkovianModelFlag()) {
((ProbGlobalStateSet) prjStateSet).setInitState(initPrjState);
}
PrjState stateStackTop = initPrjState;
if (Options.getDebugMode())
printStateArray(stateStackTop.toStateArray(), "%%%%%%% stateStackTop %%%%%%%%");
stateStack.add(stateStackTop);
constructDstLpnList(sgList);
if (Options.getDebugMode())
printDstLpnList(sgList);
// Determine statistically the dependency relations between transitions.
HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length);
//HashMap<Transition, StaticSets> staticSetsMap = new HashMap<Transition, StaticSets>();
HashMap<Transition, Integer> allProcessTransInOneLpn = new HashMap<Transition, Integer>();
HashMap<Transition, LpnProcess> allTransitionsToLpnProcesses = new HashMap<Transition, LpnProcess>();
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
allTransitions.put(lpnIndex, lpnList[lpnIndex].getAllTransitions());
Abstraction abs = new Abstraction(lpnList[lpnIndex]);
abs.decomposeLpnIntoProcesses();
allProcessTransInOneLpn = abs.getTransWithProcIDs();
HashMap<Integer, LpnProcess> processMapForOneLpn = new HashMap<Integer, LpnProcess>();
for (Transition curTran: allProcessTransInOneLpn.keySet()) {
Integer procId = allProcessTransInOneLpn.get(curTran);
if (!processMapForOneLpn.containsKey(procId)) {
LpnProcess newProcess = new LpnProcess(procId);
newProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (newProcess.getStateMachineFlag()
&& ((curTran.getPreset().length > 1)
|| (curTran.getPostset().length > 1))) {
newProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
newProcess.addPlaceToProcess(p);
}
}
processMapForOneLpn.put(procId, newProcess);
allTransitionsToLpnProcesses.put(curTran, newProcess);
}
else {
LpnProcess curProcess = processMapForOneLpn.get(procId);
curProcess.addTranToProcess(curTran);
if (curTran.getPreset() != null) {
if (curProcess.getStateMachineFlag()
&& (curTran.getPreset().length > 1
|| curTran.getPostset().length > 1)) {
curProcess.setStateMachineFlag(false);
}
Place[] preset = curTran.getPreset();
for (Place p : preset) {
curProcess.addPlaceToProcess(p);
}
}
allTransitionsToLpnProcesses.put(curTran, curProcess);
}
}
}
HashMap<Transition, Integer> tranFiringFreq = null;
// if (Options.getUseDependentQueue())
tranFiringFreq = new HashMap<Transition, Integer>(allTransitions.keySet().size());
// Build conjuncts for each transition's enabling condition first before dealing with dependency and enable sets.
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
for (Transition curTran: allTransitions.get(lpnIndex)) {
if (curTran.getEnablingTree() != null)
curTran.buildConjunctsOfEnabling(curTran.getEnablingTree());
}
}
for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) {
if (Options.getDebugMode()) {
System.out.println("=======LPN = " + lpnList[lpnIndex].getLabel() + "=======");
}
for (Transition seedTran: allTransitions.get(lpnIndex)) {
StaticDependencySets seedStatic = null;
if (!Options.getMarkovianModelFlag())
seedStatic = new StaticDependencySets(seedTran, allTransitionsToLpnProcesses);
else
seedStatic = new ProbStaticDependencySets(seedTran, allTransitionsToLpnProcesses);
// Requires buildConjunctsOfEnabling(ExprTree) in Transition class to be called on all transitions here.
seedStatic.buildOtherTransSetSeedTranEnablingTrue();
seedStatic.buildSeedTranDisableOtherTrans();
seedStatic.buildOtherTransDisableSeedTran();
if (Options.getMarkovianModelFlag() && Options.getTranRatePorDef().toLowerCase().equals("full")) {
((ProbStaticDependencySets) seedStatic).buildSeedTranModifyOtherTransRatesSet();
((ProbStaticDependencySets) seedStatic).buildOtherTransModifySeedTranRateSet();
}
staticDependency.put(seedTran, seedStatic);
tranFiringFreq.put(seedTran, 0);
}
}
if (Options.getDebugMode()) {
printStaticSetsMap(lpnList);
}
LpnTranList initStrongStubbornTrans = buildStrongStubbornSet(initStateArray, null, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop, null);
lpnTranStack.push(initStrongStubbornTrans);
if (Options.getDebugMode()) {
printTransList(initStrongStubbornTrans, "+++++++ Push trans onto lpnTranStack @ 1++++++++");
drawDependencyGraphs(lpnList);
}
updateLocalStrongStubbornSetTbl(initStrongStubbornTrans, sgList, initStateArray);
main_while_loop: while (failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~~~ loop " + iterations + " begins ~~~~~~~~~~~");
}
if (iterations % 100000 == 0) {
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack_depth: " + stateStack.size()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
LinkedList<Transition> curStrongStubbornTrans = lpnTranStack.peek();
firedFailure = failureTranIsEnabled(curStrongStubbornTrans); // Null mean no failure.
//if (failureTranIsEnabled(curStrongStubbornTrans)) {
if(firedFailure != null){
return null;
}
if (curStrongStubbornTrans.size() == 0) {
lpnTranStack.pop();
prjStateSet.add(stateStackTop);
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (Options.getDebugMode()) {
System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
printTranStack(lpnTranStack, "
// System.out.println("
// printPrjStateSet(prjStateSet);
}
continue;
}
Transition firedTran = curStrongStubbornTrans.removeLast();
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Fired Transition: " + firedTran.getFullLabel());
System.out.println("
}
Integer freq = tranFiringFreq.get(firedTran) + 1;
tranFiringFreq.put(firedTran, freq);
// if (Options.getDebugMode()) {
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// //printHashMap(tranFiringFreq, sgList);
State[] nextStateArray = sgList[firedTran.getLpn().getLpnIndex()].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
PrjState nextPrjState;
if (!Options.getMarkovianModelFlag())
nextPrjState = new PrjState(nextStateArray);
else
nextPrjState = new ProbGlobalState(nextStateArray);
// Check if the firedTran causes disabling error or deadlock.
// TODO: (temp) Stochastic model does not need disabling error?
if (Options.getReportDisablingError() && !Options.getMarkovianModelFlag()) {
for (int i=0; i<numLpns; i++) {
Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
}
LpnTranList nextStrongStubbornTrans = new LpnTranList();
nextStrongStubbornTrans = buildStrongStubbornSet(curStateArray, nextStateArray, tranFiringFreq, sgList, lpnList, prjStateSet, stateStackTop, firedTran);
// check for possible deadlock
if (nextStrongStubbornTrans.size() == 0) {
System.out.println("*** Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
// Build transition rate map on global state.
if (Options.getMarkovianModelFlag()) {
for (State localSt : stateStackTop.toStateArray()) {
for (Transition t : localSt.getEnabledTransitions()) {
double tranRate = ((ProbLocalStateGraph) localSt.getLpn().getStateGraph()).getTranRate(localSt, t);
((ProbGlobalState) stateStackTop).addNextGlobalTranRate(t, tranRate);
}
}
}
// Moved earlier.
// PrjState nextPrjState;
// if (!Options.getMarkovianModelFlag())
// nextPrjState = new PrjState(nextStateArray);
// else
// nextPrjState = new ProbGlobalState(nextStateArray);
boolean existingState;
existingState = prjStateSet.contains(nextPrjState);//|| stateStack.contains(nextPrjState);
if (existingState == false) {
if (Options.getDebugMode()) {
System.out.println("%%%%%%% existingSate == false %%%%%%%%");
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
printStateArray(stateStackTop.toStateArray(), "stateStackTop");
System.out.println("firedTran = " + firedTran.getFullLabel());
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
System.out.println("
}
prjStateSet.add(nextPrjState);
//updateLocalStrongStubbornSetTbl(nextStrongStubbornTrans, sgList, nextStateArray);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
if (Options.getMarkovianModelFlag() || Options.getOutputSgFlag()) {
stateStackTop.addNextGlobalState(firedTran, nextPrjState);
// System.out.println("@1, added (" + firedTran.getFullLabel() + ", " + nextPrjState.getLabel() + ") to curGlobalState " + stateStackTop.getLabel());
}
stateStackTop = nextPrjState;
stateStack.add(stateStackTop);
lpnTranStack.push(nextStrongStubbornTrans.clone());
updateLocalStrongStubbornSetTbl(nextStrongStubbornTrans, sgList, nextStateArray);
totalStates++;
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add global state to stateStack %%%%%%%%");
printTransList(nextStrongStubbornTrans, "+++++++ Push trans onto lpnTranStack @ 2++++++++");
}
}
else { // existingState = true
PrjState nextPrjStInStateSet = null;
if (Options.getMarkovianModelFlag()) {
nextPrjStInStateSet = ((ProbGlobalStateSet) prjStateSet).get(nextPrjState);
stateStackTop.addNextGlobalState(firedTran, nextPrjStInStateSet);
// System.out.println("@2, added (" + firedTran.getFullLabel() + ", " + nextPrjState.getLabel() + ") to curGlobalState " + stateStackTop.getLabel());
}
else if (!Options.getMarkovianModelFlag() && Options.getOutputSgFlag()) { // non-stochastic model, but need to draw global state graph.
for (PrjState prjSt : prjStateSet) {
if (prjSt.equals(nextPrjState)) {
nextPrjStInStateSet = prjSt;
break;
}
}
stateStackTop.addNextGlobalState(firedTran, nextPrjStInStateSet);
// System.out.println("@3, added (" + firedTran.getFullLabel() + ", " + nextPrjStInStateSet.getLabel() + ") to curGlobalState " + stateStackTop.getLabel());
}
else { // non-stochastic model, no need to draw global state graph, so no need to add the next global state to stateStackTop
if (Options.getDebugMode()) {
printStateArray(curStateArray, "******* curStateArray *******");
printStateArray(nextStateArray, "******* nextStateArray *******");
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray(), "stateStackTop: ");
System.out.println("firedTran = " + firedTran.getFullLabel());
// System.out.println("nextStateMap for stateStackTop before firedTran being added: ");
// printNextGlobalStateMap(stateStackTop.getNextStateMap());
System.out.println("
}
}
if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check
if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) {
if (Options.getDebugMode()) {
System.out.println("
System.out.println("Global state " + printGlobalStateLabel(nextPrjState) + " has been seen before and is on state stack.");
}
HashSet<Transition> nextStrongStubbornSet = new HashSet<Transition>();
HashSet<Transition> curStrongStubbornSet = new HashSet<Transition>();
for (Transition t : nextStrongStubbornTrans)
nextStrongStubbornSet.add(t);
for (State curSt : curStateArray) {
if (curSt.getStateGraph().getEnabledSetTbl().get(curSt) != null) {
curStrongStubbornSet.addAll(curSt.getStateGraph().getEnabledSetTbl().get(curSt));
}
}
LpnTranList newCurStateStrongStubborn = new LpnTranList();
newCurStateStrongStubborn = computeCycleClosingTrans(curStateArray, nextStateArray,
tranFiringFreq, sgList, nextStrongStubbornSet, curStrongStubbornSet, firedTran);
if (newCurStateStrongStubborn != null && !newCurStateStrongStubborn.isEmpty()) {
if (Options.getDebugMode()) {
printStateArray(stateStackTop.toStateArray(), "%%%%%%% Add state to stateStack %%%%%%%%");
System.out.println("stateStackTop: ");
printStateArray(stateStackTop.toStateArray(), "stateStackTop");
System.out.println("nextStateMap for stateStackTop: ");
//printNextGlobalStateMap(nextPrjState.getNextStateMap());
}
lpnTranStack.peek().addAll(newCurStateStrongStubborn);
// lpnTranStack.push(newNextPersistent);
// stateStackTop.setChild(nextPrjStInStateSet);
// nextPrjStInStateSet.setFather(stateStackTop);
// stateStackTop = nextPrjStInStateSet;
// stateStack.add(stateStackTop);
updateLocalStrongStubbornSetTbl(newCurStateStrongStubborn, sgList, nextStateArray);
if (Options.getDebugMode()) {
printTransList(newCurStateStrongStubborn, "+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++");
printTranStack(lpnTranStack, "******* lpnTranStack ***************");
}
}
}
}
else {
updateLocalStrongStubbornSetTbl(nextStrongStubbornTrans, sgList, nextStateArray);
}
}
}
double totalStateCnt = prjStateSet.size();
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStateCnt
+ ", max_stack_depth: " + max_stack_depth
+ ", peak total memory: " + peakTotalMem / 1000000 + " MB"
+ ", peak used memory: " + peakUsedMem / 1000000 + " MB");
if (Options.getOutputLogFlag())
writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000);
if (Options.getOutputSgFlag()) {
System.out.println("outputSGPath = " + Options.getPrjSgPath());
drawGlobalStateGraph(initPrjState, prjStateSet);
}
return prjStateSet;
}
/**
* Print the prjState's label. The label consists of full labels of each local state that composes it.
* @param prjState
* @return
*/
private static String printGlobalStateLabel(PrjState prjState) {
String prjStateLabel = "";
for (State local : prjState.toStateArray()) {
prjStateLabel += local.getFullLabel() + "_";
}
return prjStateLabel.substring(0, prjStateLabel.lastIndexOf("_"));
}
private static String printGlobalStateLabel(State[] nextStateArray) {
String prjStateLabel = "";
for (State local : nextStateArray) {
prjStateLabel += local.getFullLabel() + "_";
}
return prjStateLabel.substring(0, prjStateLabel.lastIndexOf("_"));
}
private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt,
double peakTotalMem, double peakUsedMem) {
try {
String fileName = null;
if (isPOR) {
fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_"
+ Options.getCycleClosingMthd() + "_" + Options.getCycleClosingStrongStubbornMethd() + ".log";
}
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n");
out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t"
+ peakUsedMem + "\n");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing performance results.");
}
}
private static void printTranStack(Stack<LinkedList<Transition>> lpnTranStack, String title) {
if (title != null)
System.out.println(title);
for (int i=0; i<lpnTranStack.size(); i++) {
LinkedList<Transition> tranList = lpnTranStack.get(i);
for (int j=0; j<tranList.size(); j++) {
System.out.println(tranList.get(j).getFullLabel());
}
System.out.println("
}
}
// private void printNextGlobalStateMap(HashMap<Transition, PrjState> nextStateMap) {
// for (Transition t: nextStateMap.keySet()) {
// System.out.println(t.getFullLabel() + " -> ");
// State[] stateArray = nextStateMap.get(t).getStateArray();
// for (int i=0; i<stateArray.length; i++) {
// System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +")" +", ");
// System.out.println("");
// private LpnTranList convertToLpnTranList(HashSet<Transition> newNextPersistent) {
// LpnTranList newNextPersistentTrans = new LpnTranList();
// for (Transition lpnTran : newNextPersistent) {
// newNextPersistentTrans.add(lpnTran);
// return newNextPersistentTrans;
private LpnTranList computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<Transition, Integer> tranFiringFreq,
StateGraph[] sgList, HashSet<Transition> nextStateStrongStubbornSet, HashSet<Transition> curStateStrongStubbornSet, Transition firedTran) {
for (State s : nextStateArray)
if (s == null)
throw new NullPointerException();
String cycleClosingMthd = Options.getCycleClosingMthd();
LpnTranList newCurStateStrongStubbornSet = new LpnTranList();
HashSet<Transition> nextStateEnabled = new HashSet<Transition>();
HashSet<Transition> curStateEnabled = new HashSet<Transition>();
for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
nextStateEnabled.addAll(StateGraph.getEnabledFromTranVector(nextStateArray[lpnIndex]));
curStateEnabled.addAll(StateGraph.getEnabledFromTranVector(curStateArray[lpnIndex]));
}
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (nextStateArray[lpnIndex].getTranVector()[i])
// nextStateEnabled.add(tran);
// if (curStateArray[lpnIndex].getTranVector()[i])
// curStateEnabled.add(tran);
// Cycle closing on global state graph
if (cycleClosingMthd.equals("strong")) {
if (Options.getDebugMode()) {
System.out.println("****** cycle closing check: Strong Cycle Closing ********");
}
// Strong cycle condition: Any cycle contains at least one state where it fully expands.
//newCurStatePersistent.addAll(setSubstraction(curStateEnabled, nextStatePersistent));
newCurStateStrongStubbornSet.addAll(curStateEnabled);
updateLocalStrongStubbornSetTbl(newCurStateStrongStubbornSet, sgList, curStateArray);
}
else if (cycleClosingMthd.equals("behavioral")) {
if (Options.getDebugMode()) {
System.out.println("****** cycle closing check: Behavioral with Strong Stubborn Set Computation ********");
}
HashSet<Transition> curStateReduced = setSubstraction(curStateEnabled, curStateStrongStubbornSet);
HashSet<Transition> oldNextStateStrongStubbornSet = new HashSet<Transition>();
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq, sgList.length-1);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextStateEnabled.size(), depComp);
if (Options.getDebugMode())
printStateArray(nextStateArray,"******* nextStateArray *******");
for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) {
if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) {
LpnTranList oldLocalNextStateStrongStubbornTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]);
if (Options.getDebugMode()) {
printTransList(oldLocalNextStateStrongStubbornTrans, "oldLocalNextStateStrongStubbornTrans");
}
for (Transition oldLocalTran : oldLocalNextStateStrongStubbornTrans)
oldNextStateStrongStubbornSet.add(oldLocalTran);
}
}
HashSet<Transition> ignored = setSubstraction(curStateReduced, oldNextStateStrongStubbornSet);
if (Options.getDebugMode()) {
printIntegerSet(ignored, "
}
boolean isCycleClosingStrongStubbornComputation = true;
for (Transition seed : ignored) {
HashSet<Transition> dependent = new HashSet<Transition>();
dependent = computeDependent(curStateArray,seed,dependent,nextStateEnabled,isCycleClosingStrongStubbornComputation);
if (Options.getDebugMode()) {
printIntegerSet(dependent, "
}
// TODO: Is this still necessary?
// boolean dependentOnlyHasDummyTrans = true;
// for (LpnTransitionPair dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if ((newNextPersistent.size() == 0 || dependent.size() < newNextPersistent.size()) && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<LpnTransitionPair>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
DependentSet dependentSet = new DependentSet(dependent, seed, isDummyTran(seed.getLabel()));
dependentSetQueue.add(dependentSet);
}
cachedNecessarySets.clear();
if (!dependentSetQueue.isEmpty()) {
// System.out.println("depdentSetQueue is NOT empty.");
// newNextPersistent = dependentSetQueue.poll().getDependent();
// TODO: Will newNextTmp - oldNextStrongStubborn be safe?
HashSet<Transition> strongStubbornIgnoredTrans = dependentSetQueue.poll().getDependent();
//newNextPersistent = setSubstraction(newNextPersistentTmp, oldNextPersistent);
newCurStateStrongStubbornSet.addAll(setSubstraction(strongStubbornIgnoredTrans, oldNextStateStrongStubbornSet));
updateLocalStrongStubbornSetTbl(newCurStateStrongStubbornSet, sgList, curStateArray);
}
if (Options.getDebugMode()) {
printTransList(newCurStateStrongStubbornSet, "
System.out.println("******** behavioral: end of cycle closing check *****");
}
}
else if (cycleClosingMthd.equals("state_search")) {
// TODO: complete cycle closing check for state search.
}
return newCurStateStrongStubbornSet;
}
private static void updateLocalStrongStubbornSetTbl(LpnTranList nextStrongStubbornTrans,
StateGraph[] sgList, State[] curStateArray) {
// Persistent set at each state is stored in the enabledSetTbl in each state graph.
for (Transition tran : nextStrongStubbornTrans) {
int lpnIndex = tran.getLpn().getLpnIndex();
State nextState = curStateArray[lpnIndex];
LpnTranList curStrongStubbornTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
if (curStrongStubbornTrans != null) {
if (!curStrongStubbornTrans.contains(tran))
curStrongStubbornTrans.add(tran);
}
else {
LpnTranList newLpnTranList = new LpnTranList();
newLpnTranList.add(tran);
sgList[lpnIndex].getEnabledSetTbl().put(curStateArray[lpnIndex], newLpnTranList);
}
}
if (Options.getDebugMode()) {
printStrongStubbornSetTbl(sgList);
}
}
// private void printPrjStateSet(StateSetInterface prjStateSet) {
// for (PrjState curGlobal : prjStateSet) {
// State[] curStateArray = curGlobal.toStateArray();
// printStateArray(curStateArray, null);
// /**
// * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back.
// * @param sgList
// * @param initStateArray
// * @param cycleClosingMthdIndex
// * @return
// */
// public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) {
// if (cycleClosingMthdIndex == 1)
// else if (cycleClosingMthdIndex == 2)
// else if (cycleClosingMthdIndex == 4)
// double peakUsedMem = 0;
// double peakTotalMem = 0;
// boolean failure = false;
// int tranFiringCnt = 0;
// int totalStates = 1;
// int numLpns = sgList.length;
// HashSet<PrjState> stateStack = new HashSet<PrjState>();
// Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
// Stack<Integer> curIndexStack = new Stack<Integer>();
// HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
// PrjState initPrjState = new PrjState(initStateArray);
// prjStateSet.add(initPrjState);
// PrjState stateStackTop = initPrjState;
// System.out.println("%%%%%%% Add states to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.add(stateStackTop);
// // Prepare static pieces for POR
// HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>();
// Transition[] allTransitions = sgList[0].getLpn().getAllTransitions();
// HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>();
// HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length);
// for (Transition curTran: allTransitions) {
// StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions);
// curStatic.buildDisableSet();
// curStatic.buildEnableSet();
// curStatic.buildModifyAssignSet();
// tmpMap.put(curTran.getIndex(), curStatic);
// tranFiringFreq.put(curTran.getIndex(), 0);
// staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap);
// printStaticSetMap(staticSetsMap);
// System.out.println("call getPersistent on initStateArray at 0: ");
// boolean init = true;
// PersistentxSet initPersistent = new PersistentSet();
// initPersistent = sgList[0].getPersistent(initStateArray[0], staticSetsMap, init, tranFiringFreq);
// HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl();
// lpnTranStack.push(initPersistent.getPersistentSet());
// curIndexStack.push(0);
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) initPersistent.getPersistentSet(), "");
// main_while_loop: while (failure == false && stateStack.size() != 0) {
// System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$");
// long curTotalMem = Runtime.getRuntime().totalMemory();
// long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
// if (curTotalMem > peakTotalMem)
// peakTotalMem = curTotalMem;
// if (curUsedMem > peakUsedMem)
// peakUsedMem = curUsedMem;
// if (stateStack.size() > max_stack_depth)
// max_stack_depth = stateStack.size();
// iterations++;
// if (iterations % 100000 == 0) {
// System.out.println("---> #iteration " + iterations
// + "> # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStates
// + ", stack_depth: " + stateStack.size()
// + " used memory: " + (float) curUsedMem / 1000000
// + " free memory: "
// + (float) Runtime.getRuntime().freeMemory() / 1000000);
// State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek();
// int curIndex = curIndexStack.peek();
//// System.out.println("curIndex = " + curIndex);
// //PersistentSet curPersistent = new PersistentSet();
// //LinkedList<Transition> curPersistentTrans = curPersistent.getPersistentSet();
// LinkedList<Transition> curPersistentTrans = lpnTranStack.peek();
//// printStateArray(curStateArray);
//// System.out.println("+++++++ curPersistent trans ++++++++");
//// printTransLinkedList(curPersistentTrans);
// // If all enabled transitions of the current LPN are considered,
// // then consider the next LPN
// // by increasing the curIndex.
// // Otherwise, if all enabled transitions of all LPNs are considered,
// // then pop the stacks.
// if (curPersistentTrans.size() == 0) {
// lpnTranStack.pop();
//// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++");
// curIndexStack.pop();
//// System.out.println("+++++++ Pop index off curIndexStack ++++++++");
// curIndex++;
//// System.out.println("curIndex = " + curIndex);
// while (curIndex < numLpns) {
// System.out.println("call getEnabled on curStateArray at 1: ");
// LpnTranList tmpPersistentTrans = (LpnTranList) (sgList[curIndex].getPersistent(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getPersistentSet();
// curPersistentTrans = tmpPersistentTrans.clone();
// //printTransitionSet(curEnabled, "curEnabled set");
// if (curPersistentTrans.size() > 0) {
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransLinkedList(curPersistentTrans);
// lpnTranStack.push(curPersistentTrans);
// curIndexStack.push(curIndex);
// printIntegerStack("curIndexStack after push 1", curIndexStack);
// break;
// curIndex++;
// if (curIndex == numLpns) {
// prjStateSet.add(stateStackTop);
// System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// stateStack.remove(stateStackTop);
// stateStackTop = stateStackTop.getFather();
// continue;
// Transition firedTran = curPersistentTrans.removeLast();
// System.out.println("
// System.out.println("Fired transition: " + firedTran.getName());
// System.out.println("
// Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1;
// tranFiringFreq.put(firedTran.getIndex(), freq);
// System.out.println("~~~~~~tranFiringFreq~~~~~~~");
// printHashMap(tranFiringFreq, allTransitions);
// State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran);
// tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] curPersistentArray = new LinkedList[numLpns];
// @SuppressWarnings("unchecked")
// LinkedList<Transition>[] nextPersistentArray = new LinkedList[numLpns];
// boolean updatedPersistentDueToCycleRule = false;
// for (int i = 0; i < numLpns; i++) {
// StateGraph sg_tmp = sgList[i];
// System.out.println("call getPersistent on curStateArray at 2: i = " + i);
// PersistentSet PersistentList = new PersistentSet();
// if (init) {
// PersistentList = initPersistent;
// sg_tmp.setEnabledSetTbl(initEnabledSetTbl);
// init = false;
// else
// PersistentList = sg_tmp.getPersistent(curStateArray[i], staticSetsMap, init, tranFiringFreq);
// curPersistentArray[i] = PersistentList.getPersistentSet();
// System.out.println("call getPersistentRefinedCycleRule on nextStateArray at 3: i = " + i);
// PersistentList = sg_tmp.getPersistentRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq);
// nextPersistentArray[i] = PersistentList.getPersistentSet();
// if (!updatedPersistentDueToCycleRule && PersistentList.getPersistentChanged()) {
// updatedPersistentDueToCycleRule = true;
// for (LinkedList<Transition> tranList : curPersistentArray) {
// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : curPersistentArray) {
//// printTransLinkedList(tranList);
//// for (LinkedList<Transition> tranList : nextPersistentArray) {
//// printTransLinkedList(tranList);
// Transition disabledTran = firedTran.disablingError(
// curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions());
// if (disabledTran != null) {
// System.err.println("Disabling Error: "
// + disabledTran.getFullLabel() + " is disabled by "
// + firedTran.getFullLabel());
// failure = true;
// break main_while_loop;
// if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) {
// failure = true;
// break main_while_loop;
// PrjState nextPrjState = new PrjState(nextStateArray);
// Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState);
// if (existingState == true && updatedPersistentDueToCycleRule) {
// // cycle closing
// System.out.println("%%%%%%% existingSate == true %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextPersistentArray[0], "");
// lpnTranStack.push((LpnTranList) nextPersistentArray[0].clone());
// curIndexStack.push(0);
// if (existingState == false) {
// System.out.println("%%%%%%% existingSate == false %%%%%%%%");
// stateStackTop.setChild(nextPrjState);
// nextPrjState.setFather(stateStackTop);
// stateStackTop = nextPrjState;
// stateStack.add(stateStackTop);
// System.out.println("%%%%%%% Add state to stateStack %%%%%%%%");
// printStateArray(stateStackTop.toStateArray());
// System.out.println("+++++++ Push trans onto lpnTranStack ++++++++");
// printTransitionSet((LpnTranList) nextPersistentArray[0], "");
// lpnTranStack.push((LpnTranList) nextPersistentArray[0].clone());
// curIndexStack.push(0);
// totalStates++;
// // end of main_while_loop
// double totalStateCnt = prjStateSet.size();
// System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt
// + ", # of prjStates found: " + totalStateCnt
// + ", max_stack_depth: " + max_stack_depth
// + ", peak total memory: " + peakTotalMem / 1000000 + " MB"
// + ", peak used memory: " + peakUsedMem / 1000000 + " MB");
// // This currently works for a single LPN.
// return sgList;
// return null;
private void printStaticSetsMap( LhpnFile[] lpnList) {
System.out.println("============ staticSetsMap ============");
for (Transition lpnTranPair : staticDependency.keySet()) {
StaticDependencySets statSets = staticDependency.get(lpnTranPair);
printLpnTranPair(statSets.getSeedTran(), statSets.getDisableSet(false), "disableSet");
for (HashSet<Transition> setOneConjunctTrue : statSets.getOtherTransSetSeedTranEnablingTrue()) {
printLpnTranPair(statSets.getSeedTran(), setOneConjunctTrue, "enableBySetingEnablingTrue for one conjunct");
}
}
}
private static void printLpnTranPair(Transition curTran,
HashSet<Transition> TransitionSet, String setName) {
System.out.println(setName + " for transition " + curTran.getFullLabel() + " is: ");
if (TransitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Transition lpnTranPair: TransitionSet)
System.out.print(lpnTranPair.getFullLabel() + "\n");
System.out.println();
}
}
// private Transition[] assignStickyTransitions(LhpnFile lpn) {
// // allProcessTrans is a hashmap from a transition to its process color (integer).
// HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>();
// // create an Abstraction object to call the divideProcesses method.
// Abstraction abs = new Abstraction(lpn);
// abs.decomposeLpnIntoProcesses();
// allProcessTrans.putAll(
// (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone());
// HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>();
// for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) {
// Transition curTran = tranIter.next();
// Integer procId = allProcessTrans.get(curTran);
// if (!processMap.containsKey(procId)) {
// LpnProcess newProcess = new LpnProcess(procId);
// newProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// newProcess.addPlaceToProcess(p);
// processMap.put(procId, newProcess);
// else {
// LpnProcess curProcess = processMap.get(procId);
// curProcess.addTranToProcess(curTran);
// if (curTran.getPreset() != null) {
// Place[] preset = curTran.getPreset();
// for (Place p : preset) {
// curProcess.addPlaceToProcess(p);
// for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) {
// LpnProcess curProc = processMap.get(processMapIter.next());
// curProc.assignStickyTransitions();
// curProc.printProcWithStickyTrans();
// return lpn.getAllTransitions();
// private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran,
// HashSet<Transition> curDisable, String setName) {
// System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: ");
// if (curDisable.isEmpty()) {
// System.out.println("empty");
// else {
// for (Transition lpnTranPair: curDisable) {
// System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel()
// + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t");
// System.out.print("\n");
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* The enabledSetTbl (for each StateGraph obj) stores the strong stubborn set for each state of each LPN.
* @param stateArray
* @param prjStateSet
* @param enable
* @param disableByStealingToken
* @param disable
* @param sgList
* @return
*/
private LpnTranList buildStrongStubbornSet(State[] curStateArray, State[] nextStateArray,
HashMap<Transition, Integer> tranFiringFreq, StateGraph[] sgList, LhpnFile[] lpnList,
StateSetInterface prjStateSet, PrjState stateStackTop, Transition lastFiredTran) {
State[] stateArray = null;
if (nextStateArray == null)
stateArray = curStateArray;
else
stateArray = nextStateArray;
for (State s : stateArray)
if (s == null)
throw new NullPointerException();
LpnTranList strongStubbornSet = new LpnTranList();
HashSet<Transition> curEnabled = new HashSet<Transition>();
for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) {
curEnabled.addAll(StateGraph.getEnabledFromTranVector(stateArray[lpnIndex]));
}
if (Options.getDebugMode()) {
System.out.println("******* Partial Order Reduction *******");
String name = null;
String globalStateLabel = "";
if (curStateArray == null)
name = "nextStateArray";
else
name = "curStateArray";
for (State st : stateArray) {
globalStateLabel += st.getFullLabel() + "_";
}
System.out.println(name + ": " +globalStateLabel.substring(0, globalStateLabel.lastIndexOf("_")));
printIntegerSet(curEnabled, "Enabled set");
System.out.println("******* Begin POR *******");
}
if (curEnabled.isEmpty()) {
return strongStubbornSet;
}
HashSet<Transition> ready = computeStrongStubbornSet(stateArray, curEnabled, tranFiringFreq, sgList);
if (Options.getDebugMode()) {
System.out.println("******* End POR *******");
printIntegerSet(ready, "Strong Stubborn Set");
System.out.println("********************");
}
if (tranFiringFreq != null) {
LinkedList<Transition> readyList = new LinkedList<Transition>();
for (Transition inReady : ready) {
readyList.add(inReady);
}
mergeSort(readyList, tranFiringFreq);
for (Transition inReady : readyList) {
strongStubbornSet.addFirst(inReady);
}
}
else {
for (Transition tran : ready) {
strongStubbornSet.add(tran);
}
}
return strongStubbornSet;
}
private LinkedList<Transition> mergeSort(LinkedList<Transition> array, HashMap<Transition, Integer> tranFiringFreq) {
if (array.size() == 1)
return array;
int middle = array.size() / 2;
LinkedList<Transition> left = new LinkedList<Transition>();
LinkedList<Transition> right = new LinkedList<Transition>();
for (int i=0; i<middle; i++) {
left.add(i, array.get(i));
}
for (int i=middle; i<array.size();i++) {
right.add(i-middle, array.get(i));
}
left = mergeSort(left, tranFiringFreq);
right = mergeSort(right, tranFiringFreq);
return merge(left, right, tranFiringFreq);
}
private static LinkedList<Transition> merge(LinkedList<Transition> left,
LinkedList<Transition> right, HashMap<Transition, Integer> tranFiringFreq) {
LinkedList<Transition> result = new LinkedList<Transition>();
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) {
result.addLast(left.poll());
}
else {
result.addLast(right.poll());
}
}
else if (left.size()>0) {
result.addLast(left.poll());
}
else if (right.size()>0) {
result.addLast(right.poll());
}
}
return result;
}
// /**
// * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition
// * needs to be evaluated.
// * @param nextState
// * @param stateStackTop
// * @param enable
// * @param disableByStealingToken
// * @param disable
// * @param init
// * @param cycleClosingMthdIndex
// * @param lpnIndex
// * @param isNextState
// * @return
// */
// private LpnTranList getPersistentRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<Transition,StaticDependencySets> staticSetsMap,
// boolean init, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList,
// HashSet<PrjState> stateStack, PrjState stateStackTop) {
// PersistentSet nextPersistent = new PersistentSet();
// if (nextState == null) {
// throw new NullPointerException();
// if(PersistentSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)PersistentSetTbl.get(nextState), "Old Persistent at this state: ");
// // Cycle closing check
// LpnTranList nextPersistentTransOld = (LpnTranList) nextPersistent.getPersistentSet();
// nextPersistentTransOld = PersistentSetTbl.get(nextState);
// LpnTranList curPersistentTrans = PersistentSetTbl.get(curState);
// LpnTranList curReduced = new LpnTranList();
// LpnTranList curEnabled = curState.getEnabledTransitions();
// for (int i=0; i<curEnabled.size(); i++) {
// if (!curPersistentTrans.contains(curEnabled.get(i))) {
// curReduced.add(curEnabled.get(i));
// if (!nextPersistentTransOld.containsAll(curReduced)) {
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// printTransitionSet(curEnabled, "curEnabled:");
// printTransitionSet(curPersistentTrans, "curPersistentTrans:");
// printTransitionSet(curReduced, "curReduced:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:");
// printTransitionSet(nextPersistentTransOld, "nextPersistentTransOld:");
// nextPersistent.setPersistentChanged();
// HashSet<Transition> curEnabledIndicies = new HashSet<Transition>();
// for (int i=0; i<curEnabled.size(); i++) {
// curEnabledIndicies.add(curEnabled.get(i).getIndex());
// // transToAdd = curReduced - nextPersistentOld
// LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextPersistentTransOld);
// HashSet<Integer> transToAddIndices = new HashSet<Integer>();
// for (int i=0; i<overlyReducedTrans.size(); i++) {
// transToAddIndices.add(overlyReducedTrans.get(i).getIndex());
// HashSet<Integer> nextPersistentNewIndices = (HashSet<Integer>) curEnabledIndicies.clone();
// for (Integer tranToAdd : transToAddIndices) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd];
// dependent = computeDependent(curState,tranToAdd,dependent,curEnabledIndicies,staticMap);
// // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]);
// boolean dependentOnlyHasDummyTrans = true;
// for (Integer curTranIndex : dependent) {
// Transition curTran = this.lpn.getAllTransitions()[curTranIndex];
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName());
// if (dependent.size() < nextPersistentNewIndices.size() && !dependentOnlyHasDummyTrans)
// nextPersistentNewIndices = (HashSet<Integer>) dependent.clone();
// if (nextPersistentNewIndices.size() == 1)
// break;
// LpnTranList nextPersistentNew = new LpnTranList();
// for (Integer nextPersistentNewIndex : nextPersistentNewIndices) {
// nextPersistentNew.add(this.getLpn().getTransition(nextPersistentNewIndex));
// LpnTranList transToAdd = getSetSubtraction(nextPersistentNew, nextPersistentTransOld);
// boolean allTransToAddFired = false;
// if (cycleClosingMthdIndex == 2) {
// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new Persistent of nextState.
// if (transToAdd != null) {
// LpnTranList transToAddCopy = transToAdd.copy();
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// allTransToAddFired = allTransToAddFired(transToAddCopy,
// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
// // Update the old Persistent of the next state
// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
// nextPersistent.getPersistentSet().clear();
// nextPersistent.getPersistentSet().addAll(transToAdd);
// PersistentSetTbl.get(nextState).addAll(transToAdd);
// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// if (cycleClosingMthdIndex == 4) {
// nextPersistent.getPersistentSet().clear();
// nextPersistent.getPersistentSet().addAll(overlyReducedTrans);
// PersistentSetTbl.get(nextState).addAll(overlyReducedTrans);
// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
// printTransitionSet(transToAdd, "transToAdd:");
// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
// // enabledSetTble stores the Persistent set at curState.
// // The fully enabled set at each state is stored in the tranVector in each state.
// return (PersistentSet) nextPersistent;
// for (State s : nextStateArray)
// if (s == null)
// throw new NullPointerException();
// cachedNecessarySets.clear();
// String cycleClosingMthd = Options.getCycleClosingMthd();
// PersistentSet nextPersistent = new PersistentSet();
// HashSet<Transition> nextEnabled = new HashSet<Transition>();
//// boolean allEnabledAreSticky = false;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State nextState = nextStateArray[lpnIndex];
// if (init) {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// //allEnabledAreSticky = true;
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (sgList[lpnIndex].isEnabled(tran,nextState)){
// nextEnabled.add(new Transition(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// else {
// LhpnFile curLpn = sgList[lpnIndex].getLpn();
// for (int i=0; i < curLpn.getAllTransitions().length; i++) {
// Transition tran = curLpn.getAllTransitions()[i];
// if (nextStateArray[lpnIndex].getTranVector()[i]) {
// nextEnabled.add(new Transition(curLpn.getLpnIndex(), i));
// //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky();
// //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList());
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp);
// LhpnFile[] lpnList = new LhpnFile[sgList.length];
// for (int i=0; i<sgList.length; i++)
// lpnList[i] = sgList[i].getLpn();
// HashMap<Transition, LpnTranList> transToAddMap = new HashMap<Transition, LpnTranList>();
// Integer cycleClosingLpnIndex = -1;
// for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) {
// State curState = curStateArray[lpnIndex];
// State nextState = nextStateArray[lpnIndex];
// if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true
// && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty()
// && stateOnStack(lpnIndex, nextState, stateStack)
// && nextState.getIndex() != curState.getIndex()) {
// cycleClosingLpnIndex = lpnIndex;
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~");
// printPersistentSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old Persistent at this state: ");
// LpnTranList oldLocalNextPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState);
// LpnTranList curLocalPersistentTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState);
// LpnTranList reducedLocalTrans = new LpnTranList();
// LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions();
// System.out.println("The firedTran is a cycle closing transition.");
// if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) {
// // firedTran is a cycle closing transition.
// for (int i=0; i<curLocalEnabledTrans.size(); i++) {
// if (!curLocalPersistentTrans.contains(curLocalEnabledTrans.get(i))) {
// reducedLocalTrans.add(curLocalEnabledTrans.get(i));
// if (!oldLocalNextPersistentTrans.containsAll(reducedLocalTrans)) {
// printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:");
// printTransitionSet(curLocalPersistentTrans, "curPersistentTrans:");
// printTransitionSet(reducedLocalTrans, "reducedLocalTrans:");
// printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:");
// printTransitionSet(oldLocalNextPersistentTrans, "nextPersistentTransOld:");
// // nextPersistent.setPersistentChanged();
// // ignoredTrans should not be empty here.
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextPersistentTrans);
// HashSet<Transition> ignored = new HashSet<Transition>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// if (cycleClosingMthd.toLowerCase().equals("behavioral")) {
// for (Transition seed : ignored) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
//// if (nextPersistentNewIndices.size() == 1)
//// break;
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextPersistentTrans = new LpnTranList();
// for (Transition tran : newNextPersistent) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextPersistentTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextPersistentTrans, oldLocalNextPersistentTrans);
// transToAddMap.put(seed, transToAdd);
// else if (cycleClosingMthd.toLowerCase().equals("state_search")) {
// // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new Persistent of nextState.
// HashSet<Integer> stateVisited = new HashSet<Integer>();
// stateVisited.add(nextState.getIndex());
// LpnTranList trulyIgnoredTrans = ignoredTrans.copy();
// trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]);
// if (!trulyIgnoredTrans.isEmpty()) {
// HashSet<Transition> trulyIgnored = new HashSet<Transition>();
// for (Transition tran : trulyIgnoredTrans) {
// trulyIgnored.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : trulyIgnored) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// LpnTranList newLocalNextPersistentTrans = new LpnTranList();
// for (Transition tran : newNextPersistent) {
// if (tran.getLpnIndex() == lpnIndex)
// newLocalNextPersistentTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex()));
// LpnTranList transToAdd = getSetSubtraction(newLocalNextPersistentTrans, oldLocalNextPersistentTrans);
// transToAddMap.put(seed, transToAdd);
// else { // All ignored transitions were fired before. It is safe to close the current cycle.
// HashSet<Transition> oldLocalNextPersistent = new HashSet<Transition>();
// for (Transition tran : oldLocalNextPersistentTrans)
// oldLocalNextPersistent.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : oldLocalNextPersistent) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextPersistent is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else {
// // oldNextPersistentTrans.containsAll(curReducedTrans) == true (safe to close the current cycle)
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// HashSet<Transition> oldLocalNextPersistent = new HashSet<Transition>();
// for (Transition tran : oldLocalNextPersistentTrans)
// oldLocalNextPersistent.add(new Transition(tran.getLpn().getLpnIndex(), tran.getIndex()));
// for (Transition seed : oldLocalNextPersistent) {
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in oldNextPersistent is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// DependentSet dependentSet = new DependentSet(newNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else if (cycleClosingMthd.toLowerCase().equals("strong")) {
// LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextPersistentTrans);
// HashSet<Transition> ignored = new HashSet<Transition>();
// for (int i=0; i<ignoredTrans.size(); i++) {
// ignored.add(new Transition(lpnIndex, ignoredTrans.get(i).getIndex()));
// HashSet<Transition> allNewNextPersistent = new HashSet<Transition>();
// for (Transition seed : ignored) {
// HashSet<Transition> newNextPersistent = (HashSet<Transition>) nextEnabled.clone();
// HashSet<Transition> dependent = new HashSet<Transition>();
// dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList);
// printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")");
// boolean dependentOnlyHasDummyTrans = true;
// for (Transition dependentTran : dependent) {
// dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans
// && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName());
// if (dependent.size() < newNextPersistent.size() && !dependentOnlyHasDummyTrans)
// newNextPersistent = (HashSet<Transition>) dependent.clone();
// allNewNextPersistent.addAll(newNextPersistent);
// // The strong cycle condition requires all seeds in ignored to be included in the allNewNextPersistent, as well as dependent set for each seed.
// // So each seed should have the same new Persistent set.
// for (Transition seed : ignored) {
// DependentSet dependentSet = new DependentSet(allNewNextPersistent, seed,
// isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName()));
// dependentSetQueue.add(dependentSet);
// else { // firedTran is not a cycle closing transition. Compute next Persistent.
//// if (nextEnabled.size() == 1)
//// return nextEnabled;
// System.out.println("The firedTran is NOT a cycle closing transition.");
// HashSet<Transition> ready = null;
// for (Transition seed : nextEnabled) {
// System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")");
// HashSet<Transition> dependent = new HashSet<Transition>();
// Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()];
// boolean enabledIsDummy = false;
//// if (enabledTransition.isSticky()) {
//// dependent = (HashSet<Transition>) nextEnabled.clone();
//// else {
//// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList);
// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList);
// printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel()
// + "(" + enabledTransition.getName() + ")");
// if (isDummyTran(enabledTransition.getName()))
// enabledIsDummy = true;
// for (Transition inDependent : dependent) {
// if(inDependent.getLpnIndex() == cycleClosingLpnIndex) {
// // check cycle closing condition
// break;
// DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// ready = dependentSetQueue.poll().getDependent();
//// // Update the old Persistent of the next state
//// boolean allTransToAddFired = false;
//// if (cycleClosingMthdIndex == 2) {
//// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new Persistent of nextState.
//// if (transToAdd != null) {
//// LpnTranList transToAddCopy = transToAdd.copy();
//// HashSet<Integer> stateVisited = new HashSet<Integer>();
//// stateVisited.add(nextState.getIndex());
//// allTransToAddFired = allTransToAddFired(transToAddCopy,
//// allTransToAddFired, stateVisited, stateStackTop, lpnIndex);
//// // Update the old Persistent of the next state
//// if (!allTransToAddFired || cycleClosingMthdIndex == 1) {
//// nextPersistent.getPersistentSet().clear();
//// nextPersistent.getPersistentSet().addAll(transToAdd);
//// PersistentSetTbl.get(nextState).addAll(transToAdd);
//// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// if (cycleClosingMthdIndex == 4) {
//// nextPersistent.getPersistentSet().clear();
//// nextPersistent.getPersistentSet().addAll(ignoredTrans);
//// PersistentSetTbl.get(nextState).addAll(ignoredTrans);
//// printTransitionSet(nextPersistentNew, "nextPersistentNew:");
//// printTransitionSet(transToAdd, "transToAdd:");
//// System.out.println("((((((((((((((((((((()))))))))))))))))))))");
//// // enabledSetTble stores the Persistent set at curState.
//// // The fully enabled set at each state is stored in the tranVector in each state.
//// return (PersistentSet) nextPersistent;
// return null;
// private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans,
// HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) {
// State state = stateStackEntry.get(lpnIndex);
// System.out.println("state = " + state.getIndex());
// State predecessor = stateStackEntry.getFather().get(lpnIndex);
// if (predecessor != null)
// System.out.println("predecessor = " + predecessor.getIndex());
// if (predecessor == null || stateVisited.contains(predecessor.getIndex())) {
// return ignoredTrans;
// else
// stateVisited.add(predecessor.getIndex());
// LpnTranList predecessorOldPersistent = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor);
// for (Transition oldPersistentTran : predecessorOldPersistent) {
// State tmpState = sg.getNextStateMap().get(predecessor).get(oldPersistentTran);
// if (tmpState.getIndex() == state.getIndex()) {
// ignoredTrans.remove(oldPersistentTran);
// break;
// if (ignoredTrans.size()==0) {
// return ignoredTrans;
// else {
// ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg);
// return ignoredTrans;
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
/**
* An iterative implement of findsg_recursive().
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) {
boolean firingOrder = false;
long peakUsedMem = 0;
long peakTotalMem = 0;
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;
HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>();
@SuppressWarnings("unchecked")
IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize];
//HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize];
Stack<LpnState[]> stateStack = new Stack<LpnState[]>();
Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>();
//get initial enable transition set
LpnTranList initEnabled = new LpnTranList();
LpnTranList initFireFirst = new LpnTranList();
LpnState[] initLpnStateArray = new LpnState[arraySize];
for (int i = 0; i < arraySize; i++)
{
lpnStateCache[i] = new IndexObjMap<LpnState>();
LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]);
HashSet<Transition> enabledSet = new HashSet<Transition>();
if(!enabledTrans.isEmpty())
{
for(Transition tran : enabledTrans) {
enabledSet.add(tran);
initEnabled.add(tran);
}
}
LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet);
lpnStateCache[i].add(curLpnState);
initLpnStateArray[i] = curLpnState;
}
LpnTranList[] initEnabledSet = new LpnTranList[2];
initEnabledSet[0] = initFireFirst;
initEnabledSet[1] = initEnabled;
lpnTranStack.push(initEnabledSet);
stateStack.push(initLpnStateArray);
globalStateTbl.add(new PrjLpnState(initLpnStateArray));
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
//if(iterations>2)break;
if (iterations % 100000 == 0)
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + globalStateTbl.size()
+ ", current_stack_depth: " + stateStack.size()
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
LpnTranList[] curEnabled = lpnTranStack.peek();
LpnState[] curLpnStateArray = stateStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if(curEnabled[0].size()==0 && curEnabled[1].size()==0){
lpnTranStack.pop();
stateStack.pop();
continue;
}
Transition firedTran = null;
if(curEnabled[0].size() != 0)
firedTran = curEnabled[0].removeFirst();
else
firedTran = curEnabled[1].removeFirst();
traceCex.addLast(firedTran);
State[] curStateArray = new State[arraySize];
for( int i = 0; i < arraySize; i++)
curStateArray[i] = curLpnStateArray[i].getState();
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled();
LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]);
HashSet<Transition> nextEnabledSet = new HashSet<Transition>();
for(Transition tran : nextEnabledList) {
nextEnabledSet.add(tran);
}
extendedNextEnabledArray[i] = nextEnabledSet;
//non_disabling
for(Transition curTran : curEnabledSet) {
if(curTran == firedTran)
continue;
if(nextEnabledSet.contains(curTran) == false) {
int[] nextMarking = nextStateArray[i].getMarking();
// Not sure if the code below is correct.
int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getLabel());
boolean included = true;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
boolean temp = false;
for (int mi = 0; mi < nextMarking.length; mi++) {
if (nextMarking[mi] == pp) {
temp = true;
break;
}
}
if (temp == false)
{
included = false;
break;
}
}
}
if(preset==null || preset.length==0 || included==true) {
extendedNextEnabledArray[i].add(curTran);
}
}
}
}
boolean deadlock=true;
for(int i = 0; i < arraySize; i++) {
if(extendedNextEnabledArray[i].size() != 0){
deadlock = false;
break;
}
}
if(deadlock==true) {
failure = true;
break main_while_loop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
LpnState[] nextLpnStateArray = new LpnState[arraySize];
for(int i = 0; i < arraySize; i++) {
HashSet<Transition> lpnEnabledSet = new HashSet<Transition>();
for(Transition tran : extendedNextEnabledArray[i]) {
lpnEnabledSet.add(tran);
}
LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet);
LpnState tmpCached = (lpnStateCache[i].add(tmp));
nextLpnStateArray[i] = tmpCached;
}
boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray));
if(newState == false) {
traceCex.removeLast();
continue;
}
stateStack.push(nextLpnStateArray);
LpnTranList[] nextEnabledSet = new LpnTranList[2];
LpnTranList fireFirstTrans = new LpnTranList();
LpnTranList otherTrans = new LpnTranList();
for(int i = 0; i < arraySize; i++)
{
for(Transition tran : nextLpnStateArray[i].getEnabled())
{
if(firingOrder == true)
if(curLpnStateArray[i].getEnabled().contains(tran))
otherTrans.add(tran);
else
fireFirstTrans.add(tran);
else
fireFirstTrans.add(tran);
}
}
nextEnabledSet[0] = fireFirstTrans;
nextEnabledSet[1] = otherTrans;
lpnTranStack.push(nextEnabledSet);
}// END while (stateStack.empty() == false)
// graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt,
// prjStateSet.size()));
System.out.println("SUMMARY: # LPN transition firings: "
+ tranFiringCnt + ", # of prjStates found: "
+ globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth);
/*
* by looking at stateStack, generate the trace showing the counter-exPersistent.
*/
if (failure == true) {
System.out.println("
System.out.println("the deadlock trace:");
//update traceCex from stateStack
// LpnState[] cur = null;
// LpnState[] next = null;
for(Transition tran : traceCex)
System.out.println(tran.getFullLabel());
}
System.out.println("Modules' local states: ");
for (int i = 0; i < arraySize; i++) {
System.out.println("module " + lpnList[i].getLpn().getLabel() + ": "
+ lpnList[i].reachSize());
}
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* When a state is considered during DFS, only one enabled transition is
* selected to fire in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_1");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 500; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean compressed = false;
boolean failure = false;
int tranFiringCnt = 0;
int totalStates = 1;
int arraySize = lpnList.length;
//int newStateCnt = 0;
Stack<State[]> stateStack = new Stack<State[]>();
Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>();
Stack<Integer> curIndexStack = new Stack<Integer>();
mddNode reachAll = null;
mddNode reach = Mdd.newNode();
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true);
mddMgr.add(reach, localIdxArray, compressed);
stateStack.push(initStateArray);
LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]);
lpnTranStack.push(initEnabled.clone());
curIndexStack.push(0);
int numMddCompression = 0;
main_while_loop: while (failure == false && stateStack.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 100000 == 0) {
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", stack depth: " + stateStack.size()
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
numMddCompression++;
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = Mdd.newNode();
if(memUpBound < 1500)
memUpBound *= numMddCompression;
}
}
State[] curStateArray = stateStack.peek();
int curIndex = curIndexStack.peek();
LinkedList<Transition> curEnabled = lpnTranStack.peek();
// If all enabled transitions of the current LPN are considered,
// then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered,
// then pop the stacks.
if (curEnabled.size() == 0) {
lpnTranStack.pop();
curIndexStack.pop();
curIndex++;
while (curIndex < arraySize) {
LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex]));
if (enabledCached.size() > 0) {
curEnabled = enabledCached.clone();
lpnTranStack.push(curEnabled);
curIndexStack.push(curIndex);
break;
}
curIndex++;
}
}
if (curIndex == arraySize) {
stateStack.pop();
continue;
}
Transition firedTran = curEnabled.removeLast();
State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
List<LinkedList<Transition>> curEnabledArray = new ArrayList<LinkedList<Transition>>();
List<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>();
//LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
//LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
//curEnabledArray[i] = enabledList;
curEnabledArray.add(i, enabledList);
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
//nextEnabledArray[i] = enabledList;
nextEnabledArray.add(i, enabledList);
Transition disabledTran = firedTran.disablingError(curEnabledArray.get(i),nextEnabledArray.get(i));
if (disabledTran != null) {
System.err.println("Disabling Error: "
+ disabledTran.getFullLabel() + " is disabled by "
+ firedTran.getFullLabel());
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
* if not, add it into reachable set, and push it onto stack.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true);
Boolean existingState = false;
if (reachAll != null && Mdd.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (Mdd.contains(reach, localIdxArray) == true)
existingState = true;
if (existingState == false) {
mddMgr.add(reach, localIdxArray, compressed);
//newStateCnt++;
stateStack.push(nextStateArray);
lpnTranStack.push((LpnTranList) nextEnabledArray.get(0).clone());
curIndexStack.push(0);
totalStates++;
}
}
double totalStateCnt = Mdd.numberOfStates(reach);
System.out.println("---> run statistics: \n"
+ "# LPN transition firings: " + tranFiringCnt + "\n"
+ "# of prjStates found: " + totalStateCnt + "\n"
+ "max_stack_depth: " + max_stack_depth + "\n"
+ "peak MDD nodes: " + peakMddNodeCnt + "\n"
+ "peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ "peak total memory: " + peakTotalMem / 1000000 + " MB\n");
return null;
}
/**
* findsg using iterative approach based on DFS search. The states found are
* stored in MDD.
*
* It is similar to findsg_dfs_mdd_1 except that when a state is considered
* during DFS, all enabled transition are fired, and all its successor
* states are found in an iteration.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> calling function search_dfs_mdd_2");
int tranFiringCnt = 0;
int totalStates = 0;
int arraySize = lpnList.length;
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
boolean failure = false;
MDT state2Explore = new MDT(arraySize);
state2Explore.push(initStateArray);
totalStates++;
long peakState2Explore = 0;
Stack<Integer> searchDepth = new Stack<Integer>();
searchDepth.push(1);
boolean compressed = false;
mddNode reachAll = null;
mddNode reach = Mdd.newNode();
main_while_loop:
while (failure == false && state2Explore.empty() == false) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
iterations++;
if (iterations % 100000 == 0) {
int mddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt;
int state2ExploreSize = state2Explore.size();
peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize;
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", # states to explore: " + state2ExploreSize
+ ", # MDT nodes: " + state2Explore.nodeCnt()
+ ", total MDD nodes: " + mddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachAll == null)
reachAll = reach;
else {
mddNode newReachAll = mddMgr.union(reachAll, reach);
if (newReachAll != reachAll) {
mddMgr.remove(reachAll);
reachAll = newReachAll;
}
}
mddMgr.remove(reach);
reach = Mdd.newNode();
}
}
State[] curStateArray = state2Explore.pop();
State[] nextStateArray = null;
int states2ExploreCurLevel = searchDepth.pop();
if(states2ExploreCurLevel > 1)
searchDepth.push(states2ExploreCurLevel-1);
int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false);
mddMgr.add(reach, localIdxArray, compressed);
int nextStates2Explore = 0;
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
State curState = curStateArray[index];
LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState);
LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone();
while (curEnabled.size() > 0) {
Transition firedTran = curEnabled.removeLast();
// TODO: (check) Not sure if curLpn.fire is correct.
nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
for (int i = 0; i < arraySize; i++) {
StateGraph lpn_tmp = lpnList[i];
if (curStateArray[i] == nextStateArray[i])
continue;
LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.err.println("Verification failed: deadlock.");
failure = true;
break main_while_loop;
}
/*
* Check if the local indices of nextStateArray already exist.
*/
localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false);
Boolean existingState = false;
if (reachAll != null && Mdd.contains(reachAll, localIdxArray) == true)
existingState = true;
else if (Mdd.contains(reach, localIdxArray) == true)
existingState = true;
else if(state2Explore.contains(nextStateArray)==true)
existingState = true;
if (existingState == false) {
totalStates++;
//mddMgr.add(reach, localIdxArray, compressed);
state2Explore.push(nextStateArray);
nextStates2Explore++;
}
}
}
if(nextStates2Explore > 0)
searchDepth.push(nextStates2Explore);
}
System.out.println("
+ "---> run statistics: \n"
+ " # Depth of search (Length of Cex): " + searchDepth.size() + "\n"
+ " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n"
+ " # of prjStates found: " + (double)totalStates / 1000000 + " M\n"
+ " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n"
+ " peak MDD nodes: " + peakMddNodeCnt + "\n"
+ " peak used memory: " + peakUsedMem / 1000000 + " MB\n"
+ " peak total memory: " + peakTotalMem /1000000 + " MB\n"
+ "_____________________________________");
return null;
}
public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
long peakMddNodeCnt = 0;
int memUpBound = 1000; // Set an upper bound of memory in MB usage to
// trigger MDD compression.
int arraySize = sgList.length;
for (int i = 0; i < arraySize; i++)
sgList[i].addState(initStateArray[i]);
mddNode reachSet = null;
mddNode reach = Mdd.newNode();
MDT frontier = new MDT(arraySize);
MDT image = new MDT(arraySize);
frontier.push(initStateArray);
State[] curStateArray = null;
int tranFiringCnt = 0;
int totalStates = 0;
int imageSize = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
long curMddNodeCnt = mddMgr.nodeCnt();
peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + totalStates
+ ", total MDD nodes: " + curMddNodeCnt
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
if (curUsedMem >= memUpBound * 1000000) {
mddMgr.compress(reach);
if (reachSet == null)
reachSet = reach;
else {
mddNode newReachSet = mddMgr.union(reachSet, reach);
if (newReachSet != reachSet) {
mddMgr.remove(reachSet);
reachSet = newReachSet;
}
}
mddMgr.remove(reach);
reach = Mdd.newNode();
}
while(frontier.empty() == false) {
boolean deadlock = true;
// Stack<State[]> curStateArrayList = frontier.pop();
// while(curStateArrayList.empty() == false) {
// curStateArray = curStateArrayList.pop();
{
curStateArray = frontier.pop();
int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false);
mddMgr.add(reach, localIdxArray, false);
totalStates++;
for (int i = 0; i < arraySize; i++) {
LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]);
if (curEnabled.size() > 0)
deadlock = false;
for (Transition firedTran : curEnabled) {
// TODO: (check) Not sure if sgList[i].fire is correct.
State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
/*
* Check if any transitions can be disabled by fireTran.
*/
LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]);
Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled);
if (disabledTran != null) {
System.err.println("*** Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ " disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false);
if (Mdd.contains(reachSet, localIdxArray) == false && Mdd.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) {
if(image.contains(nextStateArray)==false) {
image.push(nextStateArray);
imageSize++;
}
}
}
}
}
/*
* If curStateArray deadlocks (no enabled transitions), terminate.
*/
if (deadlock == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
}
if(image.empty()==true) break;
System.out.println("---> size of image: " + imageSize);
frontier = image;
image = new MDT(arraySize);
imageSize = 0;
}
System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n"
+ "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n"
+ "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n"
+ "---> peak MDD nodes: " + peakMddNodeCnt);
return null;
}
/**
* BFS findsg using iterative approach. THe states found are stored in MDD.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
* @return a linked list of a sequence of LPN transitions leading to the
* failure if it is not empty.
*/
public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) {
System.out.println("---> starting search_bfs");
long peakUsedMem = 0;
long peakTotalMem = 0;
int arraySize = lpnList.length;
for (int i = 0; i < arraySize; i++)
lpnList[i].addState(initStateArray[i]);
// mddNode reachSet = mddMgr.newNode();
// mddMgr.add(reachSet, curLocalStateArray);
mddNode reachSet = null;
mddNode exploredSet = null;
List<LinkedList<State>> nextSetArray = new ArrayList<LinkedList<State>>();
//LinkedList<State>[] nextSetArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++)
nextSetArray.add(i,new LinkedList<State>());
mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null);
mddNode curMdd = initMdd;
reachSet = curMdd;
mddNode nextMdd = null;
int[] curStateArray = null;
int tranFiringCnt = 0;
boolean verifyError = false;
bfsWhileLoop: while (true) {
if (verifyError == true)
break;
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
curStateArray = mddMgr.next(curMdd, curStateArray);
if (curStateArray == null) {
// Break the loop if no new next states are found.
// System.out.println("nextSet size " + nextSet.size());
if (nextMdd == null)
break bfsWhileLoop;
if (exploredSet == null)
exploredSet = curMdd;
else {
mddNode newExplored = mddMgr.union(exploredSet, curMdd);
if (newExplored != exploredSet)
mddMgr.remove(exploredSet);
exploredSet = newExplored;
}
mddMgr.remove(curMdd);
curMdd = nextMdd;
nextMdd = null;
iterations++;
System.out.println("iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of union calls: " + mddNode.numCalls
+ ", # of union cache nodes: " + mddNode.cacheNodes
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
System.out.println("---> # of prjStates found: " + Mdd.numberOfStates(reachSet)
+ ", CurSet.Size = " + Mdd.numberOfStates(curMdd));
continue;
}
if (exploredSet != null && Mdd.contains(exploredSet, curStateArray) == true)
continue;
// If curStateArray deadlocks (no enabled transitions), terminate.
if (Analysis.deadLock(lpnList, curStateArray) == true) {
System.err.println("*** Verification failed: deadlock.");
verifyError = true;
break bfsWhileLoop;
}
// Do firings of non-local LPN transitions.
for (int index = arraySize - 1; index >= 0; index
StateGraph curLpn = lpnList[index];
LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]);
if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true)
continue;
for (Transition firedTran : curLocalEnabled) {
if (firedTran.isLocal() == true)
continue;
// TODO: (check) Not sure if curLpn.fire is correct.
State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
@SuppressWarnings("unused")
ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1);
for (int i = 0; i < arraySize; i++) {
if (curStateArray[i] == nextStateArray[i].getIndex())
continue;
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]);
LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex());
Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList);
if (disabledTran != null) {
System.err.println("Verification failed: disabling error: "
+ disabledTran.getFullLabel()
+ ": is disabled by "
+ firedTran.getFullLabel() + "!!!");
verifyError = true;
break bfsWhileLoop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
verifyError = true;
break bfsWhileLoop;
}
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the
// next
// enabled transition.
int[] nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (reachSet != null && Mdd.contains(reachSet, nextIdxArray) == true)
continue;
mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet);
mddNode newReachSet = mddMgr.union(reachSet, newNextMdd);
if (newReachSet != reachSet)
mddMgr.remove(reachSet);
reachSet = newReachSet;
if (nextMdd == null)
nextMdd = newNextMdd;
else {
mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd);
if (tmpNextMdd != nextMdd)
mddMgr.remove(nextMdd);
nextMdd = tmpNextMdd;
mddMgr.remove(newNextMdd);
}
}
}
}
System.out.println("---> final numbers: # LPN transition firings: "
+ tranFiringCnt + "\n" + "---> # of prjStates found: "
+ (Mdd.numberOfStates(reachSet)) + "\n"
+ "---> peak total memory: " + peakTotalMem / 1000000F
+ " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F
+ " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt());
return null;
}
/**
* partial order reduction (Original version of Hao's POR with behavioral analysis)
* This method is not used anywhere. See searchPOR_behavioral for POR with behavioral analysis.
*
* @param lpnList
* @param curLocalStateArray
* @param enabledArray
*/
public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> Calling search_dfs with partial order reduction");
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
boolean useMdd = true;
mddNode reach = Mdd.newNode();
//init por
verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = lpnList.length;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = Mdd.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
//System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel());
// TODO: (??) Not sure if the state graph sg below is correct.
StateGraph sg = null;
for (int i=0; i<lpnList.length; i++) {
if (lpnList[i].getLpn().equals(firedTran.getLpn())) {
sg = lpnList[i];
}
}
State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
lpnList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = lpnList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + lpnList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(lpnList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = Mdd.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = Mdd.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return null;
}
/**
* partial order reduction with behavioral analysis. (Adapted from search_dfs_por.)
*
* @param sgList
* @param curLocalStateArray
* @param enabledArray
*/
public StateGraph[] searchPOR_behavioral(final StateGraph[] sgList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) {
System.out.println("---> calling function searchPOR_behavioral");
System.out.println("---> " + Options.getPOR());
long peakUsedMem = 0;
long peakTotalMem = 0;
double stateCount = 1;
int max_stack_depth = 0;
int iterations = 0;
//boolean useMdd = true;
boolean useMdd = false;
mddNode reach = Mdd.newNode();
//init por
AmpleSet ampleClass = new AmpleSet();
//AmpleSubset ampleClass = new AmpleSubset();
HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>();
if(approach == "state")
indepTranSet = ampleClass.getIndepTranSet_FromState(sgList, lpnTranRelation);
else if (approach == "lpn")
indepTranSet = ampleClass.getIndepTranSet_FromLPN(sgList);
System.out.println("finish get independent set!!!!");
boolean failure = false;
int tranFiringCnt = 0;
int arraySize = sgList.length;
HashSet<PrjState> stateStack = new HashSet<PrjState>();
Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>();
Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>();
//get initial enable transition set
@SuppressWarnings("unchecked")
LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
sgList[i].getLpn().setLpnIndex(i);
initEnabledArray[i] = sgList[i].getEnabled(initStateArray[i]);
}
//set initEnableSubset
//LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet);
LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet);
/*
* Initialize the reach state set with the initial state.
*/
HashSet<PrjState> prjStateSet = new HashSet<PrjState>();
PrjState initPrjState = new PrjState(initStateArray);
if (useMdd) {
int[] initIdxArray = Analysis.getIdxArray(initStateArray);
mddMgr.add(reach, initIdxArray, true);
}
else
prjStateSet.add(initPrjState);
stateStack.add(initPrjState);
PrjState stateStackTop = initPrjState;
lpnTranStack.push(initEnableSubset);
firedTranStack.push(new HashSet<Transition>());
/*
* Start the main search loop.
*/
main_while_loop:
while(failure == false && stateStack.size() != 0) {
long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
if (curTotalMem > peakTotalMem)
peakTotalMem = curTotalMem;
if (curUsedMem > peakUsedMem)
peakUsedMem = curUsedMem;
if (stateStack.size() > max_stack_depth)
max_stack_depth = stateStack.size();
iterations++;
if (iterations % 500000 == 0) {
if (useMdd==true)
stateCount = Mdd.numberOfStates(reach);
else
stateCount = prjStateSet.size();
System.out.println("---> #iteration " + iterations
+ "> # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", total MDD nodes: " + mddMgr.nodeCnt()
+ " used memory: " + (float) curUsedMem / 1000000
+ " free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
}
State[] curStateArray = stateStackTop.toStateArray();
LpnTranList curEnabled = lpnTranStack.peek();
// for (LPNTran tran : curEnabled)
// for (int i = 0; i < arraySize; i++)
// if (lpnList[i] == tran.getLpn())
// if (tran.isEnabled(curStateArray[i]) == false) {
// System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state");
// System.exit(0);
// If all enabled transitions of the current LPN are considered, then consider the next LPN
// by increasing the curIndex.
// Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks.
if(curEnabled.size() == 0) {
lpnTranStack.pop();
firedTranStack.pop();
stateStack.remove(stateStackTop);
stateStackTop = stateStackTop.getFather();
if (stateStack.size() > 0)
traceCex.removeLast();
continue;
}
Transition firedTran = curEnabled.removeFirst();
firedTranStack.peek().add(firedTran);
traceCex.addLast(firedTran);
StateGraph sg = null;
for (int i=0; i<sgList.length; i++) {
if (sgList[i].getLpn().equals(firedTran.getLpn())) {
sg = sgList[i];
}
}
State[] nextStateArray = sg.fire(sgList, curStateArray, firedTran);
tranFiringCnt++;
// Check if the firedTran causes disabling error or deadlock.
@SuppressWarnings("unchecked")
LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize];
@SuppressWarnings("unchecked")
LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize];
for (int i = 0; i < arraySize; i++) {
sgList[i].getLpn().setLpnIndex(i);
StateGraph lpn_tmp = sgList[i];
LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]);
curEnabledArray[i] = enabledList;
enabledList = lpn_tmp.getEnabled(nextStateArray[i]);
nextEnabledArray[i] = enabledList;
Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]);
if(disabledTran != null) {
System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel());
System.out.println("Current state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + sgList[ii].getLpn().getLabel());
System.out.println(curStateArray[ii]);
System.out.println("Enabled set: " + curEnabledArray[ii]);
}
System.out.println("======================\nNext state:");
for(int ii = 0; ii < arraySize; ii++) {
System.out.println("module " + sgList[ii].getLpn().getLabel());
System.out.println(nextStateArray[ii]);
System.out.println("Enabled set: " + nextEnabledArray[ii]);
}
System.out.println();
failure = true;
break main_while_loop;
}
}
if (Analysis.deadLock(sgList, nextStateArray) == true) {
System.out.println("---> Deadlock.");
// System.out.println("Deadlock state:");
// for(int ii = 0; ii < arraySize; ii++) {
// System.out.println("module " + lpnList[ii].getLabel());
// System.out.println(nextStateArray[ii]);
// System.out.println("Enabled set: " + nextEnabledArray[ii]);
failure = true;
break main_while_loop;
}
/*
// Add nextPrjState into prjStateSet
// If nextPrjState has been traversed before, skip to the next
// enabled transition.
//exist cycle
*/
PrjState nextPrjState = new PrjState(nextStateArray);
boolean isExisting = false;
int[] nextIdxArray = null;
if(useMdd==true)
nextIdxArray = Analysis.getIdxArray(nextStateArray);
if (useMdd == true)
isExisting = Mdd.contains(reach, nextIdxArray);
else
isExisting = prjStateSet.contains(nextPrjState);
if (isExisting == false) {
if (useMdd == true) {
mddMgr.add(reach, nextIdxArray, true);
}
else
prjStateSet.add(nextPrjState);
//get next enable transition set
//LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// LPNTranSet nextEnableSubset = new LPNTranSet();
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// nextEnableSubset.addLast(tran);
stateStack.add(nextPrjState);
stateStackTop.setChild(nextPrjState);
nextPrjState.setFather(stateStackTop);
stateStackTop = nextPrjState;
lpnTranStack.push(nextEnableSubset);
firedTranStack.push(new HashSet<Transition>());
// for (int i = 0; i < arraySize; i++)
// for (LPNTran tran : nextEnabledArray[i])
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for (LPNTran tran : nextEnableSubset)
// System.out.print(tran.getFullLabel() + ", ");
// HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>();
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : nextEnabledArray[i]) {
// allEnabledSet.add(tran);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// if(nextEnableSubset.size() > 0) {
// for (LPNTran tran : nextEnableSubset) {
// if (allEnabledSet.contains(tran) == false) {
// System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n");
// System.exit(0);
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n
continue;
}
/*
* Remove firedTran from traceCex if its successor state already exists.
*/
traceCex.removeLast();
/*
* When firedTran forms a cycle in the state graph, consider all enabled transitions except those
* 1. already fired in the current state,
* 2. in the ample set of the next state.
*/
if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) {
//System.out.println("formed a cycle......");
LpnTranList original = new LpnTranList();
LpnTranList reduced = new LpnTranList();
//LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet);
LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet);
// System.out.println("Back state's ample set:");
// for(LPNTran tran : nextStateAmpleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
int enabledTranCnt = 0;
LpnTranList[] tmp = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++) {
tmp[i] = new LpnTranList();
for (Transition tran : curEnabledArray[i]) {
original.addLast(tran);
if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) {
tmp[i].addLast(tran);
reduced.addLast(tran);
enabledTranCnt++;
}
}
}
LpnTranList ampleSet = new LpnTranList();
if(enabledTranCnt > 0)
//ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet);
ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet);
LpnTranList sortedAmpleSet = ampleSet;
/*
* Sort transitions in ampleSet for better performance for MDD.
* Not needed for hash table.
*/
if (useMdd == true) {
LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize];
for (int i = 0; i < arraySize; i++)
newCurEnabledArray[i] = new LpnTranList();
for (Transition tran : ampleSet)
newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran);
sortedAmpleSet = new LpnTranList();
for (int i = 0; i < arraySize; i++) {
LpnTranList localEnabledSet = newCurEnabledArray[i];
for (Transition tran : localEnabledSet)
sortedAmpleSet.addLast(tran);
}
}
// for(LPNTran tran : original)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : ampleSet)
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : firedTranStack.peek())
// allCurEnabled.remove(tran);
lpnTranStack.pop();
lpnTranStack.push(sortedAmpleSet);
// for (int i = 0; i < arraySize; i++) {
// for (LPNTran tran : curEnabledArray[i]) {
// System.out.print(tran.getFullLabel() + ", ");
// System.out.println("\n");
// for(LPNTran tran : allCurEnabled)
// System.out.print(tran.getFullLabel() + ", ");
}
//System.out.println("Backtrack........\n");
}//END while (stateStack.empty() == false)
if (useMdd==true)
stateCount = Mdd.numberOfStates(reach);
else
stateCount = prjStateSet.size();
//long curTotalMem = Runtime.getRuntime().totalMemory();
long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt
+ ", # of prjStates found: " + stateCount
+ ", max_stack_depth: " + max_stack_depth
+ ", used memory: " + (float) curUsedMem / 1000000
+ ", free memory: "
+ (float) Runtime.getRuntime().freeMemory() / 1000000);
return sgList;
}
// /**
// * Check if this project deadlocks in the current state 'stateArray'.
// * @param sgList
// * @param stateArray
// * @param staticSetsMap
// * @param enableSet
// * @param disableByStealingToken
// * @param disableSet
// * @param init
// * @return
// */
// // Called by search search_dfsPOR
// public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<Transition,StaticSets> staticSetsMap,
// boolean init, HashMap<Transition, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) {
// boolean deadlock = true;
// System.out.println("@ deadlock:");
//// for (int i = 0; i < stateArray.length; i++) {
//// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
//// if (tmp.size() > 0) {
//// deadlock = false;
//// break;
// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet();
// if (tmp.size() > 0) {
// deadlock = false;
// System.out.println("@ end of deadlock");
// return deadlock;
public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) {
boolean deadlock = true;
for (int i = 0; i < stateArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) {
boolean deadlock = true;
for (int i = 0; i < stateIdxArray.length; i++) {
LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
public static boolean deadLock(List<LinkedList<Transition>> lpnList) {
boolean deadlock = true;
for (int i = 0; i < lpnList.size(); i++) {
LinkedList<Transition> tmp = lpnList.get(i);
if (tmp.size() > 0) {
deadlock = false;
break;
}
}
return deadlock;
}
// /*
// * Scan enabledArray, identify all sticky transitions other the firedTran, and return them.
// *
// * Arguments remain constant.
// */
// public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) {
// int arraySize = enabledArray.length;
// LpnTranList[] stickyTranArray = new LpnTranList[arraySize];
// for (int i = 0; i < arraySize; i++) {
// stickyTranArray[i] = new LpnTranList();
// for (Transition tran : enabledArray[i]) {
// if (tran != firedTran)
// stickyTranArray[i].add(tran);
// if(stickyTranArray[i].size()==0)
// stickyTranArray[i] = null;
// return stickyTranArray;
/**
* Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to
* nextStickyTransArray.
*
* Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions
* from curStickyTransArray.
*
* Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState.
*/
public static LpnTranList[] checkStickyTrans(
LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray,
LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) {
int arraySize = curStickyTransArray.length;
LpnTranList[] stickyTransArray = new LpnTranList[arraySize];
boolean[] hasStickyTrans = new boolean[arraySize];
for (int i = 0; i < arraySize; i++) {
HashSet<Transition> tmp = new HashSet<Transition>();
if(nextStickyTransArray[i] != null)
for(Transition tran : nextStickyTransArray[i])
tmp.add(tran);
stickyTransArray[i] = new LpnTranList();
hasStickyTrans[i] = false;
for (Transition tran : curStickyTransArray[i]) {
if (tran.isPersistent() == true && tmp.contains(tran)==false) {
int[] nextMarking = nextState.getMarking();
int[] preset = LPN.getPresetIndex(tran.getLabel());//tran.getPreSet();
boolean included = false;
if (preset != null && preset.length > 0) {
for (int pp : preset) {
for (int mi = 0; i < nextMarking.length; i++) {
if (nextMarking[mi] == pp) {
included = true;
break;
}
}
if (included == false)
break;
}
}
if(preset==null || preset.length==0 || included==true) {
stickyTransArray[i].add(tran);
hasStickyTrans[i] = true;
}
}
}
if(stickyTransArray[i].size()==0)
stickyTransArray[i] = null;
}
return stickyTransArray;
}
/*
* Return an array of indices for the given stateArray.
*/
private static int[] getIdxArray(State[] stateArray) {
int[] idxArray = new int[stateArray.length];
for(int i = 0; i < stateArray.length; i++) {
idxArray[i] = stateArray[i].getIndex();
}
return idxArray;
}
private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) {
int arraySize = sgList.length;
int[] localIdxArray = new int[arraySize];
for(int i = 0; i < arraySize; i++) {
if(reverse == false)
localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex();
else
localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex();
//System.out.print(localIdxArray[i] + " ");
}
//System.out.println();
return localIdxArray;
}
private static void printStrongStubbornSetTbl(StateGraph[] sgList) {
for (int i=0; i<sgList.length; i++) {
System.out.println("******* Stored strong stubborn sets for state graph " + sgList[i].getLpn().getLabel() + " *******");
for (State s : sgList[i].getEnabledSetTbl().keySet()) {
System.out.print(s.getFullLabel() + " -> ");
printTransList(sgList[i].getEnabledSetTbl().get(s), "");
}
}
}
private HashSet<Transition> computeStrongStubbornSet(State[] curStateArray,
HashSet<Transition> curEnabled, HashMap<Transition,Integer> tranFiringFreq, StateGraph[] sgList) {
if (curEnabled.size() == 1)
return curEnabled;
HashSet<Transition> ready = new HashSet<Transition>();
// for (Transition enabledTran : curEnabled) {
// if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) {
// ready.add(enabledTran);
// return ready;
DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq, sgList.length-1);
PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
for (Transition enabledTran : curEnabled) {
if (Options.getDebugMode())
System.out.println("@ beginning of partialOrderReduction, consider seed transition " + enabledTran.getFullLabel());
HashSet<Transition> dependent = new HashSet<Transition>();
boolean enabledIsDummy = false;
boolean isCycleClosingStrongStubbornComputation = false;
dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingStrongStubbornComputation);
if (Options.getDebugMode())
printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
+ enabledTran.getFullLabel());
// Check if the computed dependent set contains both immediate and non-immediate transitions.
boolean dependentOnlyHasImmediateTrans = false;
boolean dependentOnlyHasNonImmediateTrans = false;
for (Transition tr: dependent) {
if (!dependentOnlyHasImmediateTrans && tr.getDelayTree() == null) {
dependentOnlyHasImmediateTrans = true;
}
if (!dependentOnlyHasNonImmediateTrans && tr.getDelayTree() != null) {
dependentOnlyHasNonImmediateTrans = true;
}
}
if (dependentOnlyHasNonImmediateTrans && dependentOnlyHasImmediateTrans) {
System.err.println("*** Error: Non-immediate transitions are dependent on immediate ones. ***");
System.out.println("dependent set: ");
for (Transition tr : dependent) {
System.out.println(tr.getFullLabel());
}
System.out.println();
}
// TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
if(isDummyTran(enabledTran.getLabel()))
enabledIsDummy = true;
DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
dependentSetQueue.add(dependentSet);
}
ready = dependentSetQueue.poll().getDependent();
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode())
// System.out.print("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// printIntegerSet(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// if (ready.isEmpty() || dependent.size() < ready.size())
// ready = dependent;
// if (ready.size() == 1) {
// cachedNecessarySets.clear();
// return ready;
cachedNecessarySets.clear();
return ready;
}
// private HashSet<Transition> partialOrderReduction(State[] curStateArray,
// HashSet<Transition> curEnabled, HashMap<Transition, StaticSets> staticMap,
// HashMap<Transition,Integer> tranFiringFreqMap, StateGraph[] sgList, LhpnFile[] lpnList) {
// if (curEnabled.size() == 1)
// return curEnabled;
// HashSet<Transition> ready = new HashSet<Transition>();
// for (Transition enabledTran : curEnabled) {
// if (staticMap.get(enabledTran).getOtherTransDisableCurTranSet().isEmpty()) {
// ready.add(enabledTran);
// return ready;
// if (Options.getUseDependentQueue()) {
// DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap);
// PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp);
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode()){
// writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean enabledIsDummy = false;
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.)
// if(isDummyTran(enabledTran.getName()))
// enabledIsDummy = true;
// DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy);
// dependentSetQueue.add(dependentSet);
// //cachedNecessarySets.clear();
// ready = dependentSetQueue.poll().getDependent();
// //return ready;
// else {
// for (Transition enabledTran : curEnabled) {
// if (Options.getDebugMode()){
// writeStringWithEndOfLineToPORDebugFile("@ beginning of partialOrderReduction, consider seed transition " + getNamesOfLPNandTrans(enabledTran));
// HashSet<Transition> dependent = new HashSet<Transition>();
// boolean isCycleClosingPersistentComputation = false;
// dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap,isCycleClosingPersistentComputation);
// if (Options.getDebugMode()) {
// writeIntegerSetToPORDebugFile(dependent, "@ end of partialOrderReduction, dependent set for enabled transition "
// + getNamesOfLPNandTrans(enabledTran));
// if (ready.isEmpty() || dependent.size() < ready.size())
// ready = dependent;//(HashSet<Transition>) dependent.clone();
// if (ready.size() == 1) {
// cachedNecessarySets.clear();
// return ready;
// cachedNecessarySets.clear();
// return ready;
private static boolean isDummyTran(String tranName) {
if (tranName.contains("_dummy"))
return true;
return false;
}
private HashSet<Transition> computeDependent(State[] curStateArray, Transition seed, HashSet<Transition> dependent,
HashSet<Transition> curEnabled, boolean isCycleClosingStrongStubbornComputation) {
// disableSet is the set of transitions that can either be disabled by firing enabledLpnTran, or disable enabledLpnTran.
boolean seedTranIsPersistent = false;
if (seed.isPersistent()) {
seedTranIsPersistent = true;
}
HashSet<Transition> disableSet = staticDependency.get(seed).getDisableSet(seedTranIsPersistent);
HashSet<Transition> otherTransDisableEnabledPeristentSeedTran
= staticDependency.get(seed).getOtherTransDisableSeedTran(seedTranIsPersistent);
if (Options.getDebugMode()) {
System.out.println("@ beginning of computeDependent, consider transition " + seed.getFullLabel());
printIntegerSet(disableSet, "Disable set for " + seed.getFullLabel());
}
dependent.add(seed);
// for (Transition lpnTranPair : canModifyAssign) {
// if (curEnabled.contains(lpnTranPair))
// dependent.add(lpnTranPair);
if (Options.getDebugMode())
printIntegerSet(dependent, "@ computeDependent at 0, dependent set for " + seed.getFullLabel());
// dependent is equal to enabled. Terminate.
if (dependent.size() == curEnabled.size()) {
if (Options.getDebugMode()) {
System.out.println("Check 0: Size of dependent is equal to enabled. Return dependent.");
}
return dependent;
}
for (Transition tr : disableSet) {
if (Options.getDebugMode())
System.out.println("Consider transition in the disable set of "
+ seed.getFullLabel() + ": "
+ tr.getFullLabel());
if (curEnabled.contains(tr) && !dependent.contains(tr)
&& (!tr.isPersistent() || otherTransDisableEnabledPeristentSeedTran.contains(tr))) {
// (tr is enabled) && (tr is not in seed's dependent set) && (tr is not persistent || )
dependent.addAll(computeDependent(curStateArray,tr,dependent,curEnabled,isCycleClosingStrongStubbornComputation));
if (Options.getDebugMode()) {
printIntegerSet(dependent, "@ computeDependent at 1 for transition " + seed.getFullLabel());
}
}
else if (!curEnabled.contains(tr)) {
if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back
|| (Options.getCycleClosingStrongStubbornMethd().toLowerCase().equals("cctboff")
&& isCycleClosingStrongStubbornComputation)) {
dependent.addAll(curEnabled);
break;
}
HashSet<Transition> necessary = null;
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
if (cachedNecessarySets.containsKey(tr)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ computeDependent: Found transition " + tr.getFullLabel() + "in the cached necessary sets.");
}
necessary = cachedNecessarySets.get(tr);
}
else {
if (Options.getDebugMode())
System.out.println("==== Compute necessary set using DFS ====");
if (visitedTrans == null)
visitedTrans = new HashSet<Transition>();
else
visitedTrans.clear();
necessary = computeNecessary(curStateArray,tr,dependent,curEnabled);
}
if (necessary != null && !necessary.isEmpty()) {
cachedNecessarySets.put(tr, necessary);
if (Options.getDebugMode())
printIntegerSet(necessary, "@ computeDependent, necessary set for transition " + tr.getFullLabel());
for (Transition tranInNecessary : necessary) {
if (!dependent.contains(tranInNecessary)) {
if (Options.getDebugMode()) {
printIntegerSet(dependent,"Check if the newly found necessary transition is in the dependent set of " + seed.getFullLabel());
System.out.println("It does not contain this transition found by computeNecessary: "
+ tranInNecessary.getFullLabel() + ". Compute its dependent set.");
}
dependent.addAll(computeDependent(curStateArray,tranInNecessary,dependent,curEnabled,isCycleClosingStrongStubbornComputation));
}
else {
if (Options.getDebugMode()) {
printIntegerSet(dependent, "Check if the newly found necessary transition is in the dependent set. Dependent set for " + seed.getFullLabel());
System.out.println("It already contains this transition found by computeNecessary: "
+ tranInNecessary.getFullLabel() + ".");
}
}
}
}
else {
if (Options.getDebugMode()) {
if (necessary == null)
System.out.println("necessary set for transition " + seed.getFullLabel() + " is null.");
else
System.out.println("necessary set for transition " + seed.getFullLabel() + " is empty.");
}
//dependent.addAll(curEnabled);
return curEnabled;
}
if (Options.getDebugMode()) {
printIntegerSet(dependent,"@ computeDependent at 2, dependent set for transition " + seed.getFullLabel());
}
}
else if (dependent.contains(tr)) {
if (Options.getDebugMode()) {
printIntegerSet(dependent,"@ computeDependent at 3 for transition " + seed.getFullLabel());
System.out.println("Transition " + tr.getFullLabel() + " is already in the dependent set of "
+ seed.getFullLabel() + ".");
}
}
}
return dependent;
}
// private String getNamesOfLPNandTrans(Transition tran) {
// return tran.getLpn().getLabel() + "(" + tran.getLabel() + ")";
private HashSet<Transition> computeNecessary(State[] curStateArray,
Transition tran, HashSet<Transition> dependent,
HashSet<Transition> curEnabled) {
if (Options.getDebugMode()) {
System.out.println("@ computeNecessary, consider transition: " + tran.getFullLabel());
}
if (cachedNecessarySets.containsKey(tran)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ computeNecessary: Found transition " + tran.getFullLabel()
+ "'s necessary set in the cached necessary sets. Return the cached necessary set.");
}
return cachedNecessarySets.get(tran);
}
// Search for transition(s) that can help to bring the marking(s).
HashSet<Transition> nMarking = null;
//Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex());
//int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName());
for (int i=0; i < tran.getPreset().length; i++) {
int placeIndex = tran.getLpn().getPresetIndex(tran.getLabel())[i];
if (curStateArray[tran.getLpn().getLpnIndex()].getMarking()[placeIndex]==0) {
if (Options.getDebugMode()) {
System.out.println("
}
HashSet<Transition> nMarkingTemp = new HashSet<Transition>();
String placeName = tran.getLpn().getPlaceList()[placeIndex];
Transition[] presetTrans = tran.getLpn().getPlace(placeName).getPreset();
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Consider preset place of " + tran.getFullLabel() + ": " + placeName);
}
for (int j=0; j < presetTrans.length; j++) {
Transition presetTran = presetTrans[j];
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Preset of place " + placeName + " has transition(s): ");
for (int k=0; k<presetTrans.length; k++) {
System.out.print(presetTrans[k].getFullLabel() + ", ");
}
System.out.println("");
System.out.println("@ nMarking: Consider transition of " + presetTran.getFullLabel());
}
if (curEnabled.contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: curEnabled contains transition "
+ presetTran.getFullLabel() + "). Add to nMarkingTmp.");
}
nMarkingTemp.add(presetTran);
}
else {
if (visitedTrans.contains(presetTran)) {//seedTranInDisableSet.getVisitedTrans().contains(presetTran)) {
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Transition " + presetTran.getFullLabel() + " was visted before");
}
if (cachedNecessarySets.containsKey(presetTran)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@nMarking: Found transition " + presetTran.getFullLabel()
+ "'s necessary set in the cached necessary sets. Add it to nMarkingTemp.");
}
nMarkingTemp = cachedNecessarySets.get(presetTran);
}
continue;
}
visitedTrans.add(presetTran);
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~~ transVisited ~~~~~~~~~");
for (Transition visitedTran :visitedTrans) {
System.out.println(visitedTran.getFullLabel());
}
System.out.println("@ nMarking, before call computeNecessary: consider transition: "
+ presetTran.getFullLabel());
System.out.println("@ nMarking: transition " + presetTran.getFullLabel() + " is not enabled. Compute its necessary set.");
}
HashSet<Transition> tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabled);
if (tmp != null) {
nMarkingTemp.addAll(tmp);
if (Options.getDebugMode()) {
System.out.println("@ nMarking: tmp returned from computeNecessary for " + presetTran.getFullLabel() + " is not null.");
printIntegerSet(nMarkingTemp, presetTran.getFullLabel() + "'s nMarkingTemp");
}
}
else
if (Options.getDebugMode()) {
System.out.println("@ nMarking: necessary set for transition "
+ presetTran.getFullLabel() + " is null.");
}
}
}
if (!nMarkingTemp.isEmpty())
//if (nMarking == null || nMarkingTemp.size() < nMarking.size())
if (nMarking == null
|| setSubstraction(nMarkingTemp, dependent).size() < setSubstraction(nMarking, dependent).size())
nMarking = nMarkingTemp;
}
else
if (Options.getDebugMode()) {
System.out.println("@ nMarking: Place " + tran.getLpn().getLabel()
+ "(" + tran.getLpn().getPlaceList()[placeIndex] + ") is marked.");
}
}
if (nMarking != null && nMarking.size() ==1 && setSubstraction(nMarking, dependent).size() == 0) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
System.out.println("Return nMarking as necessary set.");
printCachedNecessarySets();
}
return nMarking;
}
// Search for transition(s) that can help to enable the current transition.
HashSet<Transition> nEnable = null;
int[] varValueVector = curStateArray[tran.getLpn().getLpnIndex()].getVariableVector();
//HashSet<Transition> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue();
ArrayList<HashSet<Transition>> canEnable = staticDependency.get(tran).getOtherTransSetSeedTranEnablingTrue();
if (Options.getDebugMode()) {
System.out.println("
printIntegerSet(canEnable, "@ nEnable: " + tran.getFullLabel() + " can be enabled by");
}
if (tran.getEnablingTree() != null
&& tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& !canEnable.isEmpty()) {
for(int index=0; index < tran.getConjunctsOfEnabling().size(); index++) {
ExprTree conjunctExprTree = tran.getConjunctsOfEnabling().get(index);
HashSet<Transition> nEnableForOneConjunct = null;
if (Options.getDebugMode()) {
printIntegerSet(canEnable, "@ nEnable: " + tran.getFullLabel() + " can be enabled by");
System.out.println("@ nEnable: Consider conjunct for transition " + tran.getFullLabel() + ": "
+ conjunctExprTree.toString());
}
if (conjunctExprTree.evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
HashSet<Transition> canEnableOneConjunctSet = staticDependency.get(tran).getOtherTransSetSeedTranEnablingTrue().get(index);
nEnableForOneConjunct = new HashSet<Transition>();
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Conjunct for transition " + tran.getFullLabel() + " "
+ conjunctExprTree.toString() + " is evaluated to FALSE.");
printIntegerSet(canEnableOneConjunctSet, "@ nEnable: Transitions that can enable this conjunct are");
}
for (Transition tranCanEnable : canEnableOneConjunctSet) {
if (curEnabled.contains(tranCanEnable)) {
nEnableForOneConjunct.add(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: curEnabled contains transition " + tranCanEnable.getFullLabel() + ". Add to nEnableOfOneConjunct.");
}
}
else {
if (visitedTrans.contains(tranCanEnable)) {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Transition " + tranCanEnable.getFullLabel() + " was visted before.");
}
if (cachedNecessarySets.containsKey(tranCanEnable)) {
if (Options.getDebugMode()) {
printCachedNecessarySets();
System.out.println("@ nEnable: Found transition " + tranCanEnable.getFullLabel()
+ "'s necessary set in the cached necessary sets. Add it to nEnableOfOneConjunct.");
}
nEnableForOneConjunct.addAll(cachedNecessarySets.get(tranCanEnable));
}
continue;
}
visitedTrans.add(tranCanEnable);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Transition " + tranCanEnable.getFullLabel()
+ " is not enabled. Compute its necessary set.");
}
HashSet<Transition> tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabled);
if (tmp != null) {
nEnableForOneConjunct.addAll(tmp);
if (Options.getDebugMode()) {
System.out.println("@ nEnable: tmp returned from computeNecessary for " + tranCanEnable.getFullLabel() + ": ");
printIntegerSet(tmp, "");
printIntegerSet(nEnableForOneConjunct, tranCanEnable.getFullLabel() + "'s nEnableOfOneConjunct");
}
}
else
if (Options.getDebugMode()) {
System.out.println("@ nEnable: necessary set for transition "
+ tranCanEnable.getFullLabel() + " is null.");
}
}
}
if (!nEnableForOneConjunct.isEmpty()) {
if (nEnable == null
|| setSubstraction(nEnableForOneConjunct, dependent).size() < setSubstraction(nEnable, dependent).size()) {
//&& !nEnableForOneConjunct.isEmpty())) {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: nEnable for transition " + tran.getFullLabel() +" is replaced by nEnableForOneConjunct.");
printIntegerSet(nEnable, "nEnable");
printIntegerSet(nEnableForOneConjunct, "nEnableForOneConjunct");
}
nEnable = nEnableForOneConjunct;
}
else {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: nEnable for transition " + tran.getFullLabel() +" remains unchanged.");
printIntegerSet(nEnable, "nEnable");
}
}
}
}
else {
if (Options.getDebugMode()) {
System.out.println("@ nEnable: Conjunct for transition " + tran.getFullLabel() + " "
+ conjunctExprTree.toString() + " is evaluated to TRUE. No need to trace back on it.");
}
}
}
}
else {
if (Options.getDebugMode()) {
if (tran.getEnablingTree() == null) {
System.out.println("@ nEnable: transition " + tran.getFullLabel() + " has no enabling condition.");
}
else if (tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) !=0.0) {
System.out.println("@ nEnable: transition " + tran.getFullLabel() + "'s enabling condition is true.");
}
else if (tran.getEnablingTree() != null
&& tran.getEnablingTree().evaluateExpr(tran.getLpn().getAllVarsWithValuesAsString(varValueVector)) == 0.0
&& canEnable.isEmpty()) {
System.out.println("@ nEnable: transition " + tran.getFullLabel()
+ "'s enabling condition is false, but no other transitions that can help to enable it were found .");
}
printIntegerSet(nMarking, "=== nMarking for transition " + tran.getFullLabel());
printIntegerSet(nEnable, "=== nEnable for transition " + tran.getFullLabel());
}
}
if (nMarking != null && nEnable == null) {
if (!nMarking.isEmpty())
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
else if (nMarking == null && nEnable != null) {
if (!nEnable.isEmpty())
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
else if (nMarking == null || nEnable == null) {
return null;
}
else {
if (!nMarking.isEmpty() && !nEnable.isEmpty()) {
if (setSubstraction(nMarking, dependent).size() < setSubstraction(nEnable, dependent).size()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
else if (nMarking.isEmpty() && !nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nEnable);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nEnable;
}
else if (!nMarking.isEmpty() && nEnable.isEmpty()) {
cachedNecessarySets.put(tran, nMarking);
if (Options.getDebugMode()) {
printCachedNecessarySets();
}
return nMarking;
}
else {
return null;
}
}
}
// private HashSet<Transition> computeNecessaryUsingDependencyGraphs(State[] curStateArray,
// Transition tran, HashSet<Transition> curEnabled,
// HashMap<Transition, StaticSets> staticMap,
// LhpnFile[] lpnList, Transition seedTran) {
// if (Options.getDebugMode()) {
//// System.out.println("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// writeStringWithEndOfLineToPORDebugFile("@ computeNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")");
// // Use breadth-first search to find the shorted path from the seed transition to an enabled transition.
// LinkedList<Transition> exploredTransQueue = new LinkedList<Transition>();
// HashSet<Transition> allExploredTrans = new HashSet<Transition>();
// exploredTransQueue.add(tran);
// //boolean foundEnabledTran = false;
// HashSet<Transition> canEnable = new HashSet<Transition>();
// while(!exploredTransQueue.isEmpty()){
// Transition curTran = exploredTransQueue.poll();
// allExploredTrans.add(curTran);
// if (cachedNecessarySets.containsKey(curTran)) {
// if (Options.getDebugMode()) {
// writeStringWithEndOfLineToPORDebugFile("Found transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")"
// + "'s necessary set in the cached necessary sets. Terminate BFS.");
// return cachedNecessarySets.get(curTran);
// canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray);
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(canEnable, lpnList, "Neighbors that can help to bring tokens to transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// // Decide if canSetEnablingTrue set can help to enable curTran.
// Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex());
// int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector();
// if (curTransition.getEnablingTree() != null
// && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) {
// canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue());
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to set the enabling of transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(staticMap.get(curTran).getEnableBySettingEnablingTrue(), lpnList, "Neighbors that can help to set the enabling transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// if (Options.getDebugMode()) {
//// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") ");
// for (Transition neighborTran : canEnable) {
// if (curEnabled.contains(neighborTran)) {
// if (!neighborTran.equals(seedTran)) {
// HashSet<Transition> necessarySet = new HashSet<Transition>();
// necessarySet.add(neighborTran);
// // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed?
// cachedNecessarySets.put(tran, necessarySet);
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ").");
// return necessarySet;
// else if (neighborTran.equals(seedTran) && canEnable.size()==1) {
// if (Options.getDebugMode()) {
//// System.out.println("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
//// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// writeStringWithEndOfLineToPORDebugFile("Enabled neighbor that can help to enable transition " + lpnList[curTran.getLpnIndex()].getLabel()
// + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + "). But " + lpnList[neighborTran.getLpnIndex()].getLabel()
// + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ") is the seed transition. Return null necessary set.");
// return null;
//// if (exploredTransQueue.isEmpty()) {
//// System.out.println("exploredTransQueue is empty. Return null necessary set.");
//// writeStringWithNewLineToPORDebugFile("exploredTransQueue is empty. Return null necessary set.");
//// return null;
// if (!allExploredTrans.contains(neighborTran)) {
// allExploredTrans.add(neighborTran);
// exploredTransQueue.add(neighborTran);
// canEnable.clear();
// return null;
private void printCachedNecessarySets() {
System.out.println("================ cached necessary sets =================");
for (Transition key : cachedNecessarySets.keySet()) {
System.out.print(key.getLpn().getLabel() + "(" + key.getLabel() + ") => ");
for (Transition necessary : cachedNecessarySets.get(key)) {
System.out.print(necessary.getLpn().getLabel() + "(" + necessary.getLabel() + ") ");
}
System.out.println("");
}
}
private static HashSet<Transition> setSubstraction(
HashSet<Transition> left, HashSet<Transition> right) {
HashSet<Transition> sub = new HashSet<Transition>();
for (Transition lpnTranPair : left) {
if (!right.contains(lpnTranPair))
sub.add(lpnTranPair);
}
return sub;
}
public static boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
if(stateArray[lpnIndex].equals(curState)) {// (stateArray[lpnIndex] == curState) {
isStateOnStack = true;
break;
}
}
return isStateOnStack;
}
private static void printIntegerSet(HashSet<Transition> Trans, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (Trans == null) {
System.out.println("null");
}
else if (Trans.isEmpty()) {
System.out.println("empty");
}
else {
for (Transition lpnTranPair : Trans) {
System.out.print(lpnTranPair.getLabel() + "("
+ lpnTranPair.getLpn().getLabel() + "),");
}
System.out.println();
}
}
private static void printIntegerSet(ArrayList<HashSet<Transition>> transSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + ": ");
if (transSet == null) {
System.out.println("null");
}
else if (transSet.isEmpty()) {
System.out.println("empty");
}
else {
for (HashSet<Transition> lpnTranPairSet : transSet) {
for (Transition lpnTranPair : lpnTranPairSet)
System.out.print(lpnTranPair.getLpn().getLabel() + "("
+ lpnTranPair.getLabel() + "),");
}
System.out.println();
}
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Objects;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
JPopupMenu popup1 = makePopupMenu();
JTextField textField1 = new JTextField("Default setComponentPopupMenu");
textField1.setComponentPopupMenu(popup1);
textField1.setName("textField1");
// // TEST:
// textField1.addMouseListener(new MouseAdapter() {
// @Override public void mousePressed(MouseEvent e) {
// e.getComponent().requestFocusInWindow();
JPopupMenu popup2 = new TextComponentPopupMenu();
JTextField textField2 = new JTextField("Override JPopupMenu#show(...)");
textField2.setComponentPopupMenu(popup2);
textField2.setName("textField2");
JComboBox<String> combo3 = new JComboBox<>(new String[] {"JPopupMenu does not open???", "111", "222"});
combo3.setEditable(true);
// NOT work: combo3.setComponentPopupMenu(popup2);
JTextField textField3 = (JTextField) combo3.getEditor().getEditorComponent();
textField3.setComponentPopupMenu(popup2);
textField3.setName("textField3");
// TEST: textField3.putClientProperty("doNotCancelPopup", null);
JComboBox<String> combo4 = new JComboBox<>(new String[] {"addMouseListener", "111", "222"});
combo4.setEditable(true);
JTextField textField4 = (JTextField) combo4.getEditor().getEditorComponent();
textField4.setComponentPopupMenu(popup2);
textField4.setName("textField4");
textField4.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
if (combo4.isPopupVisible()) {
System.out.println("Close all JPopupMenu(excludes dropdown list of own JComboBox)");
for (MenuElement m: MenuSelectionManager.defaultManager().getSelectedPath()) {
if (m instanceof JPopupMenu) {
((JPopupMenu) m).setVisible(false);
}
}
}
}
});
// textField4.addFocusListener(new FocusAdapter() {
// @Override public void focusGained(FocusEvent e) {
// System.out.println("focusGained");
// for (MenuElement m: MenuSelectionManager.defaultManager().getSelectedPath()) {
// if (m instanceof JPopupMenu) {
// ((JPopupMenu) m).setVisible(false);
Box box = Box.createVerticalBox();
Stream.of(textField1, textField2, combo3, combo4).forEach(c -> {
box.add(c);
box.add(Box.createVerticalStrut(5));
});
JTextArea textArea = new JTextArea("dummy");
textArea.setComponentPopupMenu(popup2);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(box, BorderLayout.NORTH);
add(new JScrollPane(textArea));
setPreferredSize(new Dimension(320, 240));
}
private static JPopupMenu makePopupMenu() {
Action cutAction = new DefaultEditorKit.CutAction();
Action copyAction = new DefaultEditorKit.CopyAction();
Action pasteAction = new DefaultEditorKit.PasteAction();
JPopupMenu popup1 = new JPopupMenu();
popup1.add(cutAction);
popup1.add(copyAction);
popup1.add(pasteAction);
popup1.addPopupMenuListener(new PopupMenuListener() {
@Override public void popupMenuCanceled(PopupMenuEvent e) {
/* not needed */
}
@Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
/* not needed */
}
@Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
JPopupMenu pop = (JPopupMenu) e.getSource();
JTextComponent tc = (JTextComponent) pop.getInvoker();
System.out.println(tc.getClass().getName() + ": " + tc.getName());
// TEST:
// tc.requestFocusInWindow();
// tc.selectAll();
boolean hasSelectedText = Objects.nonNull(tc.getSelectedText());
cutAction.setEnabled(hasSelectedText);
copyAction.setEnabled(hasSelectedText);
}
});
return popup1;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TextComponentPopupMenu extends JPopupMenu {
private final transient Action cutAction = new DefaultEditorKit.CutAction();
private final transient Action copyAction = new DefaultEditorKit.CopyAction();
// private final transient Action pasteAction = new DefaultEditorKit.PasteAction();
protected TextComponentPopupMenu() {
super();
add(cutAction);
add(copyAction);
add(new DefaultEditorKit.PasteAction());
}
@Override public void show(Component c, int x, int y) {
System.out.println(c.getClass().getName() + ": " + c.getName());
if (c instanceof JTextComponent) {
JTextComponent tc = (JTextComponent) c;
tc.requestFocusInWindow();
boolean hasSelectedText = Objects.nonNull(tc.getSelectedText());
if (tc instanceof JTextField && !tc.isFocusOwner() && !hasSelectedText) {
tc.selectAll();
hasSelectedText = true;
}
cutAction.setEnabled(hasSelectedText);
copyAction.setEnabled(hasSelectedText);
super.show(c, x, y);
}
}
}
|
package connection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.jms.Connection;
import javax.jms.ConnectionConsumer;
import javax.jms.ConnectionMetaData;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ServerSessionPool;
import javax.jms.Session;
import javax.jms.Topic;
import messages.MyMessage;
import server.query.AckQuery;
import server.query.CreateTopicQuery;
import server.query.MessageQuery;
import server.query.Query;
import server.query.QueryType;
import server.query.SubscriberQuery;
import server.query.UnsubscriberQuery;
import session.MySession;
import session.SessionMessageReceiverListener;
import topic.MyTopic;
import utils.ClientRequestHandler;
public class MyConnection implements Connection, MyConnectionSendMessage, Runnable {
private String clientId;
private String hostIp;
private int hostPort;
private ExceptionListener exceptionListener;
private ConnectionMetaData connectionMetaData;
private ClientRequestHandler receiverConnection;
private ClientRequestHandler senderConnection;
private boolean open = false;
private boolean stopped = false;
private boolean modified = false;
private HashMap<String,ArrayList<SessionMessageReceiverListener>> subscribed;
private ConcurrentLinkedQueue<MessageWaitingAck> waitingAck;
private ArrayList<Session> sessions;
ReentrantLock lock = new ReentrantLock();
private Condition messageSent;
private static int id = 0;
public MyConnection(String hostIp, int hostPort){
this.lock = new ReentrantLock();
this.hostPort = hostPort;
this.hostIp = hostIp;
this.subscribed = new HashMap<String,ArrayList<SessionMessageReceiverListener>>();
this.sessions = new ArrayList<Session>();
this.clientId = "CLT:"+UUID.randomUUID().toString()+id;
this.messageSent = lock.newCondition();
id++;
this.waitingAck = new ConcurrentLinkedQueue<MessageWaitingAck>();
}
private void isOpen() throws JMSException{
if(!this.open){
throw new JMSException("Operation perfomed on closed session");
}
}
public void onMessageReceived(Query query){
System.out.println("Message Received");
Topic destination;
if(!this.stopped){
try {
if(query instanceof MessageQuery){
Message msg = ((MessageQuery) query).getMessage();
destination = (Topic)msg.getJMSDestination();
lock.lock();
ArrayList<SessionMessageReceiverListener> sessions = this.subscribed.get(destination.getTopicName());
String[] arr2 = new String[1];
this.subscribed.keySet().toArray(arr2);
System.out.println(arr2[0]);
if(sessions != null){
for(SessionMessageReceiverListener session : sessions ){
session.onMessageReceived(msg);
}
}
}else if(query instanceof AckQuery){
AckQuery ackQuery = (AckQuery) query;
MessageWaitingAck remove = new MessageWaitingAck(ackQuery.getMessageID());
System.out.println("Message Acked: "+ackQuery.getMessageID());
System.out.println("Before remove"+this.waitingAck.size());
this.waitingAck.remove(remove);
System.out.println("After remove"+this.waitingAck.size());
}
} catch (JMSException e) {
e.printStackTrace();
}finally{
if(lock.isLocked())lock.unlock();
}
}
}
private void callExceptionListener(Exception e){
JMSException error = new JMSException(e.getMessage());
error.setLinkedException(e);
if(this.exceptionListener != null){
this.exceptionListener.onException(error);
}
}
@Override
public void close() throws JMSException {
setModified();
this.open = false;
try {
this.receiverConnection.closeConnection();
this.senderConnection.closeConnection();
} catch (IOException e) {
callExceptionListener(e);
e.printStackTrace();
}
}
@Override
public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3)
throws JMSException {
throw new JMSException("Method not Implemented");
}
@Override
public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2,
ServerSessionPool arg3, int arg4) throws JMSException {
throw new JMSException("Method not Implemented");
}
@Override
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
setModified();
Session session = new MySession(transacted,acknowledgeMode,this);
this.sessions.add(session);
return session;
}
@Override
public String getClientID() throws JMSException {
return clientId;
}
@Override
public ExceptionListener getExceptionListener() throws JMSException {
return exceptionListener;
}
@Override
public ConnectionMetaData getMetaData() throws JMSException {
return connectionMetaData;
}
@Override
public void setClientID(String arg0) throws JMSException {
if(modified){
throw new JMSException("Set the client ID must be performed before any other action.");
}
clientId = arg0;
}
@Override
public void setExceptionListener(ExceptionListener arg0) throws JMSException {
exceptionListener = arg0;
}
@Override
public void start() throws JMSException {
try {
if(!this.open){
int numberOfTries = 0;
while(numberOfTries<3){
numberOfTries++;
try {
receiverConnection = new ClientRequestHandler(hostIp, hostPort, true, getClientID());
System.out.println("Connected receiver");
senderConnection = new ClientRequestHandler(hostIp, hostPort, false, getClientID());
this.open = true;
System.out.println("Connected sender");
this.stopped = false;
this.receiverConnection.setConnection(this);
this.senderConnection.setConnection(this);
this.receiverConnection.startMessageReceving();
Thread listenAcks = new Thread(this);
listenAcks.start();
break;
} catch (Exception e) {
e.printStackTrace();
if(receiverConnection != null) receiverConnection.closeConnection();
if(senderConnection != null) senderConnection.closeConnection();
}
int delay = (int) (1000*Math.pow(2, numberOfTries));
System.out.println("Connection failure, trying again in "+ delay + "...");
Thread.sleep(delay);
}
if(numberOfTries >=3) throw new JMSException("Could not connect to server");
}
} catch (Exception e) {
callExceptionListener(e);
e.printStackTrace();
}
}
@Override
public void stop() throws JMSException {
this.stopped = true;
}
public void setModified() {
this.modified = true;
}
@Override
public void sendMessage(Message myMessage) throws IOException, JMSException {
isOpen();
setModified();
this.waitingAck.add(new MessageWaitingAck(myMessage));
System.out.println("Message send: "+myMessage.getJMSMessageID());
this.lock.lock();
if(lock.hasWaiters(this.messageSent)){
this.messageSent.signal();
}
this.lock.unlock();
MyMessage msg = (MyMessage) myMessage;
msg.setReadOnly(true);
Query query = new MessageQuery(getClientID(),msg);
senderConnection.sendMessageAsync(query);
}
private void subscribeSessionToDestination(Destination destination, SessionMessageReceiverListener session) throws JMSException{
lock.lock();
Topic topic = (Topic) destination;
ArrayList<SessionMessageReceiverListener> arr = this.subscribed.get(topic.getTopicName());
if(arr == null){
arr = new ArrayList<SessionMessageReceiverListener>();
arr.add(session);
}else{
if(!arr.contains(session)){
arr.add(session);
}
}
this.subscribed.put(topic.getTopicName(), arr);
lock.unlock();
}
private boolean unsubscribeSessionToDestination(Destination destination, SessionMessageReceiverListener session) throws JMSException{
try{
lock.lock();
Topic topic = (Topic) destination;
ArrayList<SessionMessageReceiverListener> arr = this.subscribed.get(topic.getTopicName());
if(arr == null){
throw new JMSException("Try to unsubscribe from a topic you have not subscribed before");
}else{
arr.remove(session);
if(arr.isEmpty()) return true;
else return false;
}
}finally{
lock.unlock();
}
}
@Override
public void subscribe(Destination destination, SessionMessageReceiverListener session) throws IOException, JMSException {
isOpen();
setModified();
Topic topic = (Topic) destination;
subscribeSessionToDestination(destination, session);
Query query = new SubscriberQuery(getClientID(),topic.getTopicName());
senderConnection.send(query);
}
@Override
public void unsubscribe(String destination, SessionMessageReceiverListener session)
throws IOException, JMSException {
isOpen();
setModified();
Topic topic = new MyTopic(destination);
boolean unsubcribe = unsubscribeSessionToDestination(topic, session);
if(unsubcribe){
Query query = new UnsubscriberQuery(getClientID(),topic.getTopicName());
senderConnection.send(query);
}
}
@Override
public void acknowledgeMessage(Message message, Session session) throws IOException, JMSException {
isOpen();
setModified();
Query query = new AckQuery(getClientID(),message.getJMSMessageID());
senderConnection.sendMessageAsync(query);
}
@Override
public void closeSession(Session session) {
for(String key:this.subscribed.keySet()){
if(this.subscribed.get(key).contains(session)){
this.subscribed.get(key).remove(session);
}
}
}
@Override
public void createTopic(Topic my) throws IOException, JMSException {
CreateTopicQuery query = new CreateTopicQuery(getClientID());
query.setTopic(my);
this.senderConnection.sendMessageAsync(query);
}
@Override
public void run() {
System.out.println("Entrou no run");
while(true){
if(this.waitingAck.isEmpty()){
lock.lock();
try {
this.messageSent.await();
} catch (InterruptedException e) {}
lock.unlock();
}
MessageWaitingAck msg = this.waitingAck.peek();
long curr =System.currentTimeMillis();
if(msg.getTimestamp() <= curr){
try {
this.waitingAck.remove(msg);
this.sendMessage(msg.getMessage());
} catch (IOException | JMSException e) {e.printStackTrace();}
}else{
try {
Thread.sleep(msg.getTimestamp()-curr);
} catch (InterruptedException e) {e.printStackTrace();}
}
}
}
private class MessageWaitingAck {
private Message message;
private long timestamp;
private String messageId;
public MessageWaitingAck(Message message) throws JMSException{
this.message =message;
this.timestamp = System.currentTimeMillis() + 10000;
this.messageId = message.getJMSMessageID();
}
public MessageWaitingAck(String messageId){
this.messageId = messageId;
}
public Message getMessage(){
return message;
}
public String getMessageID(){
return messageId;
}
public long getTimestamp() {
return timestamp;
}
@Override
public boolean equals(Object o){
if(o instanceof MessageWaitingAck){
System.out.println("compare: "+ getMessageID());
System.out.println("with : "+ ((MessageWaitingAck) o).getMessageID());
System.out.println("result : "+ ((MessageWaitingAck) o).getMessageID().equals(getMessageID()));
return ((MessageWaitingAck) o).getMessageID().equals(getMessageID());
}
System.out.println("Not same type ");
return false;
}
}
}
|
package com.example.qmain;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.content.DialogInterface;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.graphics.Color;
import android.os.Environment;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.io.File;
import java.io.FileNotFoundException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.text.InputFilter;
import android.support.v4.view.PagerAdapter;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
public class PVQ extends AppCompatActivity {
List Questions = new ArrayList(); // List of all questions
HashMap<String,List> Groups = new HashMap<>(); // Hash map mapping questions to groups
List Image_Tags = new ArrayList();
String answers = "";
TextView ans = null;
LinearLayout req_buttons;
static List Counter = new ArrayList();
public static AlertDialog.Builder builder = null; // For building alert dialogs when necessary
public Context context = this; // For accessing context of the questionnaire
public static String LOCATION = ""; // Location stored here
ImageView mImageView = null;
LinearLayout camera_question = null;
LinearLayout map_question = null;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String author = "";
List pages = new ArrayList();
ViewPager vp = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pvq);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Create and set up new questionnaire ViewPager
//final ViewPager vp = (ViewPager) findViewById(R.id.activity_pvq);
LinearLayout form = (LinearLayout) findViewById(R.id.activity_pvq);
author = getIntent().getStringExtra("author");
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle("Questionnaire");
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
vp = new ViewPager(this);
vp.setId(View.generateViewId());
setupUI(vp);
form.addView(vp);
final MainPagerAdapter pg = new MainPagerAdapter();
vp.setAdapter(pg);
LinearLayout navbar = new LinearLayout(this);
navbar.setOrientation(LinearLayout.HORIZONTAL);
navbar.setBackgroundColor(Color.WHITE);
// creates back to menu, previous, and next buttons
Button menu_button = new Button(this);
String menu = "Menu";
menu_button.setText(menu);
menu_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
vp.setCurrentItem(0, false);
if(vp.getCurrentItem() != vp.getChildCount()-1){
ans.setText("");
}
}catch(Exception e){
System.out.println("no menu");
}
}
});
Button scroll_up = new Button(this);
String btt = "Back to Top";
scroll_up.setText(btt);
scroll_up.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
ScrollView view = (ScrollView) vp.findViewWithTag("myview" + vp.getCurrentItem());
view.fullScroll(ScrollView.FOCUS_UP);
}catch(Exception e){
System.out.println("scroll up error");
}
}
});
Button prev = new Button(this);
String pr = "Previous";
prev.setText(pr);
prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
int gb = vp.getCurrentItem();
vp.setCurrentItem(gb -1, false);
if(vp.getCurrentItem() != vp.getChildCount()-1){
ans.setText("");
}
}catch(Exception e){
System.out.println("prev button error");
}
}
});
Button next = new Button(this);
String nxt = "Next";
next.setText(nxt);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
int gb = vp.getCurrentItem();
vp.setCurrentItem(gb + 1, false);
}catch(Exception e){
System.out.println("next button error");
}
}
});
setupUI(prev);
setupUI(menu_button);
setupUI(next);
setupUI(scroll_up);
navbar.addView(prev);
navbar.addView(menu_button);
navbar.addView(scroll_up);
navbar.addView(next);
navbar.setGravity(100);
setupUI(navbar);
/*
RelativeLayout.LayoutParams rLParams =
new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
rLParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
form.addView(navbar, rLParams);
*/
form.addView(navbar);
LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
12.0f
);
vp.setLayoutParams(param1);
navbar.setLayoutParams(param2);
// Sets up an alert dialog builder for use when necessary
builder = new AlertDialog.Builder(this);
// Builds Questionnaire
try{
// Parses XML doc so code can read it
InputStream in = getResources().openRawResource(R.raw.questionnaire);
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
in.close();
// Builds first page
// Each page consists of a scrollview containing a linear layout containing smaller linear layouts
ScrollView sv1 = new ScrollView(this);
LinearLayout p1 = new LinearLayout(this);
p1.setOrientation(LinearLayout.VERTICAL);
// Adds first page to ViewPager
pg.addView(sv1,0);
sv1.addView(p1);
setupUI(sv1);
setupUI(p1);
// Adds "Sections" title to first page
TextView title = new TextView(this);
title.setTextSize(30);
String sections = "Sections";
title.setText(sections);
p1.addView(title);
pages.add(sections);
// iterates through all groups of questions in XML doc
NodeList groups = doc.getElementsByTagName("group");
for(int g = 0; g<groups.getLength(); g++){
System.out.println(g);
Node gr = groups.item(g);
Element eE = (Element) gr;
final int g_button = g; // number of group, counting from 0
String g_name = ((Element) gr).getElementsByTagName("gtext").item(0).getTextContent(); // group name
// creates button on menu page linked to group page
Button p1_button = new Button(this);
p1.addView(p1_button);
p1_button.setText(g_name);
pages.add(g_name);
p1_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vp.setCurrentItem(g_button+1, false);
}
});
// creates group page
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
pg.addView(sv,g+1);
setupUI(sv);
// adds name to group page
TextView group_name = new TextView(this);
group_name.setText(g_name);
group_name.setTextSize(30);
ll.addView(group_name);
// iterates through all questions in group
NodeList nList = eE.getElementsByTagName("question");
List Qs = new ArrayList();
System.out.println(nList.getLength());
for(int j=0; j<nList.getLength();j++){
Node nNode = nList.item(j);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
LinearLayout qu = Questionnaire.build_question(nNode, Questions, Qs, ll, this);
if(null == qu){
Element eElement = (Element) nNode;
// Obtains question type, hint, and text; adds * to question text if required
String text = eElement.getElementsByTagName("qtext").item(0).getTextContent();
String type = eElement.getElementsByTagName("qtype").item(0).getTextContent();
if (type.equals("M")){
// Map question
qu = Map(text, context);
map_question = qu;
Questions.add(qu);
Qs.add(qu);
ll.addView(qu);
} else if (type.equals("C")) {
// Camera question; still being worked out
qu = Camera(text, context);
camera_question = qu;
Questions.add(qu);
Qs.add(qu);
ll.addView(qu);
}
}
}
}
for(int qn = 0; qn < Questions.size(); qn++){
LinearLayout q = (LinearLayout) Questions.get(qn);
setupUI(q);
int x = q.getChildCount();
for(int qi = 0; qi < x; qi++){
setupUI(q.getChildAt(qi));
}
}
// Iterates through all repeatable chunks in the group
NodeList nList2 = eE.getElementsByTagName("rchunk");
String num = "";
try{
num = eE.getElementsByTagName("rsize").item(0).getTextContent();
}catch(Exception e){
num="";
}
for(int z=0; z<nList2.getLength();z++){
Node chunk = nList2.item(z);
Element chunkE = (Element) chunk;
if(num.equals("")) {
// question chunk button
Button rbt = new Button(this);
String rtext = chunkE.getElementsByTagName("rtext").item(0).getTextContent() + " +";
rbt.setText(rtext);
ll.addView(rbt);
setupUI(rbt);
// XML question chunk
NodeList chqs = chunkE.getElementsByTagName("rquestion");
// when button is clicked, following code takes as arguments linear layout, XML chunk of questions, context
rbt.setOnClickListener(new RepeatOnClickListener(ll, chqs, this) {
public void onClick(View v) {
// new linear layout of questions in chunk
LinearLayout qchunk = new LinearLayout(context);
qchunk.setOrientation(LinearLayout.VERTICAL);
// iterates through questions and adds them to the linear layout
for (int y = 0; y < nlist.getLength(); y++) {
Node question = nlist.item(y);
if (question.getNodeType() == Node.ELEMENT_NODE) {
String g_name = (String) ((TextView) view1.getChildAt(0)).getText();
LinearLayout qu = Questionnaire.build_question(question, Questions, Groups.get(g_name), qchunk, context);
}
}
view1.addView(qchunk, view1.getChildCount() - 1);
}
});
}else{
EditText num_times = new EditText(this);
num_times.setHint(num);
num_times.setInputType(2);
String limit = (chunkE.getElementsByTagName("rlimit").item(0).getTextContent());
int max = Integer.parseInt(limit);
NodeList chqs = chunkE.getElementsByTagName("rquestion");
LinearLayout questions_here = new LinearLayout(this);
questions_here.setOrientation(LinearLayout.VERTICAL);
num_times.addTextChangedListener(new NumWatcher(max, questions_here, chqs, this, Questions, Qs));
ll.addView(num_times);
ll.addView(questions_here);
}
}
// puts list of questions for current group in Groups dictionary with group name as key
Groups.put(g_name,Qs);
setupUI(ll);
}
// review page
ScrollView rv = new ScrollView(this);
LinearLayout rv1 = new LinearLayout(this);
rv1.setOrientation(LinearLayout.VERTICAL);
pg.addView(rv,pg.getCount());
TextView rev = new TextView(this);
rev.setTextSize(30);
String review = "Review";
rev.setText(review);
rv1.addView(rev);
rv.addView(rv1);
// review button
Button review_button = new Button(this);
review_button.setText(review);
review_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
update_answers();
}
});
// submit button
Button submit = new Button(this);
String sub = "Submit";
submit.setText(sub);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
submit();
}
});
// blank text view to be updated
ans = new TextView(this);
req_buttons = new LinearLayout(this);
req_buttons.setOrientation(LinearLayout.VERTICAL);
rv1.addView(review_button);
rv1.addView(ans);
rv1.addView(req_buttons);
rv1.addView(submit);
vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(vp.getCurrentItem() != vp.getChildCount()-1) {
req_buttons.removeAllViews();
req_buttons.setBackgroundColor(Color.TRANSPARENT);
ans.setText("");
}
}
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrollStateChanged(int state) {}
});
vp.setCurrentItem(1);
}catch (Exception e){
e.printStackTrace();
}
}
int PLACE_PICKER_REQUEST = 1;
static final int REQUEST_IMAGE_CAPTURE = 2;
// creates map question
public LinearLayout Map(String questiontext, Context context){
// set up question linear layout with text and button
LinearLayout qlayout = new LinearLayout(context);
qlayout.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(context);
tv.setTag("text");
tv.setText(questiontext);
Button bt = new Button(context);
bt.setText(questiontext);
bt.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
final Activity a = this;
// on click, attempts to start place picker activity
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hideSoftKeyboard(a,v);
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(a), PLACE_PICKER_REQUEST);
}catch(GooglePlayServicesNotAvailableException e){
System.out.println("didn't work");
}catch(GooglePlayServicesRepairableException e){
System.out.println(":(");
}
}
});
qlayout.addView(tv);
qlayout.addView(bt);
qlayout.setTag("M");
return qlayout;
}
public LinearLayout Camera(String questiontext, Context context){
LinearLayout qlayout = new LinearLayout(context);
qlayout.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(context);
tv.setTag("text");
tv.setText(questiontext);
Button bt = new Button(context);
bt.setText(questiontext);
bt.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
final AlertDialog.Builder bdr = new AlertDialog.Builder(this);
final Context context1 = this;
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText input_tag = new EditText(context1);
input_tag.setInputType(InputType.TYPE_CLASS_TEXT);
input_tag.setHint("Enter a description (max 30 characters)");
int maxLength = 30;
input_tag.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
bdr.setView(input_tag);
// Set up the buttons
bdr.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//tag = input_tag.getText().toString();
dispatchTakePictureIntent(input_tag.getText().toString());
}
});
bdr.setNegativeButton("No description", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent("");
dialog.cancel();
}
});
AlertDialog alert = bdr.create();
alert.show();
}
});
qlayout.addView(tv);
qlayout.addView(bt);
qlayout.setTag("C");
return qlayout;
}
String mCurrentPhotoPath = "";
private File createImageFile(String tag) throws IOException {
// Create an image file name
Image_Tags.add(tag);
System.out.println(Image_Tags);
tag = tag.replaceAll(" ", "_");
System.out.println(tag);
String imageFileName = timeStamp+"_t__"+tag+"__t_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpeg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
System.out.println(imageFileName);
System.out.println(mCurrentPhotoPath);
return image;
}
private void dispatchTakePictureIntent(String tag) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile(tag);
} catch (IOException ex) {
System.out.println("filename creation error");
}
// Continue only if the File was successfully created
System.out.println(getFilesDir());
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.qmain.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
// depending on request code (1 for place picker, 2 for image capture), performs action
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
// Displays map and prompts user to place picker on location
Place place = PlacePicker.getPlace(this, data);
// Displays location in toast message after map activity is closed
String toastMsg = String.format("Place: %s", place.getLatLng());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
System.out.println(toastMsg);
System.out.println(PlacePicker.getLatLngBounds(data));
// saves location
LOCATION = toastMsg.substring(7);
TextView update_loc = new TextView(this);
update_loc.setText(LOCATION);
if(map_question.getChildCount() > 2){
map_question.removeView(map_question.getChildAt(map_question.getChildCount()-1));
}
map_question.addView(update_loc);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
} else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
// opens camera, saves image as bitmap
//Bundle extras = data.getExtras();
//Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView = new ImageView(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
mImageView.setLayoutParams(lp);
File file = new File(mCurrentPhotoPath);
Uri uri = Uri.fromFile(file);
Bitmap imageBitmap;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
float w = imageBitmap.getWidth();
float h = imageBitmap.getHeight();
int width = 480;
float hw_ratio = width/w;
float new_h = hw_ratio*h;
int nh = (int) new_h;
Bitmap scaled = Bitmap.createScaledBitmap(imageBitmap, width, nh, true);
mImageView.setImageBitmap(scaled);
System.out.println("bitmap set");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("NO FILE");
} catch (IOException e) {
e.printStackTrace();
System.out.println("SOMETHING ELSE");
}
mImageView.setBackgroundColor(Color.CYAN);
TextView itag = new TextView(this);
itag.setText((String)Image_Tags.get(Image_Tags.size()-1));
camera_question.addView(itag);
camera_question.addView(mImageView);
}
}
// don't generate a picture when report has not been completed
// writes current answers and returns them as one string; optionally writes them to file
public String writeAnswers(HashMap qgs, boolean toFile, FileOutputStream f, boolean incomplete, FileOutputStream jf) {
String total = ""; // string with all answers
//String unanswered = "REQUIRED QUESTIONS MUST BE FILLED OUT \n"; // string with all blank required questions
String unanswered = "";
Boolean use_un = false;
HashMap json = new HashMap();
HashMap groups = new HashMap();
json.put("Groups", groups);
if (toFile) {
try {
// writes answers to file
json.put("Author", author);
String line = "Author: " + author + "~~";
total += line;
f.write(line.getBytes());
} catch (Exception e) {
System.out.println("problem writing line");
}
}
// set of group names
Set<String> keys = qgs.keySet();
// iterates through group names
for(String key:keys) {
String name = "Section: "+key + "\n";
total += name;
//unanswered += "\n"+name;
List qs = (List) qgs.get(key);
boolean in_list = false;
// iterates through list of questions
HashMap questions = new HashMap();
groups.put(key, questions);
for (int i = 0; i < qs.size(); i++) {
// gets question linear layout
LinearLayout q = (LinearLayout) qs.get(i);
// gets question text
TextView text = (TextView) q.findViewWithTag("text");
text.setTextColor(Color.GRAY);
String question = (String) text.getText();
String line = "";
String tag = "";
String qans = "";
try {
tag = (String) q.getTag();
} catch (Exception e) {
System.out.println("there's no tag?");
}
// based on question tag (type), completes question line with answer in appropriate fashion
// if for submission, returns "" if any required (*) questions don't have answers
// otherwise adds unanswered required questions to unanswered string
if (tag.equals("T") || tag.equals("N")) {
EditText editText = (EditText) q.findViewWithTag("answer");
if (editText.getText().toString().equals("") && question.endsWith("*") && !incomplete) {
System.out.println("oops");
return "";
} else {
if (editText.getText().toString().equals("") && question.endsWith("*")) {
//unanswered += "\n" + name+question + "\n";
if(! in_list){
unanswered += key + ",, ";
in_list = true;
}
use_un = true;
text.setTextColor(Color.RED);
}
line = question + ": " + editText.getText();
qans = line.substring(line.indexOf(": ") + 2);
}
} else if (tag.equals("S")){
TextView answer_total = (TextView) q.findViewWithTag("answer");
String at = answer_total.getText().toString();
if(question.endsWith("*") && !incomplete && at.equals("Total: ")){
System.out.println("oops");
return "";
}else if(question.endsWith("*")&& at.equals("Total: ")){
//unanswered += "\n" + name+question + "\n";
if(! in_list){
unanswered += key + ",, ";
in_list = true;
}
use_un = true;
text.setTextColor(Color.RED);
} else{
try {
if(at.equals("Total: ")){
at = " 0";
}
line = question + ": " + at.substring(at.indexOf(" ") + 1);
qans = at.substring(at.indexOf(" ") + 1);
}catch(Exception e){
line = question + ": ";
}
}
} else if (tag.equals("SC")) {
line = question + ": ";
RadioGroup rg = (RadioGroup) q.findViewWithTag("choices");
int id = rg.getCheckedRadioButtonId();
if (id == -1 && !incomplete && question.endsWith("*")) {
return "";
} else {
RadioButton rb = (RadioButton) rg.getChildAt(id);
try {
if (id == -1 && question.endsWith("*")) {
//unanswered += "\n" + name+question + "\n";
if(! in_list){
unanswered += key + ",, ";
in_list = true;
}
use_un = true;
text.setTextColor(Color.RED);
line = line.toUpperCase();
continue;
} else if(id == -1){
continue;
}
line += rb.getText();
qans = (String) rb.getText();
} catch (Exception e) {
System.out.println("something went wrong");
System.out.println(question);
}
}
} else if (tag.equals("MC")) {
line = question + ": ";
for (int j = 0; j < q.getChildCount(); j++) {
String ctag = (String) q.getChildAt(j).getTag();
if (ctag.equals("choice")) {
CheckBox cb = (CheckBox) q.getChildAt(j);
if (cb.isChecked()) {
line += cb.getText() + ", ";
}
}
}
if (line.length() > 20) {
line = line.substring(0, line.length() - 2);
}
qans = line.substring(line.indexOf(": ") + 2);
} else if (tag.equals("M")) {
line = question + ": " + LOCATION;
qans = LOCATION;
} else if (tag.equals("C")) {
String imtags = "";
for(int t = 0; t<Image_Tags.size()-1; t++){
imtags += Image_Tags.get(t) + ", ";
}
if(Image_Tags.size() > 0) {
imtags += Image_Tags.get(Image_Tags.size() - 1);
}
line = question + ": ";
line += imtags;
qans = imtags;
}
String jquestion = question;
if(question.endsWith("*")){
jquestion = question.substring(0,question.length()-1);
}
questions.put(jquestion,qans);
if (toFile) {
try {
// writes answers to file
line = line + "~~";
total += line;
f.write(line.getBytes());
} catch (Exception e) {
System.out.println("problem writing line");
}
} else {
// adds line to total string of answers
line = line + "\n";
total += line;
}
}
}
if(use_un){
// returns string of unanswered questions if any are present
return "!<!," + unanswered;
}
if(jf != null) {
JSONObject j = new JSONObject(json);
String jstring = j.toString();
try {
jf.write(jstring.getBytes());
}catch(Exception e){
System.out.println("problem writing json");
}
}
// returns total string of questions and answers
return total;
}
public String submit(){
// time stamp of submission -> filename for file in which data from form at time to be saved
//String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());
String filename = timeStamp+".txt";
String jsonfilename = timeStamp + ".json";
FileOutputStream fos = null;
FileOutputStream jfos = null;
// opens file
try{
fos = openFileOutput(filename, Context.MODE_PRIVATE);
jfos = openFileOutput(jsonfilename, Context.MODE_PRIVATE);
}catch(Exception e){
return "";
}
// calls writeAnswers first to check for unanswered required questions
String answers = writeAnswers(Groups, false, fos, false, null);
if (answers.equals("")) {
AlertDialog.Builder bdr = builder;
bdr.setMessage("Answer all required questions before submitting");
AlertDialog dialog = bdr.create();
dialog.show();
this.deleteFile(filename);
return "";
} else{
// if all required questions answered, writes questions and answers to file
System.out.println(writeAnswers(Groups, true, fos, false, jfos));
}
try {
fos.close();
jfos.close();
}catch(Exception e){}
// goes back to main page of app
Intent intent = new Intent(this, Home.class);
startActivity(intent);
// resets values for new questionnaire
Counter = new ArrayList();
LOCATION = "";
mImageView = null;
timeStamp = "";
return filename;
}
// updates ans TextView on submit page with current answers
public void update_answers(){
answers = writeAnswers(Groups, false, null, true, null);
//ans.setText(answers);
if(answers.substring(0,4).equals("!<!,")){
String req_msg = "The following sections have required questions that need to be answered:";
ans.setText(req_msg);
List rsects = new ArrayList();
String scts = answers.substring(4);
req_buttons.setBackgroundColor(Color.MAGENTA);
while(scts.length() > 3){
System.out.println(pages);
String sct = scts.substring(0, scts.indexOf(",, "));
scts = scts.substring(scts.indexOf(",, ") + 3);
Button br = new Button(this);
br.setText(sct);
br.setOnClickListener(new StringOnClickListener(sct) {
public void onClick(View v) {
vp.setCurrentItem(pages.indexOf(s));
System.out.println(s+" " + Integer.toString(pages.indexOf(s)));
}
});
req_buttons.addView(br);
}
System.out.println(scts);
}else{
ans.setText(answers);
}
}
// hides soft keyboard
public static void hideSoftKeyboard (Activity activity, View view)
{
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}
// calls hideSoftKeyboard on non-EditText views
public Activity a = this;
public void setupUI(View view) {
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
hideSoftKeyboard(a, v);
return false;
}
});
}
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit? Your answers will not be saved.")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteFile("JPEG_" + timeStamp + ".jpeg");
PVQ.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
// class used to create a PagerAdapter to work with ViewPager
class MainPagerAdapter extends PagerAdapter
{
// This holds all the currently displayable views, in order from left to right.
private ArrayList<View> views = new ArrayList<View>();
public void addView (View v, int position)
{
views.add (position, v);
super.notifyDataSetChanged();
}
public void removeView (int position)
{
views.remove (position);
super.notifyDataSetChanged();
}
public boolean isViewFromObject (View view, Object object)
{
return view == object;
}
public int getCount ()
{
return views.size();
}
public Object instantiateItem (ViewGroup container, int position)
{
View v = views.get (position);
v.setTag("myview" + position);
container.addView (v);
return v;
}
@Override
public void destroyItem (ViewGroup container, int position, Object object)
{
container.removeView (views.get (position));
}
}
// onClickListener customized for repeatable chunks
class RepeatOnClickListener implements View.OnClickListener
{
LinearLayout view1;
NodeList nlist;
Context context;
// can take a linear layout, nodelist, and context as parameters
public RepeatOnClickListener(LinearLayout view1, NodeList nlist, Context context) {
this.view1 = view1;
this.nlist = nlist;
this.context = context;
}
@Override
public void onClick(View v)
{
}
}
class StringOnClickListener implements View.OnClickListener
{
String s;
// can take a linear layout, nodelist, and context as parameters
public StringOnClickListener(String str) {
this.s = str;
}
@Override
public void onClick(View v)
{
}
}
class NumWatcher implements TextWatcher {
private LinearLayout view1;
private NodeList nodes;
private Context context;
private List list1;
private List list2;
private int max;
NumWatcher(int max, LinearLayout ll, NodeList nodes, Context context, List list1, List list2){
this.view1 = ll;
this.nodes = nodes;
this.context = context;
this.list1 = list1;
this.list2 = list2;
this.max = max;
}
public void afterTextChanged(Editable s) {
String value = s.toString();
for(int i = 0; i < view1.getChildCount(); i++){
for(int j = 0; j < ((LinearLayout)view1.getChildAt(i)).getChildCount(); j++){
System.out.println(list1.remove(((LinearLayout)view1.getChildAt(i)).getChildAt(j)));
System.out.println(list2.remove(((LinearLayout)view1.getChildAt(i)).getChildAt(j)));
}
}
view1.removeAllViews();
if(value.equals("")){
return;
}
int times = Integer.parseInt(value);
if(times > max){
System.out.println("in here");
return;
}
for(int i = 0;i<times;i++){
LinearLayout qchunk = new LinearLayout(context);
qchunk.setOrientation(LinearLayout.VERTICAL);
for (int y = 0; y < nodes.getLength(); y++) {
Node question = nodes.item(y);
if (question.getNodeType() == Node.ELEMENT_NODE) {
LinearLayout qu = Questionnaire.build_question(question, list1, list2, qchunk, context);
}
}
view1.addView(qchunk, view1.getChildCount() - 1);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
}
|
package controllers.samples;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jobs.JenaOwlReaderConfiguration;
import models.ClassCondition;
import models.ConditionDeserializer;
import models.ontologyModel.OntoClass;
import models.ontologyReading.OntologyReader;
import models.ontologyReading.jena.JenaOwlReader;
import models.ontologyReading.jena.JenaOwlReaderConfig;
import models.owlGeneration.OntologyGenerator;
import play.*;
import play.mvc.*;
import play.data.Form;
import play.Logger.*;
import views.html.samples.*;
import views.html.*;
//TODO: This should generate individual describing the configuration, instead of constraints
public class PizzaSample extends Controller {
private static OntologyReader ontologyReader;
private static OntologyGenerator owlApi;
private final static String PIZZA_NS = "http://www.co-ode.org/ontologies/pizza/pizza.owl
private final static String PIZZA_NEW_NS = "http://www.co-ode.org/ontologies/pizza/new/pizza.owl
// TODO: Eventually this should be kept in a database
private static Map<String, ClassCondition> conditions = new HashMap<String, ClassCondition>();
public static Result index() {
ontologyReader = createOwlReader();
OntoClass owlClass = ontologyReader.getOwlClass(PIZZA_NS + "Pizza");
return ok(pizzasample.render(owlClass));
}
private static OntologyGenerator createOwlGenerator() {
return OntologyGenerator.loadFromFile("file:samples/PizzaSample/pizza.owl", "./samples/PizzaSample");
}
private static OntologyReader createOwlReader() {
new JenaOwlReaderConfiguration().initialize("file:samples/PizzaSample/pizza.owl", new JenaOwlReaderConfig()
.useLocalMapping("http:
return OntologyReader.getGlobalInstance();
}
public static Result updateConditions() {
owlApi = createOwlGenerator();
String conditionJson = Form.form().bindFromRequest().get("conditionJson");
ClassCondition condition = ConditionDeserializer.deserializeCondition(ontologyReader, conditionJson);
ALogger log = play.Logger.of("application");
log.info("owlapi:"+ (owlApi == null ? "yup" : "nope"));
String conditionRdf = owlApi.convertToOwlIndividual(PIZZA_NEW_NS + "NewPizza", condition);
return ok(conditionRdf);//updateSuccessful(conditionRdf);
}
public static void updateSuccessful(String response) {
//TODO: render(response);
}
}
|
package org.azavea.otm.ui;
import org.azavea.otm.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;
public abstract class MapActivity extends android.support.v4.app.FragmentActivity {
@Override
protected void onResume() {
super.onResume();
int googlePlayStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapActivity.this);
if (googlePlayStatus != ConnectionResult.SUCCESS) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(googlePlayStatus, this, 1);
dialog.show();
}
}
protected void showPhotoDetail(String photoUrl) {
if (photoUrl == null) {
return;
}
String html = "<img width=100% src='" + photoUrl + "'></img>";
Log.d("PHOTO_HTML", html);
WebView webview = new WebView(this);
webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
Dialog d = new Dialog(this);
d.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
d.setContentView(webview);
d.show();
}
}
|
package com.maxtimv.hello;
/**
* @author Maxim Timofeev
*
*/
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
// eefre
}
|
import android.graphics.Paint;
import android.view.Gravity;
import android.widget.TextView;
public class TextJustifyUtils{
// Please use run(...) instead
public static void justify(TextView textView)
{
Paint paint = new Paint();
String [] blocks;
float spaceOffset = 0;
float textWrapWidth = 0;
int spacesToSpread;
float wrappedEdgeSpace;
String block;
String [] lineAsWords;
String wrappedLine;
String smb = "";
Object [] wrappedObj;
// Pull widget properties
paint.setColor(textView.getCurrentTextColor());
paint.setTypeface(textView.getTypeface());
paint.setTextSize(textView.getTextSize());
textWrapWidth = textView.getWidth();
spaceOffset = paint.measureText(" ");
blocks = textView.getText().toString().split("((?<=\n)|(?=\n))");
if(textWrapWidth < 20)
{
return;
}
for(int i = 0; i < blocks.length; i++)
{
block = blocks[i];
if(block.length() == 0)
{
continue;
}
else if(block.equals("\n"))
{
smb += block;
continue;
}
block = block.trim();
if(block.length() == 0) continue;
wrappedObj = TextJustifyUtils.createWrappedLine(block, paint, spaceOffset, textWrapWidth);
wrappedLine = ((String) wrappedObj[0]);
wrappedEdgeSpace = (Float) wrappedObj[1];
lineAsWords = wrappedLine.split(" ");
spacesToSpread = (int) (wrappedEdgeSpace != Float.MIN_VALUE ? wrappedEdgeSpace/spaceOffset : 0);
for(String word : lineAsWords)
{
smb += word + " ";
if(--spacesToSpread > 0)
{
smb += " ";
}
}
smb = smb.trim();
if(blocks[i].length() > 0)
{
blocks[i] = blocks[i].substring(wrappedLine.length());
if(blocks[i].length() > 0)
{
smb += "\n";
}
i
}
}
textView.setGravity(Gravity.LEFT);
textView.setText(smb);
}
public static Object [] createWrappedLine(String block, Paint paint, float spaceOffset, float maxWidth)
{
float cacheWidth = maxWidth;
float origMaxWidth = maxWidth;
String line = "";
for(String word : block.split("\\s"))
{
cacheWidth = paint.measureText(word);
maxWidth -= cacheWidth;
if(maxWidth <= 0)
{
return new Object[] { line, maxWidth + cacheWidth + spaceOffset };
}
line += word + " ";
maxWidth -= spaceOffset;
}
if(paint.measureText(block) <= origMaxWidth)
{
return new Object[] { block, Float.MIN_VALUE };
}
return new Object[] { line, maxWidth };
}
final static String SYSTEM_NEWLINE = "\n";
final static float COMPLEXITY = 5.12f; //Reducing this will increase efficiency but will decrease effectiveness
final static Paint p = new Paint();
/* @author Mathew Kurian */
public static void run(final TextView tv, float origWidth) {
String s = tv.getText().toString();
p.setTypeface(tv.getTypeface());
String [] splits = s.split(SYSTEM_NEWLINE);
float width = origWidth - 5;
for(int x = 0; x<splits.length;x++)
if(p.measureText(splits[x])>width){
splits[x] = wrap(splits[x], width, p);
String [] microSplits = splits[x].split(SYSTEM_NEWLINE);
for(int y = 0; y<microSplits.length-1;y++)
microSplits[y] = justify(removeLast(microSplits[y], " "), width, p);
StringBuilder smb_internal = new StringBuilder();
for(int z = 0; z<microSplits.length;z++)
smb_internal.append(microSplits[z]+((z+1<microSplits.length) ? SYSTEM_NEWLINE : ""));
splits[x] = smb_internal.toString();
}
final StringBuilder smb = new StringBuilder();
for(String cleaned : splits)
smb.append(cleaned+SYSTEM_NEWLINE);
tv.setGravity(Gravity.LEFT);
tv.setText(smb);
}
private static String wrap(String s, float width, Paint p){
String [] str = s.split("\\s"); //regex
StringBuilder smb = new StringBuilder(); //save memory
smb.append(SYSTEM_NEWLINE);
for(int x = 0; x<str.length; x++){
float length = p.measureText(str[x]);
String [] pieces = smb.toString().split(SYSTEM_NEWLINE);
try{
if(p.measureText(pieces[pieces.length-1])+length>width)
smb.append(SYSTEM_NEWLINE);
}catch(Exception e){}
smb.append(str[x] + " ");
}
return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}
private static String removeLast(String s, String g){
if(s.contains(g)){
int index = s.lastIndexOf(g);
int indexEnd = index + g.length();
if(index == 0) return s.substring(1);
else if(index == s.length()-1) return s.substring(0, index);
else
return s.substring(0, index) + s.substring(indexEnd);
}
return s;
}
private static String justifyOperation(String s, float width, Paint p){
float holder = (float) (COMPLEXITY*Math.random());
while(s.contains(Float.toString(holder)))
holder = (float) (COMPLEXITY*Math.random());
String holder_string = Float.toString(holder);
float lessThan = width;
int timeOut = 100;
int current = 0;
while(p.measureText(s)<lessThan&¤t<timeOut) {
s = s.replaceFirst(" ([^"+holder_string+"])", " "+holder_string+"$1");
lessThan = p.measureText(holder_string)+lessThan-p.measureText(" ");
current++;
}
String cleaned = s.replaceAll(holder_string, " ");
return cleaned;
}
private static String justify(String s, float width, Paint p){
while(p.measureText(s)<width){
s = justifyOperation(s,width, p);
}
return s;
}
}
|
public class Solution {
public boolean canWinNim(int n) {
return (n % 4 != 0)
}
}
|
package com.tivogi.widget.calendar;
import hirondelle.date4j.DateTime;
import java.util.Locale;
import java.util.TimeZone;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
public class DaysGridView extends View {
public class DayCell {
private DateTime mDateTime;
protected RectF mBound;
private String mDayOfMonth;
protected Paint mTextPaint;
private PointF mTextOrigin;
protected Paint mPaint;
private boolean mPressed;
private boolean mFocussed;
private boolean mSelected;
private boolean mHasDownEvent;
private RectF mTodayRect;
public DayCell() {
mTextOrigin = new PointF();
mBound = new RectF();
mTodayRect = new RectF();
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);
mTextPaint.setTextSize(convertSpToPx(16));
mPaint = new Paint();
mPaint.setStyle(Style.FILL);
}
private void calculateTextOrigin() {
mTextOrigin.x = mBound.centerX() - mTextPaint.measureText(mDayOfMonth) / 2;
mTextOrigin.y = mBound.centerY() + mTextPaint.getTextSize() / 2;
}
protected void draw(Canvas canvas) {
drawBackground(canvas);
if (isToday()) {
canvas.drawRect(mTodayRect, sTodayPaint);
}
drawDateText(canvas);
if (isSelected()) drawSelected(canvas);
}
protected void drawBackground(Canvas canvas) {
mPaint.setColor(isFromActiveMonth() ? DEFAULT_BACKGROUND_ACTIVE_COLOR : DEFAULT_BACKGROUND_INACTIVE_COLOR);
canvas.drawRect(mBound, mPaint);
}
protected void drawDateText(Canvas canvas) {
canvas.drawText(mDayOfMonth, mTextOrigin.x, mTextOrigin.y, mTextPaint);
}
protected void drawSelected(Canvas canvas) {
mPaint.setColor(DEFAULT_SELECTED_COLOR);
canvas.drawRect(mBound, mPaint);
}
public DateTime getDateTime() {
return mDateTime;
}
public boolean isFocussed() {
return mFocussed;
}
public boolean isFromActiveMonth() {
return mDateTime.getMonth() == mActiveMonth;
}
public boolean isPressed() {
return mPressed;
}
public boolean isSelected() {
return mSelected;
}
public boolean isToday() {
return mDateTime.isSameDayAs(DateTime.today(TimeZone.getDefault()));
}
public boolean isWeekend() {
final int weekDay = mDateTime.getWeekDay();
return weekDay == 1 || weekDay == 7;
}
protected void onClick() {
onDayCellClick(this);
}
public boolean onTouchEvent(MotionEvent event) {
if (!mBound.contains(event.getX(), event.getY())) return false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mHasDownEvent = true;
break;
case MotionEvent.ACTION_CANCEL:
mHasDownEvent = false;
break;
case MotionEvent.ACTION_UP:
if (mHasDownEvent) onClick();
mHasDownEvent = false;
break;
default:
break;
}
return true;
}
public void setBound(RectF bound) {
mBound.set(bound);
mTodayRect.set(mBound);
float delta = sTodayPaint.getStrokeWidth() / 2;
mTodayRect.inset(delta, delta);
calculateTextOrigin();
}
public void setDate(DateTime dateTime) {
mDateTime = dateTime;
mDayOfMonth = String.valueOf(mDateTime.getDay());
int textColor = Color.GRAY;
if (isFromActiveMonth()) {
// TODO move to attributes of CalendarView
textColor = isWeekend() ? Color.RED : Color.BLACK;
}
mTextPaint.setColor(textColor);
calculateTextOrigin();
}
public void setFocussed(boolean focussed) {
mFocussed = focussed;
}
public void setPressed(boolean pressed) {
mPressed = pressed;
}
public void setSelected(boolean selected) {
if (getCalendarView().isSelectable()) mSelected = selected;
}
}
protected static class WeekRow {
protected static final int DAYS_COUNT = 7;
protected DayCell[] mDays = new DayCell[DAYS_COUNT];
protected void draw(Canvas canvas) {
for (DayCell day : mDays) {
day.draw(canvas);
}
}
public DayCell[] getDays() {
return mDays;
}
}
protected static final int DEFAULT_TODAY_COLOR = Color.parseColor("#90F00000");
protected static final int DEFAULT_SELECTED_COLOR = Color.parseColor("#33000000");
private static final int WEEKS_COUNT = 6;
public static float convertDpToPx(float dpValue) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, Resources.getSystem().getDisplayMetrics());
}
public static float convertSpToPx(float spValue) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spValue, Resources.getSystem().getDisplayMetrics());
}
private int mActiveMonth;
protected static final int DEFAULT_BACKGROUND_ACTIVE_COLOR = Color.WHITE;
protected static final int DEFAULT_BACKGROUND_INACTIVE_COLOR = Color.parseColor("#ffeeeeee");
private static Paint sTodayPaint;
private static final int DEFAULT_GRID_LINE_WIDTH = 1; // size in pixels
static {
sTodayPaint = new Paint();
sTodayPaint.setStyle(Paint.Style.STROKE);
sTodayPaint.setColor(DEFAULT_TODAY_COLOR);
sTodayPaint.setStrokeWidth(convertDpToPx(3));
}
public static int getWeekHeaderColumnCount() {
return WeekRow.DAYS_COUNT;
}
private DayCell mSeletectedDay;
private WeekRow[] mWeeks = new WeekRow[WEEKS_COUNT];
private int mGridLineWidth;
private CalendarView<?> mCalendarView;
public DaysGridView(Context context) {
super(context);
initialize();
}
protected DayCell createEmptyDayCell() {
return new DayCell();
}
protected CalendarView<?> getCalendarView() {
return mCalendarView;
}
private int getIndexForDayOfWeek(DateTime dateTime) {
switch (dateTime.getWeekDay()) {
case 2: // MONDAY
return 0;
case 3: // TURSDAY
return 1;
case 4: // WEDNESDAY
return 2;
case 5: // THIRDAY
return 3;
case 6: // FRIDAY
return 4;
case 7: // SATURDAY
return 5;
default:// SUNDAY
return 6;
}
}
/**
* Return string with localized short name for day of the week. Call this method only after date was set.
*
* @param index
* column of grid. Must be range between 0 and {@link DaysGridView#getWeekHeaderColumnCount()}
* @return localized value
*
*/
public String getWeekHeaderColumnTitle(int index) {
return mWeeks[0].mDays[index].getDateTime().format("WWW", Locale.getDefault());
}
public WeekRow[] getWeeks() {
return mWeeks;
}
private void initialize() {
mGridLineWidth = DEFAULT_GRID_LINE_WIDTH;
for (int i = 0; i < WEEKS_COUNT; i++) {
mWeeks[i] = new WeekRow();
for (int j = 0; j < WeekRow.DAYS_COUNT; j++) {
mWeeks[i].mDays[j] = createEmptyDayCell();
}
}
}
protected void onDayCellClick(DayCell dayCell) {
if (!getCalendarView().isSelectable()) return;
if (!dayCell.isFromActiveMonth()) {
mCalendarView.setDate(dayCell.getDateTime());
return;
}
selectDayCell(dayCell);
mCalendarView.onDateClick(dayCell.getDateTime());
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (WeekRow week : mWeeks) {
week.draw(canvas);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int cellWidth = (int) (w - mGridLineWidth * (WeekRow.DAYS_COUNT - 1)) / WeekRow.DAYS_COUNT;
int cellHeight = (int) (h - mGridLineWidth * (WEEKS_COUNT - 1)) / WEEKS_COUNT;
RectF cellBound = new RectF(0, 0, 0, 0);
float currentLeft = 0, currentTop = 0;
for (int y = 0; y < WEEKS_COUNT; y++) {
currentLeft = 0;
for (int x = 0; x < WeekRow.DAYS_COUNT; x++) {
cellBound.left = currentLeft;
cellBound.right = currentLeft + cellWidth;
cellBound.top = currentTop;
cellBound.bottom = currentTop + cellHeight;
mWeeks[y].mDays[x].setBound(cellBound);
currentLeft += cellWidth + mGridLineWidth;
}
currentTop += cellHeight + mGridLineWidth;
}
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
for (WeekRow week : mWeeks) {
for (DayCell day : week.mDays) {
if (day.onTouchEvent(event)) {
invalidate();
return true;
}
}
}
return super.onTouchEvent(event);
}
public void selectDayCell(DayCell dayCell) {
if (mSeletectedDay == dayCell) return;
if (mSeletectedDay != null) mSeletectedDay.setSelected(false);
mSeletectedDay = dayCell;
mSeletectedDay.setSelected(true);
mCalendarView.setDate(dayCell.getDateTime());
}
public void setCalendarView(CalendarView<?> calendarView) {
mCalendarView = calendarView;
}
public void setDate(DateTime dateTime) {
mActiveMonth = dateTime.getMonth();
dateTime = DateTime.forDateOnly(dateTime.getYear(), dateTime.getMonth(), 1);
int dayOfWeekForMonthBegin = getIndexForDayOfWeek(dateTime);
dateTime = dateTime.minusDays(dayOfWeekForMonthBegin);
DateTime selectedDate = mCalendarView.getSelectedDate();
for (WeekRow week : mWeeks) {
for (DayCell day : week.mDays) {
day.setDate(dateTime);
day.setSelected(selectedDate != null && selectedDate.isSameDayAs(dateTime));
dateTime = dateTime.plusDays(1);
}
}
updateDaysCells();
}
public void updateDaysCells() {
invalidate();
}
}
|
package com.dqc.qlibrary.utils;
import com.dqc.qlibrary.library.codec.StringUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Java
*/
public class QUtils {
public static class FileUtil {
/**
*
*
* @param file File
* @return long
*/
public static long getFileSize(File file) {
long size = 0;
try {
File[] fileList = file.listFiles();
for (File aFileList : fileList) {
if (aFileList.isDirectory()) {
size = size + getFileSize(aFileList);
} else {
size = size + aFileList.length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
/**
* /
*
* @param filePath
* @param isDeleteFolder
*/
public static void deleteFile(String filePath, boolean isDeleteFolder) {
if (!StringUtil.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles(); // files[];
for (File file1 : files) {
file1.delete();
}
}
if (isDeleteFolder) {
file.delete();
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
*
* @param folderPath
* @return
*/
public static boolean newCreateFolder(String folderPath) {
File file = new File(folderPath);
return !file.exists() && file.mkdirs();
}
/**
*
*
* @param sourcePath
* @param targetPath
*/
public static void copyFile(String sourcePath, String targetPath) {
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
try {
if (sourceFile.exists()) {
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
outBuff.flush();
inBuff.close();
outBuff.close();
output.close();
input.close();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*
* @param size length
* @return
*/
public static String formatFileSize(double size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
}
public static class MathUtil {
/**
* mix~max
*
* @param min
* @param max
* @return
*/
public static int random(int min, int max) {
return new Random().nextInt(max - min + 1) + min;
}
/**
* m mkm
*
* @return
*/
public static String formatDistance(double m) {
DecimalFormat df;
String formatStr;
if (m < 1000) {
df = new DecimalFormat("
formatStr = df.format(m) + "m";
} else {
df = new DecimalFormat("
formatStr = df.format(m / 1000) + "km";
}
return formatStr;
}
}
public static class DoubleUtil implements Serializable {
private static final long serialVersionUID = -3345205828566485102L;
private static final Integer DEF_DIV_SCALE = 2;
/**
*
*
* @param value1
* @param value2
* @return
*/
public static Double add(Number value1, Number value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
return b1.add(b2).doubleValue();
}
/**
*
*
* @param value1
* @param value2
* @return
*/
public static double sub(Number value1, Number value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
return b1.subtract(b2).doubleValue();
}
/**
*
*
* @param value1
* @param value2
* @return
*/
public static Double mul(Number value1, Number value2) {
BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
return b1.multiply(b2).doubleValue();
}
/**
* 10
*
* @param dividend
* @param divisor
* @return
*/
public static Double div(Double dividend, Double divisor) {
return div(dividend, divisor, DEF_DIV_SCALE);
}
/**
* scale
*
* @param dividend
* @param divisor
* @param scale
* @return
*/
public static Double div(Double dividend, Double divisor, Integer scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(dividend));
BigDecimal b2 = new BigDecimal(Double.toString(divisor));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
*
*
* @param value
* @param scale
* @return
*/
public static Double round(Double value, Integer scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(value));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
public static class StringUtil {
/**
* Email
*
* @param email
* @return boolean
*/
public static boolean isEmail(String email) {
Pattern emailPattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
Matcher matcher = emailPattern.matcher(email);
return matcher.find();
}
|
package hotchemi.android.rate;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import java.util.Date;
/**
* Help you promote your app by prompting users to rate the app after using it for a few days.
*
* @author Shintaro Katafuchi
*/
public class AppRate {
private static final String TAG = AppRate.class.getName();
private static final AppRate INSTANCE = new AppRate();
private static int sLaunchTimesThreshold = 10;
private static int sInstallDaysThreshold = 10;
private static long sInstallDateTime = new Date().getTime();
private static int sLaunchTimes = 0;
private static boolean sIsAgreeShoWDialog = true;
private static boolean sIsShoWNeutralButton = true;
private AppRate() {
}
public static AppRate setLaunchTimes(final int launchTimesThreshold) {
sLaunchTimesThreshold = launchTimesThreshold;
return INSTANCE;
}
public static AppRate setInstallDays(final int installDaysThreshold) {
sInstallDaysThreshold = installDaysThreshold;
return INSTANCE;
}
public static AppRate setShowNeutralButton(final boolean isShowNeutralButton) {
sIsShoWNeutralButton = isShowNeutralButton;
return INSTANCE;
}
public static AppRate clearAgreeShowDialog(final Context context) {
PreferenceUtils.setAgreeShowDialog(context, true);
return INSTANCE;
}
/**
* Monitor launch times and interval from installation.<br/>
* Call this method when the launcher activity's onCreate() is launched.
*/
public static void monitor(final Context context) {
final SharedPreferences pref = PreferenceUtils.getPreferences(context);
final Editor editor = pref.edit();
if (isFirstLaunch(pref)) {
editor.putLong(Constants.PREF_KEY_INSTALL_DATE, sInstallDateTime);
}
int launchTimes = pref.getInt(Constants.PREF_KEY_LAUNCH_TIMES, 0);
editor.putInt(Constants.PREF_KEY_LAUNCH_TIMES, launchTimes + 1);
editor.commit();
sInstallDateTime = new Date(pref.getLong(Constants.PREF_KEY_INSTALL_DATE, 0)).getTime();
sLaunchTimes = pref.getInt(Constants.PREF_KEY_LAUNCH_TIMES, 0);
sIsAgreeShoWDialog = pref.getBoolean(Constants.PREF_KEY_IS_AGREE_SHOW_DIALOG, true);
}
/**
* Show rate dialog when meets conditions.
*
* @param activity fragment activity
*/
public static void showRateDialogIfMeetsConditions(final FragmentActivity activity) {
if (shouldShowRateDialog()) {
final RateDialogSupportFragment fragment = new RateDialogSupportFragment();
final Bundle bundle = new Bundle();
bundle.putBoolean(Constants.BUNDLE_KEY_IS_SHOW_NEUTRAL_BUTTON, sIsShoWNeutralButton);
fragment.setArguments(bundle);
fragment.show(activity.getSupportFragmentManager(), TAG);
}
}
/**
* Show rate dialog when meets conditions.
*
* @param activity fragment activity
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void showRateDialogIfMeetsConditions(final Activity activity) {
if (shouldShowRateDialog()) {
final RateDialogFragment fragment = new RateDialogFragment();
final Bundle bundle = new Bundle();
bundle.putBoolean(Constants.BUNDLE_KEY_IS_SHOW_NEUTRAL_BUTTON, sIsShoWNeutralButton);
fragment.setArguments(bundle);
fragment.show(activity.getFragmentManager(), TAG);
}
}
private static boolean isFirstLaunch(final SharedPreferences pref) {
return pref.getLong(Constants.PREF_KEY_INSTALL_DATE, 0) == 0L;
}
private static boolean isOverLaunchTimes() {
return sLaunchTimes >= sLaunchTimesThreshold;
}
private static boolean isOverInstallDate() {
return new Date().getTime() - sInstallDateTime >= sInstallDaysThreshold * 24 * 60 * 60 * 1000; //msec
}
private static boolean shouldShowRateDialog() {
return sIsAgreeShoWDialog && isOverLaunchTimes() && isOverInstallDate();
}
}
|
package com.lightcrafts.ui.crop;
import static com.lightcrafts.ui.crop.Locale.LOCALE;
import com.lightcrafts.ui.toolkit.CoolButton;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
final class ResetButton extends CoolButton {
ResetButton( ResetAction action, boolean isRotateOnly ) {
setText(LOCALE.get("ResetButton"));
addActionListener(action);
setToolTipText(
LOCALE.get(
isRotateOnly ? "ResetRotateToolTip" : "ResetCropToolTip"
)
);
// Shave off some of the width padded around the button text by the L&F.
Dimension size = getPreferredSize();
size.width -= 16;
setMinimumSize(size);
setPreferredSize(size);
setMaximumSize(size);
setEnabled(action.isEnabled());
action.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("enabled")) {
setEnabled(evt.getNewValue().equals(Boolean.TRUE));
}
}
}
);
}
}
|
package com.google.sprint1;
import java.io.IOException;
import java.util.ArrayList;
import com.google.sprint1.NetworkService.LocalBinder;
import com.metaio.sdk.MetaioDebug;
import com.metaio.tools.io.AssetsManager;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.ServiceConnection;
import android.net.nsd.NsdServiceInfo;
import android.os.Handler;
import android.os.Message;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Activity to handle the screen between mainmenu and the gamescreen
*
* where players should connect to each other before entering gamemode.
*
*
*/
public class NetworkActivity extends Activity {
private AssetsExtracter startGame; // a variable used to start the
// AssetExtraxter class
Handler mNSDHandler;
// Variables for Network Service handling
public NetworkService mService;
public NsdHelper mNsdHelper;
private boolean mBound = false;
public static final String TAG = "NetworkActivity";
ArrayAdapter<NsdServiceInfo> listAdapter;
ArrayAdapter<Player> playerListAdapter;
ArrayList<NsdServiceInfo> arraylist;
ListView serviceListView;
// Function to set up layout of activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_network);
// Bind to NetworkService. The service will not destroy
// until there is no activity bound to it
Intent intent = new Intent(this, NetworkService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
serviceListView = (ListView) findViewById(R.id.serviceListView);
/* Start game */
startGame = new AssetsExtracter();
//ArrayList to store all services
arraylist = new ArrayList<NsdServiceInfo>();
listAdapter = new ArrayAdapter<NsdServiceInfo>(this,
android.R.layout.simple_list_item_1,
arraylist);
mNSDHandler = new Handler() {
@Override
// Called whenever a message is sent to the handler.
// Currently assumes that the message contains a NsdServiceInfo
// object.
public void handleMessage(Message msg) {
NsdServiceInfo service;
// If message is of type 1, meaning "delete list".
// TODO: Should probably be an enum
if (msg.what == 1) {
listAdapter.clear();
}
// If key is "found", add to the adapter
else if ((service = (NsdServiceInfo) msg.getData().get("found")) != null) {
//listAdapter.add(service);
arraylist.add(service);
}
// If key is "lost", remove from adapter
else if ((service = (NsdServiceInfo) msg.getData().get("lost")) != null) {
for(int i = 0; i < arraylist.size(); i++){
if(arraylist.get(i).getServiceName().equals(service.getServiceName()))
arraylist.remove(i);
}
}
// Notify adapter that the list is updated.
listAdapter.notifyDataSetChanged();
}
};
serviceListView.setAdapter(listAdapter);
serviceListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// When clicking on a service, an AlertDialog window pops up
// to allow you to connect to said service.
public void onItemClick(AdapterView parent, View view,
final int pos, long id) {
// Instantiate an AlertDialog.Builder with its
// constructor
AlertDialog.Builder builder = new AlertDialog.Builder(
NetworkActivity.this);
builder.setMessage(
"Connect to "
+ listAdapter.getItem(pos)
.getServiceName() + "?")
.setTitle("Connect")
.setPositiveButton(R.string.BTN_OK,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
NsdServiceInfo service = listAdapter
.getItem(pos);
service = mNsdHelper
.resolveService(service);
if (service != null) {
Log.d(TAG,
"Connecting to: "
+ service
.getServiceName());
mService.mConnection.connectToPeer(
service.getHost(),
service.getPort());
} else {
Log.d(TAG,
"No service to connect to!");
}
}
})
.setNegativeButton(R.string.BTN_CANCEL,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// TODO Auto-generated method
// stub
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
// Show the AlertDialog
dialog.show();
}
});
mNsdHelper = new NsdHelper(this, mNSDHandler);
mNsdHelper.initializeNsd();
}
/** Called when the user clicks the start Game button (starta spel) */
public void startGame(View view) {
// In order to start the game we need to extract our assets to the
// metaio SDK
startGame.execute(0); // Starts the assetsExtracter class
}
/** Called when the user clicks the mainMenu button (huvudmeny) */
public void mainMenu(View view) {
Intent intentmenu = new Intent(this, MainActivity.class);
startActivity(intentmenu);
}
/** Called when the user clicks the Send Data button */
public void sendData(View view) {
TestClass test = new TestClass(5, "hej");
//mService.mConnection.sendData(test);
}
/** Called when user minimize the window or clicks home button */
@Override
protected void onPause() {
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
// If mNsdHelper is other than null it will be teared down.
// This is done to unregister from the network and stop the
// service discovery.
if (mNsdHelper != null) {
mNsdHelper.stopDiscovery();
mNsdHelper.unregisterService();
mNsdHelper = null;
}
super.onPause();
}
/**
* Called when after onStart() when a new instance of NetworkActivity is
* started and when ever the user enters the activity from a paused state
*/
@Override
protected void onResume() {
super.onResume();
if(mNsdHelper == null){
mNsdHelper = new NsdHelper(this, mNSDHandler);
mNsdHelper.initializeNsd();
}
if (mNsdHelper != null) {
mNsdHelper.discoverServices();
mNsdHelper.registerService(MobileConnection.SERVER_PORT);
}
}
/**
* Called when user exits the Activity or pausing and then destroy the app
* by brute force
*/
protected void onDestroy() {
// Check if mNsdHelper is not null(will throw NullPointerException
// otherwise). Unregister from network and stops the discovery.
if (mNsdHelper != null) {
mNsdHelper.stopDiscovery();
mNsdHelper.unregisterService();
}
if(mService != null)
unbindService(mServiceConnection);
super.onDestroy();
}
/**
* This task extracts all the assets to an external or internal location to
* make them accessible to Metaio SDK.
*/
private class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean> {
/** Extract all assets to make them accessible to Metaio SDK */
@Override
protected Boolean doInBackground(Integer... params) {
try {
// Extract all assets except Menu. Overwrite existing files for
// debug build only.
final String[] ignoreList = { "Menu", "webkit", "sounds",
"images", "webkitsec" };
AssetsManager.extractAllAssets(getApplicationContext(), "",
ignoreList, BuildConfig.DEBUG);
// AssetsManager.extractAllAssets(getApplicationContext(),
// BuildConfig.DEBUG);
} catch (IOException e) {
MetaioDebug.printStackTrace(Log.ERROR, e);
return false;
}
return true;
}
/** when extraction is done, we load the game activity */
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Intent intent = new Intent(getApplicationContext(),
GameActivity.class);
startActivity(intent);
}
finish();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get
// LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
|
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class SendReceiveSocket {
private static final String usageDoc = "RECEIPT_PORT DESTINATION_HOST DEST_PORT";
private static final int outSourcePort = 63000;
public static void main(String[] args) {
final int expectedArgs = 3;
if (args.length != expectedArgs) {
System.err.printf(
"Error: got %d argument(s), but expected %d...\nusage: %s\n",
args.length, expectedArgs, usageDoc);
System.exit(1);
}
final int receiptPort = BrittleNetwork.mustParsePort(args[0], "RECEIPT_PORT");
final String destHostName = args[1].trim();
final int destPort = BrittleNetwork.mustParsePort(args[2], "DEST_PORT");
InetAddress destIP = null;
try {
destIP = InetAddress.getByName(destHostName);
} catch (UnknownHostException e) {
System.out.printf("[setup] failed resolving destination host '%s': %s\n", destHostName, e);
System.exit(1);
}
System.out.printf("[setup] successfully resolved DESTINATION_HOST: %s\n", destIP);
InetAddress receiptHost = null;
try {
receiptHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
System.out.printf("[setup] failed finding current host address: %s\n", e);
System.exit(1);
}
final DatagramSocket outSock = BrittleNetwork.mustOpenSocket(
receiptHost, outSourcePort,
"[setup] failed to open a sending socket [via %s] on port %d: %s\n");
final DatagramSocket inSocket = BrittleNetwork.mustOpenSocket(
receiptHost, receiptPort,
"[setup] failed opening receiving socket on %s:%d: %s\n");
System.out.printf("[setup] successfully resolved current host as: %s\n", receiptHost);
System.out.printf("[setup] listener & sender setups complete.\n\n");
new RecvClient(inSocket).listenInThread();
new SendClient(destIP, destPort, outSock).sendMessagePerLine(new Scanner(System.in));
}
}
class SendClient {
private static final String LOG_TAG = "recv'r";
private static final String senderUXInstruction =
"\tType messages & [enter] to send\n\t[enter] twice to exit.\n";
private InetAddress destIP;
private int destPort;
private DatagramSocket socket = null;
public SendClient(final InetAddress destIP, final int destPort, DatagramSocket outSock) {
this.destIP = destIP;
this.destPort = destPort;
this.socket = outSock;
}
public void sendMessagePerLine(Scanner ui) {
System.out.printf("[%s] usage instructions:\n%s", LOG_TAG, senderUXInstruction);
boolean isPrevEmpty = false;
String message;
byte[] buffer = new byte[100];
int msgIndex = 0;
while (true) {
message = ui.nextLine().trim();
if (message.length() == 0) {
if (isPrevEmpty) {
System.out.printf("[%s] caught two empty messages, exiting....\n", LOG_TAG);
break;
}
isPrevEmpty = true;
System.out.printf("[%s] press enter again to exit normally.\n", LOG_TAG);
}
msgIndex++;
buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(
buffer, message.length(),
destIP, destPort);
System.out.printf("[%s] sending message #%03d: '%s'\n", LOG_TAG, msgIndex, message);
try {
this.socket.send(packet);
} catch (Exception e) {
System.err.printf("[%s] failed sending '%s':\n%s\n", LOG_TAG, message, e);
System.exit(1);
}
}
}
}
class RecvClient implements Runnable {
private static final String LOG_TAG = "recv'r";
DatagramSocket inSock = null;
public RecvClient(DatagramSocket inSocket) {
this.inSock = inSocket;
}
public void listenInThread() {
Thread recvrThred = new Thread(this);
recvrThred.setName("Receive Thread");
recvrThred.start();
}
/** blocking receiver that accepts packets on inSocket. */
public void run() {
byte[] inBuffer = new byte[100];
DatagramPacket inPacket = new DatagramPacket(inBuffer, inBuffer.length);
int receiptIndex = 0;
while (true) {
for ( int i = 0 ; i < inBuffer.length ; i++ ) {
inBuffer[i] = ' '; // TODO(zacsh) find out why fakhouri does this
}
System.out.printf("[%s] waiting for input...\n", LOG_TAG);
try {
this.inSock.receive(inPacket);
} catch (Exception e) {
System.err.printf("[%s] failed receiving packet %03d: %s\n", LOG_TAG, receiptIndex+1, e);
System.exit(1);
}
receiptIndex++;
System.out.printf(
"[%s] received #%03d: %s\n%s\n%s\n",
LOG_TAG, receiptIndex, "\"\"\"", "\"\"\"",
new String(inPacket.getData()));
}
}
}
/** Fast-failing, program-exiting, loud, tiny utils. */
class BrittleNetwork {
/**
* failMessage should accept a host(%s), port (%d), and error (%s).
*/ // TODO(zacsh) see about java8's lambdas instead of failMessage's current API
public static final DatagramSocket mustOpenSocket(
final InetAddress host,
final int port,
final String failMessage) {
DatagramSocket sock = null;
try {
sock = new DatagramSocket(port, host);
} catch (SocketException e) {
System.err.printf(failMessage, port, host, e);
System.exit(1);
}
return sock;
}
public static final int mustParsePort(String portRaw, String label) {
final String errContext = String.format("%s must be an unsigned 2-byte integer", label);
int port = -1;
try {
port = Integer.parseInt(portRaw.trim());
} catch (NumberFormatException e) {
System.err.printf(errContext + ", but got: %s\n", e);
System.exit(1);
}
if (port < 0 || port > 0xFFFF) {
System.err.printf(errContext + ", but got %d\n", port);
System.exit(1);
}
return port;
}
}
|
package org.broadinstitute.sting.utils;
import net.sf.functionalj.reflect.StdReflect;
import net.sf.functionalj.reflect.JdkStdReflect;
import net.sf.functionalj.FunctionN;
import net.sf.functionalj.Function1;
import net.sf.functionalj.Functions;
import net.sf.functionalj.util.Operators;
import net.sf.samtools.SAMSequenceDictionary;
import net.sf.samtools.SAMSequenceRecord;
import net.sf.samtools.SAMRecord;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import edu.mit.broad.picard.reference.ReferenceSequenceFile;
import org.apache.log4j.Logger;
public class GenomeLoc implements Comparable<GenomeLoc> {
private static Logger logger = Logger.getLogger(GenomeLoc.class);
private String contig;
private long start;
private long stop;
// Ugly global variable defining the optional ordering of contig elements
//public static Map<String, Integer> refContigOrdering = null;
private static SAMSequenceDictionary contigInfo = null;
private static HashMap<String, String> interns = null;
public static boolean hasKnownContigOrdering() {
return contigInfo != null;
}
public static SAMSequenceRecord getContigInfo( final String contig ) {
return contigInfo.getSequence(contig);
}
public static int getContigIndex( final String contig ) {
return contigInfo.getSequenceIndex(contig);
}
/*
public static void setContigOrdering(Map<String, Integer> rco) {
refContigOrdering = rco;
interns = new HashMap<String, String>();
for ( String contig : rco.keySet() )
interns.put( contig, contig );
}
*/
/*
public static boolean setupRefContigOrdering(final ReferenceSequenceFile refFile) {
final SAMSequenceDictionary seqDict = refFile.getSequenceDictionary();
if (seqDict == null) // we couldn't load the reference dictionary
return false;
List<SAMSequenceRecord> refContigs = seqDict.getSequences();
HashMap<String, Integer> refContigOrdering = new HashMap<String, Integer>();
if (refContigs != null) {
int i = 0;
logger.info(String.format("Prepared reference sequence contig dictionary%n order ->"));
for (SAMSequenceRecord contig : refContigs) {
logger.info(String.format(" %s (%d bp)", contig.getSequenceName(), contig.getSequenceLength()));
refContigOrdering.put(contig.getSequenceName(), i);
i++;
}
}
setContigOrdering(refContigOrdering);
return refContigs != null;
}
*/
public static boolean setupRefContigOrdering(final ReferenceSequenceFile refFile) {
return setupRefContigOrdering(refFile.getSequenceDictionary());
}
public static boolean setupRefContigOrdering(final SAMSequenceDictionary seqDict) {
if (seqDict == null) // we couldn't load the reference dictionary
return false;
else {
contigInfo = seqDict;
logger.info(String.format("Prepared reference sequence contig dictionary%n order ->"));
for (SAMSequenceRecord contig : seqDict.getSequences() ) {
logger.info(String.format(" %s (%d bp)", contig.getSequenceName(), contig.getSequenceLength()));
}
}
return true;
}
// constructors
public GenomeLoc( String contig, final long start, final long stop ) {
if ( interns != null )
contig = interns.get(contig);
this.contig = contig;
this.start = start;
this.stop = stop;
}
public GenomeLoc( final String contig, final long pos ) {
this( contig, pos, pos );
}
public GenomeLoc( final GenomeLoc toCopy ) {
this( new String(toCopy.getContig()), toCopy.getStart(), toCopy.getStop() );
}
public static GenomeLoc genomicLocationOf(final SAMRecord read) {
String contig = read.getReferenceName();
if (read.getReadUnmappedFlag())
contig = null;
return new GenomeLoc(contig, read.getAlignmentStart(), read.getAlignmentEnd());
}
// Parsing string representations
private static long parsePosition( final String pos ) {
String x = pos.replaceAll(",", "");
return Long.parseLong(x);
}
public static GenomeLoc parseGenomeLoc( final String str ) {
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
//System.out.printf("Parsing location '%s'%n", str);
final Pattern regex1 = Pattern.compile("([\\w&&[^:]]+)$"); // matches case 1
final Pattern regex2 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)$"); // matches case 2
final Pattern regex3 = Pattern.compile("([\\w&&[^:]]+):([\\d,]+)-([\\d,]+)$");// matches case 3
String contig = null;
long start = 1;
long stop = Integer.MAX_VALUE;
boolean bad = false;
Matcher match1 = regex1.matcher(str);
Matcher match2 = regex2.matcher(str);
Matcher match3 = regex3.matcher(str);
try {
if ( match1.matches() ) {
contig = match1.group(1);
}
else if ( match2.matches() ) {
contig = match2.group(1);
start = parsePosition(match2.group(2));
}
else if ( match3.matches() ) {
contig = match3.group(1);
start = parsePosition(match3.group(2));
stop = parsePosition(match3.group(3));
if ( start > stop )
bad = true;
}
else {
bad = true;
}
} catch ( Exception e ) {
bad = true;
}
if ( bad ) {
throw new RuntimeException("Invalid Genome Location string: " + str);
}
if ( stop == Integer.MAX_VALUE && hasKnownContigOrdering() ) {
// lookup the actually stop position!
stop = getContigInfo(contig).getSequenceLength();
}
GenomeLoc loc = new GenomeLoc(contig, start, stop);
//System.out.printf(" => Parsed location '%s' into %s%n", str, loc);
return loc;
}
/**
* Useful utility function that parses a location string into a coordinate-order sorted
* array of GenomeLoc objects
*
* @param str
* @return Array of GenomeLoc objects corresponding to the locations in the string, sorted by coordinate order
*/
public static ArrayList<GenomeLoc> parseGenomeLocs(final String str) {
// Of the form: loc1;loc2;...
// Where each locN can be:
// 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'
StdReflect reflect = new JdkStdReflect();
FunctionN<GenomeLoc> parseOne = reflect.staticFunction(GenomeLoc.class, "parseGenomeLoc", String.class);
Function1<GenomeLoc, String> f1 = parseOne.f1();
try {
Collection<GenomeLoc> result = Functions.map(f1, Arrays.asList(str.split(";")));
ArrayList<GenomeLoc> locs = new ArrayList(result);
Collections.sort(locs);
//logger.info(String.format("Going to process %d locations", locs.length));
locs = mergeOverlappingLocations(locs);
logger.info(" Locations are:\n" + Utils.join("\n", Functions.map(Operators.toString, locs)));
return locs;
} catch (Exception e) {
e.printStackTrace();
Utils.scareUser(String.format("Invalid locations string: %s, format is loc1;loc2; where each locN can be 'chr2', 'chr2:1000000' or 'chr2:1,000,000-2,000,000'", str));
return null;
}
}
public static ArrayList<GenomeLoc> mergeOverlappingLocations(final ArrayList<GenomeLoc> raw) {
logger.info(" Raw locations are:\n" + Utils.join("\n", Functions.map(Operators.toString, raw)));
if ( raw.size() <= 1 )
return raw;
else {
ArrayList<GenomeLoc> merged = new ArrayList<GenomeLoc>();
Iterator<GenomeLoc> it = raw.iterator();
GenomeLoc prev = it.next();
while ( it.hasNext() ) {
GenomeLoc curr = it.next();
if ( prev.contiguousP(curr) ) {
prev = prev.merge(curr);
} else {
merged.add(prev);
prev = curr;
}
}
merged.add(prev);
return merged;
}
}
/**
* Returns true iff we have a specified series of locations to process AND we are past the last
* location in the list. It means that, in a serial processing of the genome, that we are done.
*
* @param curr Current genome Location
* @return true if we are past the last location to process
*/
public static boolean pastFinalLocation(GenomeLoc curr, ArrayList<GenomeLoc> locs) {
if ( locs.size() == 0 )
return false;
else {
GenomeLoc last = locs.get(locs.size() - 1);
return last.compareTo(curr) == -1 && ! last.overlapsP(curr);
}
}
/**
* A key function that returns true if the proposed GenomeLoc curr is within the list of
* locations we are processing in this TraversalEngine
*
* @param curr
* @return true if we should process GenomeLoc curr, otherwise false
*/
public static boolean inLocations(GenomeLoc curr, ArrayList<GenomeLoc> locs) {
if ( locs.size() == 0 ) {
return true;
} else {
for ( GenomeLoc loc : locs ) {
//System.out.printf(" Overlap %s vs. %s => %b%n", loc, curr, loc.overlapsP(curr));
if (loc.overlapsP(curr))
return true;
}
return false;
}
}
public static void removePastLocs(GenomeLoc curr, List<GenomeLoc> locs) {
while ( !locs.isEmpty() && curr.isPast(locs.get(0)) ) {
//System.out.println("At: " + curr + ", removing: " + locs.get(0));
locs.remove(0);
}
}
public static boolean overlapswithSortedLocsP(GenomeLoc curr, List<GenomeLoc> locs, boolean returnTrueIfEmpty) {
if ( locs.isEmpty() )
return returnTrueIfEmpty;
// skip loci before intervals begin
if ( hasKnownContigOrdering() && getContigIndex(curr.contig) < getContigIndex(locs.get(0).contig) )
return false;
for ( GenomeLoc loc : locs ) {
//System.out.printf(" Overlap %s vs. %s => %b%n", loc, curr, loc.overlapsP(curr));
if ( loc.overlapsP(curr) )
return true;
if ( curr.compareTo(loc) < 0 )
return false;
}
return false;
}
// Accessors and setters
public final String getContig() { return this.contig; }
public final long getStart() { return this.start; }
public final long getStop() { return this.stop; }
public final String toString() {
if ( throughEndOfContigP() && atBeginningOfContigP() )
return getContig();
else if ( throughEndOfContigP() || getStart() == getStop() )
return String.format("%s:%d", getContig(), getStart());
else
return String.format("%s:%d-%d", getContig(), getStart(), getStop());
}
public final boolean isUnmapped() { return this.contig == null; }
public final boolean throughEndOfContigP() { return this.stop == Integer.MAX_VALUE; }
public final boolean atBeginningOfContigP() { return this.start == 1; }
public void setContig(String contig) {
this.contig = contig;
}
public void setStart(long start) {
this.start = start;
}
public void setStop(long stop) {
this.stop = stop;
}
public final boolean isSingleBP() { return stop == start; }
public final boolean disjointP(GenomeLoc that) {
if ( compareContigs(this.contig, that.contig) != 0 ) return true; // different chromosomes
if ( this.start > that.stop ) return true; // this guy is past that
if ( that.start > this.stop ) return true; // that guy is past our start
return false;
}
public final boolean discontinuousP(GenomeLoc that) {
if ( compareContigs(this.contig, that.contig) != 0 ) return true; // different chromosomes
if ( (this.start - 1) > that.stop ) return true; // this guy is past that
if ( (that.start - 1) > this.stop ) return true; // that guy is past our start
return false;
}
public final boolean overlapsP(GenomeLoc that) {
return ! disjointP( that );
}
public final boolean contiguousP(GenomeLoc that) {
return ! discontinuousP( that );
}
public GenomeLoc merge( GenomeLoc that ) {
assert this.contiguousP(that);
return new GenomeLoc(getContig(),
Math.min(getStart(), that.getStart()),
Math.max( getStop(), that.getStop()) );
}
public final boolean containsP(GenomeLoc that) {
if ( ! onSameContig(that) ) return false;
return getStart() <= that.getStart() && getStop() >= that.getStop();
}
public final boolean onSameContig(GenomeLoc that) {
return this.contig.equals(that.contig);
}
public final int minus( final GenomeLoc that ) {
if ( this.getContig().equals(that.getContig()) )
return (int) (this.getStart() - that.getStart());
else
return Integer.MAX_VALUE;
}
public final int distance( final GenomeLoc that ) {
return Math.abs(minus(that));
}
public final boolean isBetween( final GenomeLoc left, final GenomeLoc right ) {
return this.compareTo(left) > -1 && this.compareTo(right) < 1;
}
public final boolean isPast( GenomeLoc that ) {
int comparison = this.compareContigs(that);
return ( comparison == 1 || ( comparison == 0 && this.getStart() > that.getStop() ));
}
public final void incPos() {
incPos(1);
}
public final void incPos(long by) {
this.start += by;
this.stop += by;
}
public final GenomeLoc nextLoc() {
GenomeLoc n = new GenomeLoc(this);
n.incPos();
return n;
}
// Comparison operations
public static int compareContigs( final String thisContig, final String thatContig )
{
if ( thisContig == thatContig )
{
// Optimization. If the pointers are equal, then the contigs are equal.
return 0;
}
//assert getContigIndex(thisContig) != -1;// : this;
//assert getContigIndex(thatContig) != -1;// : that;
if ( hasKnownContigOrdering() )
{
int thisIndex = getContigIndex(thisContig);
int thatIndex = getContigIndex(thatContig);
if ( thisIndex == -1 )
{
if ( thatIndex == -1 )
{
// Use regular sorted order
return thisContig.compareTo(thatContig);
}
else
{
// this is always bigger if that is in the key set
return 1;
}
}
else if ( thatIndex == -1 )
{
return -1;
}
else
{
if ( thisIndex < thatIndex ) return -1;
if ( thisIndex > thatIndex ) return 1;
return 0;
}
}
else
{
return thisContig.compareTo(thatContig);
}
}
public int compareContigs( GenomeLoc that ) {
return compareContigs( this.contig, that.contig );
}
public int compareTo( GenomeLoc that ) {
if ( this == that ) return 0;
final int cmpContig = compareContigs( this.getContig(), that.getContig() );
if ( cmpContig != 0 ) return cmpContig;
if ( this.getStart() < that.getStart() ) return -1;
if ( this.getStart() > that.getStart() ) return 1;
// TODO: and error is being thrown because we are treating reads with the same start positions
// but different stop as out of order
//if ( this.getStop() < that.getStop() ) return -1;
//if ( this.getStop() > that.getStop() ) return 1;
return 0;
}
}
|
package org.jpos.util;
import org.jpos.core.Configuration;
import org.jpos.core.ConfigurationException;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Rotates log daily and compress the previous log.
* @author <a href="mailto:alcarraz@jpos.org">Andrés Alcarraz</a>
* @since jPOS 1.5.1
*/
public class DailyLogListener extends RotateLogListener{
private static final String DEF_SUFFIX = ".log";
private static final int DEF_WIN = 24*3600;
private static final long DEF_MAXSIZE = -1;
private static final String DEF_DATE_FMT = "-yyyy-MM-dd";
private static final int NONE = 0;
private static final int GZIP = 1;
private static final int ZIP = 2;
private static final int DEF_COMPRESSION = NONE;
private static final int DEF_BUFFER_SIZE = 128*1024;//128 KB
private static final String[] DEF_COMPRESSED_SUFFIX= {"",".gz",".zip"};
private static final Map<String,Integer> COMPRESSION_FORMATS = new HashMap<String,Integer>(3);
static {
COMPRESSION_FORMATS.put("none", NONE);
COMPRESSION_FORMATS.put("gzip", GZIP);
COMPRESSION_FORMATS.put("zip", ZIP);
}
/** Creates a new instance of DailyLogListener */
public DailyLogListener() {
setLastDate(getDateFmt().format(new Date()));
}
public void setConfiguration(Configuration cfg) throws ConfigurationException {
String suffix = cfg.get("suffix", DEF_SUFFIX), prefix = cfg.get("prefix");
setSuffix(suffix);
setPrefix(prefix);
Integer formatObj =
COMPRESSION_FORMATS
.get(cfg.get("compression-format","none").toLowerCase());
int compressionFormat = formatObj == null ? 0 : formatObj;
setCompressionFormat(compressionFormat);
setCompressedSuffix(cfg.get("compressed-suffix",
DEF_COMPRESSED_SUFFIX[compressionFormat]));
setCompressionBufferSize(cfg.getInt("compression-buffer-size",
DEF_BUFFER_SIZE));
logName = prefix + suffix;
maxSize = cfg.getLong("maxsize",DEF_MAXSIZE);
try {
openLogFile();
} catch (IOException e) {
throw new ConfigurationException ("error opening file: " + logName,
e);
}
sleepTime = cfg.getInt("window", DEF_WIN);
if (sleepTime <= 0)
sleepTime = DEF_WIN;
sleepTime*=1000;
DateFormat fmt = new SimpleDateFormat(cfg.get("date-format",DEF_DATE_FMT));
setDateFmt(fmt);
setLastDate(fmt.format(new Date()));
Date time;
try {
time = new SimpleDateFormat("HH:mm:ss").parse(cfg.get("first-rotate-time", "00:00:00"));
} catch (ParseException ex) {
throw new ConfigurationException("Bad 'first-rotate-time' format " +
"expected HH(0-23):mm:ss ",ex);
}
String strDate = cfg.get("first-rotate-date",null);
//calculate the first execution time
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND,0);
Calendar calTemp = Calendar.getInstance();
calTemp.setTime(time);
cal.set(Calendar.SECOND,calTemp.get(Calendar.SECOND));
cal.set(Calendar.MINUTE,calTemp.get(Calendar.MINUTE));
cal.set(Calendar.HOUR_OF_DAY,calTemp.get(Calendar.HOUR_OF_DAY));
if (strDate != null) {
Date date;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(strDate);
} catch (ParseException ex) {
throw new ConfigurationException("Bad 'first-rotate-date' " +
"format, expected (yyyy-MM-dd)", ex);
}
calTemp.setTime(date);
cal.set(calTemp.get(Calendar.YEAR), calTemp.get(Calendar.MONTH),
calTemp.get(Calendar.DATE));
}
//here cal contains the first execution, let/s calculate the next one
calTemp.setTime(new Date());
//if first executiontime already happened
if (cal.before(calTemp)){
//how many windows between cal and now
long n = (calTemp.getTimeInMillis() - cal.getTimeInMillis()) /
sleepTime;
cal.setTimeInMillis(cal.getTimeInMillis() + sleepTime*(n+1));
}
DefaultTimer.getTimer().scheduleAtFixedRate(
rotate = new DailyRotate(), cal.getTime(), sleepTime);
}
public synchronized void logRotate() throws IOException {
closeLogFile ();
super.close ();
setPrintStream (null);
String suffix = getSuffix() + getCompressedSuffix();
String newName = getPrefix()+getLastDate();
int i=0;
File dest = new File (newName+suffix), source = new File(logName);
while (dest.exists())
dest = new File (newName + "." + ++i + suffix);
source.renameTo(dest);
setLastDate(getDateFmt().format(new Date()));
openLogFile();
compress(dest);
}
/**
* Holds value of property suffix.
*/
private String suffix = DEF_SUFFIX;
/**
* Getter for property suffix.
* @return Value of property suffix.
*/
public String getSuffix() {
return this.suffix;
}
/**
* Setter for property suffix.
* @param suffix New value of property suffix.
*/
public void setSuffix(String suffix) {
this.suffix = suffix;
}
/**
* Holds value of property prefix.
*/
private String prefix;
/**
* Getter for property prefix.
* @return Value of property prefix.
*/
public String getPrefix() {
return this.prefix;
}
/**
* Setter for property prefix.
* @param prefix New value of property prefix.
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Holds value of property rotateCount.
*/
private int rotateCount;
/**
* Getter for property rotateCount.
* @return Value of property rotateCount.
*/
public int getRotateCount() {
return this.rotateCount;
}
/**
* Setter for property rotateCount.
* @param rotateCount New value of property rotateCount.
*/
public void setRotateCount(int rotateCount) {
this.rotateCount = rotateCount;
}
/**
* Holds value of property dateFmt.
*/
private DateFormat dateFmt = new SimpleDateFormat(DEF_DATE_FMT);
/**
* Getter for property dateFmt.
* @return Value of property dateFmt.
*/
public DateFormat getDateFmt() {
return this.dateFmt;
}
/**
* Setter for property dateFmt.
* @param dateFmt New value of property dateFmt.
*/
public void setDateFmt(DateFormat dateFmt) {
this.dateFmt = dateFmt;
}
/**
* Holds value of property lastDate.
*/
private String lastDate ;
/**
* Getter for property lastDate.
* @return Value of property lastDate.
*/
public String getLastDate() {
return this.lastDate;
}
/**
* Setter for property lastDate.
* @param lastDate New value of property lastDate.
*/
public void setLastDate(String lastDate) {
this.lastDate = lastDate;
}
/**
* Holds value of property compressedSuffix.
*/
private String compressedSuffix = DEF_COMPRESSED_SUFFIX[DEF_COMPRESSION];
/**
* Getter for property compressedExt.
* @return Value of property compressedExt.
*/
public String getCompressedSuffix() {
return this.compressedSuffix;
}
/**
* Setter for property compressedExt.
* @param compressedSuffix New value of property compressedExt.
*/
public void setCompressedSuffix(String compressedSuffix) {
this.compressedSuffix = compressedSuffix;
}
/**
* Hook method that creates a thread to compress the file f.
* @param f the file name
* @return a thread to compress the file and null if it is not necesary
*/
protected Thread getCompressorThread(File f){
return new Thread(new Compressor(f),"DailyLogListener-Compressor");
}
/**
* Hook method that creates an output stream that will compress the data.
* @param f the file name
* @return ZIP/GZip OutputStream
* @throws java.io.IOException on error
*/
protected OutputStream getCompressedOutputStream(File f) throws IOException{
OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
if (getCompressionFormat() == ZIP) {
ZipOutputStream ret = new ZipOutputStream(os);
ret.putNextEntry(new ZipEntry(logName));
return ret;
} else {
return new GZIPOutputStream(os);
}
}
protected void closeCompressedOutputStream(OutputStream os) throws IOException{
if (os instanceof DeflaterOutputStream)
((DeflaterOutputStream)os).finish();
os.close();
}
protected void logDebugEx(String msg, Throwable e){
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
ps.println(msg);
e.printStackTrace(ps);
ps.close();
logDebug(os.toString());
}
protected class Compressor implements Runnable{
File f;
public Compressor(File f) {
this.f = f;
}
public void run() {
OutputStream os = null;
InputStream is = null;
File tmp = null;
try {
tmp = File.createTempFile(f.getName(), ".tmp", f.getParentFile());
os = getCompressedOutputStream(tmp);
is = new BufferedInputStream(new FileInputStream(f));
byte[] buff = new byte[getCompressionBufferSize()];
int read;
do {
read = is.read(buff);
if ( read > 0 )
os.write(buff,0,read);
} while (read > 0);
} catch (Throwable ex) {
logDebugEx("error compressing file " + f, ex);
} finally {
try {
if (is!=null)
is.close();
if (os != null)
closeCompressedOutputStream(os);
if (f != null){
f.delete();
if (tmp!=null)
tmp.renameTo(f);
}
} catch (Throwable ex) {
logDebugEx("error closing files", ex);
}
}
}
}
/**
* Holds value of property compressionFormat.
*/
private int compressionFormat = DEF_COMPRESSION;
/**
* Getter for property compressionFormat.
* @return Value of property compressionFormat.
*/
public int getCompressionFormat() {
return this.compressionFormat;
}
/**
* Setter for property compressionFormat.
* @param compressionFormat New value of property compressionFormat.
*/
public void setCompressionFormat(int compressionFormat) {
this.compressionFormat = compressionFormat;
}
/**
* Holds value of property compressionBufferSize.
*/
private int compressionBufferSize = DEF_BUFFER_SIZE;
/**
* Getter for property compressionBufferSize.
* @return Value of property compressionBufferSize.
*/
public int getCompressionBufferSize() {
return this.compressionBufferSize;
}
/**
* Setter for property compressionBufferSize.
* @param compressionBufferSize New value of property compressionBufferSize.
*/
public void setCompressionBufferSize(int compressionBufferSize) {
this.compressionBufferSize = compressionBufferSize >= 0 ?
compressionBufferSize : DEF_BUFFER_SIZE;
}
protected void checkSize() {
if (maxSize>0 )
super.checkSize();
}
/**
* Hook method to optionally compress the file
* @param logFile the file name
*/
protected void compress(File logFile) {
if (getCompressionFormat() != NONE){
Thread t = getCompressorThread(logFile);
try{
if (t != null)
t.start();
} catch (Exception e){
logDebugEx("error compressing file",e);
}
}
}
final class DailyRotate extends Rotate {
public void run() {
super.run();
setLastDate(getDateFmt().format(new Date(scheduledExecutionTime())));
}
}
}
|
package com.rultor.aws;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.Tv;
import com.jcabi.log.Logger;
import com.rultor.spi.Conveyer;
import com.rultor.spi.Pulse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.ws.rs.core.MediaType;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.CharUtils;
/**
* Mutable and thread-safe in-memory cache of a single S3 object.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.0
* @checkstyle ClassDataAbstractionCoupling (500 lines)
*/
@ToString
@EqualsAndHashCode(of = "key")
@Loggable(Loggable.DEBUG)
final class Cache implements Flushable {
/**
* S3 key.
*/
private final transient Key key;
/**
* When was is touched last time (in milliseconds)?
*/
private final transient AtomicLong touched =
new AtomicLong(System.currentTimeMillis());
/**
* New lines.
*/
private final transient Collection<String> lines =
new CopyOnWriteArrayList<String>();
/**
* Data.
*/
private transient ByteArrayOutputStream data;
/**
* Public ctor.
* @param akey S3 key
*/
protected Cache(final Key akey) {
this.key = akey;
}
/**
* Append new line to an object.
* @param line Line to add
* @throws IOException If fails
*/
public void append(final Conveyer.Line line) throws IOException {
this.lines.add(line.toString());
}
/**
* Read the entire object.
* @return Input stream
* @throws IOException If fails
*/
public InputStream read() throws IOException {
return new ByteArrayInputStream(this.stream().toByteArray());
}
/**
* {@inheritDoc}
*/
@Override
public void flush() throws IOException {
synchronized (this.key) {
if (this.data != null && !this.lines.isEmpty()) {
final S3Client client = this.key.client();
final AmazonS3 aws = client.get();
final ObjectMetadata meta = new ObjectMetadata();
meta.setContentEncoding(CharEncoding.UTF_8);
meta.setContentLength(this.data.size());
meta.setContentType(MediaType.TEXT_PLAIN);
try {
if (this.valuable()) {
final PutObjectResult result = aws.putObject(
client.bucket(),
this.key.toString(),
this.read(),
meta
);
Logger.info(
this,
"'%s' saved to S3, size=%d, etag=%s",
this.key,
this.data.size(),
result.getETag()
);
}
} catch (AmazonS3Exception ex) {
throw new IOException(
String.format(
"failed to flush %s to %s: %s",
this.key,
client.bucket(),
ex
),
ex
);
}
}
}
}
/**
* Is it expired (called from {@link Caches})?
* @return TRUE if it is not required in memory any more
* @throws IOException If fails
*/
public boolean expired() throws IOException {
final long mins = (System.currentTimeMillis() - this.touched.get())
/ TimeUnit.MINUTES.toMillis(1);
return mins > Tv.TWENTY || !this.valuable();
}
/**
* Get stream.
* @return Stream with data
* @throws IOException If fails
*/
private ByteArrayOutputStream stream() throws IOException {
synchronized (this.key) {
if (this.data == null) {
this.data = new ByteArrayOutputStream();
final S3Client client = this.key.client();
final AmazonS3 aws = client.get();
try {
if (!aws.listObjects(client.bucket(), this.key.toString())
.getObjectSummaries().isEmpty()) {
final S3Object object =
aws.getObject(client.bucket(), this.key.toString());
IOUtils.copy(object.getObjectContent(), this.data);
Logger.info(
this,
"'%s' loaded from S3, size=%d, etag=%s",
this.key,
this.data.size(),
object.getObjectMetadata().getETag()
);
}
} catch (AmazonS3Exception ex) {
throw new IOException(
String.format(
"failed to read %s from %s: %s",
this.key,
client.bucket(),
ex
),
ex
);
}
}
this.touched.set(System.currentTimeMillis());
final PrintWriter writer = new PrintWriter(this.data);
for (String line : this.lines) {
writer.append(line).append(CharUtils.LF);
}
writer.flush();
writer.close();
this.lines.clear();
return this.data;
}
}
/**
* Is it a valuable log?
* @return TRUE if it is valuable and should be persisted
* @throws IOException If fails
*/
private boolean valuable() throws IOException {
final Protocol protocol = new Protocol(
new Protocol.Source() {
@Override
public InputStream stream() throws IOException {
return Cache.this.read();
}
}
);
return !protocol.find(Pulse.Signal.STAGE, "").isEmpty();
}
}
|
package ru.qa.sandbox;
public class FirstStep {
public static void main(String[] args) {
System.out.println("Hello, world");
int l = 6;
int s = l * l;
System.out.println("Площадь квадрата со стороной " + l + " = " + s);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.