answer
stringlengths 17
10.2M
|
|---|
package io.luna.game.model.item;
import io.luna.game.model.def.ItemDefinition;
import static com.google.common.base.Preconditions.checkArgument;
public final class Item {
/**
* The identifier for this {@code Item}.
*/
private final int id;
/**
* The amount of this {@code Item}.
*/
private final int amount;
/**
* The definition instance for this {@code Item}.
*/
private final ItemDefinition definition;
/**
* Creates a new {@link Item}.
*
* @param id The identifier for this {@code Item}.
* @param amount The amount of this {@code Item}.
*/
public Item(int id, int amount) {
checkArgument(id > 0 && id < ItemDefinition.DEFINITIONS.length, "invalid item id");
checkArgument(amount > 0, "amount <= 0");
this.id = id;
this.amount = amount;
definition = ItemDefinition.DEFINITIONS[id];
}
/**
* Creates a new {@link Item} with an {@code amount} of {@code 1}.
*
* @param id The identifier for this {@code Item}.
*/
public Item(int id) {
this(id, 1);
}
/**
* Increments the amount by {@code addAmount}. The returned {@code Item} <strong>does not</strong> hold any references to
* this one. It will also have a maximum amount of {@code Integer.MAX_VALUE}.
*
* @param addAmount The amount to add.
* @return The newly incremented {@code Item}.
*/
public Item increment(int addAmount) {
if (addAmount < 0) { // Same effect as decrementing.
return decrement(Math.abs(addAmount));
}
int newAmount = amount + addAmount;
if (newAmount < amount) { // An overflow.
newAmount = Integer.MAX_VALUE;
}
return new Item(id, newAmount);
}
/**
* Decrements the amount by {@code removeAmount}. The returned {@code Item} <strong>does not</strong> hold any references
* to this one. It will also have a minimum amount of {@code 1}.
*
* @param removeAmount The amount to remove.
* @return The newly incremented {@code Item}.
*/
public Item decrement(int removeAmount) {
if (removeAmount < 0) { // Same effect as incrementing.
return increment(Math.abs(removeAmount));
}
int newAmount = amount - removeAmount;
// Value too low, or an overflow.
if (newAmount < 1 || newAmount > amount) {
newAmount = 1;
}
return new Item(id, newAmount);
}
/**
* Sets the amount to {@code newAmount}. The returned {@code Item} <strong>does not</strong> hold any references to this
* one. It will throw an exception on overflows and negative values.
*
* @param newAmount The new amount to set.
* @return The newly amount set {@code Item}.
*/
public Item setAmount(int newAmount) {
return new Item(id, newAmount);
}
/**
* The definition instance for this {@code Item}.
*/
public ItemDefinition getDefinition() {
return definition;
}
/**
* @return The identifier for this {@code Item}.
*/
public int getId() {
return id;
}
/**
* Sets the id to {@code newId}. The returned {@code Item} <strong>does not</strong> hold any references to this one. It
* will throw an exception on an invalid id.
*
* @param newId The new id to set.
* @return The newly id set {@code Item}.
*/
public Item setId(int newId) {
return new Item(newId, amount);
}
/**
* @return The amount of this {@code Item}.
*/
public int getAmount() {
return amount;
}
}
|
package io.scif.formats;
import io.scif.AbstractFormat;
import io.scif.AbstractWriter;
import io.scif.DefaultMetadata;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.Metadata;
import io.scif.Plane;
import io.scif.Reader;
import io.scif.SCIFIO;
import io.scif.config.SCIFIOConfig;
import io.scif.formats.imaris.ImarisWriter;
import io.scif.io.Location;
import io.scif.io.RandomAccessOutputStream;
import io.scif.util.FormatTools;
import io.scif.util.SCIFIOMetadataTools;
import java.awt.image.ColorModel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import net.imagej.axis.Axes;
import org.scijava.plugin.Plugin;
/**
* SCIFIO Format supporting the writer for Imaris 5.5 files
*
* @author Henry Pinkard
*/
@Plugin(type = Format.class, name = "Imaris 5.5")
public class ImarisFormat extends AbstractFormat {
//for testing
// public static void main(String[] args) throws IOException, FormatException {
// final SCIFIO scifio = new SCIFIO();
// String name = "mitosis";
// final String sampleImage = "/Users/henrypinkard/Desktop/" + name + ".tif";
// final String outPath = "/Users/henrypinkard/Desktop/" + name + ".ims";
// final Location l = new Location(scifio.getContext(), outPath);
// if (l.exists()) {
// l.delete();
// final Reader reader = scifio.initializer().initializeReader(sampleImage);
// final io.scif.Writer writer
// = scifio.initializer().initializeWriter(sampleImage, outPath);
// for (int i = 0; i < reader.getImageCount(); i++) {
// for (int j = 0; j < reader.getPlaneCount(i); j++) {
// writer.savePlane(i, j, reader.openPlane(i, j));
// reader.close();
// writer.close();
@Override
public String getFormatName() {
return "Imaris 5.5 files";
}
@Override
protected String[] makeSuffixArray() {
return new String[]{"ims"};
}
public static class Writer extends AbstractWriter<DefaultMetadata> {
private Metadata metadata;
private ImarisWriter imsWriter;
private String path;
private int bitDepth;
private long sizeX, sizeY, sizeZ, sizeC, sizeT;
private double pixelSizeXY, pixelSizeZ;
private ColorModel colorModel;
//SCIFIO will internally (1) initialize, (2) save planes, and (3) close the writer
//during initialization: destination metadata created, writer instance created,
//writer.setMetadata(destMeta) called, and finally writer.setDest(destination, config);
@Override
public void setMetadata(final Metadata meta) throws FormatException {
metadata = meta;
//read metadata for writer initialization
bitDepth = meta.get(0).getBitsPerPixel();
sizeX = meta.get(0).getAxisLength(Axes.X);
sizeY = meta.get(0).getAxisLength(Axes.Y);
sizeZ = Math.max(1, meta.get(0).getAxisLength(Axes.Z));
sizeC = Math.max(1, meta.get(0).getAxisLength(Axes.CHANNEL));
sizeT = Math.max(1, meta.get(0).getAxisLength(Axes.TIME));
if (meta.get(0).getPlaneCount() != sizeZ*sizeC*sizeT) {
throw new FormatException("Channels * Frames * Z Slices must equal number of planes");
}
//get pixel sizes
pixelSizeXY = FormatTools.getScale(meta, 0, Axes.X);
pixelSizeZ = FormatTools.getScale(meta, 0, Axes.Z);
// if (metadata != null && metadata != meta) {
// try {
// metadata.close();
// catch (final IOException e) {
// throw new FormatException(e);
// if (out != null) {
// try {
// close();
// catch (final IOException e) {
// throw new FormatException(e);
// metadata = meta;
// // Check the first pixel type for compatibility with this writer
// for (int i = 0; i < metadata.getImageCount(); i++) {
// final int pixelType = metadata.get(i).getPixelType();
// if (!DataTools.containsValue(getPixelTypes(compression), pixelType)) {
// throw new FormatException("Unsupported image type '" +
// FormatTools.getPixelTypeString(pixelType) + "'.");
}
@Override
public void setDest(final String fileName, final int imageIndex,
final SCIFIOConfig config) throws FormatException, IOException {
path = fileName;
//Imaris writier uses JNI calls rather than output stream to write data,
//override this method and don't unnecessarily create object
setDest((RandomAccessOutputStream) null, imageIndex, config);
}
@Override
public void setDest(final RandomAccessOutputStream out, final int imageIndex,
final SCIFIOConfig config) throws FormatException, IOException {
colorModel = config.writerGetColorModel();
// if (metadata == null) throw new FormatException(
// "Can not set Destination without setting Metadata first.");
// // FIXME
// // set metadata.datasetName here when RAOS has better id handling
// this.out = out;
// fps = config.writerGetFramesPerSecond();
// options = config.writerGetCodecOptions();
// model = config.writerGetColorModel();
// compression = config.writerGetCompression();
// sequential = config.writerIsSequential();
// SCIFIOMetadataTools.verifyMinimumPopulated(metadata, out);
// initialized = new boolean[metadata.getImageCount()][];
// for (int i = 0; i < metadata.getImageCount(); i++) {
// initialized[i] =
// new boolean[(int) metadata.get(imageIndex).getPlaneCount()];
}
// If your writer supports a compression type, you can declare that here.
// Otherwise it is sufficient to return an empty String[]
@Override
protected String[] makeCompressionTypes() {
return new String[0];
}
///Override these methods to prevent exceptions because acces to fields in AbstractWriter is private rther than protected
protected void initialize(final int imageIndex, final long planeIndex,
final long[] planeMin, final long[] planeMax) throws FormatException,
IOException {
//nothing to do
}
//have to override this method because access to metadata is private
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane) throws FormatException, IOException {
final long[] planeMax = metadata.get(imageIndex).getAxesLengthsPlanar();
final long[] planeMin = new long[planeMax.length];
savePlane(imageIndex, planeIndex, plane, planeMin, planeMax);
}
@Override
public boolean isInitialized(final int imageIndex, final long planeIndex) {
return true;
}
// Take a provided data plane, of specified dimensionality, and
// write it to the given indices on disk.
@Override
public void writePlane(int imageIndex, long planeIndex, Plane plane,
long[] planeMin, long[] planeMax) throws FormatException, IOException {
if (!SCIFIOMetadataTools.wholePlane(imageIndex, metadata, planeMin, planeMax)) {
throw new FormatException("Imaris writer does not support saving image tiles.");
}
if (imsWriter == null) {
imsWriter = new ImarisWriter(path, sizeX, sizeY, sizeZ, sizeC, sizeT, pixelSizeXY, pixelSizeZ, bitDepth, null);
}
int zAxis = plane.getImageMetadata().getAxisIndex(Axes.Z);
int channelAxis = plane.getImageMetadata().getAxisIndex(Axes.CHANNEL);
int frameAxis = plane.getImageMetadata().getAxisIndex(Axes.TIME);
int t, z, c;
if (frameAxis != -1 && (frameAxis < zAxis || frameAxis < channelAxis) ) {
throw new FormatException("Unsupported plane ordering: Imaris writer can only write"
+ "in CZT or ZCT sequence");
} else {
t = (int) (planeIndex / (sizeC * sizeZ));
if (channelAxis < zAxis) {
//channels first or no channels
z = (int) ((planeIndex / sizeC) % sizeZ);
c = (int) (planeIndex % sizeC);
} else {
//slices first or no slices
c = (int) ((planeIndex / sizeZ) % sizeC);
z = (int) (planeIndex % sizeZ);
}
}
//Get date and time. Used for image timestamps,
//which are important for calibration in ims files
//Date + Time format
//"YYYY-MM-DD HH:MM:SS.XXX"
//TODO: replace with reading from metadata
String dnt = "2014-01-01 00:00:00.00" + t;
//Accepts byte[] or short[] pixels, convert as needed
Object pixels;
int pixelType = plane.getImageMetadata().getPixelType();
if (pixelType == FormatTools.INT8 || pixelType == FormatTools.UINT8) {
pixels = plane.getBytes();
} else if (pixelType == FormatTools.INT16 || pixelType == FormatTools.UINT16) {
byte[] bytes = plane.getBytes();
short[] shorts = new short[bytes.length / 2];
ByteBuffer.wrap(bytes).order(plane.getImageMetadata().isLittleEndian() ?
ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN).asShortBuffer().get(shorts);
pixels = shorts;
}else {
throw new FormatException("Unsupported pixel type: Imaris writer only "
+ "supports 8 or 16 bit pixels");
}
// System.out.println(planeIndex + "\t" + c + "\t" + z + "\t" + t);
imsWriter.addImage(pixels, z, c, t, dnt);
}
@Override
public void close() throws IOException {
// close(false);
imsWriter.close();
}
}
}
|
package legends.web;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import legends.helper.Templates;
import legends.model.World;
import legends.web.basic.Controller;
import legends.web.basic.RequestMapping;
import legends.web.util.SearchResult;
@Controller
public class SearchController {
@RequestMapping("/search")
public Template search(VelocityContext context) {
if (context.containsKey("query")) {
String query = context.get("query").toString().toLowerCase();
context.put("query", query);
context.put("regions", World.getRegions().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("sites", World.getSites().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("artifacts", World.getArtifacts().stream()
.filter(e -> e.getName().toLowerCase().contains(query)).collect(Collectors.toList()));
context.put("entities", World.getEntities().stream().filter(e -> e.getName().toLowerCase().contains(query))
.collect(Collectors.toList()));
context.put("hfs", World.getHistoricalFigures().stream()
.filter(e -> e.getName().toLowerCase().contains(query)).collect(Collectors.toList()));
return Templates.get("search.vm");
} else
return Templates.get("index.vm");
}
@RequestMapping("/search.json")
public Template searchJSON(VelocityContext context) {
String query = context.get("query").toString().toLowerCase();
List<SearchResult> results = new ArrayList<>();
World.getEntities().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getSites().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getStructures().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getHistoricalFigures().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getIdentities().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getRegions().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getArtifacts().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
World.getWorldConstructions().stream().filter(e -> e.getName().toLowerCase().contains(query)).limit(6)
.map(e -> new SearchResult(e.getName(), e.getURL())).forEach(results::add);
context.put("results", results);
context.put("contentType", "application/json");
return Templates.get("searchjson.vm");
}
}
|
package loci.deepzoomplugin;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij.process.ImageProcessor;
import java.util.prefs.Preferences;
/**
*
* @author Aivar Grislis
*/
public class DeepZoom implements PlugIn {
private static final String FILE = "FILE";
private static final String OUTPUT = "OUTPUT";
private static final String NAME ="NAME";
private static final String DESCRIPTION = "DESCRIPTION";
private static final String WIDTH = "WIDTH";
private static final String HEIGHT = "HEIGHT";
private static final String LAUNCH = "LAUNCH";
private static final String URL = "URL";
private enum Implementation { CHAINED, MULTITHREADED, MULTIINSTANCE };
private static final String[] m_choices = { Implementation.CHAINED.name(), Implementation.MULTITHREADED.name(), Implementation.MULTIINSTANCE.name() };
private Preferences m_prefs = Preferences.userRoot().node(this.getClass().getName());
public void run(String arg) {
ImagePlus imp = WindowManager.getCurrentImage();
if (null == imp) {
return;
}
ImageProcessor ip = imp.getChannelProcessor();
String folder = m_prefs.get(OUTPUT, "");
String name = m_prefs.get(NAME, "image");
String description = m_prefs.get(DESCRIPTION, "Zoomable image");
int width = m_prefs.getInt(WIDTH, 640);
int height = m_prefs.getInt(HEIGHT, 480);
boolean launch = m_prefs.getBoolean(LAUNCH, true);
String url = m_prefs.get(URL, "");
GenericDialog dialog = new GenericDialog("Save Image to Deep Zoom");
dialog.addStringField("Output folder: ", folder);
dialog.addStringField("HTML file name: ", name);
dialog.addStringField("HTML title: ", description);
dialog.addNumericField("Image window width: ", width, 0);
dialog.addNumericField("Image window height: ", height, 0);
dialog.addCheckbox("Launch browser: ", launch);
dialog.addStringField("URL (optional): ", url);
dialog.addChoice("Implementation: ", m_choices, Implementation.CHAINED.toString());
dialog.showDialog();
if (dialog.wasCanceled()) {
return;
}
folder = dialog.getNextString();
name = dialog.getNextString();
description = dialog.getNextString();
width = (int) dialog.getNextNumber();
height = (int) dialog.getNextNumber();
launch = dialog.getNextBoolean();
url = dialog.getNextString();
int choiceIndex = dialog.getNextChoiceIndex();
Implementation implementation = Implementation.values()[choiceIndex];
m_prefs.put(OUTPUT, folder);
m_prefs.put(NAME, name);
m_prefs.put(DESCRIPTION, description);
m_prefs.putInt(WIDTH, width);
m_prefs.putInt(HEIGHT, height);
m_prefs.putBoolean(LAUNCH, launch);
m_prefs.put(URL, url);
//TODO just define an IDeepZoomExporter interface
switch (implementation) {
case CHAINED:
case MULTITHREADED:
loci.chainableplugin.deepzoom.DeepZoomExporter
deepZoomExporter1 = new loci.chainableplugin.deepzoom.DeepZoomExporter
(launch, false, folder, url, name, description, width, height);
loci.plugin.ImageWrapper imageWrapper1 = new loci.plugin.ImageWrapper(ip);
deepZoomExporter1.process(imageWrapper1);
break;
case MULTIINSTANCE:
loci.multiinstanceplugin.deepzoom.DeepZoomExporter
deepZoomExporter2 = new loci.multiinstanceplugin.deepzoom.DeepZoomExporter
(launch, false, folder, url, name, description, width, height);
loci.plugin.ImageWrapper imageWrapper2 = new loci.plugin.ImageWrapper(ip);
deepZoomExporter2.process(imageWrapper2);
break;
}
}
/**
* Main method used for testing only. This allows the tester to compare
* different implementations of the plugin that use different frameworks
* to chain the processor components together.
*
* @param args the command line arguments
*/
public static void main(String [] args)
{
new ImageJ();
// ask for file to load
Preferences prefs = Preferences.userRoot().node("tmp");
String file = prefs.get(FILE, "");
GenericDialog dialog = new GenericDialog("Choose Image");
dialog.addStringField("File: ", "");
dialog.showDialog();
if (dialog.wasCanceled()) {
return;
}
file = dialog.getNextString();
prefs.put(FILE, file);
IJ.open(file);
ImagePlus imp = WindowManager.getCurrentImage();
imp.hide();
System.out.println("imp size is " + imp.getStackSize());
System.out.println("imp type is " + imp.getType());
//ij.process.ImageConverter converter = new ij.process.ImageConverter(imp); //FAIL for some reason the image type is IMGLIB and conversion fails
//converter.convertRGBStackToRGB();
convertRGBStackToRGB(imp);
imp.show();
// run plugin
DeepZoom plugin = new DeepZoom();
plugin.run("");
System.exit(0); //TODO just for testing.
}
/**
* This is just a hack to make the main method work:
*/
/** Converts a 2 or 3 slice 8-bit stack to RGB. */
public static void convertRGBStackToRGB(ImagePlus imp) {
int stackSize = imp.getStackSize();
int type = imp.getType();
//if (stackSize<2 || stackSize>3 || type!=ImagePlus.GRAY8) //FAIL, the ImageConverter version encounters ImagePlus.IMGLIB == 5
int width = imp.getWidth();
int height = imp.getHeight();
ij.ImageStack stack = imp.getStack();
byte[] R = (byte[])stack.getPixels(1);
byte[] G = (byte[])stack.getPixels(2);
byte[] B;
if (stackSize>2)
B = (byte[])stack.getPixels(3);
else
B = new byte[width*height];
imp.trimProcessor();
ij.process.ColorProcessor cp = new ij.process.ColorProcessor(width, height);
cp.setRGB(R, G, B);
if (imp.isInvertedLut())
cp.invert();
imp.setImage(cp.createImage());
imp.killStack();
}
}
|
package mezz.jei;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.abahgat.suffixtree.GeneralizedSuffixTree;
import com.google.common.collect.ImmutableList;
import gnu.trove.set.TIntSet;
import mezz.jei.config.Config;
import mezz.jei.gui.ingredients.IIngredientListElement;
public class ItemFilterInternals {
private static final Pattern spacePattern = Pattern.compile("\\s");
private static final Pattern quotePattern = Pattern.compile("\"");
private static final Pattern filterSplitPattern = Pattern.compile("(\".*?(?:\"|$)|\\S+)");
private ImmutableList<Object> baseList;
private GeneralizedSuffixTree searchTree;
private GeneralizedSuffixTree modNameTree;
private GeneralizedSuffixTree tooltipTree;
private GeneralizedSuffixTree oreDictTree;
private GeneralizedSuffixTree creativeTabTree;
private GeneralizedSuffixTree colorTree;
private Map<Character, GeneralizedSuffixTree> prefixedSearchTrees = new HashMap<Character, GeneralizedSuffixTree>();
@Nullable
private String filterCached;
private ImmutableList<Object> ingredientListCached = ImmutableList.of();
public ItemFilterInternals() {
List<IIngredientListElement> ingredientList = IngredientBaseListFactory.create();
ImmutableList.Builder<Object> baseListBuilder = ImmutableList.builder();
for (IIngredientListElement element : ingredientList) {
baseListBuilder.add(element.getIngredient());
}
this.baseList = baseListBuilder.build();
this.searchTree = new GeneralizedSuffixTree();
this.prefixedSearchTrees.put('@', this.modNameTree = new GeneralizedSuffixTree());
this.prefixedSearchTrees.put('#', this.tooltipTree = new GeneralizedSuffixTree());
this.prefixedSearchTrees.put('$', this.oreDictTree = new GeneralizedSuffixTree());
this.prefixedSearchTrees.put('%', this.creativeTabTree = new GeneralizedSuffixTree());
this.prefixedSearchTrees.put('^', this.colorTree = new GeneralizedSuffixTree());
buildSuffixTrees(ingredientList);
}
private void buildSuffixTrees(List<IIngredientListElement> ingredientList) {
for (int i = 0; i < ingredientList.size(); i++) {
IIngredientListElement element = ingredientList.get(i);
searchTree.put(element.getDisplayName(), i);
Config.SearchMode modNameSearchMode = Config.getModNameSearchMode();
if (modNameSearchMode != Config.SearchMode.DISABLED) {
String modNameString = element.getModName();
String modIdString = element.getModId();
modNameTree.put(modNameString, i);
modNameTree.put(modIdString, i);
modNameTree.put(spacePattern.matcher(modNameString).replaceAll(""), i);
modNameTree.put(spacePattern.matcher(modIdString).replaceAll(""), i);
if (modNameSearchMode == Config.SearchMode.ENABLED) {
searchTree.put(modNameString, i);
searchTree.put(modIdString, i);
searchTree.put(spacePattern.matcher(modNameString).replaceAll(""), i);
searchTree.put(spacePattern.matcher(modIdString).replaceAll(""), i);
}
}
Config.SearchMode tooltipSearchMode = Config.getTooltipSearchMode();
if (tooltipSearchMode != Config.SearchMode.DISABLED) {
String tooltipString = element.getTooltipString();
tooltipTree.put(tooltipString, i);
if (tooltipSearchMode == Config.SearchMode.ENABLED) {
searchTree.put(tooltipString, i);
}
}
Config.SearchMode oreDictSearchMode = Config.getOreDictSearchMode();
if (oreDictSearchMode != Config.SearchMode.DISABLED) {
String oreDictString = element.getOreDictString();
oreDictTree.put(oreDictString, i);
if (oreDictSearchMode == Config.SearchMode.ENABLED) {
searchTree.put(oreDictString, i);
}
}
Config.SearchMode creativeTabSearchMode = Config.getCreativeTabSearchMode();
if (creativeTabSearchMode != Config.SearchMode.DISABLED) {
String creativeTabsString = element.getCreativeTabsString();
creativeTabTree.put(creativeTabsString, i);
if (creativeTabSearchMode == Config.SearchMode.ENABLED) {
searchTree.put(creativeTabsString, i);
}
}
Config.SearchMode colorSearchMode = Config.getColorSearchMode();
if (colorSearchMode != Config.SearchMode.DISABLED) {
String colorString = element.getColorString();
colorTree.put(colorString, i);
if (colorSearchMode == Config.SearchMode.ENABLED) {
searchTree.put(colorString, i);
}
}
}
}
public ImmutableList<Object> getIngredientList() {
if (!Config.getFilterText().equals(filterCached)) {
ingredientListCached = getIngredientListUncached();
filterCached = Config.getFilterText();
}
return ingredientListCached;
}
private ImmutableList<Object> getIngredientListUncached() {
String[] filters = Config.getFilterText().split("\\|");
if (filters.length == 1) {
String filter = filters[0];
return getElements(filter);
} else {
ImmutableList.Builder<Object> ingredientList = ImmutableList.builder();
for (String filter : filters) {
List<Object> ingredients = getElements(filter);
ingredientList.addAll(ingredients);
}
return ingredientList.build();
}
}
private ImmutableList<Object> getElements(String filterText) {
Matcher filterMatcher = filterSplitPattern.matcher(filterText);
TIntSet matches = null;
while (filterMatcher.find()) {
String token = filterMatcher.group(1);
token = quotePattern.matcher(token).replaceAll("");
if (!token.isEmpty()) {
char firstChar = token.charAt(0);
GeneralizedSuffixTree tree = this.prefixedSearchTrees.get(firstChar);
if (tree != null) {
token = token.substring(1);
if (token.isEmpty()) {
continue;
}
} else {
tree = searchTree;
}
TIntSet searchResults = tree.search(token);
if (matches == null) {
matches = searchResults;
} else if (matches.size() > searchResults.size()) {
searchResults.retainAll(matches);
matches = searchResults;
} else {
matches.retainAll(searchResults);
}
if (matches.isEmpty()) {
break;
}
}
}
if (matches == null) {
return this.baseList;
}
int[] matchesList = matches.toArray();
Arrays.sort(matchesList);
ImmutableList.Builder<Object> matchingElements = ImmutableList.builder();
for (Integer match : matchesList) {
Object element = baseList.get(match);
matchingElements.add(element);
}
return matchingElements.build();
}
}
|
package mtr.render;
import mtr.block.BlockRailwaySign;
import mtr.block.BlockStationNameBase;
import mtr.block.IBlock;
import mtr.config.CustomResources;
import mtr.data.*;
import mtr.gui.ClientCache;
import mtr.gui.ClientData;
import mtr.gui.IDrawing;
import mtr.gui.RenderingInstruction;
import net.minecraft.block.BlockState;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher;
import net.minecraft.client.render.block.entity.BlockEntityRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3f;
import net.minecraft.world.WorldAccess;
import java.util.*;
import java.util.stream.Collectors;
public class RenderRailwaySign<T extends BlockRailwaySign.TileEntityRailwaySign> extends BlockEntityRenderer<T> implements IBlock, IGui, IDrawing {
public static final int HEIGHT_TO_SCALE = 27;
public RenderRailwaySign(BlockEntityRenderDispatcher dispatcher) {
super(dispatcher);
}
@Override
public void render(T entity, float tickDelta, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int overlay) {
final WorldAccess world = entity.getWorld();
if (world == null) {
return;
}
final BlockPos pos = entity.getPos();
final BlockState state = world.getBlockState(pos);
if (!(state.getBlock() instanceof BlockRailwaySign)) {
return;
}
final BlockRailwaySign block = (BlockRailwaySign) state.getBlock();
if (entity.getSignIds().length != block.length) {
return;
}
final Direction facing = IBlock.getStatePropertySafe(state, BlockStationNameBase.FACING);
final String[] signIds = entity.getSignIds();
boolean renderBackground = false;
int backgroundColor = 0;
for (final String signId : signIds) {
if (signId != null) {
final CustomResources.CustomSign sign = getSign(signId);
if (sign != null) {
renderBackground = true;
if (sign.backgroundColor != 0) {
backgroundColor = sign.backgroundColor;
break;
}
}
}
}
matrices.push();
matrices.translate(0.5, 0.53125, 0.5);
matrices.multiply(Vec3f.POSITIVE_Y.getDegreesQuaternion(-facing.asRotation()));
matrices.multiply(Vec3f.POSITIVE_Z.getDegreesQuaternion(180));
matrices.translate(block.getXStart() / 16F - 0.5, 0, -0.0625 - SMALL_OFFSET * 3);
if (renderBackground) {
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getLight(new Identifier("mtr:textures/block/white.png")));
IDrawing.drawTexture(matrices, vertexConsumer, 0, 0, SMALL_OFFSET * 2, 0.5F * (signIds.length), 0.5F, SMALL_OFFSET * 2, facing, backgroundColor + ARGB_BLACK, MAX_LIGHT_GLOWING);
}
for (int i = 0; i < signIds.length; i++) {
if (signIds[i] != null) {
drawSign(matrices, vertexConsumers, dispatcher.getTextRenderer(), pos, signIds[i], 0.5F * i, 0, 0.5F, i, signIds.length - i - 1, entity.getSelectedIds(), facing, (textureId, x, y, size, flipTexture) -> {
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getLight(new Identifier(textureId.toString())));
IDrawing.drawTexture(matrices, vertexConsumer, x, y, size, size, flipTexture ? 1 : 0, 0, flipTexture ? 0 : 1, 1, facing, -1, MAX_LIGHT_GLOWING);
});
}
}
matrices.pop();
}
@Override
public boolean rendersOutsideBoundingBox(T blockEntity) {
return true;
}
public static void drawSign(MatrixStack matrices, VertexConsumerProvider vertexConsumers, TextRenderer textRenderer, BlockPos pos, String signId, float x, float y, float size, float maxWidthLeft, float maxWidthRight, Set<Long> selectedIds, Direction facing, DrawTexture drawTexture) {
if (RenderTrains.shouldNotRender(pos, RenderTrains.maxTrainRenderDistance, facing)) {
return;
}
final CustomResources.CustomSign sign = getSign(signId);
if (sign == null) {
return;
}
final float signSize = (sign.small ? BlockRailwaySign.SMALL_SIGN_PERCENTAGE : 1) * size;
final float margin = (size - signSize) / 2;
final boolean hasCustomText = sign.hasCustomText();
final boolean flipCustomText = sign.flipCustomText;
final boolean flipTexture = sign.flipTexture;
final boolean isExit = signId.equals(BlockRailwaySign.SignType.EXIT_LETTER.toString()) || signId.equals(BlockRailwaySign.SignType.EXIT_LETTER_FLIPPED.toString());
final boolean isLine = signId.equals(BlockRailwaySign.SignType.LINE.toString()) || signId.equals(BlockRailwaySign.SignType.LINE_FLIPPED.toString());
final boolean isPlatform = signId.equals(BlockRailwaySign.SignType.PLATFORM.toString()) || signId.equals(BlockRailwaySign.SignType.PLATFORM_FLIPPED.toString());
final VertexConsumerProvider.Immediate immediate = RenderTrains.shouldNotRender(pos, RenderTrains.maxTrainRenderDistance / 2, null) ? null : VertexConsumerProvider.immediate(Tessellator.getInstance().getBuffer());
if (vertexConsumers != null && isExit) {
final Station station = ClientData.getStation(pos);
if (station == null) {
return;
}
final Map<String, List<String>> exits = station.getGeneratedExits();
final List<String> selectedExitsSorted = selectedIds.stream().map(Station::deserializeExit).filter(exits::containsKey).sorted(String::compareTo).collect(Collectors.toList());
matrices.push();
matrices.translate(x + margin + (flipCustomText ? signSize : 0), y + margin, 0);
final float maxWidth = ((flipCustomText ? maxWidthLeft : maxWidthRight) + 1) * size - margin * 2;
final float exitWidth = signSize * selectedExitsSorted.size();
matrices.scale(Math.min(1, maxWidth / exitWidth), 1, 1);
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getLight(new Identifier("mtr:textures/sign/exit_letter_blank.png")));
for (int i = 0; i < selectedExitsSorted.size(); i++) {
final String selectedExit = selectedExitsSorted.get(flipCustomText ? selectedExitsSorted.size() - i - 1 : i);
final float offset = (flipCustomText ? -1 : 1) * signSize * i - (flipCustomText ? signSize : 0);
IDrawing.drawTexture(matrices, vertexConsumer, offset, 0, SMALL_OFFSET, offset + signSize, signSize, SMALL_OFFSET, facing, -1, MAX_LIGHT_GLOWING);
final String selectedExitLetter = selectedExit.substring(0, 1);
final String selectedExitNumber = selectedExit.substring(1);
final boolean hasNumber = !selectedExitNumber.isEmpty();
final float space = hasNumber ? margin * 1.5F : 0;
IDrawing.drawStringWithFont(matrices, textRenderer, immediate, selectedExitLetter, hasNumber ? HorizontalAlignment.LEFT : HorizontalAlignment.CENTER, VerticalAlignment.CENTER, offset + (hasNumber ? margin : signSize / 2), signSize / 2 + margin, signSize - margin * 2 - space, signSize - margin, 1, ARGB_WHITE, false, MAX_LIGHT_GLOWING, null);
if (hasNumber) {
IDrawing.drawStringWithFont(matrices, textRenderer, immediate, selectedExitNumber, HorizontalAlignment.RIGHT, VerticalAlignment.TOP, offset + signSize - margin, signSize / 2, space, signSize / 2 - margin / 4, 1, ARGB_WHITE, false, MAX_LIGHT_GLOWING, null);
}
if (maxWidth > exitWidth && selectedExitsSorted.size() == 1 && !exits.get(selectedExit).isEmpty()) {
IDrawing.drawStringWithFont(matrices, textRenderer, immediate, exits.get(selectedExit).get(0), flipCustomText ? HorizontalAlignment.RIGHT : HorizontalAlignment.LEFT, VerticalAlignment.CENTER, flipCustomText ? offset - margin : offset + signSize + margin, signSize / 2, maxWidth - exitWidth - margin * 2, signSize, HEIGHT_TO_SCALE / signSize, ARGB_WHITE, false, MAX_LIGHT_GLOWING, null);
}
}
matrices.pop();
} else if (vertexConsumers != null && isLine) {
final Station station = ClientData.getStation(pos);
if (station == null) {
return;
}
final Map<Integer, ClientCache.ColorNamePair> routesInStation = ClientData.DATA_CACHE.stationIdToRoutes.get(station.id);
if (routesInStation != null) {
final List<ClientCache.ColorNamePair> selectedIdsSorted = selectedIds.stream().filter(selectedId -> RailwayData.isBetween(selectedId, Integer.MIN_VALUE, Integer.MAX_VALUE)).map(Math::toIntExact).filter(routesInStation::containsKey).map(routesInStation::get).sorted(Comparator.comparingInt(route -> route.color)).collect(Collectors.toList());
final int selectedCount = selectedIdsSorted.size();
final float maxWidth = Math.max(0, ((flipCustomText ? maxWidthLeft : maxWidthRight) + 1) * size - margin * 1.5F);
final List<Float> textWidths = new ArrayList<>();
for (final ClientCache.ColorNamePair route : selectedIdsSorted) {
IDrawing.drawStringWithFont(matrices, textRenderer, null, route.name, HorizontalAlignment.LEFT, VerticalAlignment.CENTER, 0, 10000, -1, size - margin * 3, HEIGHT_TO_SCALE / (size - margin * 3), 0, false, MAX_LIGHT_GLOWING, (x1, y1, x2, y2) -> textWidths.add(x2));
}
matrices.push();
matrices.translate(flipCustomText ? x + size - margin : x + margin, 0, 0);
final float totalTextWidth = textWidths.stream().reduce(Float::sum).orElse(0F) + 1.5F * margin * selectedCount;
if (totalTextWidth > maxWidth) {
matrices.scale((maxWidth - margin / 2) / (totalTextWidth - margin / 2), 1, 1);
}
final VertexConsumer vertexConsumer = vertexConsumers.getBuffer(MoreRenderLayers.getLight(new Identifier("mtr:textures/block/white.png")));
float xOffset = margin * 0.5F;
for (int i = 0; i < selectedIdsSorted.size(); i++) {
final ClientCache.ColorNamePair route = selectedIdsSorted.get(i);
IDrawing.drawStringWithFont(matrices, textRenderer, immediate, route.name, flipCustomText ? HorizontalAlignment.RIGHT : HorizontalAlignment.LEFT, VerticalAlignment.CENTER, flipCustomText ? -xOffset : xOffset, y + size / 2, -1, size - margin * 3, HEIGHT_TO_SCALE / (size - margin * 3), ARGB_WHITE, false, MAX_LIGHT_GLOWING, (x1, y1, x2, y2) -> IDrawing.drawTexture(matrices, vertexConsumer, x1 - margin / 2, y + margin, SMALL_OFFSET, x2 + margin / 2, y + size - margin, SMALL_OFFSET, facing, route.color + ARGB_BLACK, MAX_LIGHT_GLOWING));
xOffset += textWidths.get(i) + margin * 1.5F;
}
matrices.pop();
}
} else if (vertexConsumers != null && isPlatform) {
final Station station = ClientData.getStation(pos);
if (station == null) {
return;
}
final Map<Long, Platform> platformPositions = ClientData.DATA_CACHE.requestStationIdToPlatforms(station.id);
if (platformPositions != null) {
final List<Platform> selectedIdsSorted = selectedIds.stream().filter(platformPositions::containsKey).map(platformPositions::get).sorted(NameColorDataBase::compareTo).collect(Collectors.toList());
final int selectedCount = selectedIdsSorted.size();
final float smallPadding = margin / selectedCount;
final float height = (size - margin * 2 + smallPadding) / selectedCount;
final List<RenderingInstruction> renderingInstructions = new ArrayList<>();
for (int i = 0; i < selectedIdsSorted.size(); i++) {
final float topOffset = i * height + margin;
final float bottomOffset = (i + 1) * height + margin - smallPadding;
final RouteRenderer routeRenderer = new RouteRenderer(renderingInstructions, selectedIdsSorted.get(i), true, true);
routeRenderer.renderArrow((flipCustomText ? x - maxWidthLeft * size : x) + margin, (flipCustomText ? x + size : x + (maxWidthRight + 1) * size) - margin, topOffset, bottomOffset, flipCustomText, !flipCustomText, facing, MAX_LIGHT_GLOWING, false);
}
RenderingInstruction.render(matrices, vertexConsumers, immediate, renderingInstructions);
}
} else {
drawTexture.drawTexture(sign.textureId, x + margin, y + margin, signSize, flipTexture);
if (hasCustomText) {
final float fixedMargin = size * (1 - BlockRailwaySign.SMALL_SIGN_PERCENTAGE) / 2;
final boolean isSmall = sign.small;
final float maxWidth = Math.max(0, (flipCustomText ? maxWidthLeft : maxWidthRight) * size - fixedMargin * (isSmall ? 1 : 2));
final float start = flipCustomText ? x - (isSmall ? 0 : fixedMargin) : x + size + (isSmall ? 0 : fixedMargin);
IDrawing.drawStringWithFont(matrices, textRenderer, immediate, isExit || isLine ? "..." : sign.customText, flipCustomText ? HorizontalAlignment.RIGHT : HorizontalAlignment.LEFT, VerticalAlignment.TOP, start, y + fixedMargin, maxWidth, size - fixedMargin * 2, 0.01F, ARGB_WHITE, false, MAX_LIGHT_GLOWING, null);
}
}
if (immediate != null) {
immediate.draw();
}
}
public static CustomResources.CustomSign getSign(String signId) {
try {
final BlockRailwaySign.SignType sign = BlockRailwaySign.SignType.valueOf(signId);
return new CustomResources.CustomSign(sign.textureId, sign.flipTexture, sign.customText, sign.flipCustomText, sign.small, sign.backgroundColor);
} catch (Exception ignored) {
return signId == null ? null : CustomResources.customSigns.get(signId);
}
}
@FunctionalInterface
public interface DrawTexture {
void drawTexture(Identifier textureId, float x, float y, float size, boolean flipTexture);
}
}
|
package net.bootsfaces.demo;
/*
* A Bean Used for Demo purposes
*/
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* @author TheCoder4eu
*/
@ManagedBean
@ViewScoped
public class TestBean implements Serializable {
private static final long serialVersionUID = -332002335165889800L;
private int val1 = 78;
private int val2 = 87;
private int val3 = 34;
private int val4 = 43;
private int val5 = 12;
private int val6 = 30;
private String label1 = "Label One";
private String label2 = "Label Two";
private String text1 = "Text One";
private String text2 = "Text Two";
private int index = 2;
public void nextTab() {
index++;
if (index > 3)
index = 0;
}
public int getVal1() {
return val1;
}
public void setVal1(int val1) {
this.val1 = val1;
}
public int getVal2() {
return val2;
}
public void setVal2(int val2) {
this.val2 = val2;
}
public String getLabel1() {
return label1;
}
public void setLabel1(String label1) {
this.label1 = label1;
}
public String getLabel2() {
return label2;
}
public void setLabel2(String label2) {
this.label2 = label2;
}
public int getVal3() {
return val3;
}
public void setVal3(int val3) {
this.val3 = val3;
}
public int getVal4() {
return val4;
}
public void setVal4(int val4) {
this.val4 = val4;
}
public int getVal5() {
return val5;
}
public void setVal5(int val5) {
this.val5 = val5;
}
public int getVal6() {
return val6;
}
public void setVal6(int val6) {
this.val6 = val6;
}
public String getText1() {
return text1;
}
public void setText1(String text1) {
this.text1 = text1;
}
public String getText2() {
return text2;
}
public void setText2(String text2) {
this.text2 = text2;
}
/**
* Creates a new instance of informBean
*/
public TestBean() {
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
|
package dr.evomodel.treelikelihood;
import dr.evolution.alignment.*;
import dr.evolution.datatype.DataType;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.TaxonList;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DefaultBranchRateModel;
import dr.evomodel.sitemodel.SiteModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.*;
import dr.xml.*;
import java.util.logging.Logger;
/**
* TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $
*/
public class TreeLikelihood extends AbstractTreeLikelihood {
public static final String TREE_LIKELIHOOD = "treeLikelihood";
public static final String USE_AMBIGUITIES = "useAmbiguities";
public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa";
public static final String STORE_PARTIALS = "storePartials";
public static final String SCALING_FACTOR = "scalingFactor";
public static final String SCALING_THRESHOLD = "scalingThreshold";
public static final String FORCE_JAVA_CORE = "forceJavaCore";
public static final String FORCE_RESCALING = "forceRescaling";
/**
* Constructor.
*/
public TreeLikelihood(PatternList patternList,
TreeModel treeModel,
SiteModel siteModel,
BranchRateModel branchRateModel,
TipPartialsModel tipPartialsModel,
boolean useAmbiguities,
boolean allowMissingTaxa,
boolean storePartials,
boolean forceJavaCore,
boolean forceRescaling) {
super(TREE_LIKELIHOOD, patternList, treeModel);
this.storePartials = storePartials;
try {
this.siteModel = siteModel;
addModel(siteModel);
this.frequencyModel = siteModel.getFrequencyModel();
addModel(frequencyModel);
this.tipPartialsModel = tipPartialsModel;
integrateAcrossCategories = siteModel.integrateAcrossCategories();
this.categoryCount = siteModel.getCategoryCount();
final Logger logger = Logger.getLogger("dr.evomodel");
String coreName = "Java general";
if (integrateAcrossCategories) {
final DataType dataType = patternList.getDataType();
if (dataType instanceof dr.evolution.datatype.Nucleotides) {
if (!forceJavaCore && NativeNucleotideLikelihoodCore.isAvailable()) {
coreName = "native nucleotide";
likelihoodCore = new NativeNucleotideLikelihoodCore();
} else {
coreName = "Java nucleotide";
likelihoodCore = new NucleotideLikelihoodCore();
}
} else if (dataType instanceof dr.evolution.datatype.AminoAcids) {
if (!forceJavaCore && NativeAminoAcidLikelihoodCore.isAvailable()) {
coreName = "native amino acid";
likelihoodCore = new NativeAminoAcidLikelihoodCore();
} else {
coreName = "Java amino acid";
likelihoodCore = new AminoAcidLikelihoodCore();
}
} else if (dataType instanceof dr.evolution.datatype.Codons) {
// The codon core was out of date and did nothing more than the general core...
likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
useAmbiguities = true;
} else {
if (!forceJavaCore && NativeGeneralLikelihoodCore.isAvailable()) {
coreName = "native general";
likelihoodCore = new NativeGeneralLikelihoodCore(patternList.getStateCount());
} else {
coreName = "Java general";
likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
}
}
} else {
likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
}
logger.info("TreeLikelihood using " + coreName + " likelihood core");
logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
logger.info(" With " + patternList.getPatternCount() + " unique site patterns.");
if (branchRateModel != null) {
this.branchRateModel = branchRateModel;
logger.info("Branch rate model used: " + branchRateModel.getModelName());
} else {
this.branchRateModel = new DefaultBranchRateModel();
}
addModel(this.branchRateModel);
probabilities = new double[stateCount * stateCount];
likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories);
int extNodeCount = treeModel.getExternalNodeCount();
int intNodeCount = treeModel.getInternalNodeCount();
if (tipPartialsModel != null) {
tipPartialsModel.setTree(treeModel);
tipPartials = new double[patternCount * stateCount];
for (int i = 0; i < extNodeCount; i++) {
// Find the id of tip i in the patternList
String id = treeModel.getTaxonId(i);
int index = patternList.getTaxonIndex(id);
if (index == -1) {
throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
", is not found in patternList, " + patternList.getId());
}
tipPartialsModel.setStates(patternList, index, i, id);
likelihoodCore.createNodePartials(i);
}
addModel(tipPartialsModel);
useAmbiguities = true;
} else {
for (int i = 0; i < extNodeCount; i++) {
// Find the id of tip i in the patternList
String id = treeModel.getTaxonId(i);
int index = patternList.getTaxonIndex(id);
if (index == -1) {
if (!allowMissingTaxa) {
throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
", is not found in patternList, " + patternList.getId());
}
if (useAmbiguities) {
setMissingPartials(likelihoodCore, i);
} else {
setMissingStates(likelihoodCore, i);
}
} else {
if (useAmbiguities) {
setPartials(likelihoodCore, patternList, categoryCount, index, i);
} else {
setStates(likelihoodCore, patternList, index, i);
}
}
}
}
for (int i = 0; i < intNodeCount; i++) {
likelihoodCore.createNodePartials(extNodeCount + i);
}
if (forceRescaling) {
likelihoodCore.setUseScaling(true);
logger.info(" Forcing use of partials rescaling.");
}
} catch (TaxonList.MissingTaxonException mte) {
throw new RuntimeException(mte.toString());
}
addStatistic(new SiteLikelihoodsStatistic());
}
public final LikelihoodCore getLikelihoodCore() {
return likelihoodCore;
}
// ModelListener IMPLEMENTATION
/**
* Handles model changed events from the submodels.
*/
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (model == treeModel) {
if (object instanceof TreeModel.TreeChangedEvent) {
if (((TreeModel.TreeChangedEvent) object).isNodeChanged()) {
// If a node event occurs the node and its two child nodes
// are flagged for updating (this will result in everything
// above being updated as well. Node events occur when a node
// is added to a branch, removed from a branch or its height or
// rate changes.
updateNodeAndChildren(((TreeModel.TreeChangedEvent) object).getNode());
} else if (((TreeModel.TreeChangedEvent) object).isTreeChanged()) {
// Full tree events result in a complete updating of the tree likelihood
// Currently this event type is not used.
System.err.println("Full tree update event - these events currently aren't used\n" +
"so either this is in error or a new feature is using them so remove this message.");
updateAllNodes();
} else {
// Other event types are ignored (probably trait changes).
//System.err.println("Another tree event has occured (possibly a trait change).");
}
}
} else if (model == branchRateModel) {
if (index == -1) {
updateAllNodes();
} else {
updateNode(treeModel.getNode(index));
}
} else if (model == frequencyModel) {
updateAllNodes();
} else if (model == tipPartialsModel) {
updateAllNodes();
} else if (model instanceof SiteModel) {
updateAllNodes();
} else {
throw new RuntimeException("Unknown componentChangedEvent");
}
super.handleModelChangedEvent(model, object, index);
}
// Model IMPLEMENTATION
/**
* Stores the additional state other than model components
*/
protected void storeState() {
if (storePartials) {
likelihoodCore.storeState();
}
super.storeState();
}
/**
* Restore the additional stored state
*/
protected void restoreState() {
if (storePartials) {
likelihoodCore.restoreState();
} else {
updateAllNodes();
}
super.restoreState();
}
// Likelihood IMPLEMENTATION
/**
* Calculate the log likelihood of the current state.
*
* @return the log likelihood.
*/
protected double calculateLogLikelihood() {
if (patternLogLikelihoods == null) {
patternLogLikelihoods = new double[patternCount];
}
if (!integrateAcrossCategories) {
if (siteCategories == null) {
siteCategories = new int[patternCount];
}
for (int i = 0; i < patternCount; i++) {
siteCategories[i] = siteModel.getCategoryOfSite(i);
}
}
if (tipPartialsModel != null) {
int extNodeCount = treeModel.getExternalNodeCount();
for (int index = 0; index < extNodeCount; index++) {
if (updateNode[index]) {
likelihoodCore.setNodePartialsForUpdate(index);
tipPartialsModel.getTipPartials(index, tipPartials);
likelihoodCore.setCurrentNodePartials(index, tipPartials);
}
}
}
final NodeRef root = treeModel.getRoot();
traverse(treeModel, root);
double logL = 0.0;
double ascertainmentCorrection = getAscertainmentCorrection(patternLogLikelihoods);
for (int i = 0; i < patternCount; i++) {
logL += (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
}
if (logL == Double.NEGATIVE_INFINITY) {
Logger.getLogger("dr.evomodel").info("TreeLikelihood, " + this.getId() + ", turning on partial likelihood scaling to avoid precision loss");
// We probably had an underflow... turn on scaling
likelihoodCore.setUseScaling(true);
// and try again...
updateAllNodes();
updateAllPatterns();
traverse(treeModel, root);
logL = 0.0;
ascertainmentCorrection = getAscertainmentCorrection(patternLogLikelihoods);
for (int i = 0; i < patternCount; i++) {
logL += (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
}
}
/* Calculate ascertainment correction if working off of AscertainedSitePatterns
@param patternProbs log pattern probabilities
@return the log total probability for a pattern.
*/
protected double getAscertainmentCorrection(double[] patternProbs) {
// This function probably belongs better to the AscertainedSitePatterns
double excludeProb = 0, includeProb = 0, returnProb = 1.0;
if (patternList instanceof AscertainedSitePatterns) {
int[] includeIndices = ((AscertainedSitePatterns) patternList).getIncludePatternIndices();
int[] excludeIndices = ((AscertainedSitePatterns) patternList).getExcludePatternIndices();
for (int i = 0; i < ((AscertainedSitePatterns) patternList).getIncludePatternCount(); i++) {
int index = includeIndices[i];
includeProb += Math.exp(patternProbs[index]);
}
for (int j = 0; j < ((AscertainedSitePatterns) patternList).getExcludePatternCount(); j++) {
int index = excludeIndices[j];
excludeProb += Math.exp(patternProbs[index]);
}
if (includeProb == 0.0) {
returnProb -= excludeProb;
} else if (excludeProb == 0.0) {
returnProb = includeProb;
} else {
returnProb = includeProb - excludeProb;
}
}
return Math.log(returnProb);
}
/**
* Check whether the scaling is still required. If the sum of all the logScalingFactors
* is zero then we simply turn off the useScaling flag. This will speed up the likelihood
* calculations when scaling is not required.
*/
public void checkScaling() {
// if (useScaling) {
// if (scalingCheckCount % 1000 == 0) {
// double totalScalingFactor = 0.0;
// for (int i = 0; i < nodeCount; i++) {
// for (int j = 0; j < patternCount; j++) {
// totalScalingFactor += scalingFactors[currentPartialsIndices[i]][i][j];
// useScaling = totalScalingFactor < 0.0;
// Logger.getLogger("dr.evomodel").info("LikelihoodCore total log scaling factor: " + totalScalingFactor);
// if (!useScaling) {
// Logger.getLogger("dr.evomodel").info("LikelihoodCore scaling turned off.");
// scalingCheckCount++;
}
/**
* Traverse the tree calculating partial likelihoods.
*
* @return whether the partials for this node were recalculated.
*/
protected boolean traverse(Tree tree, NodeRef node) {
boolean update = false;
int nodeNum = node.getNumber();
NodeRef parent = tree.getParent(node);
// First update the transition probability matrix(ices) for this branch
if (parent != null && updateNode[nodeNum]) {
final double branchRate = branchRateModel.getBranchRate(tree, node);
// Get the operational time of the branch
final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
if (branchTime < 0.0) {
throw new RuntimeException("Negative branch length: " + branchTime);
}
likelihoodCore.setNodeMatrixForUpdate(nodeNum);
for (int i = 0; i < categoryCount; i++) {
double branchLength = siteModel.getRateForCategory(i) * branchTime;
siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
}
update = true;
}
// If the node is internal, update the partial likelihoods.
if (!tree.isExternal(node)) {
// Traverse down the two child nodes
NodeRef child1 = tree.getChild(node, 0);
final boolean update1 = traverse(tree, child1);
NodeRef child2 = tree.getChild(node, 1);
final boolean update2 = traverse(tree, child2);
// If either child node was updated then update this node too
if (update1 || update2) {
final int childNum1 = child1.getNumber();
final int childNum2 = child2.getNumber();
likelihoodCore.setNodePartialsForUpdate(nodeNum);
if (integrateAcrossCategories) {
likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
} else {
likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories);
}
if (COUNT_TOTAL_OPERATIONS) {
totalOperationCount ++;
}
if (parent == null) {
// No parent this is the root of the tree -
// calculate the pattern likelihoods
double[] frequencies = frequencyModel.getFrequencies();
double[] partials = getRootPartials();
likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods);
}
update = true;
}
}
return update;
}
public final double[] getRootPartials() {
if (rootPartials == null) {
rootPartials = new double[patternCount * stateCount];
}
int nodeNum = treeModel.getRoot().getNumber();
if (integrateAcrossCategories) {
// moved this call to here, because non-integrating siteModels don't need to support it - AD
double[] proportions = siteModel.getCategoryProportions();
likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
} else {
likelihoodCore.getPartials(nodeNum, rootPartials);
}
return rootPartials;
}
/**
* the root partial likelihoods (a temporary array that is used
* to fetch the partials - it should not be examined directly -
* use getRootPartials() instead).
*/
private double[] rootPartials = null;
public class SiteLikelihoodsStatistic extends Statistic.Abstract {
public SiteLikelihoodsStatistic() {
super("siteLikelihoods");
}
public int getDimension() {
if (patternList instanceof SitePatterns) {
return ((SitePatterns)patternList).getSiteCount();
} else {
return patternList.getPatternCount();
}
}
public String getDimensionName(int dim) {
return getTreeModel().getId() + "site-" + dim;
}
public double getStatisticValue(int i) {
if (patternList instanceof SitePatterns) {
int index = ((SitePatterns)patternList).getPatternIndex(i);
if( index >= 0 ) {
return patternLogLikelihoods[index] / patternWeights[index];
} else {
return 0.0;
}
} else {
return patternList.getPatternCount();
}
}
}
/**
* The XML parser
*/
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return TREE_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false);
boolean allowMissingTaxa = xo.getAttribute(ALLOW_MISSING_TAXA, false);
boolean storePartials = xo.getAttribute(STORE_PARTIALS, true);
boolean forceJavaCore = xo.getAttribute(FORCE_JAVA_CORE, false);
if (Boolean.valueOf(System.getProperty("java_only"))) {
forceJavaCore = true;
}
PatternList patternList = (PatternList) xo.getChild(PatternList.class);
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
TipPartialsModel tipPartialsModel = (TipPartialsModel) xo.getChild(TipPartialsModel.class);
boolean forceRescaling = xo.getAttribute(FORCE_RESCALING,false);
return new TreeLikelihood(
patternList,
treeModel,
siteModel,
branchRateModel,
tipPartialsModel,
useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore, forceRescaling);
}
/**
* the frequency model for these sites
*/
protected final FrequencyModel frequencyModel;
/**
* the site model for these sites
*/
protected final SiteModel siteModel;
/**
* the branch rate model
*/
protected final BranchRateModel branchRateModel;
/**
* the tip partials model
*/
private final TipPartialsModel tipPartialsModel;
private final boolean storePartials;
protected final boolean integrateAcrossCategories;
/**
* the categories for each site
*/
protected int[] siteCategories = null;
/**
* the pattern likelihoods
*/
protected double[] patternLogLikelihoods = null;
/**
* the number of rate categories
*/
protected int categoryCount;
/**
* an array used to transfer transition probabilities
*/
protected double[] probabilities;
/**
* an array used to transfer tip partials
*/
protected double[] tipPartials;
/**
* the LikelihoodCore
*/
protected LikelihoodCore likelihoodCore;
}
|
package net.sf.jabref.logic.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DOI {
private static final Log LOGGER = LogFactory.getLog(DOI.class);
// DOI resolver
public static final URI RESOLVER = URI.create("http://doi.org");
// Regex
private static final String DOI_EXP = ""
+ "(?:urn:)?" // optional urn
+ "(?:doi:)?" // optional doi
+ "(" // begin group \1
+ "10" // directory indicator
+ "(?:\\.[0-9]+)+" // registrant codes
+ "[/:]" // divider
+ "(?:.+)" // suffix alphanumeric string
+ ")"; // end group \1
private static final String HTTP_EXP = "https?://[^\\s]+?" + DOI_EXP;
// Pattern
private static final Pattern DOI_PATT = Pattern.compile("^(?:https?://[^\\s]+?)?" + DOI_EXP + "$", Pattern.CASE_INSENSITIVE);
public static Optional<DOI> build(String doi) {
try {
return Optional.of(new DOI(doi));
} catch(NullPointerException | IllegalArgumentException e) {
return Optional.empty();
}
}
// DOI
private final String doi;
public DOI(String doi) {
Objects.requireNonNull(doi);
// Remove whitespace
doi = doi.trim();
// HTTP URL decoding
if(doi.matches(HTTP_EXP)) {
try {
// decodes path segment
URI url = new URI(doi);
doi = url.getScheme() + "://" + url.getHost() + url.getPath();
} catch(URISyntaxException e) {
throw new IllegalArgumentException(doi + " is not a valid HTTP DOI.");
}
}
// Extract DOI
Matcher matcher = DOI_PATT.matcher(doi);
if (matcher.find()) {
// match only group \1
this.doi = matcher.group(1);
} else {
throw new IllegalArgumentException(doi + " is not a valid DOI.");
}
}
/**
* Return the plain DOI
*
* @return the plain DOI value.
*/
public String getDOI() {
return doi;
}
/**
* Return a URI presentation for the DOI
*
* @return an encoded URI representation of the DOI
*/
public URI getURI() {
try {
URI uri = new URI(RESOLVER.getScheme(), RESOLVER.getHost(), "/" + doi, null);
return uri;
} catch(URISyntaxException e) {
// should never happen
LOGGER.error(doi + " could not be encoded as URI.");
return null;
}
}
/**
* Return an ASCII URL presentation for the DOI
*
* @return an encoded URL representation of the DOI
*/
public String getURLAsASCIIString() {
return getURI().toASCIIString();
}
}
|
package dr.inferencexml.distribution;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import jebl.math.Binomial;
import dr.evolution.coalescent.Coalescent;
import dr.evolution.io.Importer.ImportException;
import dr.evolution.io.TreeTrace;
import dr.evomodel.tree.ConditionalCladeFrequency;
import dr.evomodel.tree.TreeModel;
import dr.inference.distribution.ConditionalCladeProbability;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.distribution.MultivariateDistributionLikelihood;
import dr.inference.model.Likelihood;
import dr.inference.model.Statistic;
import dr.inference.trace.LogFileTraces;
import dr.inference.trace.TraceException;
import dr.math.distributions.BetaDistribution;
import dr.math.distributions.ExponentialDistribution;
import dr.math.distributions.GammaDistribution;
import dr.math.distributions.GammaKDEDistribution;
import dr.math.distributions.HalfTDistribution;
import dr.math.distributions.InverseGammaDistribution;
import dr.math.distributions.LaplaceDistribution;
import dr.math.distributions.LogNormalDistribution;
import dr.math.distributions.LogTransformedNormalKDEDistribution;
import dr.math.distributions.MultivariateGammaDistribution;
import dr.math.distributions.MultivariateKDEDistribution;
import dr.math.distributions.NormalDistribution;
import dr.math.distributions.NormalKDEDistribution;
import dr.math.distributions.PoissonDistribution;
import dr.math.distributions.UniformDistribution;
import dr.stats.DiscreteStatistics;
import dr.util.FileHelpers;
import dr.xml.AbstractXMLObjectParser;
import dr.xml.AttributeRule;
import dr.xml.ElementRule;
import dr.xml.XMLObject;
import dr.xml.XMLObjectParser;
import dr.xml.XMLParseException;
import dr.xml.XMLSyntaxRule;
import dr.xml.XORRule;
public class PriorParsers {
public static final String UNIFORM_PRIOR = "uniformPrior";
public static final String EXPONENTIAL_PRIOR = "exponentialPrior";
public static final String POISSON_PRIOR = "poissonPrior";
public static final String NORMAL_PRIOR = "normalPrior";
public static final String NORMAL_REFERENCE_PRIOR = "normalReferencePrior";
public static final String CONDITIONAL_CLADE_REFERENCE_PRIOR = "conditionalCladeProbability";
public static final String COALESCENT_HEIGHTS_REFERENCE_PRIOR = "coalescentHeightsReferencePrior";
public final static String BURNIN = "burnin";
public final static String EPSILON = "epsilon";
public static final String LOG_TRANSFORMED_NORMAL_REFERENCE_PRIOR = "logTransformedNormalReferencePrior";
public static final String LOG_NORMAL_PRIOR = "logNormalPrior";
public static final String GAMMA_PRIOR = "gammaPrior";
public static final String GAMMA_REFERENCE_PRIOR = "gammaReferencePrior";
public static final String INVGAMMA_PRIOR = "invgammaPrior";
public static final String INVGAMMA_PRIOR_CORRECT = "inverseGammaPrior";
public static final String LAPLACE_PRIOR = "laplacePrior";
public static final String BETA_PRIOR = "betaPrior";
public static final String PARAMETER_COLUMN = "parameterColumn";
public static final String UPPER = "upper";
public static final String LOWER = "lower";
public static final String MEAN = "mean";
public static final String MEAN_IN_REAL_SPACE = "meanInRealSpace";
public static final String STDEV = "stdev";
public static final String SHAPE = "shape";
public static final String SHAPEB = "shapeB";
public static final String SCALE = "scale";
public static final String DF = "df";
public static final String OFFSET = "offset";
public static final String UNINFORMATIVE = "uninformative";
public static final String HALF_T_PRIOR = "halfTPrior";
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser UNIFORM_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return UNIFORM_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double lower = xo.getDoubleAttribute(LOWER);
double upper = xo.getDoubleAttribute(UPPER);
if (lower == Double.NEGATIVE_INFINITY || upper == Double.POSITIVE_INFINITY)
throw new XMLParseException("Uniform prior " + xo.getName() + " cannot take a bound at infinity, " +
"because it returns 1/(high-low) = 1/inf");
DistributionLikelihood likelihood = new DistributionLikelihood(new UniformDistribution(lower, upper));
System.out.println("Uniform prior: " + xo.getChildCount());
for (int j = 0; j < xo.getChildCount(); j++) {
System.out.println(xo.getChild(j));
if (xo.getChild(j) instanceof Statistic) {
//System.out.println((Statistic) xo.getChild(j));
Statistic test = (Statistic) xo.getChild(j);
System.out.println(test.getDimension());
for (int i = 0; i < test.getDimension(); i++) {
System.out.println(" " + test.getDimensionName(i) + " - " + test.getStatisticValue(i));
}
System.out.println(test.getClass());
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(LOWER),
AttributeRule.newDoubleRule(UPPER),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given uniform distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser EXPONENTIAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return EXPONENTIAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double scale;
if (xo.hasAttribute(SCALE)) {
scale = xo.getDoubleAttribute(SCALE);
} else {
scale = xo.getDoubleAttribute(MEAN);
}
final double offset = xo.hasAttribute(OFFSET) ? xo.getDoubleAttribute(OFFSET) : 0.0;
DistributionLikelihood likelihood = new DistributionLikelihood(new ExponentialDistribution(1.0 / scale), offset);
System.out.println("Exponential prior: " + xo.getChildCount());
for (int j = 0; j < xo.getChildCount(); j++) {
System.out.println(xo.getChild(j));
if (xo.getChild(j) instanceof Statistic) {
//System.out.println((Statistic) xo.getChild(j));
Statistic test = (Statistic) xo.getChild(j);
System.out.println(test.getDimension());
for (int i = 0; i < test.getDimension(); i++) {
System.out.println(" " + test.getDimensionName(i) + " - " + test.getStatisticValue(i));
}
System.out.println(test.getClass());
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new XORRule(
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(MEAN)
),
AttributeRule.newDoubleRule(OFFSET, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given exponential distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser POISSON_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return POISSON_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double offset = xo.getDoubleAttribute(OFFSET);
DistributionLikelihood likelihood = new DistributionLikelihood(new PoissonDistribution(mean), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(OFFSET),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given poisson distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser HALF_T_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return HALF_T_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double scale = xo.getDoubleAttribute(SCALE);
double df = xo.getDoubleAttribute(DF);
DistributionLikelihood likelihood = new DistributionLikelihood(new HalfTDistribution(scale, df));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(DF),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given half-T distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser NORMAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NORMAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double stdev = xo.getDoubleAttribute(STDEV);
DistributionLikelihood likelihood = new DistributionLikelihood(new NormalDistribution(mean, stdev));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(STDEV),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of reference priors on parameters.
*/
public static XMLObjectParser GAMMA_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return GAMMA_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int traceIndexParameter = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(parameterName)) {
traceIndexParameter = i;
}
}
if (traceIndexParameter == -1) {
throw new XMLParseException("Column '" + parameterName + "' can not be found for " + getParserName() + " element.");
}
Double[] parameterSamples = new Double[traces.getStateCount()];
DistributionLikelihood likelihood = new DistributionLikelihood(new GammaKDEDistribution((Double[]) traces.getValues(traceIndexParameter).toArray(parameterSamples)));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the reference prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of reference priors on parameters.
*/
public static XMLObjectParser LOG_TRANSFORMED_NORMAL_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return LOG_TRANSFORMED_NORMAL_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int traceIndexParameter = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(parameterName)) {
traceIndexParameter = i;
}
}
if (traceIndexParameter == -1) {
throw new XMLParseException("Column '" + parameterName + "' can not be found for " + getParserName() + " element.");
}
Double[] parameterSamples = new Double[traces.getStateCount()];
traces.getValues(traceIndexParameter).toArray(parameterSamples);
DistributionLikelihood likelihood = new DistributionLikelihood(new LogTransformedNormalKDEDistribution(parameterSamples));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the reference prior probability of some data under log transformed normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of reference priors on parameters.
*/
public static XMLObjectParser NORMAL_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NORMAL_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int traceIndexParameter = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(parameterName)) {
traceIndexParameter = i;
}
}
if (traceIndexParameter == -1) {
throw new XMLParseException("Column '" + parameterName + "' can not be found for " + getParserName() + " element.");
}
Double[] parameterSamples = new Double[traces.getStateCount()];
DistributionLikelihood likelihood = new DistributionLikelihood(new NormalKDEDistribution((Double[]) traces.getValues(traceIndexParameter).toArray(parameterSamples)));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the reference prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads coalescent heights and builds reference priors for them.
*/
public static XMLObjectParser COALESCENT_HEIGHTS_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return COALESCENT_HEIGHTS_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
int dimension = xo.getIntegerAttribute("dimension");
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int[] traceIndexParameter = new int[dimension];
for (int i = 0; i < traceIndexParameter.length; i++) {
traceIndexParameter[i] = -1;
}
String[] columnNames = new String[dimension];
for (int i = 1; i <= columnNames.length; i++) {
columnNames[i-1] = parameterName + i;
}
System.out.println("Looking for the following columns:");
for (int i = 0; i < columnNames.length; i++) {
System.out.println(" " + columnNames[i]);
}
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
for (int j = 0; j < columnNames.length; j++) {
if (traceName.trim().equals(columnNames[j])) {
traceIndexParameter[j] = i;
break;
}
}
}
System.out.println("Overview of traceIndexParameter:");
for (int i = 0; i < traceIndexParameter.length; i++) {
if (traceIndexParameter[i] == -1) {
throw new XMLParseException("Not all traces could be linked to the required columns.");
}
System.out.println(" traceIndexParameter[" + i + "]: " + traceIndexParameter[i] );
}
boolean[] flags = new boolean[dimension];
for (int i = 0; i < dimension; i++) {
flags[i] = true;
}
Double[][] parameterSamples = new Double[dimension][traces.getStateCount()];
for (int i = 0; i < dimension; i++) {
traces.getValues(traceIndexParameter[i]).toArray(parameterSamples[i]);
double initial = parameterSamples[i][0];
boolean tempFlag = false;
for (int j = 0; j < parameterSamples[i].length; j++) {
if (parameterSamples[i][j] != initial) {
tempFlag = true;
break;
}
}
flags[i] = tempFlag;
}
double[] shapes = new double[flags.length];
double[] scales = new double[flags.length];
/*for (int i = 0; i < flags.length; i++) {
if (flags[i]) {
double mean = 0.0;
for (int j = 0; j < parameterSamples[i].length; j++) {
mean += parameterSamples[i][j];
}
mean /= ((double)parameterSamples[i].length);
double variance = 0.0;
for (int j = 0; j < parameterSamples[i].length; j++) {
variance += Math.pow(parameterSamples[i][j] - mean, 2);
}
variance /= ((double)(parameterSamples[i].length-1));
scales[i] = variance/mean;
shapes[i] = mean/scales[i];
System.err.println(i + ": " + scales[i] + " " + shapes[i]);
}
}*/
for (int i = 0; i < flags.length; i++) {
if (flags[i]) {
shapes[i] = 1.0;
scales[i] = 60.9194/(double)(Binomial.choose2(9-i));
}
}
MultivariateGammaDistribution mvgd = new MultivariateGammaDistribution(shapes, scales, flags);
MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(mvgd);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("dimension"),
//AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the coalescent height probabilities based on a sample of coalescent heights.";
}
public Class getReturnType() {
return MultivariateDistributionLikelihood.class;
}
};
/*private boolean isVariable(Double[] samples) {
if (samples.length == 0) {
throw new XMLParseException("Column length is zero.");
}
double initial = samples[0];
int stop = samples.length;
boolean flag = false;
for (int i = 0; i < stop; i++) {
if (samples[i] != initial) {
flag = true;
break;
}
}
return flag;
}*/
/**
* A special parser that reads a convenient short form of reference priors on trees.
*/
public static XMLObjectParser CONDITIONAL_CLADE_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return CONDITIONAL_CLADE_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
//Coalescent.TREEPRIOR = true;
TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String name = file.getName();
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
Reader reader = new FileReader(new File(parent, name));
// the burn-in is used as the number of trees discarded
int burnin = -1;
if (xo.hasAttribute(BURNIN)) {
// leaving the burnin attribute off will result in 10% being used
burnin = xo.getIntegerAttribute(BURNIN);
}
// the epsilon value which represents the number of occurrences for every not observed clade
double e = 1.0;
if (xo.hasAttribute(EPSILON)) {
// leaving the epsilon attribute off will result in 1.0 being used
e = xo.getDoubleAttribute(EPSILON);
}
TreeTrace trace = TreeTrace.loadTreeTrace(reader);
ConditionalCladeFrequency ccf = new ConditionalCladeFrequency(new TreeTrace[]{trace}, e, burnin, false);
ConditionalCladeProbability ccp = new ConditionalCladeProbability(ccf, treeModel);
return ccp;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (ImportException ie) {
throw new XMLParseException(ie.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newIntegerRule(BURNIN),
AttributeRule.newDoubleRule(EPSILON),
new ElementRule(TreeModel.class)
};
public String getParserDescription() {
return "Calculates the conditional clade probability of a tree based on a sample of tree space.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
* <p/>
* If X ~ logNormal, then log(X) ~ Normal.
* <br>
* <br>
* If meanInRealSpace=false, <code>mean</code> specifies the mean of log(X) and
* <code>stdev</code> specifies the standard deviation of log(X).
* <br>
* <br>
* If meanInRealSpace=true, <code>mean</code> specifies the mean of X, but <code>
* stdev</code> specifies the standard deviation of log(X).
* <br>
*/
public static XMLObjectParser LOG_NORMAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return LOG_NORMAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
final double stdev = xo.getDoubleAttribute(STDEV);
final double offset = xo.getAttribute(OFFSET, 0.0);
final boolean meanInRealSpace = xo.getAttribute(MEAN_IN_REAL_SPACE, false);
if (meanInRealSpace) {
if (mean <= 0) {
throw new IllegalArgumentException("meanInRealSpace works only for a positive mean");
}
mean = Math.log(mean) - 0.5 * stdev * stdev;
}
final DistributionLikelihood likelihood = new DistributionLikelihood(new LogNormalDistribution(mean, stdev), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(STDEV),
AttributeRule.newDoubleRule(OFFSET, true),
AttributeRule.newBooleanRule(MEAN_IN_REAL_SPACE, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given lognormal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser GAMMA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return GAMMA_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double scale = xo.getDoubleAttribute(SCALE);
final double offset = xo.getAttribute(OFFSET, 0.0);
DistributionLikelihood likelihood = new DistributionLikelihood(new GammaDistribution(shape, scale), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(OFFSET, true),
// AttributeRule.newBooleanRule(UNINFORMATIVE, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given gamma distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser INVGAMMA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return INVGAMMA_PRIOR;
}
public String[] getParserNames() {
return new String[]{INVGAMMA_PRIOR, INVGAMMA_PRIOR_CORRECT};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double scale = xo.getDoubleAttribute(SCALE);
final double offset = xo.getDoubleAttribute(OFFSET);
DistributionLikelihood likelihood = new DistributionLikelihood(new InverseGammaDistribution(shape, scale), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(OFFSET),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given inverse gamma distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
public static XMLObjectParser LAPLACE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return LAPLACE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double scale = xo.getDoubleAttribute(SCALE);
DistributionLikelihood likelihood = new DistributionLikelihood(new LaplaceDistribution(mean, scale));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(SCALE),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given laplace distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser BETA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return BETA_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double shapeB = xo.getDoubleAttribute(SHAPEB);
final double offset = xo.getAttribute(OFFSET, 0.0);
DistributionLikelihood likelihood = new DistributionLikelihood(new BetaDistribution(shape, shapeB), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SHAPEB),
AttributeRule.newDoubleRule(OFFSET, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given beta distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
}
|
package nl.mpi.kinnate.svg;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class GraphData {
protected GraphDataNode[] graphDataNodeArray = new GraphDataNode[]{};
public int gridWidth;
public int gridHeight;
// public void setEgoNodes(String[] treeNodesArray) {
// if (treeNodesArray != null) {
// graphDataNodeList = new HashMap<String, GraphDataNode>();
// for (String currentNodeString : treeNodesArray) {
// try {
// ImdiTreeObject imdiTreeObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString));
// graphDataNodeList.put(imdiTreeObject.getUrlString(), new GraphDataNode(imdiTreeObject));
// } catch (URISyntaxException exception) {
// System.err.println(exception.getMessage());
// exception.printStackTrace();
// calculateLinks();
// sanguineSort();
// printLocations();
public void setEgoNodes(GraphDataNode[] graphDataNodeArrayLocal) {
graphDataNodeArray = graphDataNodeArrayLocal;
// if (graphDataNodeArray != null) {
// graphDataNodeList = new HashMap<String, GraphDataNode>();
// for (URI entityUri : treeNodesArray) {
// graphDataNodeList.put(entityUri.toASCIIString(), new GraphDataNode(ImdiLoader.getSingleInstance().getImdiObject(null, entityUri)));
// calculateLinks();
sanguineSort();
printLocations();
}
// public void readData() {
// String[] treeNodesArray = LinorgSessionStorage.getSingleInstance().loadStringArray("KinGraphTree");
// if (treeNodesArray != null) {
// for (String currentNodeString : treeNodesArray) {
// try {
// ImdiTreeObject imdiTreeObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString));
// graphDataNodeList.put(imdiTreeObject.getUrlString(), new GraphDataNode(imdiTreeObject));
// } catch (URISyntaxException exception) {
// System.err.println(exception.getMessage());
// exception.printStackTrace();
// calculateLinks();
// sanguineSort();
// printLocations();
// protected void calculateLinks() {
// System.out.println("calculateLinks");
// for (GraphDataNode currentNode : graphDataNodeList.values()) {
// System.out.println("currentNode: " + currentNode.getLabel());
//// currentNode.calculateLinks(graphDataNodeList);
// todo: and http://books.google.nl/books?id=diqHjRjMhW0C&pg=PA138&lpg=PA138&dq=SVGDOMImplementation+add+namespace&source=bl&ots=IuqzAz7dsz&sig=e5FW_B1bQbhnth6i2rifalv2LuQ&hl=nl&ei=zYpnTYD3E4KVOuPF2YoL&sa=X&oi=book_result&ct=result&resnum=3&ved=0CC0Q6AEwAg#v=onepage&q&f=false
// page 139 shows jgraph layout usage
// todo: lookinto:
// layouts.put("Hierarchical", new JGraphHierarchicalLayout());
// layouts.put("Compound", new JGraphCompoundLayout());
// layouts.put("CompactTree", new JGraphCompactTreeLayout());
// layouts.put("Tree", new JGraphTreeLayout());
// layouts.put("RadialTree", new JGraphRadialTreeLayout());
// layouts.put("Organic", new JGraphOrganicLayout());
// layouts.put("FastOrganic", new JGraphFastOrganicLayout());
// layouts.put("SelfOrganizingOrganic", new JGraphSelfOrganizingOrganicLayout());
// layouts.put("SimpleCircle", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_CIRCLE));
// layouts.put("SimpleTilt", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_TILT));
// layouts.put("SimpleRandom", new JGraphSimpleLayout(JGraphSimpleLayout.TYPE_RANDOM));
// layouts.put("Spring", new JGraphSpringLayout());
// layouts.put("Grid", new SimpleGridLayout());
private void sanguineSubnodeSort(ArrayList<HashSet<GraphDataNode>> generationRows, HashSet<GraphDataNode> currentColumns, ArrayList<GraphDataNode> inputNodes, GraphDataNode currentNode) {
int currentRowIndex = generationRows.indexOf(currentColumns);
HashSet<GraphDataNode> ancestorColumns;
HashSet<GraphDataNode> descendentColumns;
if (currentRowIndex < generationRows.size() - 1) {
descendentColumns = generationRows.get(currentRowIndex + 1);
} else {
descendentColumns = new HashSet<GraphDataNode>();
generationRows.add(currentRowIndex + 1, descendentColumns);
}
if (currentRowIndex > 0) {
ancestorColumns = generationRows.get(currentRowIndex - 1);
} else {
ancestorColumns = new HashSet<GraphDataNode>();
generationRows.add(currentRowIndex, ancestorColumns);
}
for (GraphDataNode.NodeRelation relatedNode : currentNode.getNodeRelations()) {
// todo: what happens here if there are multiple relations specified?
if (inputNodes.contains(relatedNode.getAlterNode())) {
HashSet<GraphDataNode> targetColumns;
switch (relatedNode.relationType) {
case ancestor:
targetColumns = ancestorColumns;
break;
case sibling:
targetColumns = currentColumns;
break;
case descendant:
targetColumns = descendentColumns;
break;
case union:
targetColumns = currentColumns;
break;
case none:
// this would be a kin term or other so skip when sorting
targetColumns = null;
break;
default:
targetColumns = null;
}
if (targetColumns != null) {
inputNodes.remove(relatedNode.getAlterNode());
targetColumns.add(relatedNode.getAlterNode());
System.out.println("sorted: " + relatedNode.getAlterNode().getLabel() + " : " + relatedNode.relationType + " of " + currentNode.getLabel());
sanguineSubnodeSort(generationRows, targetColumns, inputNodes, relatedNode.getAlterNode());
}
}
}
}
protected void sanguineSort() {
System.out.println("calculateLocations");
// create an array of rows
ArrayList<HashSet<GraphDataNode>> generationRows = new ArrayList<HashSet<GraphDataNode>>();
ArrayList<GraphDataNode> inputNodes = new ArrayList<GraphDataNode>();
inputNodes.addAll(Arrays.asList(graphDataNodeArray));
// put an array of columns into the current row
HashSet<GraphDataNode> currentColumns = new HashSet<GraphDataNode>();
generationRows.add(currentColumns);
while (inputNodes.size() > 0) {
GraphDataNode currentNode = inputNodes.remove(0);
System.out.println("add as root node: " + currentNode.getLabel());
currentColumns.add(currentNode);
sanguineSubnodeSort(generationRows, currentColumns, inputNodes, currentNode);
}
gridWidth = 0;
int yPos = 0;
for (HashSet<GraphDataNode> currentRow : generationRows) {
System.out.println("row: : " + yPos);
if (currentRow.isEmpty()) {
System.out.println("Skipping empty row");
} else {
int xPos = 0;
if (gridWidth < currentRow.size()) {
gridWidth = currentRow.size();
}
for (GraphDataNode graphDataNode : currentRow) {
System.out.println("updating: " + xPos + " : " + yPos + " : " + graphDataNode.getLabel());
graphDataNode.yPos = yPos;
graphDataNode.xPos = xPos;
xPos++;
}
yPos++;
}
}
System.out.println("gridWidth: " + gridWidth);
gridHeight = yPos;
sortByLinkDistance();
sortByLinkDistance();
}
private void sortByLinkDistance() {
GraphDataNode[][] graphGrid = new GraphDataNode[gridHeight][gridWidth];
for (GraphDataNode graphDataNode : graphDataNodeArray) {
graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode;
}
for (GraphDataNode graphDataNode : graphDataNodeArray) {
int relationCounter = 0;
int totalPositionCounter = 0;
for (GraphDataNode.NodeRelation graphLinkNode : graphDataNode.getNodeRelations()) {
relationCounter++;
totalPositionCounter += graphLinkNode.getAlterNode().xPos;
//totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos);
// totalPositionCounter += Math.abs(graphLinkNode.linkedNode.xPos - graphLinkNode.sourceNode.xPos);
System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().xPos);
System.out.println("totalPositionCounter: " + totalPositionCounter);
}
if (relationCounter > 0) {
int averagePosition = totalPositionCounter / relationCounter;
while (averagePosition < gridWidth - 1 && graphGrid[graphDataNode.yPos][averagePosition] != null) {
averagePosition++;
}
while (averagePosition > 0 && graphGrid[graphDataNode.yPos][averagePosition] != null) {
averagePosition
}
if (graphGrid[graphDataNode.yPos][averagePosition] == null) {
graphGrid[graphDataNode.yPos][graphDataNode.xPos] = null;
graphDataNode.xPos = averagePosition; // todo: swap what ever is aready there
graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode;
}
System.out.println("averagePosition: " + averagePosition);
}
// if (relationCounter > 0) {
// int averagePosition = totalPositionCounter / relationCounter;
// System.out.println("averagePosition: " + averagePosition);
// if (graphGrid[graphDataNode.yPos][averagePosition] == null) {
// graphGrid[graphDataNode.yPos][graphDataNode.xPos] = null;
// graphDataNode.xPos = averagePosition; // todo: swap what ever is aready there
// graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode;
}
}
// private void siblingSort() {
// GraphDataNode[][] graphGrid = new GraphDataNode[gridHeight][gridWidth];
// for (GraphDataNode graphDataNode : graphDataNodeList.values()) {
// graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode;
// private void calculateLinkDistance() {
// GraphDataNode[][] graphGrid = new GraphDataNode[gridHeight][gridWidth];
// for (GraphDataNode graphDataNode : graphDataNodeList.values()) {
// graphGrid[graphDataNode.yPos][graphDataNode.xPos] = graphDataNode;
public GraphDataNode[] getDataNodes() {
return graphDataNodeArray;
}
private void printLocations() {
System.out.println("printLocations");
for (GraphDataNode graphDataNode : graphDataNodeArray) {
System.out.println("node: " + graphDataNode.xPos + ":" + graphDataNode.yPos);
for (GraphDataNode.NodeRelation graphLinkNode : graphDataNode.getNodeRelations()) {
System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos);
}
}
}
// public static void main(String args[]) {
// GraphData graphData = new GraphData();
// graphData.readData();
// System.exit(0);
}
|
package com.alexvasilkov.events;
import android.content.Context;
import android.support.annotation.NonNull;
import com.alexvasilkov.events.cache.CacheProvider;
import com.alexvasilkov.events.cache.MemoryCache;
import com.alexvasilkov.events.internal.Dispatcher;
import com.alexvasilkov.events.internal.EventsParams;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO: documentation.
*/
public class Events {
private Events() {
// No instances
}
/**
* Initializes event bus.
*
* @deprecated This method does nothing, do not use it.
*/
@Deprecated
@SuppressWarnings("unused")
public static void init(@NonNull Context context) {}
public static void setDebug(boolean isDebug) {
EventsParams.setDebug(isDebug);
}
public static void register(@NonNull Object target) {
Dispatcher.register(target);
}
public static void unregister(@NonNull Object target) {
Dispatcher.unregister(target);
}
public static Event.Builder create(@NonNull String eventKey) {
return new Event.Builder(eventKey);
}
public static Event post(@NonNull String eventKey) {
return new Event.Builder(eventKey).post();
}
/**
* <p>Method marked with this annotation will receive events with specified key on main thread.
* </p>
* <p>See {@link Background} annotation if you want to receive events on background thread.</p>
* <p>See {@link Cache} annotation if you want to use cache feature.</p>
* <p>You may listen for event's execution status using methods annotated with {@link Status}.
* </p>
* <p>Object returned from this method will be sent to the bus and can be received by anyone
* using methods annotated with {@link Result}.<br>
* You can return {@link EventResult} object which can contain several values.<br>
* You can also send several results during method execution using
* {@link Event#postResult(EventResult)} and {@link Event#postResult(Object...)}.</p>
* <p>Any uncaught exception thrown during method execution will be sent to the bus and can be
* received using methods annotated with {@link Failure}.</p>
* <p><b>Allowed method parameters</b>
* <ul>
* <li><code>method()</code></li>
* <li><code>method({@link Event})</code></li>
* <li><code>method({@link Event}, T1, T2, ...)</code></li>
* <li><code>method(T1, T2, ...)</code></li>
* </ul>
* Where {@code T1, T2, ...} - corresponding types of values passed to
* {@link Event.Builder#param(Object...)} method. You may also access event's parameters
* using {@link Event#getParam(int)} method.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Subscribe {
String value();
}
/**
* <p>Method marked with this annotation will receive events on background thread.</p>
* <p>Method must also be marked with {@link Subscribe} annotation.</p>
* <p>If {@link #singleThread()} set to {@code true} then only one thread will be used to
* execute this method. All other events targeting this method will wait until it is finished.
* </p>
* <p><b>Note</b>: method executed in background should be static to not leek object reference
* (i.e. Activity reference). To subscribe static methods use {@link Events#register(Object)}
* method with {@link Class} object.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Background {
boolean singleThread() default false;
}
/**
* <p>Method marked with this annotation will use new instance of given {@link CacheProvider}
* class to handle results caching. See also {@link MemoryCache} implementation.</p>
* <p>Method must also be marked with {@link Subscribe} annotation.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Cache {
Class<? extends CacheProvider> value();
}
/**
* <p>Method marked with this annotation will receive status updates for events
* with specified key on main thread.<br>
* <ul>
* <li>{@link EventStatus#STARTED} status will be sent before any subscribed method is executed
* (right after event is posted to the bus) and for all newly registered events receivers
* if execution of all subscribed methods is no yet finished.</li>
* <li>{@link EventStatus#FINISHED} status will be sent after all subscribed methods
* (including background) are executed.</li>
* </ul></p>
* <p><b>Allowed method parameters</b>
* <ul>
* <li><code>method({@link EventStatus})</code></li>
* <li><code>method({@link Event}, {@link EventStatus})</code></li>
* </ul></p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
String value();
}
/**
* <p>Method marked with this annotation will receive results for events
* with specified key on main thread.<br>
* Result can be accessed either directly as method's parameter or through
* {@link EventResult} object.</p>
* <p><b>Allowed method parameters</b>
* <ul>
* <li><code>method()</code></li>
* <li><code>method({@link Event})</code></li>
* <li><code>method({@link Event}, T1, T2, ...)</code></li>
* <li><code>method({@link Event}, {@link EventResult})</code></li>
* <li><code>method(T1, T2, ...)</code></li>
* <li><code>method({@link EventResult})</code></li>
* </ul>
* Where {@code T1, T2, ...} - corresponding types of values returned by method
* marked with {@link Subscribe} annotation. Same values can be accessed using
* {@link EventResult#getResult(int)} method.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Result {
String value();
}
/**
* <p>Method marked with this annotation will receive failure callbacks for events
* with specified key on main thread.</p>
* <p><b>Allowed method parameters</b>
* <ul>
* <li><code>method()</code></li>
* <li><code>method({@link Event})</code></li>
* <li><code>method({@link Event}, {@link Throwable})</code></li>
* <li><code>method({@link Event}, {@link EventFailure})</code></li>
* <li><code>method({@link Throwable})</code></li>
* <li><code>method({@link EventFailure})</code></li>
* </ul></p>
* <p><b>Note</b>: You may skip event key to handle all failures of all events.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Failure {
String value() default EventsParams.EMPTY_KEY;
}
}
|
package edu.afs.commands;
import edu.afs.subsystems.drivesubsystem.*;
import edu.afs.subsystems.autoranger.*;
import edu.afs.commands.AutoDriveToShotRangeCommand;
/**
*
* @author User
*/
public class DriveWithJoystickCommand extends CommandBase {
private static double RANGE_TOLERANCE = 12.0; // In inches.
RangeBeacon m_rangeBeacon;
double m_desiredRange;
boolean m_driveControlsInverted;
public DriveWithJoystickCommand() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(drive); // reserve the chassis subsystem
m_rangeBeacon = RangeBeacon.getInstance();
m_desiredRange = AutoDriveToShotRangeCommand.GetDesiredRange();
m_driveControlsInverted = false;
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
// Check the range to target.
double range = autoRanger.GetRange();
double absError = Math.abs(m_desiredRange - range);
if(absError <= RANGE_TOLERANCE){
// At shooting range - set beaon indicator.
m_rangeBeacon.SetAtShotRangeIndicator(true);
} else {
m_rangeBeacon.SetAtShotRangeIndicator(false);
}
//TODO: Get state of OI input to determine if controls should be set to
// drive with forklift or launcher in front.
drive.driveWithJoystick(m_driveControlsInverted);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
package org.avaje.resteasy;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.spi.DefaultBindingScopingVisitor;
import org.avaje.resteasy.websocket.BasicWebSocketConfigurator;
import org.avaje.resteasy.websocket.BasicWebSocketEndpointConfig;
import org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
/**
* Extends the Resteasy Guice servlet context listener with the detection of
* eager singleton WebSocket server endpoints and registers them with the
* servlet container.
*/
public class Bootstrap extends GuiceResteasyBootstrapServletContextListener {
protected static final Logger log = LoggerFactory.getLogger(Bootstrap.class);
protected ServletContextEvent event;
protected ServerContainer serverContainer;
/**
* On contextInitialized additional obtain the WebSocket ServerContainer.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
this.event = event;
this.serverContainer = getServerContainer(event);
super.contextInitialized(event);
}
/**
* Return the WebSocket ServerContainer from the servletContext.
*/
protected ServerContainer getServerContainer(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
return (ServerContainer) context.getAttribute("javax.websocket.server.ServerContainer");
}
/**
* Invoked internally via contextInitialized() this finds and registers WebSocket
* endpoints that Guice is injecting (that are eager singletons).
*/
@Override
protected void withInjector(Injector injector) {
if (serverContainer != null) {
registerWebSockets(injector);
}
}
/**
* Find any Guice eager singletons that are WebSocket endpoints
* and register them with the servlet container.
*/
private void registerWebSockets(Injector injector) {
Map<Key<?>, Binding<?>> allBindings = injector.getAllBindings();
// loop all the Guice bindings looking for @ServerEndpoint singletons
for (Map.Entry<Key<?>, Binding<?>> entry : allBindings.entrySet()) {
final Binding<?> binding = entry.getValue();
binding.acceptScopingVisitor(new DefaultBindingScopingVisitor() {
@Override
public Object visitEagerSingleton() {
// also a eager singleton so register it
registerWebSocketEndpoint(binding);
return null;
}
});
}
}
/**
* Check if the binding is a WebSocket endpoint. If it is then register the webSocket
* server endpoint with the servlet container.
*/
protected void registerWebSocketEndpoint(Binding<?> binding) {//}, ServerEndpoint serverEndpoint) {
Object instance = binding.getProvider().get();
Class<?> instanceClass = instance.getClass();
ServerEndpoint serverEndpoint = instanceClass.getAnnotation(ServerEndpoint.class);
if (serverEndpoint != null) {
try {
// register with the servlet container such that the Guice created singleton instance
// is the instance that is used (and not an instance created per request etc)
log.debug("registering ServerEndpoint [{}] with servlet container", instanceClass);
BasicWebSocketConfigurator configurator = new BasicWebSocketConfigurator(instance);
serverContainer.addEndpoint(new BasicWebSocketEndpointConfig(instanceClass, serverEndpoint, configurator));
} catch (Exception e) {
log.error("Error registering WebSocket Singleton " + instance + " with the servlet container", e);
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import entity.Planning;
import java.sql.Timestamp;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Roy
*/
public class PlanningControllerTest {
public PlanningControllerTest() {
}
private Planning planning;
private PlanningController planningController;
@Before
public void before()
{
planning = new Planning();
planningController = new PlanningController();
}
@Test
public void trueVisibilty()
{
planningController.changePlanningVisibility(planning, true);
Assert.assertEquals(true, planning.isVisible());
}
@Test
public void falseVisibilty()
{
planningController.changePlanningVisibility(planning, false);
Assert.assertEquals(false, planning.isVisible());
}
@Test(expected = NullPointerException.class)
public void planningNullVisibilty()
{
planningController.changePlanningVisibility(null, false);
}
@Test
public void testRegisterVisibilityPeriod()
{
Timestamp visibleStart = new Timestamp(20140310L);
Timestamp visibleEnd = new Timestamp(20140311L);
planningController.registerVisibilityPeriod(planning, visibleStart , visibleEnd);
Assert.assertEquals(planning.getVisibleStart(), visibleStart);
Assert.assertEquals(planning.getVisibleEnd(), visibleEnd);
}
@Test(expected = NullPointerException.class)
public void testNullRegisterVisibilityPeriod()
{
planningController.registerVisibilityPeriod(planning, null , null);
}
@Test(expected = NullPointerException.class)
public void testPlanningNullRegisterVisibilityPeriod()
{
Timestamp visibleStart = new Timestamp(20140310L);
Timestamp visibleEnd = new Timestamp(20140311L);
planningController.registerVisibilityPeriod(null, visibleStart , visibleEnd);
}
}
|
package com.mindera.skeletoid.logs;
import com.mindera.skeletoid.logs.appenders.ILogAppender;
import android.content.Context;
import java.util.List;
import java.util.Set;
/**
* LOG static class. It is used to abstract the LOG and have multiple possible implementations
* It is used also to serve as static references for logging methods to be called.
*/
public class LOG {
public enum PRIORITY {
VERBOSE, DEBUG, INFO, ERROR, WARN, FATAL
}
// private static final String LOGGER = "LOG";
private static volatile ILoggerManager mInstance;
/**
* Init the logger. This method MUST be called before using LoggerManager
*
* @param context
*/
public static void init(Context context) {
getInstance(context).removeAllAppenders();
}
/**
* Init the logger. This method MUST be called before using LoggerManager
*
* @param context
*/
public static void init(Context context, String packageName) {
getInstance(context, packageName).removeAllAppenders();
}
/**
* Init the logger. This method MUST be called before using LoggerManager
*
* @param context Context app
* @param logAppenders The log appenders to be started
*/
public synchronized static Set<String> init(Context context, List<ILogAppender> logAppenders) {
ILoggerManager logger = getInstance(context);
logger.removeAllAppenders();
return logger.addAppenders(context, logAppenders);
}
/**
* Init the logger. This method MUST be called before using LoggerManager
*
* @param context Context app
* @param packageName Packagename
* @param logAppenders The log appenders to be started
*/
public synchronized static Set<String> init(Context context, String packageName, List<ILogAppender> logAppenders) {
ILoggerManager logger = getInstance(packageName);
logger.removeAllAppenders();
return logger.addAppenders(context, logAppenders);
}
/**
* Deinit the logger
* This method can be called if the LOG is not needed any longer on the app.
*/
public static void deinit(Context context) {
if (mInstance != null) {
getInstance().removeAllAppenders();
mInstance = null;
}
}
/**
* Enable log appenders
*
* @param context Context
* @param logAppenders Log appenders to enable
* @return Ids of the logs enabled by their order
*/
public static Set<String> addAppenders(Context context, List<ILogAppender> logAppenders) {
return getInstance().addAppenders(context, logAppenders);
}
/**
* Disable log appenders
*
* @param context Context
* @param loggerIds Log ids of each of the loggers enabled by the order sent
*/
public static void removeAppenders(Context context, Set<String> loggerIds) {
getInstance().removeAppenders(context, loggerIds);
}
/**
* Set method name visible in logs (careful this is a HEAVY operation)
*
* @param visibility true if enabled
*/
public static void setMethodNameVisible(boolean visibility) {
getInstance().setMethodNameVisible(visibility);
}
/**
* Obtain a instance of the logger to guarantee it's unique
*
* @param context
* @return
*/
private static ILoggerManager getInstance(Context context, String packageName) {
if (context == null && packageName == null) {
throw new IllegalArgumentException("Context and packageName cannot both be null");
}
ILoggerManager result = mInstance;
if (result == null) {
synchronized (LOG.class) {
result = mInstance;
if (result == null) {
if (packageName == null) {
mInstance = new LoggerManager(context);
} else {
mInstance = new LoggerManager(packageName);
}
}
}
}
return mInstance;
}
/**
* Obtain a instance of the logger to guarantee it's unique
*
* @param context
* @return
*/
private static ILoggerManager getInstance(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context cannot be null");
}
return getInstance(context, null);
}
/**
* Obtain a instance of the logger to guarantee it's unique
*
* @param packageName
* @return
*/
private static ILoggerManager getInstance(String packageName) {
if (packageName == null) {
throw new IllegalArgumentException("PackageName cannot be null");
}
return getInstance(null, packageName);
}
/**
* Get LoggerManager instance.
*
* @return
*/
private static ILoggerManager getInstance() {
if (mInstance == null) {
throw new IllegalStateException("You MUST init() the LOG.");
}
return mInstance;
}
/**
* Log with a DEBUG level
*
* @param tag Tag
* @param text List of strings
*/
public static void d(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.DEBUG, text);
}
/**
* Log with a ERROR level
*
* @param tag Tag
* @param text List of strings
*/
public static void e(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.ERROR, text);
}
/**
* Log with a VERBOSE level
*
* @param tag Tag
* @param text List of strings
*/
public static void v(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.VERBOSE, text);
}
/**
* Log with a INFO level
*
* @param tag Tag
* @param text List of strings
*/
public static void i(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.INFO, text);
}
/**
* Log with a WARN level
*
* @param tag Tag
* @param text List of strings
*/
public static void w(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.WARN, text);
}
/**
* Log a What a Terrible Failure: Report an exception that should never happen.
*
* @param tag Tag
* @param text List of strings
*/
public static void wtf(String tag, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.FATAL, text);
}
/**
* Log with a DEBUG level
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void d(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.DEBUG, t, text);
}
/**
* Log with a ERROR level
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void e(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.ERROR, t, text);
}
/**
* Log with a VERBOSE level
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void v(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.VERBOSE, t, text);
}
/**
* Log with a INFO level
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void i(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.INFO, t, text);
}
/**
* Log with a WARN level
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void w(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.WARN, t, text);
}
/**
* Log a What a Terrible Failure: Report an exception that should never happen.
*
* @param tag Tag
* @param t Throwable
* @param text List of strings
*/
public static void wtf(String tag, Throwable t, String... text) {
if (mInstance == null) {
return;
}
mInstance.log(tag, PRIORITY.FATAL, t, text);
}
/**
* Return true if initialized
*
* @return true if initialized
*/
public static boolean isInitialized() {
return mInstance != null;
}
}
|
package edu.utdallas.robotchess.pathplanning;
import java.util.ArrayList;
import edu.utdallas.robotchess.robotcommunication.commands.Command;
import edu.utdallas.robotchess.robotcommunication.commands.MoveToSquareCommand;
public class Path
{
private int robotID;
private int origin;
private ArrayList<Integer> squareSequence;
public Path(int robotID, int origin)
{
this.robotID = robotID;
this.origin = origin;
squareSequence = new ArrayList<>();
}
protected void add(int location)
{
squareSequence.add(location);
}
public void setSquareSequence(ArrayList<Integer> squareSequence)
{
this.squareSequence = squareSequence;
}
public ArrayList<Integer> getPath()
{
return squareSequence;
}
public int getRobotID()
{
return robotID;
}
public Command generateCommand()
{
if (squareSequence.size() == 0)
return null;
ArrayList<Integer> payload = new ArrayList<>();
int previousDirection = squareSequence.get(0) - origin;
for(int i = 1; i < squareSequence.size(); i++) {
int newDirection = squareSequence.get(i) - squareSequence.get(i - 1);
if (newDirection != previousDirection) {
payload.add(squareSequence.get(i - 1));
previousDirection = newDirection;
}
}
payload.add(squareSequence.get(squareSequence.size() - 1));
int[] payloadArr = new int[payload.size()];
for (int i = 0; i < payloadArr.length; i++)
payloadArr[i] = payload.get(i);
return new MoveToSquareCommand(robotID, payloadArr);
}
@Override
public String toString()
{
String str = new String();
str = String.format("<%d> (%d) [", robotID, origin);
for (Integer i : squareSequence)
str += String.format("%d ", i);
str += String.format("]");
return str;
}
}
|
package edu.washington.escience.myria;
import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
/**
* This class holds the key that identifies a relation. The notation is user.program.relation.
*
*/
public final class RelationKey implements Serializable {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/** The user who owns/creates this relation. */
@JsonProperty
private final String userName;
/** The user's program that owns/creates this relation. */
@JsonProperty
private final String programName;
/** The name of the relation. */
@JsonProperty
private final String relationName;
/**
* Static function to create a RelationKey object.
*
* @param userName the user who owns/creates this relation.
* @param programName the user's program that owns/creates this relation.
* @param relationName the name of the relation.
* @return a new RelationKey reference to the specified relation.
*/
@JsonCreator
public static RelationKey of(@JsonProperty("userName") final String userName,
@JsonProperty("programName") final String programName, @JsonProperty("relationName") final String relationName) {
return new RelationKey(userName, programName, relationName);
}
/** The regular expression specifying what names are valid. */
public static final String VALID_NAME_REGEX = "^[a-zA-Z_]\\w*$";
/** The regular expression matcher for {@link #VALID_NAME_REGEX}. */
private static final Pattern VALID_NAME_PATTERN = Pattern.compile(VALID_NAME_REGEX);
private static String checkName(final String name, final String whichName) {
Objects.requireNonNull(name, whichName);
Preconditions.checkArgument(VALID_NAME_PATTERN.matcher(name).matches(),
"supplied %s %s does not match the valid name regex %s", whichName, name, VALID_NAME_REGEX);
return name;
}
/**
* Private constructor to create a RelationKey object.
*
* @param userName the user who owns/creates this relation.
* @param programName the user's program that owns/creates this relation.
* @param relationName the name of the relation.
*/
public RelationKey(final String userName, final String programName, final String relationName) {
checkName(userName, "userName");
checkName(programName, "programName");
checkName(relationName, "relationName");
this.userName = userName;
this.programName = programName;
this.relationName = relationName;
}
/**
* @return the name of this relation.
*/
public String getRelationName() {
return relationName;
}
/**
* @return the name of the program containing this relation.
*/
public String getProgramName() {
return programName;
}
/**
* @return the name of the user who owns the program containing this relation.
*/
public String getUserName() {
return userName;
}
@Override
public String toString() {
return Joiner.on(':').join(userName, programName, relationName);
}
/**
* Helper function for computing strings of different types.
*
* @param leftEscape the left escape character, e.g., '\"'.
* @param separate the separating character, e.g., ':'.
* @param rightEscape the right escape character, e.g., '\"'.
* @return <code>"user:program:relation"</code>, for example.
*/
private String toString(final char leftEscape, final char separate, final char rightEscape) {
StringBuilder sb = new StringBuilder();
sb.append(leftEscape).append(Joiner.on(separate).join(userName, programName, relationName)).append(rightEscape);
return sb.toString();
}
/** The maximum length of a postgres identifier is 63 chars. Ugh. */
private static final int MAX_POSTGRESQL_IDENTIFIER_LENGTH = 63;
/**
* Helper function for computing strings of different types.
*
* @param dbms the DBMS, e.g., {@link MyriaConstants.STORAGE_SYSTEM_MYSQL}.
* @return <code>"user:program:relation"</code>, for example.
*/
public String toString(final String dbms) {
switch (dbms) {
case MyriaConstants.STORAGE_SYSTEM_POSTGRESQL:
String ret = toString('\"', ':', '\"');
Preconditions.checkArgument(ret.length() <= MAX_POSTGRESQL_IDENTIFIER_LENGTH,
"PostgreSQL does not allow relation names longer than %s characters: %s", MAX_POSTGRESQL_IDENTIFIER_LENGTH,
ret);
return ret;
case MyriaConstants.STORAGE_SYSTEM_SQLITE:
return toString('\"', ':', '\"');
case MyriaConstants.STORAGE_SYSTEM_MONETDB:
/* TODO: can we switch the other DBMS to : as well? */
return toString('\"', ' ', '\"');
case MyriaConstants.STORAGE_SYSTEM_MYSQL:
/* TODO: can we switch the other DBMS to : as well? */
return toString('`', ' ', '`');
default:
throw new IllegalArgumentException("Unsupported dbms " + dbms);
}
}
@Override
public int hashCode() {
return Objects.hash(userName, programName, relationName);
}
@Override
public boolean equals(final Object other) {
if (other == null || !(other instanceof RelationKey)) {
return false;
}
RelationKey o = (RelationKey) other;
return Objects.equals(userName, o.userName) && Objects.equals(programName, o.programName)
&& Objects.equals(relationName, o.relationName);
}
/**
* Return the default relation key for a temporary table created for the given query.
*
* @param queryId the query that will generate this temporary table
* @param table the name of the table
* @return the default relation key for this temp table created for the given query
*/
public static RelationKey ofTemp(final long queryId, final String table) {
return RelationKey.of("myria_q_" + queryId, "__temp__", table);
}
}
|
package org.jtrfp.trcl;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.mem.MemoryWindow;
public abstract class PrimitiveList<PRIMITIVE_TYPE> {
protected static final double coordDownScaler = 512;
protected static final double uvUpScaler = 4096;
private final PRIMITIVE_TYPE[][] primitives;
private final Model model;
public static enum RenderStyle {
OPAQUE, TRANSPARENT
};
protected final String debugName;
protected double scale;
protected int packedScale;
protected final TR tr;
protected final MemoryWindow window;
public PrimitiveList(String debugName, PRIMITIVE_TYPE[][] primitives,
MemoryWindow window, TR tr, Model model) {
this.tr = tr;
this.window=window;
this.debugName = debugName;
this.primitives = primitives;
this.model = model;
setScale((getMaximumVertexValue() / 2048.));
//addList(this);
}
protected int packScale(double scaleToPack) {
int result = (int) Math.round(Math.log(scaleToPack) / Math.log(2));// Base-2
// log
return result + 16;
}
protected double applyScale(double value) {
return value / Math.pow(2, packedScale - 16);
}
protected abstract double getMaximumVertexValue();
public PRIMITIVE_TYPE[][] getPrimitives() {
return primitives;
}
public int getNumElements() {
return primitives[0].length;
}
public abstract int getElementSizeInVec4s();
public abstract int getGPUVerticesPerElement();
public abstract RenderStyle getRenderStyle();
public int getTotalSizeInVec4s() {
return getElementSizeInVec4s() * getNumElements();
}
public int getTotalSizeInGPUVertices() {
return (getTotalSizeInVec4s() / getElementSizeInVec4s())
* getGPUVerticesPerElement();
}
public String getDebugName() {
return debugName;
}
public abstract void uploadToGPU();
/**
* @param scale
* the scale to set
*/
public final void setScale(double scale) {
this.scale = scale;
packedScale = packScale(scale);
}
public final double getScale() {
return scale;
}
public final int getPackedScale() {
return packedScale;
}
public final MemoryWindow getMemoryWindow(){
return window;
}
/**
* @return the primitiveRenderMode
*/
public abstract byte getPrimitiveRenderMode();
public abstract int getNumMemoryWindowIndicesPerElement();
/**
* @return the model
*/
protected Model getModel() {
return model;
}
}// end PrimitiveList
|
package org.jtrfp.trcl.obj;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Model;
import org.jtrfp.trcl.beh.AdjustAltitudeToPlayerBehavior;
import org.jtrfp.trcl.beh.AutoFiring;
import org.jtrfp.trcl.beh.AutoLeveling;
import org.jtrfp.trcl.beh.Bobbing;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.DamagedByCollisionWithGameplayObject;
import org.jtrfp.trcl.beh.DeathBehavior;
import org.jtrfp.trcl.beh.DebrisOnDeathBehavior;
import org.jtrfp.trcl.beh.ExplodesOnDeath;
import org.jtrfp.trcl.beh.HorizAimAtPlayerBehavior;
import org.jtrfp.trcl.beh.LeavesPowerupOnDeathBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.ProjectileFiringBehavior;
import org.jtrfp.trcl.beh.ResetsRandomlyAfterDeath;
import org.jtrfp.trcl.beh.SteadilyRotating;
import org.jtrfp.trcl.beh.TerrainLocked;
import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion;
import org.jtrfp.trcl.beh.phy.BouncesOffSurfaces;
import org.jtrfp.trcl.beh.phy.HasPropulsion;
import org.jtrfp.trcl.beh.phy.MovesByVelocity;
import org.jtrfp.trcl.beh.phy.PulledDownByGravityBehavior;
import org.jtrfp.trcl.beh.phy.RotationalDragBehavior;
import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior;
import org.jtrfp.trcl.beh.phy.VelocityDragBehavior;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition;
import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic;
import org.jtrfp.trcl.file.DEFFile.EnemyPlacement;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
public class DEFObject extends WorldObject {
private final double boundingRadius;
private WorldObject ruinObject;
private final EnemyLogic logic;
private boolean mobile,canTurn,foliage,boss,groundLocked;
public DEFObject(TR tr,Model model, EnemyDefinition def, EnemyPlacement pl){
super(tr,model);
boundingRadius = TR.legacy2Modern(def.getBoundingBoxRadius())/1.5;
logic = def.getLogic();
mobile=true;
canTurn=true;
foliage=false;
boss=def.isObjectIsBoss();
groundLocked=false;
switch(logic){
case groundDumb:
mobile=false;
canTurn=false;
break;
case groundTargeting://Ground turrets
mobile=false;
canTurn=true;
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
//TODO: def.getFiringVertices() needs actual vertex lookup.
addBehavior(new ProjectileFiringBehavior().setFiringPositions(new Vector3D[]{
new Vector3D(0,0,0)
}));
break;
case flyingDumb:
canTurn=false;
break;
case groundTargetingDumb:
groundLocked=true;
break;
case flyingSmart:
smartPlaneBehavior(tr);
break;
case bankSpinDrill:
unhandled(def);
break;
case sphereBoss:
unhandled(def);
mobile=true;
break;
case flyingAttackRetreatSmart:
smartPlaneBehavior(tr);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case splitShipSmart:
smartPlaneBehavior(tr);
//addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case groundStaticRuin://Destroyed object is replaced with another using SimpleModel i.e. weapons bunker
mobile=false;
canTurn=false;
break;
case targetHeadingSmart:
mobile=false;//Belazure's crane bots
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
break;
case targetPitchSmart:
unhandled(def);
break;
case coreBossSmart:
mobile=false;
break;
case cityBossSmart:
mobile=false;
break;
case staticFiringSmart:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case sittingDuck:
canTurn=false;
mobile=false;
break;
case tunnelAttack://TODO
mobile=false;
break;
case takeoffAndEscape://TODO
canTurn=false;
break;
case fallingAsteroid:
fallingObjectBehavior();
addBehavior(new RotationalMomentumBehavior()
.accellerateEquatorialMomentum(1)
.accellerateLateralMomentum(1)
.accelleratePolarMomentum(1));
{ final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
break;
case cNome://Walky bot?
groundLocked=true;
break;
case cNomeLegs://Walky bot?
groundLocked=true;
break;
case cNomeFactory:
mobile=false;
break;
case geigerBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcanoBoss:
addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
mobile=false;
break;
case volcano://Wat.
unhandled(def);
canTurn=false;
mobile=false;
break;
case missile://Silo?
mobile=false;//TODO
break;
case bob:
addBehavior(new Bobbing());
addBehavior(new SteadilyRotating());
mobile=false;
canTurn=false;//ironic?
break;
case alienBoss:
break;
case canyonBoss1:
mobile=false;
break;
case canyonBoss2:
mobile=false;
break;
case lavaMan://Also terraform-o-bot
mobile=false;
break;
case arcticBoss:
mobile=false;
break;
case helicopter://TODO
break;
case tree:
canTurn=false;
mobile=false;
foliage=true;
break;
case ceilingStatic:
canTurn=false;
mobile=false;
break;
case bobAndAttack:{
addBehavior(new SteadilyRotating().setRotationPhase(2*Math.PI*Math.random()));
final ProjectileFiringBehavior pfb = new ProjectileFiringBehavior();
pfb.addSupply(99999999);
pfb.setMultiplexLevel(1);
pfb.setProjectileFactory(tr.getResourceManager().getProjectileFactories()[/*def.getWeapon().ordinal()*/1]);
addBehavior(pfb);
addBehavior(new AutoFiring().setProjectileFiringBehavior(pfb));
addBehavior(new Bobbing().setPhase(Math.random()).setBobPeriodMillis(10*1000+Math.random()*3000));
mobile=false;
canTurn=false;
break;}
case forwardDrive:
canTurn=false;
groundLocked=true;
break;
case fallingStalag:
fallingObjectBehavior();
{final DEFObject thisObject = this;
final Vector3D centerPos = new Vector3D(this.getPosition());
final TR thisTr = tr;
addBehavior(new ResetsRandomlyAfterDeath()
.setMinWaitMillis(100)
.setMaxWaitMillis(1000)
.setRunOnReset(new Runnable(){
@Override
public void run(){
final double [] pos = thisObject.getPosition();
pos[0]=centerPos.getX()+Math.random()*TR.mapSquareSize*10;
pos[1]=thisTr.getWorld().sizeY/1.5;
pos[2]=centerPos.getZ()+Math.random()*TR.mapSquareSize*10;
thisObject.notifyPositionChange();
}//end run()
}));}
canTurn=false;
mobile=false;
break;
case attackRetreatBelowSky:
smartPlaneBehavior(tr);
break;
case attackRetreatAboveSky:
smartPlaneBehavior(tr);
break;
case bobAboveSky:
mobile=false;
break;
case factory:
canTurn=false;
mobile=false;
break;
}//end switch(logic)
addBehavior(new DeathBehavior());
addBehavior(new DamageableBehavior().setHealth(pl.getStrength()).setMaxHealth(pl.getStrength()).setEnable(!boss));
setActive(!boss);
addBehavior(new DamagedByCollisionWithGameplayObject());
if(!foliage)addBehavior(new DebrisOnDeathBehavior());
if(canTurn||boss){
addBehavior(new RotationalMomentumBehavior());
addBehavior(new RotationalDragBehavior()).setDragCoefficient(.86);
addBehavior(new AutoLeveling());
}
if(!mobile || groundLocked){
addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion));
}else{
addBehavior(new ExplodesOnDeath(ExplosionType.Blast));
}
if(mobile){
addBehavior(new MovesByVelocity());
addBehavior(new HasPropulsion());
addBehavior(new AccelleratedByPropulsion());
addBehavior(new VelocityDragBehavior());
if(groundLocked){
addBehavior(new TerrainLocked());}
else {addBehavior(new BouncesOffSurfaces());
addBehavior(new CollidesWithTerrain());
}
getBehavior().probeForBehavior(VelocityDragBehavior.class).setDragCoefficient(.86);
getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0);
getBehavior().probeForBehavior(Propelled.class).setPropulsion(def.getThrustSpeed());
addBehavior(new LoopingPositionBehavior());
}//end if(mobile)
if(boss){bossBehavior(tr,def);}
if(def.getPowerup()!=null && Math.random()*100. < def.getPowerupProbability()){addBehavior(new LeavesPowerupOnDeathBehavior(def.getPowerup()));}
}//end DEFObject
@Override
public void destroy(){
if(ruinObject!=null)ruinObject.setVisible(true);//TODO: Switch to setActive later.
super.destroy();
}
private void unhandled(EnemyDefinition def){
System.err.println("UNHANDLED DEF LOGIC: "+def.getLogic()+". MODEL="+def.getComplexModelFile()+" DESC="+def.getDescription());
}
private void bossBehavior(TR tr, EnemyDefinition def){//Don't include hitzones for aiming.
if(!def.getComplexModelFile().toUpperCase().contains("HITZO"))addBehavior(new HorizAimAtPlayerBehavior(tr.getPlayer()));
}
private void fallingObjectBehavior(){
canTurn=false;
addBehavior(new PulledDownByGravityBehavior());
addBehavior(new DamageableBehavior().setHealth(1));
addBehavior(new CollidesWithTerrain());
}
private void smartPlaneBehavior(TR tr){
final HorizAimAtPlayerBehavior haapb =new HorizAimAtPlayerBehavior(tr.getPlayer());
addBehavior(haapb);
final AdjustAltitudeToPlayerBehavior aatpb = new AdjustAltitudeToPlayerBehavior(tr.getPlayer()).setAccelleration(1000);
addBehavior(aatpb);
}
/**
* @return the boundingRadius
*/
public double getBoundingRadius() {
return boundingRadius;
}
public void setRuinObject(DEFObject ruin) {
ruinObject=ruin;
}
/**
* @return the logic
*/
public EnemyLogic getLogic() {
return logic;
}
/**
* @return the mobile
*/
public boolean isMobile() {
return mobile;
}
/**
* @return the canTurn
*/
public boolean isCanTurn() {
return canTurn;
}
/**
* @return the foliage
*/
public boolean isFoliage() {
return foliage;
}
/**
* @return the boss
*/
public boolean isBoss() {
return boss;
}
/**
* @return the groundLocked
*/
public boolean isGroundLocked() {
return groundLocked;
}
}//end DEFObject
|
package org.kohsuke.github;
import com.fasterxml.jackson.databind.JsonMappingException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.WillClose;
import static java.util.Arrays.asList;
import static java.util.logging.Level.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.kohsuke.github.GitHub.MAPPER;
import static org.kohsuke.github.GitHub.connect;
/**
* A builder pattern for making HTTP call and parsing its output.
*
* @author Kohsuke Kawaguchi
*/
class Requester {
private final GitHub root;
private final List<Entry> args = new ArrayList<Entry>();
private final Map<String, String> headers = new LinkedHashMap<String, String>();
@Nonnull
private String urlPath = "/";
/**
* Request method.
*/
private String method = "GET";
private String contentType = null;
private InputStream body;
/**
* Current connection.
*/
private HttpURLConnection uc;
private boolean forceBody;
private static class Entry {
final String key;
final Object value;
private Entry(String key, Object value) {
this.key = key;
this.value = value;
}
}
/**
* If timeout issues let's retry after milliseconds.
*/
private static final int retryTimeoutMillis = 500;
Requester(GitHub root) {
this.root = root;
}
/**
* Sets the request HTTP header.
* <p>
* If a header of the same name is already set, this method overrides it.
*
* @param name
* the name
* @param value
* the value
*/
public void setHeader(String name, String value) {
headers.put(name, value);
}
/**
* With header requester.
*
* @param name
* the name
* @param value
* the value
* @return the requester
*/
public Requester withHeader(String name, String value) {
setHeader(name, value);
return this;
}
public Requester withPreview(String name) {
return withHeader("Accept", name);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, int value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, long value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, boolean value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param e
* the e
* @return the requester
*/
public Requester with(String key, Enum e) {
if (e == null)
return with(key, (Object) null);
return with(key, transformEnum(e));
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, String value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, Collection<?> value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, Map<String, String> value) {
return with(key, (Object) value);
}
/**
* With requester.
*
* @param body
* the body
* @return the requester
*/
public Requester with(@WillClose /* later */ InputStream body) {
this.body = body;
return this;
}
/**
* With nullable requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester withNullable(String key, Object value) {
args.add(new Entry(key, value));
return this;
}
/**
* With requester.
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester with(String key, Object value) {
if (value != null) {
args.add(new Entry(key, value));
}
return this;
}
/**
* Unlike {@link #with(String, String)}, overrides the existing value
*
* @param key
* the key
* @param value
* the value
* @return the requester
*/
public Requester set(String key, Object value) {
for (int index = 0; index < args.size(); index++) {
if (args.get(index).key.equals(key)) {
args.set(index, new Entry(key, value));
return this;
}
}
return with(key, value);
}
/**
* Method requester.
*
* @param method
* the method
* @return the requester
*/
public Requester method(String method) {
this.method = method;
return this;
}
/**
* Content type requester.
*
* @param contentType
* the content type
* @return the requester
*/
public Requester contentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* NOT FOR PUBLIC USE. Do not make this method public.
* <p>
* Sets the path component of api URL without URI encoding.
* <p>
* Should only be used when passing a literal URL field from a GHObject, such as {@link GHContent#refresh()} or when
* needing to set query parameters on requests methods that don't usually have them, such as
* {@link GHRelease#uploadAsset(String, InputStream, String)}.
*
* @param urlOrPath
* the content type
* @return the requester
*/
Requester setRawUrlPath(String urlOrPath) {
Objects.requireNonNull(urlOrPath);
this.urlPath = urlOrPath;
return this;
}
/**
* Path component of api URL. Appended to api url.
* <p>
* If urlPath starts with a slash, it will be URI encoded as a path. If it starts with anything else, it will be
* used as is.
*
* @param urlPathItems
* the content type
* @return the requester
*/
public Requester withUrlPath(String... urlPathItems) {
if (!this.urlPath.startsWith("/")) {
throw new GHException("Cannot append to url path after setting a raw path");
}
if (urlPathItems.length == 1 && !urlPathItems[0].startsWith("/")) {
return setRawUrlPath(urlPathItems[0]);
}
String tailUrlPath = String.join("/", urlPathItems);
if (this.urlPath.endsWith("/")) {
tailUrlPath = StringUtils.stripStart(tailUrlPath, "/");
} else {
tailUrlPath = StringUtils.prependIfMissing(tailUrlPath, "/");
}
this.urlPath += urlPathEncode(tailUrlPath);
return this;
}
/**
* Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected.
* Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method
* forces the parameters to be sent as a body.
*/
public Requester inBody() {
forceBody = true;
return this;
}
/**
* Sends a request to the specified URL and checks that it is sucessful.
*
* @throws IOException
* the io exception
*/
public void send() throws IOException {
_fetch(() -> parse(null, null));
}
/**
* Sends a request and parses the response into the given type via databinding.
*
* @param <T>
* the type parameter
* @param type
* the type
* @return {@link Reader} that reads the response.
* @throws IOException
* if the server returns 4xx/5xx responses.
*/
public <T> T fetch(@Nonnull Class<T> type) throws IOException {
return _fetch(() -> parse(type, null));
}
/**
* Sends a request and parses the response into an array of the given type via databinding.
*
* @param <T>
* the type parameter
* @param type
* the type
* @return {@link Reader} that reads the response.
* @throws IOException
* if the server returns 4xx/5xx responses.
*/
public <T> T[] fetchArray(@Nonnull Class<T[]> type) throws IOException {
T[] result = null;
try {
// for arrays we might have to loop for pagination
// use the iterator to handle it
List<T[]> pages = new ArrayList<>();
int totalSize = 0;
for (Iterator<T[]> iterator = asIterator(type, 0); iterator.hasNext();) {
T[] nextResult = iterator.next();
totalSize += Array.getLength(nextResult);
pages.add(nextResult);
}
result = concatenatePages(type, pages, totalSize);
} catch (GHException e) {
// if there was an exception inside the iterator it is wrapped as a GHException
// if the wrapped exception is an IOException, throw that
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw e;
}
}
return result;
}
/**
* Like {@link #fetch(Class)} but updates an existing object instead of creating a new instance.
*
* @param <T>
* the type parameter
* @param existingInstance
* the existing instance
* @return the t
* @throws IOException
* the io exception
*/
public <T> T fetchInto(@Nonnull T existingInstance) throws IOException {
return _fetch(() -> parse(null, existingInstance));
}
/**
* Makes a request and just obtains the HTTP status code. Method does not throw exceptions for many status codes
* that would otherwise throw.
*
* @return the int
* @throws IOException
* the io exception
*/
public int fetchHttpStatusCode() throws IOException {
return _fetch(() -> uc.getResponseCode());
}
/**
* As stream input stream.
*
* @return the input stream
* @throws IOException
* the io exception
*/
public InputStream fetchStream() throws IOException {
return _fetch(() -> parse(InputStream.class, null));
}
private <T> T _fetch(SupplierThrows<T, IOException> supplier) throws IOException {
String tailApiUrl = buildTailApiUrl(urlPath);
URL url = root.getApiURL(tailApiUrl);
return _fetch(tailApiUrl, url, supplier);
}
private <T> T _fetch(String tailApiUrl, URL url, SupplierThrows<T, IOException> supplier) throws IOException {
while (true) {// loop while API rate limit is hit
uc = setupConnection(url);
try {
retryInvalidCached404Response();
return supplier.get();
} catch (IOException e) {
handleApiError(e);
} finally {
noteRateLimit(tailApiUrl);
}
}
}
private <T> T[] concatenatePages(Class<T[]> type, List<T[]> pages, int totalLength) {
T[] result = type.cast(Array.newInstance(type.getComponentType(), totalLength));
int position = 0;
for (T[] page : pages) {
final int pageLength = Array.getLength(page);
System.arraycopy(page, 0, result, position, pageLength);
position += pageLength;
}
return result;
}
private String buildTailApiUrl(String tailApiUrl) {
if (!isMethodWithBody() && !args.isEmpty()) {
try {
boolean questionMarkFound = tailApiUrl.indexOf('?') != -1;
StringBuilder argString = new StringBuilder();
argString.append(questionMarkFound ? '&' : '?');
for (Iterator<Entry> it = args.listIterator(); it.hasNext();) {
Entry arg = it.next();
argString.append(URLEncoder.encode(arg.key, StandardCharsets.UTF_8.name()));
argString.append('=');
argString.append(URLEncoder.encode(arg.value.toString(), StandardCharsets.UTF_8.name()));
if (it.hasNext()) {
argString.append('&');
}
}
tailApiUrl += argString;
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e); // UTF-8 is mandatory
}
}
return tailApiUrl;
}
private void noteRateLimit(String tailApiUrl) {
if (uc == null) {
return;
}
if (tailApiUrl.startsWith("/search")) {
// the search API uses a different rate limit
return;
}
String limitString = uc.getHeaderField("X-RateLimit-Limit");
if (StringUtils.isBlank(limitString)) {
// if we are missing a header, return fast
return;
}
String remainingString = uc.getHeaderField("X-RateLimit-Remaining");
if (StringUtils.isBlank(remainingString)) {
// if we are missing a header, return fast
return;
}
String resetString = uc.getHeaderField("X-RateLimit-Reset");
if (StringUtils.isBlank(resetString)) {
// if we are missing a header, return fast
return;
}
int limit, remaining;
long reset;
try {
limit = Integer.parseInt(limitString);
} catch (NumberFormatException e) {
if (LOGGER.isLoggable(FINEST)) {
LOGGER.log(FINEST, "Malformed X-RateLimit-Limit header value " + limitString, e);
}
return;
}
try {
remaining = Integer.parseInt(remainingString);
} catch (NumberFormatException e) {
if (LOGGER.isLoggable(FINEST)) {
LOGGER.log(FINEST, "Malformed X-RateLimit-Remaining header value " + remainingString, e);
}
return;
}
try {
reset = Long.parseLong(resetString);
} catch (NumberFormatException e) {
if (LOGGER.isLoggable(FINEST)) {
LOGGER.log(FINEST, "Malformed X-RateLimit-Reset header value " + resetString, e);
}
return;
}
GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, uc.getHeaderField("Date"));
root.updateCoreRateLimit(observed);
}
/**
* Gets response header.
*
* @param header
* the header
* @return the response header
*/
public String getResponseHeader(String header) {
return uc.getHeaderField(header);
}
/**
* Set up the request parameters or POST payload.
*/
private void buildRequest(HttpURLConnection connection) throws IOException {
if (isMethodWithBody()) {
connection.setDoOutput(true);
if (body == null) {
connection.setRequestProperty("Content-type", defaultString(contentType, "application/json"));
Map json = new HashMap();
for (Entry e : args) {
json.put(e.key, e.value);
}
MAPPER.writeValue(connection.getOutputStream(), json);
} else {
connection.setRequestProperty("Content-type",
defaultString(contentType, "application/x-www-form-urlencoded"));
try {
byte[] bytes = new byte[32768];
int read;
while ((read = body.read(bytes)) != -1) {
connection.getOutputStream().write(bytes, 0, read);
}
} finally {
body.close();
}
}
}
}
private boolean isMethodWithBody() {
return forceBody || !METHODS_WITHOUT_BODY.contains(method);
}
<T> PagedIterable<T> toIterable(Class<T[]> type, Consumer<T> consumer) {
return new PagedIterableWithConsumer<>(type, consumer);
}
class PagedIterableWithConsumer<T> extends PagedIterable<T> {
private final Class<T[]> clazz;
private final Consumer<T> consumer;
PagedIterableWithConsumer(Class<T[]> clazz, Consumer<T> consumer) {
this.clazz = clazz;
this.consumer = consumer;
}
@Override
public PagedIterator<T> _iterator(int pageSize) {
final Iterator<T[]> iterator = asIterator(clazz, pageSize);
return new PagedIterator<T>(iterator) {
@Override
protected void wrapUp(T[] page) {
if (consumer != null) {
for (T item : page) {
consumer.accept(item);
}
}
}
};
}
}
/**
* Loads paginated resources.
*
* @param type
* type of each page (not the items in the page).
* @param pageSize
* the size of the
* @param <T>
* type of each page (not the items in the page).
* @return
*/
<T> Iterator<T> asIterator(Class<T> type, int pageSize) {
if (!"GET".equals(method)) {
throw new IllegalStateException("Request method \"GET\" is required for iterator.");
}
if (pageSize > 0)
args.add(new Entry("per_page", pageSize));
String tailApiUrl = buildTailApiUrl(urlPath);
try {
return new PagingIterator<>(type, tailApiUrl, root.getApiURL(tailApiUrl));
} catch (IOException e) {
throw new GHException("Unable to build github Api URL", e);
}
}
/**
* May be used for any item that has pagination information.
*
* Works for array responses, also works for search results which are single instances with an array of items
* inside.
*
* @param <T>
* type of each page (not the items in the page).
*/
class PagingIterator<T> implements Iterator<T> {
private final Class<T> type;
private final String tailApiUrl;
/**
* The next batch to be returned from {@link #next()}.
*/
private T next;
/**
* URL of the next resource to be retrieved, or null if no more data is available.
*/
private URL url;
PagingIterator(Class<T> type, String tailApiUrl, URL url) {
this.type = type;
this.tailApiUrl = tailApiUrl;
this.url = url;
}
public boolean hasNext() {
fetch();
return next != null;
}
public T next() {
fetch();
T r = next;
if (r == null)
throw new NoSuchElementException();
next = null;
return r;
}
public void remove() {
throw new UnsupportedOperationException();
}
private void fetch() {
if (next != null)
return; // already fetched
if (url == null)
return; // no more data to fetch
try {
next = _fetch(tailApiUrl, url, () -> parse(type, null));
assert next != null;
findNextURL();
} catch (IOException e) {
throw new GHException("Failed to retrieve " + url, e);
}
}
/**
* Locate the next page from the pagination "Link" tag.
*/
private void findNextURL() throws MalformedURLException {
url = null; // start defensively
String link = uc.getHeaderField("Link");
if (link == null)
return;
for (String token : link.split(", ")) {
if (token.endsWith("rel=\"next\"")) {
// found the next page. This should look something like
int idx = token.indexOf('>');
url = new URL(token.substring(1, idx));
return;
}
}
// no more "next" link. we are done.
}
}
private HttpURLConnection setupConnection(URL url) throws IOException {
if (LOGGER.isLoggable(FINE)) {
LOGGER.log(FINE,
"GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + " "
+ url.toString());
}
HttpURLConnection connection = root.getConnector().connect(url);
// if the authentication is needed but no credential is given, try it anyway (so that some calls
// that do work with anonymous access in the reduced form should still work.)
if (root.encodedAuthorization != null)
connection.setRequestProperty("Authorization", root.encodedAuthorization);
for (Map.Entry<String, String> e : headers.entrySet()) {
String v = e.getValue();
if (v != null)
connection.setRequestProperty(e.getKey(), v);
}
setRequestMethod(connection);
connection.setRequestProperty("Accept-Encoding", "gzip");
buildRequest(connection);
return connection;
}
private void setRequestMethod(HttpURLConnection connection) throws IOException {
try {
connection.setRequestMethod(method);
} catch (ProtocolException e) {
// JDK only allows one of the fixed set of verbs. Try to override that
try {
Field $method = HttpURLConnection.class.getDeclaredField("method");
$method.setAccessible(true);
$method.set(connection, method);
} catch (Exception x) {
throw (IOException) new IOException("Failed to set the custom verb").initCause(x);
}
try {
Field $delegate = connection.getClass().getDeclaredField("delegate");
$delegate.setAccessible(true);
Object delegate = $delegate.get(connection);
if (delegate instanceof HttpURLConnection) {
HttpURLConnection nested = (HttpURLConnection) delegate;
setRequestMethod(nested);
}
} catch (NoSuchFieldException x) {
// no problem
} catch (IllegalAccessException x) {
throw (IOException) new IOException("Failed to set the custom verb").initCause(x);
}
}
if (!connection.getRequestMethod().equals(method))
throw new IllegalStateException("Failed to set the request method to " + method);
}
@CheckForNull
private <T> T parse(Class<T> type, T instance) throws IOException {
return parse(type, instance, 2);
}
private <T> T parse(Class<T> type, T instance, int timeouts) throws IOException {
InputStreamReader r = null;
int responseCode = -1;
String responseMessage = null;
try {
responseCode = uc.getResponseCode();
responseMessage = uc.getResponseMessage();
if (responseCode == 304) {
return null; // special case handling for 304 unmodified, as the content will be ""
}
if (responseCode == 204 && type != null && type.isArray()) {
// no content
return type.cast(Array.newInstance(type.getComponentType(), 0));
}
// Response code 202 means data is being generated still being cached.
// This happens in for statistics:
// See https://developer.github.com/v3/repos/statistics/#a-word-about-caching
// And for fork creation:
// See https://developer.github.com/v3/repos/forks/#create-a-fork
if (responseCode == 202) {
if (uc.getURL().toString().endsWith("/forks")) {
LOGGER.log(INFO, "The fork is being created. Please try again in 5 seconds.");
} else if (uc.getURL().toString().endsWith("/statistics")) {
LOGGER.log(INFO, "The statistics are being generated. Please try again in 5 seconds.");
} else {
LOGGER.log(INFO,
"Received 202 from " + uc.getURL().toString() + " . Please try again in 5 seconds.");
}
// Maybe throw an exception instead?
return null;
}
if (type != null && type.equals(InputStream.class)) {
return type.cast(wrapStream(uc.getInputStream()));
}
r = new InputStreamReader(wrapStream(uc.getInputStream()), StandardCharsets.UTF_8);
String data = IOUtils.toString(r);
if (type != null)
try {
return setResponseHeaders(MAPPER.readValue(data, type));
} catch (JsonMappingException e) {
String message = "Failed to deserialize " + data;
throw (IOException) new IOException(message).initCause(e);
}
if (instance != null) {
return setResponseHeaders(MAPPER.readerForUpdating(instance).<T>readValue(data));
}
return null;
} catch (FileNotFoundException e) {
// java.net.URLConnection handles 404 exception as FileNotFoundException,
// don't wrap exception in HttpException to preserve backward compatibility
throw e;
} catch (IOException e) {
if ((e instanceof SocketException || e instanceof SocketTimeoutException) && timeouts > 0) {
LOGGER.log(INFO,
"timed out accessing " + uc.getURL() + ". Sleeping " + Requester.retryTimeoutMillis
+ " milliseconds before retrying... ; will try " + timeouts + " more time(s)",
e);
try {
Thread.sleep(Requester.retryTimeoutMillis);
} catch (InterruptedException ie) {
throw (IOException) new InterruptedIOException().initCause(e);
}
uc = setupConnection(uc.getURL());
return parse(type, instance, timeouts - 1);
}
throw new HttpException(responseCode, responseMessage, uc.getURL(), e);
} finally {
IOUtils.closeQuietly(r);
}
}
private void retryInvalidCached404Response() throws IOException {
// WORKAROUND FOR ISSUE #669:
// When the Requester detects a 404 response with an ETag (only happpens when the server's 304
// is bogus and would cause cache corruption), try the query again with new request header
// that forces the server to not return 304 and return new data instead.
// This solution is transparent to users of this library and automatically handles a
// situation that was cause insidious and hard to debug bad responses in caching
// scenarios. If GitHub ever fixes their issue and/or begins providing accurate ETags to
// their 404 responses, this will result in at worst two requests being made for each 404
// responses. However, only the second request will count against rate limit.
int responseCode = 0;
try {
uc.getResponseCode();
} catch (Exception e) {
}
if (responseCode == 404 && Objects.equals(uc.getRequestMethod(), "GET") && uc.getHeaderField("ETag") != null
&& !Objects.equals(uc.getRequestProperty("Cache-Control"), "no-cache")) {
uc = setupConnection(uc.getURL());
// Setting "Cache-Control" to "no-cache" stops the cache from supplying
// "If-Modified-Since" or "If-None-Match" values.
// This makes GitHub give us current data (not incorrectly cached data)
uc.setRequestProperty("Cache-Control", "no-cache");
uc.getResponseCode();
}
}
private <T> T setResponseHeaders(T readValue) {
if (readValue instanceof GHObject[]) {
for (GHObject ghObject : (GHObject[]) readValue) {
setResponseHeaders(ghObject);
}
} else if (readValue instanceof GHObject) {
setResponseHeaders((GHObject) readValue);
} else if (readValue instanceof JsonRateLimit) {
// if we're getting a GHRateLimit it needs the server date
((JsonRateLimit) readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date"));
}
return readValue;
}
private void setResponseHeaders(GHObject readValue) {
readValue.responseHeaderFields = uc.getHeaderFields();
}
/**
* Handles the "Content-Encoding" header.
*/
private InputStream wrapStream(InputStream in) throws IOException {
String encoding = uc.getContentEncoding();
if (encoding == null || in == null)
return in;
if (encoding.equals("gzip"))
return new GZIPInputStream(in);
throw new UnsupportedOperationException("Unexpected Content-Encoding: " + encoding);
}
/**
* Handle API error by either throwing it or by returning normally to retry.
*/
void handleApiError(IOException e) throws IOException {
int responseCode;
try {
responseCode = uc.getResponseCode();
} catch (IOException e2) {
// likely to be a network exception (e.g. SSLHandshakeException),
// uc.getResponseCode() and any other getter on the response will cause an exception
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE,
"Silently ignore exception retrieving response code for '" + uc.getURL() + "'"
+ " handling exception " + e,
e);
throw e;
}
InputStream es = wrapStream(uc.getErrorStream());
if (es != null) {
try {
String error = IOUtils.toString(es, StandardCharsets.UTF_8);
if (e instanceof FileNotFoundException) {
// pass through 404 Not Found to allow the caller to handle it intelligently
e = (IOException) new GHFileNotFoundException(error).withResponseHeaderFields(uc).initCause(e);
} else if (e instanceof HttpException) {
HttpException http = (HttpException) e;
e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e);
} else {
e = (IOException) new GHIOException(error).withResponseHeaderFields(uc).initCause(e);
}
} finally {
IOUtils.closeQuietly(es);
}
}
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 Unauthorized == bad creds or OTP request
// In the case of a user with 2fa enabled, a header with X-GitHub-OTP
// will be returned indicating the user needs to respond with an otp
if (uc.getHeaderField("X-GitHub-OTP") != null)
throw (IOException) new GHOTPRequiredException().withResponseHeaderFields(uc).initCause(e);
else
throw e; // usually org.kohsuke.github.HttpException (which extends IOException)
if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) {
root.rateLimitHandler.onError(e, uc);
return;
}
// Retry-After is not documented but apparently that field exists
if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) {
this.root.abuseLimitHandler.onError(e, uc);
return;
}
throw e;
}
/**
* Transform Java Enum into Github constants given its conventions
*
* @param en
* Enum to be transformed
* @return a String containing the value of a Github constant
*/
static String transformEnum(Enum en) {
// by convention Java constant names are upper cases, but github uses
// lower-case constants. GitHub also uses '-', which in Java we always
// replace by '_'
return en.toString().toLowerCase(Locale.ENGLISH).replace('_', '-');
}
/**
* Encode the path to url safe string.
*
* @param value
* string to be path encoded.
* @return The encoded string.
*/
public static String urlPathEncode(String value) {
try {
return new URI(null, null, value, null, null).toString();
} catch (URISyntaxException ex) {
throw new AssertionError(ex);
}
}
private static final List<String> METHODS_WITHOUT_BODY = asList("GET", "DELETE");
private static final Logger LOGGER = Logger.getLogger(Requester.class.getName());
/**
* Represents a supplier of results that can throw.
*
* <p>
* This is a <a href="package-summary.html">functional interface</a> whose functional method is {@link #get()}.
*
* @param <T>
* the type of results supplied by this supplier
* @param <E>
* the type of throwable that could be thrown
*/
@FunctionalInterface
interface SupplierThrows<T, E extends Throwable> {
/**
* Gets a result.
*
* @return a result
* @throws E
*/
T get() throws E;
}
}
|
package org.lightmare.jpa;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.jndi.JndiManager;
import org.lightmare.jpa.jta.HibernateConfig;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.NamingUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Creates and caches {@link EntityManagerFactory} for each EJB bean
* {@link Class}'s appropriate field (annotated by @PersistenceContext)
*
* @author Levan
*
*/
public class JpaManager {
private List<String> classes;
private String path;
private URL url;
private Map<Object, Object> properties;
private boolean swapDataSource;
private boolean scanArchives;
private ClassLoader loader;
private static final Logger LOG = Logger.getLogger(JpaManager.class);
private JpaManager() {
}
/**
* Checks if entity persistence.xml {@link URL} is provided
*
* @return boolean
*/
private boolean checkForURL() {
return ObjectUtils.notNull(url)
&& ObjectUtils.available(url.toString());
}
/**
* Checks if entity classes or persistence.xml path are provided
*
* @param classes
* @return boolean
*/
private boolean checkForBuild() {
return ObjectUtils.available(classes) || ObjectUtils.available(path)
|| checkForURL() || swapDataSource || scanArchives;
}
/**
* Added transaction properties for JTA data sources
*/
private void addTransactionManager() {
if (properties == null) {
properties = new HashMap<Object, Object>();
}
properties.put(HibernateConfig.FACTORY_KEY,
HibernateConfig.FACTORY_VALUE);
properties.put(HibernateConfig.PLATFORM_KEY,
HibernateConfig.PLATFORM_VALUE);
}
/**
* Creates {@link EntityManagerFactory} by hibernate or by extended builder
* {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file
* path are provided
*
* @see Ejb3ConfigurationImpl#configure(String, Map) and
* Ejb3ConfigurationImpl#createEntityManagerFactory()
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
@SuppressWarnings("deprecation")
private EntityManagerFactory buildEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
Ejb3ConfigurationImpl cfg;
boolean pathCheck = ObjectUtils.available(path);
boolean urlCheck = checkForURL();
Ejb3ConfigurationImpl.Builder builder = new Ejb3ConfigurationImpl.Builder();
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
}
if (ObjectUtils.available(classes)) {
builder.setClasses(classes);
// Loads entity classes to current ClassLoader instance
LibraryLoader.loadClasses(classes, loader);
}
if (pathCheck || urlCheck) {
Enumeration<URL> xmls;
ConfigLoader configLoader = new ConfigLoader();
if (pathCheck) {
xmls = configLoader.readFile(path);
} else {
xmls = configLoader.readURL(url);
}
builder.setXmls(xmls);
String shortPath = configLoader.getShortPath();
builder.setShortPath(shortPath);
}
builder.setSwapDataSource(swapDataSource);
builder.setScanArchives(scanArchives);
builder.setOverridenClassLoader(loader);
cfg = builder.build();
if (ObjectUtils.notTrue(swapDataSource)) {
addTransactionManager();
}
Ejb3ConfigurationImpl configured = cfg.configure(unitName, properties);
emf = ObjectUtils.notNull(configured) ? configured
.buildEntityManagerFactory() : null;
return emf;
}
/**
* Checks if entity classes or persistence.xml file path are provided to
* create {@link EntityManagerFactory}
*
* @see #buildEntityManagerFactory(String, String, Map, List)
*
* @param unitName
* @param properties
* @param path
* @param classes
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private EntityManagerFactory createEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
if (checkForBuild()) {
emf = buildEntityManagerFactory(unitName);
} else if (properties == null) {
emf = Persistence.createEntityManagerFactory(unitName);
} else {
emf = Persistence.createEntityManagerFactory(unitName, properties);
}
return emf;
}
/**
* Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext}
*
* @param jndiName
* @param unitName
* @param emf
* @throws IOException
*/
private void bindJndiName(ConnectionSemaphore semaphore) throws IOException {
boolean bound = semaphore.isBound();
if (!bound) {
String jndiName = semaphore.getJndiName();
if (ObjectUtils.available(jndiName)) {
JndiManager jndiManager = new JndiManager();
try {
String fullJndiName = NamingUtils
.createJpaJndiName(jndiName);
if (jndiManager.lookup(fullJndiName) == null) {
jndiManager.rebind(fullJndiName, semaphore.getEmf());
}
semaphore.setBound(Boolean.TRUE);
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw new IOException(String.format(
"could not bind connection %s",
semaphore.getUnitName()), ex);
}
} else {
semaphore.setBound(Boolean.TRUE);
}
}
}
/**
* Builds connection, wraps it in {@link ConnectionSemaphore} locks and
* caches appropriate instance
*
* @param unitName
* @throws IOException
*/
public void setConnection(String unitName) throws IOException {
ConnectionSemaphore semaphore = ConnectionContainer
.getSemaphore(unitName);
if (semaphore.isInProgress()) {
EntityManagerFactory emf = createEntityManagerFactory(unitName);
semaphore.setEmf(emf);
semaphore.setInProgress(Boolean.FALSE);
bindJndiName(semaphore);
} else if (semaphore.getEmf() == null) {
throw new IOException(String.format(
"Connection %s was not in progress", unitName));
} else {
bindJndiName(semaphore);
}
}
/**
* Closes passed {@link EntityManagerFactory}
*
* @param emf
*/
public static void closeEntityManagerFactory(EntityManagerFactory emf) {
if (ObjectUtils.notNull(emf) && emf.isOpen()) {
emf.close();
}
}
public static void closeEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em) && em.isOpen()) {
em.close();
}
}
/**
* Builder class to create {@link JpaManager} class object
*
* @author Levan
*
*/
public static class Builder {
private JpaManager manager;
public Builder() {
manager = new JpaManager();
manager.scanArchives = Boolean.TRUE;
}
/**
* Sets {@link javax.persistence.Entity} class names to initialize
*
* @param classes
* @return {@link Builder}
*/
public Builder setClasses(List<String> classes) {
manager.classes = classes;
return this;
}
/**
* Sets {@link URL} for persistence.xml file
*
* @param url
* @return {@link Builder}
*/
public Builder setURL(URL url) {
manager.url = url;
return this;
}
/**
* Sets path for persistence.xml file
*
* @param path
* @return {@link Builder}
*/
public Builder setPath(String path) {
manager.path = path;
return this;
}
/**
* Sets additional persistence properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setProperties(Map<Object, Object> properties) {
manager.properties = properties;
return this;
}
/**
* Sets boolean check property to swap jta data source value with non
* jta data source value
*
* @param swapDataSource
* @return {@link Builder}
*/
public Builder setSwapDataSource(boolean swapDataSource) {
manager.swapDataSource = swapDataSource;
return this;
}
/**
* Sets boolean check to scan deployed archive files for
* {@link javax.persistence.Entity} annotated classes
*
* @param scanArchives
* @return {@link Builder}
*/
public Builder setScanArchives(boolean scanArchives) {
manager.scanArchives = scanArchives;
return this;
}
/**
* Sets {@link ClassLoader} for persistence classes
*
* @param loader
* @return {@link Builder}
*/
public Builder setClassLoader(ClassLoader loader) {
manager.loader = loader;
return this;
}
public JpaManager build() {
return manager;
}
}
}
|
package org.lightmare.jpa;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.log4j.Logger;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.ConnectionSemaphore;
import org.lightmare.config.Configuration;
import org.lightmare.jndi.JndiManager;
import org.lightmare.jpa.hibernate.jpa.HibernatePersistenceProviderExt;
import org.lightmare.jpa.jta.HibernateConfig;
import org.lightmare.libraries.LibraryLoader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.NamingUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
/**
* Creates and caches {@link EntityManagerFactory} for each EJB bean
* {@link Class}'s appropriate field (annotated by @PersistenceContext)
*
* @author Levan Tsinadze
* @since 0.0.79-SNAPSHOT
*/
public class JpaManager {
// Entity classes
private List<String> classes;
private String path;
private URL url;
// Additional properties
private Map<Object, Object> properties;
private boolean swapDataSource;
private boolean scanArchives;
// Initialize level class loader
private ClassLoader loader;
// Error message for connection binding to JNDI names
private static final String COULD_NOT_BIND_JNDI_ERROR = "could not bind connection";
private static final Logger LOG = Logger.getLogger(JpaManager.class);
/**
* Private constructor to avoid initialization beside
* {@link JpaManager.Builder} class
*/
private JpaManager() {
}
/**
* Checks if entity persistence.xml {@link URL} is provided
*
* @return boolean
*/
private boolean checkForURL() {
return ObjectUtils.notNull(url) && StringUtils.valid(url.toString());
}
/**
* Added transaction properties for JTA data sources
*/
private void addTransactionManager() {
if (properties == null) {
properties = new HashMap<Object, Object>();
}
HibernateConfig[] hibernateConfigs = HibernateConfig.values();
for (HibernateConfig hibernateConfig : hibernateConfigs) {
properties.put(hibernateConfig.key, hibernateConfig.value);
}
}
/**
* Creates {@link EntityManagerFactory} by hibernate or by extended builder
* {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file
* path are provided
*
* @see Ejb3ConfigurationImpl#configure(String, Map) and
* Ejb3ConfigurationImpl#createEntityManagerFactory()
*
* @param unitName
* @return {@link EntityManagerFactory}
*/
private EntityManagerFactory buildEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf;
HibernatePersistenceProvider provider;
boolean pathCheck = StringUtils.valid(path);
boolean urlCheck = checkForURL();
HibernatePersistenceProviderExt.Builder builder = new HibernatePersistenceProviderExt.Builder();
if (loader == null) {
loader = LibraryLoader.getContextClassLoader();
}
if (CollectionUtils.valid(classes)) {
builder.setClasses(classes);
// Loads entity classes to current ClassLoader instance
LibraryLoader.loadClasses(classes, loader);
}
if (pathCheck || urlCheck) {
List<URL> xmls;
ConfigLoader configLoader = new ConfigLoader();
if (pathCheck) {
xmls = configLoader.readFile(path);
} else {
xmls = configLoader.readURL(url);
}
builder.setXmls(xmls);
String shortPath = configLoader.getShortPath();
builder.setShortPath(shortPath);
}
builder.setSwapDataSource(swapDataSource);
builder.setScanArchives(scanArchives);
builder.setOverridenClassLoader(loader);
provider = builder.build();
if (ObjectUtils.notTrue(swapDataSource)) {
addTransactionManager();
}
emf = provider.createEntityManagerFactory(unitName, properties);
return emf;
}
/**
* Checks if entity classes or persistence.xml file path are provided to
* create {@link EntityManagerFactory}
*
* @see #buildEntityManagerFactory(String, String, Map, List)
*
* @param unitName
* @param properties
* @param path
* @param classes
* @return {@link EntityManagerFactory}
* @throws IOException
*/
private EntityManagerFactory createEntityManagerFactory(String unitName)
throws IOException {
EntityManagerFactory emf = buildEntityManagerFactory(unitName);
return emf;
}
/**
* Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext}
*
* @param jndiName
* @param unitName
* @param emf
* @throws IOException
*/
private void bindJndiName(ConnectionSemaphore semaphore) throws IOException {
boolean bound = semaphore.isBound();
if (ObjectUtils.notTrue(bound)) {
String jndiName = semaphore.getJndiName();
if (StringUtils.valid(jndiName)) {
JndiManager jndiManager = new JndiManager();
try {
String fullJndiName = NamingUtils
.createJpaJndiName(jndiName);
if (jndiManager.lookup(fullJndiName) == null) {
jndiManager.rebind(fullJndiName, semaphore.getEmf());
}
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
String errorMessage = StringUtils.concat(
COULD_NOT_BIND_JNDI_ERROR, semaphore.getUnitName());
throw new IOException(errorMessage, ex);
}
}
}
semaphore.setBound(Boolean.TRUE);
}
/**
* Builds connection, wraps it in {@link ConnectionSemaphore} locks and
* caches appropriate instance
*
* @param unitName
* @throws IOException
*/
public void create(String unitName) throws IOException {
ConnectionSemaphore semaphore = ConnectionContainer
.getSemaphore(unitName);
if (semaphore.isInProgress()) {
EntityManagerFactory emf = createEntityManagerFactory(unitName);
semaphore.setEmf(emf);
semaphore.setInProgress(Boolean.FALSE);
bindJndiName(semaphore);
} else if (semaphore.getEmf() == null) {
String errorMessage = String.format(
"Connection %s was not in progress", unitName);
throw new IOException(errorMessage);
} else {
bindJndiName(semaphore);
}
}
/**
* Closes passed {@link EntityManagerFactory}
*
* @param emf
*/
public static void closeEntityManagerFactory(EntityManagerFactory emf) {
if (ObjectUtils.notNull(emf) && emf.isOpen()) {
emf.close();
}
}
/**
* Closes passed {@link EntityManager} instance if it is not null and it is
* open
*
* @param em
*/
public static void closeEntityManager(EntityManager em) {
if (ObjectUtils.notNull(em) && em.isOpen()) {
em.close();
}
}
/**
* Builder class to create {@link JpaManager} class object
*
* @author Levan Tsinadze
* @since 0.0.79-SNAPSHOT
*/
public static class Builder {
private JpaManager manager;
public Builder() {
manager = new JpaManager();
manager.scanArchives = Boolean.TRUE;
}
/**
* Sets {@link javax.persistence.Entity} class names to initialize
*
* @param classes
* @return {@link Builder}
*/
public Builder setClasses(List<String> classes) {
manager.classes = classes;
return this;
}
/**
* Sets {@link URL} for persistence.xml file
*
* @param url
* @return {@link Builder}
*/
public Builder setURL(URL url) {
manager.url = url;
return this;
}
/**
* Sets path for persistence.xml file
*
* @param path
* @return {@link Builder}
*/
public Builder setPath(String path) {
manager.path = path;
return this;
}
/**
* Sets additional persistence properties
*
* @param properties
* @return {@link Builder}
*/
public Builder setProperties(Map<Object, Object> properties) {
manager.properties = properties;
return this;
}
/**
* Sets boolean check property to swap jta data source value with non
* JTA data source value
*
* @param swapDataSource
* @return {@link Builder}
*/
public Builder setSwapDataSource(boolean swapDataSource) {
manager.swapDataSource = swapDataSource;
return this;
}
/**
* Sets boolean check to scan deployed archive files for
* {@link javax.persistence.Entity} annotated classes
*
* @param scanArchives
* @return {@link Builder}
*/
public Builder setScanArchives(boolean scanArchives) {
manager.scanArchives = scanArchives;
return this;
}
/**
* Sets {@link ClassLoader} for persistence classes
*
* @param loader
* @return {@link Builder}
*/
public Builder setClassLoader(ClassLoader loader) {
manager.loader = loader;
return this;
}
/**
* Sets all parameters from passed {@link Configuration} instance
*
* @param configuration
* @return {@link Builder}
*/
public Builder configure(Configuration configuration) {
// Sets all parameters from Configuration class
setPath(configuration.getPersXmlPath())
.setProperties(configuration.getPersistenceProperties())
.setSwapDataSource(configuration.isSwapDataSource())
.setScanArchives(configuration.isScanArchives());
return this;
}
public JpaManager build() {
return manager;
}
}
}
|
package org.marat.advent.day03;
import org.apache.commons.lang3.StringUtils;
import org.marat.advent.common.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Day03 {
public static void main(String[] args) {
Pattern delimiter = Pattern.compile("\\W+");
String[] sides = Util.readElementsWithDelimiter("day03/input.txt", delimiter)
.map(StringUtils::trim)
.filter(StringUtils::isNotEmpty)
.collect(Collectors.toList())
.toArray(new String[0]);
if (sides.length % 3 != 0) {
throw new IllegalArgumentException();
}
List<Triangle> triangles = new ArrayList<>(sides.length / 3);
for (int i = 0; i < sides.length; i += 9) {
for (int j = 0; j < 3; j++) {
triangles.add(new Triangle(
Integer.parseInt(sides[i + j]),
Integer.parseInt(sides[i + j + 3]),
Integer.parseInt(sides[i + j + 6])
));
}
}
long count = triangles.stream().filter(Triangle::isValid).count();
System.out.println(count);
}
static class Triangle {
private final int a;
private final int b;
private final int c;
public Triangle(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public boolean isValid() {
return (a + b) > c && (b + c) > a && (a + c) > b;
}
}
}
|
package org.myrobotlab.service;
import java.util.Map;
import java.util.TreeMap;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.repo.Repo;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
public class Intro extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Intro.class);
public class TutorialInfo {
public String id;
public String title;
public boolean isInstalled;
public String[] servicesRequired;
public String script;
}
Map<String, TutorialInfo> tutorials = new TreeMap<>();
public Intro(String n, String id) {
super(n, id);
try {
Runtime runtime = Runtime.getInstance();
Repo repo = runtime.getRepo();
TutorialInfo tuto = new TutorialInfo();
tuto.id = "servo-hardware";
tuto.title = "Servo with Arduino Hardware";
tuto.servicesRequired = new String[] { "Servo", "Arduino" };
tuto.isInstalled = repo.isInstalled(Servo.class) && repo.isInstalled(Arduino.class);
tuto.script = getResourceAsString(Servo.class, "Servo.py"); //FileIO.toString(getResource(Servo.class,"Servo.py"));
tutorials.put(tuto.title, tuto);
} catch (Exception e) {
log.error("Intro constructor threw", e);
}
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Intro.class);
meta.addDescription("Introduction to MyRobotlab");
meta.setAvailable(true);
meta.addCategory("general");
return meta;
}
public void checkInstalled(String forTutorial, String serviceType) {
Runtime runtime = Runtime.getInstance();
Repo repo = runtime.getRepo();
TutorialInfo tutorial = new TutorialInfo();
tutorial.title = forTutorial;
tutorial.isInstalled = repo.isInstalled(serviceType);
}
/**
* This method will load a python file into the python interpreter.
*/
public static boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Runtime.main(new String[] { "--interactive", "--id", "admin", "-s", "intro", "Intro", "python", "Python" });
// Arduino arduino = (Arduino)Runtime.start("arduino", "Arduino");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
// webgui.setSsl(true);
webgui.autoStartBrowser(false);
webgui.setPort(8888);
webgui.startService();
} catch (Exception e) {
log.error("main threw", e);
}
}
}
|
package eu.fireblade.fireffa.ability;
import java.util.ArrayList;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import eu.fireblade.fireffa.Main;
import eu.fireblade.fireffa.Var;
import eu.fireblade.fireffa.events.PlayerInteractAtPlayerEvent;
import eu.fireblade.fireffa.items.Kits;
import fr.glowstoner.api.bukkit.title.GlowstoneTitle;
public class RobinDesBois implements Listener {
public static ArrayList<Player> cooldown = new ArrayList<Player>();
@EventHandler
public void onInteract(PlayerInteractAtPlayerEvent e){
final Player p = e.getPlayer();
final Player t = e.getTarget();
final ItemStack i = e.getItemInHand();
if(Var.robindesbois.contains(p) && i.equals(Kits.ItemGen1(Material.WOOD_SWORD, Enchantment.DAMAGE_ALL, 1, "9pe des bois",
Kits.LoreCreator("9clique droit - vole un item alatoire au joueur", "930 secondes de rcupration"), 1))){
if(cooldown.contains(p)) {
p.sendMessage(ChatColor.GOLD+"6[eFireFFA6] "+ChatColor.RED+"Vous tes en cooldown pour cette attaque !");
p.playSound(p.getLocation(), Sound.ITEM_BREAK, 30, 30);
return;
}else {
ItemStack[] targetItem = t.getInventory().getContents();
ItemStack[] targetArmor = t.getInventory().getArmorContents();
ArrayList<ItemStack> targetAll = new ArrayList<ItemStack>();
for(ItemStack inList : targetItem) {
if(inList != null) {
targetAll.add(inList);
}
}
for(ItemStack inList : targetArmor) {
if(inList != null) {
targetAll.add(inList);
}
}
Random r = new Random();
int item = r.nextInt(targetAll.size());
if(item > targetAll.size() - 1) item
p.getInventory().addItem(targetAll.get(item));
t.getInventory().remove(targetAll.get(item));
cooldown.add(p);
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() {
@Override
public void run() {
if(Var.robindesbois.contains(p)){
GlowstoneTitle gt = new GlowstoneTitle(p, "", "9Votre attaque est prte !", 20, 30, 20);
gt.send();
p.playSound(p.getLocation(), Sound.ORB_PICKUP, 30, 30);
}
if(cooldown.contains(p)) {
cooldown.remove(p);
}
}
}, 600L);
}
}
}
}
|
package org.opennars.io;
import org.opennars.interfaces.pub.Reasoner;
import org.opennars.main.NarParameters;
import org.opennars.main.Parameters;
import org.opennars.plugin.Plugin;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class ConfigReader {
public static void loadFrom(final String filepath, final Reasoner reasoner, final NarParameters parameters) throws IOException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException {
loadFromImpl(new File(filepath), reasoner, parameters);
}
public static void loadFrom(final File file, final Reasoner reasoner, final NarParameters parameters) throws IOException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException {
loadFromImpl(file, reasoner, parameters);
}
private static void loadFromImpl(final File file, final Reasoner reasoner, final NarParameters parameters) throws IOException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException {
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.parse(file);
final NodeList config = document.getElementsByTagName("config").item(0).getChildNodes();
for (int iterationConfigIdx = 0; iterationConfigIdx < config.getLength(); iterationConfigIdx++) {
final Node iConfig = config.item(iterationConfigIdx);
if (iConfig.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
final String nodeName = iConfig.getNodeName();
if( nodeName.equals("plugins") ) {
final NodeList plugins = iConfig.getChildNodes();
for (int iterationPluginIdx = 0; iterationPluginIdx < config.getLength(); iterationPluginIdx++) {
final Node iPlugin = plugins.item(iterationPluginIdx);
if (iPlugin.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
final String pluginClassPath = iPlugin.getAttributes().getNamedItem("classpath").getNodeValue();
final NodeList arguments = iPlugin.getChildNodes();
Plugin createdPlugin = createPluginByClassnameAndArguments(pluginClassPath, arguments, reasoner);
reasoner.addPlugin(createdPlugin);
}
}
else {
final String propertyName = iConfig.getAttributes().getNamedItem("name").getNodeValue();
final String propertyValueAsString = iConfig.getAttributes().getNamedItem("value").getNodeValue();
boolean wasConfigValueAssigned = false;
try {
final Field fieldOfProperty = NarParameters.class.getField(propertyName);
if (fieldOfProperty.getType() == int.class) {
fieldOfProperty.set(parameters, Integer.parseInt(propertyValueAsString));
} else if (fieldOfProperty.getType() == float.class) {
fieldOfProperty.set(parameters, Float.parseFloat(propertyValueAsString));
} else {
throw new ParseException("Unknown type", 0);
}
wasConfigValueAssigned = true;
} catch (NoSuchFieldException e) {
// ignore
}
if (!wasConfigValueAssigned) {
try {
final Field fieldOfProperty = Parameters.class.getDeclaredField(propertyName);
if (fieldOfProperty.getType() == int.class) {
fieldOfProperty.set(parameters, Integer.parseInt(propertyValueAsString));
} else if (fieldOfProperty.getType() == float.class) {
fieldOfProperty.set(parameters, Float.parseFloat(propertyValueAsString));
} else {
throw new ParseException("Unknown type", 0);
}
wasConfigValueAssigned = true;
} catch (NoSuchFieldException e) {
// ignore
}
}
}
}
}
private static Plugin createPluginByClassnameAndArguments(String pluginClassPath, NodeList arguments, Reasoner reasoner) throws ParseException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
List<Class> types = new ArrayList<>();
List<Object> values = new ArrayList<>();
for (int parameterIdx = 0; parameterIdx < arguments.getLength(); parameterIdx++) {
final Node iParameter = arguments.item(parameterIdx);
if (iParameter.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
String typeString = null;
String valueString = null;
final boolean specialIsReasoner = iParameter.getAttributes().getNamedItem("isReasoner") != null;
if (!specialIsReasoner) {
typeString = iParameter.getAttributes().getNamedItem("type").getNodeValue();
valueString = iParameter.getAttributes().getNamedItem("value").getNodeValue();
}
if (specialIsReasoner) {
types.add(Reasoner.class);
values.add(reasoner);
}
else if (typeString.equals("int.class")) {
types.add(int.class);
values.add(Integer.parseInt(valueString));
}
else if (typeString.equals("float.class")) {
types.add(float.class);
values.add(Float.parseFloat(valueString));
}
else if (typeString.equals("java.lang.String.class")) {
types.add(java.lang.String.class);
values.add(valueString);
}
else {
throw new ParseException("Unknown type", 0);
}
}
Class[] typesAsArr = types.toArray(new Class[types.size()]);
Object[] valuesAsArr = values.toArray(new Object[values.size()]);
Class c = Class.forName(pluginClassPath);
Plugin createdPlugin = (Plugin)c.getConstructor(typesAsArr).newInstance(valuesAsArr);
return createdPlugin;
}
public static void main(String[] args) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException {
NarParameters params = new NarParameters();
loadFrom("../opennars/src/main/config/defaultConfig.xml", null, params);
}
}
|
package org.voovan.tools;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Properties;
import org.voovan.tools.log.Logger;
public class TProperties {
private static HashMap<File, Properties> propertiesCache = new HashMap<File, Properties>();
/**
* Properties
*
* @param file
* @return
*/
public static Properties getProperties(File file) {
try {
if (!propertiesCache.containsKey(file)) {
Properties properites = new Properties();
String content = new String(TFile.loadFile(file));
properites.load(new StringReader(content));
propertiesCache.put(file, properites);
}
return propertiesCache.get(file);
} catch (IOException e) {
Logger.error(e);
return null;
}
}
/**
* Properties
*
* @param file
* @param name
* @return
*/
public static String getString(File file, String name) {
Properties properites = getProperties(file);
return TObject.nullDefault(properites.getProperty(name), null);
}
/**
* Properties
*
* @param file
* @param name
* @return
*/
public static int getInt(File file, String name) {
String value = getString(file, name);
return TObject.nullDefault(Integer.valueOf(value), 0);
}
/**
* Properties
*
* @param file
* @param name
* @return
*/
public static float getFloat(File file, String name) {
String value = getString(file, name);
return TObject.nullDefault(Float.valueOf(value.trim()), 0).floatValue();
}
/**
* Properties
*
* @param file
* @param name
* @return
*/
public static double getDouble(File file, String name) {
String value = getString(file, name);
return TObject.nullDefault(Double.valueOf(value.trim()), 0).doubleValue();
}
/**
* Properites
*/
public void clear(){
propertiesCache.clear();
}
}
|
package scala_maven;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyNode;
import org.apache.maven.shared.dependency.graph.filter.AncestorOrSelfDependencyNodeFilter;
import org.apache.maven.shared.dependency.graph.filter.AndDependencyNodeFilter;
import org.apache.maven.shared.dependency.graph.filter.DependencyNodeFilter;
import org.apache.maven.shared.dependency.graph.traversal.CollectingDependencyNodeVisitor;
import org.apache.maven.shared.dependency.graph.traversal.DependencyNodeVisitor;
import org.apache.maven.shared.dependency.graph.traversal.FilteringDependencyNodeVisitor;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.util.StringUtils;
import sbt_inc.SbtIncrementalCompiler;
import scala_maven_dependency.CheckScalaVersionVisitor;
import scala_maven_dependency.ScalaDistroArtifactFilter;
import scala_maven_executions.JavaMainCaller;
import scala_maven_executions.JavaMainCallerByFork;
import scala_maven_executions.JavaMainCallerInProcess;
import scala_maven_executions.MainHelper;
public abstract class ScalaMojoSupport extends AbstractMojo {
private static final String SCALA_LIBRARY_ARTIFACTID = "scala-library";
private static final String SCALA_REFLECT_ARTIFACTID = "scala-reflect";
private static final String SCALA_COMPILER_ARTIFACTID = "scala-compiler";
/**
* Constant {@link String} for "pom". Used to specify the Maven POM artifact
* type.
*/
protected static final String POM = "pom";
/**
* Constant {@link String} for "jar". Used to specify the Maven JAR artifact
* type.
*/
static final String JAR = "jar";
/**
* The maven project.
*
*/
@Parameter(property = "project", required = true, readonly = true)
protected MavenProject project;
/**
* The Maven Session Object
*
* Note: Allows extending for 3rd-party usages
*/
@Parameter(property = "session", required = true, readonly = true)
protected MavenSession session;
/**
* Used to look up Artifacts in the remote repository.
*
*/
@Component
RepositorySystem factory;
/**
* Used to look up Artifacts in the remote repository.
*
*/
@Component
private ArtifactResolver resolver;
/**
* Location of the local repository.
*
*/
@Parameter(property = "localRepository", readonly = true, required = true)
private ArtifactRepository localRepo;
/**
* List of Remote Repositories used by the resolver
*
*/
@Parameter(property = "project.remoteArtifactRepositories", readonly = true, required = true)
private List<ArtifactRepository> remoteRepos;
/**
* Additional dependencies/jar to add to classpath to run "scalaClassName"
* (scope and optional field not supported) ex :
*
* <pre>
* <dependencies>
* <dependency>
* <groupId>org.scala-tools</groupId>
* <artifactId>scala-compiler-addon</artifactId>
* <version>1.0-SNAPSHOT</version>
* </dependency>
* </dependencies>
* </pre>
*
*/
@Parameter
protected BasicArtifact[] dependencies;
/**
* Compiler plugin dependencies to use when compiling. ex:
*
* <pre>
* <compilerPlugins>
* <compilerPlugin>
* <groupId>my.scala.plugin</groupId>
* <artifactId>amazingPlugin</artifactId>
* <version>1.0-SNAPSHOT</version>
* </compilerPlugin>
* </compilerPlugins>
* </pre>
*
*/
@Parameter
private BasicArtifact[] compilerPlugins;
/**
* Jvm Arguments.
*
*/
@Parameter
protected String[] jvmArgs;
/**
* compiler additional arguments
*
*/
@Parameter
protected String[] args;
/**
* Additional parameter to use to call the main class. Use this parameter only
* from command line ("-DaddScalacArgs=arg1|arg2|arg3|..."), not from pom.xml.
* To define compiler arguments in pom.xml see the "args" parameter.
*
*/
@Parameter(property = "addScalacArgs")
private String addScalacArgs;
/**
* className (FQN) of the scala tool to provide as
*
*/
@Parameter(required = true, property = "maven.scala.className", defaultValue = "scala.tools.nsc.Main")
protected String scalaClassName;
/**
* Scala 's version to use. (property 'maven.scala.version' replaced by
* 'scala.version')
*
*/
@Parameter(property = "scala.version")
private String scalaVersion;
/**
* Organization/group ID of the Scala used in the project. Default value is
* 'org.scala-lang'. This is an advanced setting used for clones of the Scala
* Language. It should be disregarded in standard use cases.
*
*/
@Parameter(property = "scala.organization", defaultValue = "org.scala-lang")
private String scalaOrganization;
public String getScalaOrganization() {
return scalaOrganization;
}
/**
* Scala 's version to use to check binary compatibility (like suffix in
* artifactId of dependency). If it is defined then it is used to
* checkMultipleScalaVersions
*
*/
@Parameter(property = "scala.compat.version")
private String scalaCompatVersion;
/**
* Path to Scala installation to use instead of the artifact (define as
* dependencies).
*
*/
@Parameter(property = "scala.home")
private String scalaHome;
/**
* Arguments for javac (when using incremental compiler).
*
*/
@Parameter(property = "javacArgs")
protected String[] javacArgs;
@Parameter(property = "javacGenerateDebugSymbols", defaultValue = "true")
protected boolean javacGenerateDebugSymbols = true;
/**
* Alternative method for specifying javac arguments (when using incremental
* compiler). Can be used from command line with
* -DaddJavacArgs=arg1|arg2|arg3|... rather than in pom.xml.
*
*/
@Parameter(property = "addJavacArgs")
protected String addJavacArgs;
/**
* The -source argument for the Java compiler (when using incremental compiler).
*
*/
@Parameter(property = "maven.compiler.source")
protected String source;
/**
* The -target argument for the Java compiler (when using incremental compiler).
*
*/
@Parameter(property = "maven.compiler.target")
protected String target;
/**
* The -encoding argument for the Java compiler. (when using incremental
* compiler).
*
*/
@Parameter(property = "project.build.sourceEncoding", defaultValue = "UTF-8")
protected String encoding;
/**
* Display the command line called ? (property 'maven.scala.displayCmd' replaced
* by 'displayCmd')
*
*/
@Parameter(property = "displayCmd", defaultValue = "false", required = true)
public boolean displayCmd;
/**
* Forks the execution of scalac into a separate process.
*
*/
@Parameter(defaultValue = "true")
protected boolean fork = true;
/**
* Force the use of an external ArgFile to run any forked process.
*
*/
@Parameter(defaultValue = "false")
protected boolean forceUseArgFile = false;
/**
* Check if every dependencies use the same version of scala-library or
* scala.compat.version.
*
*/
@Parameter(property = "maven.scala.checkConsistency", defaultValue = "true")
protected boolean checkMultipleScalaVersions;
/**
* Determines if a detection of multiple scala versions in the dependencies will
* cause the build to fail.
*
*/
@Parameter(defaultValue = "false")
protected boolean failOnMultipleScalaVersions = false;
@Parameter(property = "maven.scala.useCanonicalPath", defaultValue = "true")
protected boolean useCanonicalPath = true;
/**
* Artifact factory, needed to download source jars.
*
*/
@Component
protected MavenProjectBuilder mavenProjectBuilder;
/**
* The artifact repository to use.
*
*/
@Parameter(property = "localRepository", required = true, readonly = true)
private ArtifactRepository localRepository;
/**
* The artifact factory to use.
*
*/
@Component
private ArtifactFactory artifactFactory;
/**
* The artifact metadata source to use.
*/
@Component
private ArtifactMetadataSource artifactMetadataSource;
/**
* The artifact collector to use.
*
*/
@Component
private ArtifactCollector artifactCollector;
/**
* The dependency tree builder to use.
*
*/
@Component
private DependencyGraphBuilder dependencyTreeBuilder;
/**
* The toolchain manager to use.
*/
@Component
protected ToolchainManager toolchainManager;
/**
* List of artifacts to run plugin
*
*/
@Parameter(defaultValue = "${plugin.artifacts}")
private List<Artifact> pluginArtifacts;
private VersionNumber _scalaVersionN;
/**
* Constructs an {@link Artifact} for Scala Compiler.
*
* @param scalaVersion
* the version of the Scala Compiler/Library we are using for this
* execution.
*
* @return a {@link Artifact} for the Scala Compiler.
*/
final Artifact scalaCompilerArtifact(final String scalaVersion) {
return this.factory.createArtifact(this.getScalaOrganization(), ScalaMojoSupport.SCALA_COMPILER_ARTIFACTID,
scalaVersion, "", ScalaMojoSupport.POM);
}
/**
* This method resolves all transitive dependencies of an artifact.
*
* @param artifact
* the {@link Artifact} used to retrieve dependencies.
*
* @return resolved {@link Set} of dependencies.
*/
final Set<Artifact> resolveArtifactDependencies(final Artifact artifact) {
final AndArtifactFilter filter = new AndArtifactFilter();
filter.add(new ScopeArtifactFilter(Artifact.SCOPE_TEST));
filter.add(art -> !art.isOptional());
// Use the collection filter as the resolution filter.
return resolveDependencyArtifacts(artifact, filter, filter);
}
/**
* This method resolves all transitive dependencies of an artifact.
*
* @param artifact
* the {@link Artifact} used to retrieve dependencies.
* @param collectionFilter
* an {@link ArtifactFilter} used to determine which members
* dependency graph should be downloaded.
* @param resolutionFilter
* an {@link ArtifactFilter} used to determine which members of the
* dependency graph should be included in resolution.
*
* @return resolved {@link Set} of dependencies.
*/
private Set<Artifact> resolveDependencyArtifacts(final Artifact artifact, final ArtifactFilter collectionFilter,
final ArtifactFilter resolutionFilter) {
return resolveDependencyArtifacts(artifact, collectionFilter, resolutionFilter, this.remoteRepos,
this.localRepo);
}
/**
* This method resolves all transitive dependencies of an artifact.
*
* @param artifact
* the {@link Artifact} used to retrieve dependencies.
* @param collectionFilter
* an {@link ArtifactFilter} used to determine which members of the
* dependency graph should be included in resolution.
* @param resolutionFilter
* an {@link ArtifactFilter} used to determine which members of the
* dependency graph should be included in resolution.
* @param remoteRepositories
* a {@link List} of remote {@link ArtifactRepository} values to used
* for dependency resolution of the provided {@link Artifact}.
* @param localRepository
* the local {@link ArtifactRepository} to use for dependency
* resolution of the given {@link Artifact}.
*
* @return resolved {@link Set} of dependencies.
*/
private Set<Artifact> resolveDependencyArtifacts(final Artifact artifact, final ArtifactFilter collectionFilter,
final ArtifactFilter resolutionFilter, final List<ArtifactRepository> remoteRepositories,
final ArtifactRepository localRepository) {
final ArtifactResolutionRequest arr = this.createArtifactResolutionRequest(artifact, collectionFilter,
resolutionFilter, remoteRepositories, localRepository);
// TODO follow the dependenciesManagement and override rules
return this.resolver.resolve(arr).getArtifacts();
}
/**
* Create a {@link ArtifactResolutionRequest}.
*
* @param artifact
* the {@link Artifact} used to retrieve dependencies.
* @param collectionFilter
* an {@link ArtifactFilter} used to determine which members
* dependency graph should be downloaded.
* @param resolutionFilter
* an {@link ArtifactFilter} used to determine which members of the
* dependency graph should be included in resolution
* @param remoteRepositories
* a {@link List} of remote {@link ArtifactRepository} values to used
* for dependency resolution of the provided {@link Artifact}.
* @param localRepository
* the local {@link ArtifactRepository} to use for dependency
* resolution of the given {@link Artifact}.
*
* @return an {@link ArtifactResolutionRequest}, typically used for dependency
* resolution requests against an {@link ArtifactResolver}.
*/
private ArtifactResolutionRequest createArtifactResolutionRequest(final Artifact artifact,
final ArtifactFilter collectionFilter, final ArtifactFilter resolutionFilter,
final List<ArtifactRepository> remoteRepositories, final ArtifactRepository localRepository) {
final ArtifactResolutionRequest arr = new ArtifactResolutionRequest();
arr.setArtifact(artifact);
arr.setCollectionFilter(collectionFilter);
arr.setResolutionFilter(resolutionFilter);
arr.setResolveRoot(false);
arr.setResolveTransitively(true);
arr.setRemoteRepositories(remoteRepositories);
arr.setLocalRepository(localRepository);
return arr;
}
private void addToClasspath(String groupId, String artifactId, String version, Set<String> classpath)
throws Exception {
addToClasspath(groupId, artifactId, version, classpath, true);
}
private void addToClasspath(String groupId, String artifactId, String version, Set<String> classpath,
boolean addDependencies) throws Exception {
addToClasspath(
factory.createArtifact(groupId, artifactId, version, Artifact.SCOPE_RUNTIME, ScalaMojoSupport.JAR),
classpath, addDependencies);
}
/**
* added for classifier support.
*
* @author Christoph Radig
* @todo might want to merge with existing "addToClasspath" methods.
*/
private void addToClasspath(String groupId, String artifactId, String version, String classifier,
Set<String> classpath, boolean addDependencies) throws Exception {
Dependency d = new Dependency();
d.setGroupId(groupId);
d.setArtifactId(artifactId);
d.setVersion(version);
d.setType(ScalaMojoSupport.JAR);
d.setClassifier(classifier);
d.setScope(Artifact.SCOPE_RUNTIME);
addToClasspath(factory.createDependencyArtifact(d), classpath, addDependencies);
}
void addToClasspath(Artifact artifact, Set<String> classpath, boolean addDependencies) throws Exception {
resolver.resolve(artifact, remoteRepos, localRepo);
classpath.add(FileUtils.pathOf(artifact.getFile(), useCanonicalPath));
if (addDependencies) {
for (Artifact dep : resolveArtifactDependencies(artifact)) {
addToClasspath(dep, classpath, addDependencies);
}
}
}
void addCompilerToClasspath(Set<String> classpath) throws Exception {
classpath.add(FileUtils.pathOf(getCompilerJar(), useCanonicalPath));
for (File dep : getCompilerDependencies()) {
classpath.add(FileUtils.pathOf(dep, useCanonicalPath));
}
}
void addLibraryToClasspath(Set<String> classpath) throws Exception {
classpath.add(FileUtils.pathOf(getLibraryJar(), useCanonicalPath));
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
String oldWay = System.getProperty("maven.scala.version");
if (oldWay != null) {
getLog().warn("using 'maven.scala.version' is deprecated, use 'scala.version' instead");
if (scalaVersion != null) {
scalaVersion = oldWay;
}
}
oldWay = System.getProperty("maven.scala.displayCmd");
if (oldWay != null) {
getLog().warn("using 'maven.scala.displayCmd' is deprecated, use 'displayCmd' instead");
displayCmd = displayCmd || Boolean.parseBoolean(oldWay);
}
checkScalaVersion();
doExecute();
} catch (MojoExecutionException exc) {
throw exc;
} catch (MojoFailureException | RuntimeException exc) {
throw exc;
} catch (Exception exc) {
throw new MojoExecutionException("wrap: " + exc, exc);
}
}
protected List<Dependency> getDependencies() {
return project.getCompileDependencies();
}
VersionNumber findScalaVersion() throws Exception {
if (_scalaVersionN == null) {
String detectedScalaVersion = scalaVersion;
if (StringUtils.isEmpty(detectedScalaVersion)) {
detectedScalaVersion = findScalaVersionFromDependencies();
}
if (StringUtils.isEmpty(detectedScalaVersion)) {
if (!ScalaMojoSupport.POM.equals(project.getPackaging().toLowerCase())) {
String error = getScalaOrganization() + ":" + SCALA_LIBRARY_ARTIFACTID
+ " is missing from project dependencies";
getLog().error(error);
throw new UnsupportedOperationException(error);
}
} else {
// grappy hack to retrieve the SNAPSHOT version without timestamp,...
// because if version is -SNAPSHOT and artifact is deploy with uniqueValue then
// the version
// get from dependency is with the timestamp and a build number (the resolved
// version)
// but scala-compiler with the same version could have different resolved
// version (timestamp,...)
boolean isSnapshot = ArtifactUtils.isSnapshot(detectedScalaVersion);
if (isSnapshot && !detectedScalaVersion.endsWith("-SNAPSHOT")) {
detectedScalaVersion = detectedScalaVersion.substring(0,
detectedScalaVersion.lastIndexOf('-', detectedScalaVersion.lastIndexOf('-') - 1)) + "-SNAPSHOT";
}
}
if (StringUtils.isEmpty(detectedScalaVersion)) {
throw new MojoFailureException("no scalaVersion detected or set");
}
if (StringUtils.isNotEmpty(scalaVersion)) {
if (!scalaVersion.equals(detectedScalaVersion)) {
getLog().warn(
"scala library version define in dependencies doesn't match the scalaVersion of the plugin");
}
// getLog().info("suggestion: remove the scalaVersion from pom.xml");
// //scalaVersion could be define in a parent pom where lib is not required
}
_scalaVersionN = new VersionNumber(detectedScalaVersion);
}
return _scalaVersionN;
}
private String findScalaVersionFromDependencies() {
return findVersionFromDependencies(getScalaOrganization(), SCALA_LIBRARY_ARTIFACTID);
}
// TODO refactor to do only one scan of dependencies to find version
private String findVersionFromDependencies(String groupId, String artifactId) {
String version = null;
for (Dependency dep : getDependencies()) {
if (groupId.equals(dep.getGroupId()) && artifactId.equals(dep.getArtifactId())) {
version = dep.getVersion();
}
}
if (StringUtils.isEmpty(version)) {
List<Dependency> deps = new ArrayList<>();
deps.addAll(project.getModel().getDependencies());
if (project.getModel().getDependencyManagement() != null) {
deps.addAll(project.getModel().getDependencyManagement().getDependencies());
}
for (Dependency dep : deps) {
if (groupId.equals(dep.getGroupId()) && artifactId.equals(dep.getArtifactId())) {
version = dep.getVersion();
}
}
}
return version;
}
void checkScalaVersion() throws Exception {
String sv = findScalaVersion().toString();
if (StringUtils.isNotEmpty(scalaHome)) {
getLog().warn(String.format(
"local scala-library.jar and scala-compiler.jar from scalaHome(%s) used instead of scala %s", scalaHome,
sv));
}
if (checkMultipleScalaVersions) {
checkCorrectVersionsOfScalaLibrary(sv);
}
}
/**
* this method checks to see if there are multiple versions of the scala library
*
* @throws Exception
*/
private void checkCorrectVersionsOfScalaLibrary(String scalaDefVersion) throws Exception {
getLog().debug("Checking for multiple versions of scala");
// TODO - Make sure we handle bad artifacts....
// TODO: note that filter does not get applied due to MNG-3236
VersionNumber sv = new VersionNumber(scalaDefVersion);
VersionNumber requiredScalaVersion = StringUtils.isNotEmpty(scalaCompatVersion)
? new VersionNumberMask(scalaCompatVersion)
: sv;
if (requiredScalaVersion.compareTo(sv) != 0) {
String msg = String.format("Scala library detected %s doesn't match scala.compat.version : %s", sv,
requiredScalaVersion);
if (failOnMultipleScalaVersions) {
getLog().error(msg);
throw new MojoFailureException(msg);
}
getLog().warn(msg);
}
ProjectBuildingRequest request = project.getProjectBuildingRequest();
request.setProject(project);
checkArtifactForScalaVersion(requiredScalaVersion, dependencyTreeBuilder.buildDependencyGraph(request, null));
}
/**
* Visits a node (and all dependencies) to see if it contains duplicate scala
* versions
*/
private void checkArtifactForScalaVersion(VersionNumber requiredScalaVersion, DependencyNode rootNode)
throws Exception {
final CheckScalaVersionVisitor visitor = new CheckScalaVersionVisitor(requiredScalaVersion, getLog(),
getScalaOrganization());
CollectingDependencyNodeVisitor collectingVisitor = new CollectingDependencyNodeVisitor();
DependencyNodeVisitor firstPassVisitor = new FilteringDependencyNodeVisitor(collectingVisitor,
createScalaDistroDependencyFilter());
rootNode.accept(firstPassVisitor);
DependencyNodeFilter secondPassFilter = new AncestorOrSelfDependencyNodeFilter(collectingVisitor.getNodes());
DependencyNodeVisitor filteredVisitor = new FilteringDependencyNodeVisitor(visitor, secondPassFilter);
rootNode.accept(filteredVisitor);
if (visitor.isFailed()) {
visitor.logScalaDependents();
if (failOnMultipleScalaVersions) {
getLog().error("Multiple versions of scala libraries detected!");
throw new MojoFailureException("Multiple versions of scala libraries detected!");
}
getLog().warn("Multiple versions of scala libraries detected!");
}
}
/**
* @return A filter to only extract artifacts deployed from scala distributions
*/
private DependencyNodeFilter createScalaDistroDependencyFilter() {
List<DependencyNodeFilter> filters = new ArrayList<>();
filters.add(new ScalaDistroArtifactFilter(getScalaOrganization()));
return new AndDependencyNodeFilter(filters);
}
protected abstract void doExecute() throws Exception;
protected JavaMainCaller getScalaCommand() throws Exception {
return getScalaCommand(fork, scalaClassName);
}
/**
* Get a {@link JavaMainCaller} used invoke a Java process. Typically this will
* be one of the Scala utilities (Compiler, ScalaDoc, REPL, etc.).
* <p>
* This method does some setup on the {@link JavaMainCaller} which is not done
* by merely invoking {@code new} on one of the implementations. Specifically,
* it adds any Scala compiler plugin options, JVM options, and Scalac options
* defined on the plugin.
*
* @param forkOverride
* override the setting for {@link #fork}. Currently this should only
* be set if you are invoking the REPL.
* @param mainClass
* the JVM main class to invoke.
*
* @return a {@link JavaMainCaller} to use to invoke the given command.
*/
final JavaMainCaller getScalaCommand(final boolean forkOverride, final String mainClass) throws Exception {
JavaMainCaller cmd = getEmptyScalaCommand(mainClass, forkOverride);
cmd.addArgs(args);
if (StringUtils.isNotEmpty(addScalacArgs)) {
cmd.addArgs(StringUtils.split(addScalacArgs, "|"));
}
addCompilerPluginOptions(cmd);
cmd.addJvmArgs(jvmArgs);
return cmd;
}
/**
* Get a {@link JavaMainCaller} used invoke a Java process. Typically this will
* be one of the Scala utilities (Compiler, ScalaDoc, REPL, etc.).
*
* @param mainClass
* the JVM main class to invoke.
*
* @return a {@link JavaMainCaller} to use to invoke the given command.
*/
final JavaMainCaller getEmptyScalaCommand(final String mainClass) throws Exception {
return getEmptyScalaCommand(mainClass, fork);
}
/**
* Get a {@link JavaMainCaller} used invoke a Java process. Typically this will
* be one of the Scala utilities (Compiler, ScalaDoc, REPL, etc.).
*
* @param mainClass
* the JVM main class to invoke.
* @param forkOverride
* override the setting for {@link #fork}. Currently this should only
* be set if you are invoking the REPL.
*
* @return a {@link JavaMainCaller} to use to invoke the given command.
*/
private JavaMainCaller getEmptyScalaCommand(final String mainClass, final boolean forkOverride) throws Exception {
// If we are deviating from the plugin settings, let the user know
// what's going on.
if (forkOverride != fork) {
super.getLog().info("Fork behavior overridden");
super.getLog().info(String.format("Fork for this execution is %s.", String.valueOf(forkOverride)));
}
// TODO - Fork or not depending on configuration?
JavaMainCaller cmd;
String toolcp = getToolClasspath();
if (forkOverride) {
// HACK (better may need refactor)
boolean bootcp = true;
if (args != null) {
for (String arg : args) {
bootcp = bootcp && !"-nobootcp".equals(arg);
}
}
String cp = bootcp ? "" : toolcp;
bootcp = bootcp && !(StringUtils.isNotEmpty(addScalacArgs) && addScalacArgs.contains("-nobootcp"));
// scalac with args in files
// * works only since 2.8.0
// * is buggy (don't manage space in path on windows)
getLog().debug("use java command with args in file forced : " + forceUseArgFile);
cmd = new JavaMainCallerByFork(this, mainClass, cp, null, null, forceUseArgFile,
toolchainManager.getToolchainFromBuildContext("jdk", session));
if (bootcp) {
cmd.addJvmArgs("-Xbootclasspath/a:" + toolcp);
}
} else {
cmd = new JavaMainCallerInProcess(this, mainClass, toolcp, null, null);
}
return cmd;
}
private String getToolClasspath() throws Exception {
Set<String> classpath = new LinkedHashSet<>();
addLibraryToClasspath(classpath);
addCompilerToClasspath(classpath);
if (dependencies != null) {
for (BasicArtifact artifact : dependencies) {
addToClasspath(artifact.groupId, artifact.artifactId, artifact.version, classpath);
}
}
return MainHelper.toMultiPath(classpath.toArray(new String[] {}));
}
protected List<String> getScalaOptions() throws Exception {
List<String> options = new ArrayList<>();
if (args != null)
Collections.addAll(options, args);
if (StringUtils.isNotEmpty(addScalacArgs)) {
Collections.addAll(options, StringUtils.split(addScalacArgs, "|"));
}
options.addAll(getCompilerPluginOptions());
return options;
}
protected List<String> getJavacOptions() {
List<String> options = new ArrayList<>();
if (javacArgs != null)
Collections.addAll(options, javacArgs);
if (StringUtils.isNotEmpty(addJavacArgs)) {
Collections.addAll(options, StringUtils.split(addJavacArgs, "|"));
}
// issue #116
if (javacGenerateDebugSymbols) {
options.add("-g");
}
if (target != null && !target.isEmpty()) {
options.add("-target");
options.add(target);
}
if (source != null && !source.isEmpty()) {
options.add("-source");
options.add(source);
}
if (encoding != null) {
options.add("-encoding");
options.add(encoding);
}
return options;
}
protected File getLibraryJar() throws Exception {
if (StringUtils.isNotEmpty(scalaHome)) {
File lib = new File(scalaHome, "lib");
return new File(lib, SCALA_LIBRARY_ARTIFACTID + ".jar");
}
return getArtifactJar(getScalaOrganization(), SCALA_LIBRARY_ARTIFACTID, findScalaVersion().toString());
}
protected File getReflectJar() throws Exception {
if (StringUtils.isNotEmpty(scalaHome)) {
File lib = new File(scalaHome, "lib");
return new File(lib, SCALA_REFLECT_ARTIFACTID + ".jar");
}
return getArtifactJar(getScalaOrganization(), SCALA_REFLECT_ARTIFACTID, findScalaVersion().toString());
}
protected File getCompilerJar() throws Exception {
if (StringUtils.isNotEmpty(scalaHome)) {
File lib = new File(scalaHome, "lib");
return new File(lib, SCALA_COMPILER_ARTIFACTID + ".jar");
}
return getArtifactJar(getScalaOrganization(), SCALA_COMPILER_ARTIFACTID, findScalaVersion().toString());
}
protected List<File> getCompilerDependencies() throws Exception {
List<File> d = new ArrayList<>();
if (StringUtils.isEmpty(scalaHome)) {
for (Artifact artifact : getAllDependencies(getScalaOrganization(), SCALA_COMPILER_ARTIFACTID,
findScalaVersion().toString())) {
d.add(artifact.getFile());
}
} else {
for (File f : new File(scalaHome, "lib").listFiles()) {
String name = f.getName();
if (name.endsWith(".jar") && !name.contains("scala-library") && !name.contains("scala-compiler")) {
d.add(f);
}
}
}
return d;
}
protected File getArtifactJar(String groupId, String artifactId, String version) throws Exception {
Artifact artifact = factory.createArtifact(groupId, artifactId, version, Artifact.SCOPE_RUNTIME,
ScalaMojoSupport.JAR);
resolver.resolve(artifact, remoteRepos, localRepo);
return artifact.getFile();
}
private Set<Artifact> getAllDependencies(String groupId, String artifactId, String version) {
Set<Artifact> result = new HashSet<>();
Artifact pom = factory.createArtifact(groupId, artifactId, version, "", ScalaMojoSupport.POM);
Set<Artifact> d = resolveArtifactDependencies(pom);
result.addAll(d);
for (Artifact dependency : d) {
Set<Artifact> transitive = getAllDependencies(dependency.getGroupId(), dependency.getArtifactId(),
dependency.getVersion());
result.addAll(transitive);
}
return result;
}
/**
* @return This returns whether or not the scala version can support having java
* sent into the compiler
*/
protected boolean isJavaSupportedByCompiler() throws Exception {
return findScalaVersion().compareTo(new VersionNumber("2.7.2")) >= 0;
}
/**
* Adds appropriate compiler plugins to the scalac command.
*
* @param scalac
* @throws Exception
*/
protected void addCompilerPluginOptions(JavaMainCaller scalac) throws Exception {
for (String option : getCompilerPluginOptions()) {
scalac.addArgs(option);
}
}
private List<String> getCompilerPluginOptions() throws Exception {
List<String> options = new ArrayList<>();
for (String plugin : getCompilerPlugins()) {
options.add("-Xplugin:" + plugin);
}
return options;
}
/**
* Retrieves a list of paths to scala compiler plugins.
*
* @return The list of plugins
* @throws Exception
*/
private Set<String> getCompilerPlugins() throws Exception {
Set<String> plugins = new HashSet<>();
if (compilerPlugins != null) {
Set<String> ignoreClasspath = new LinkedHashSet<>();
addCompilerToClasspath(ignoreClasspath);
addLibraryToClasspath(ignoreClasspath);
for (BasicArtifact artifact : compilerPlugins) {
getLog().info("compiler plugin: " + artifact.toString());
// TODO - Ensure proper scala version for plugins
Set<String> pluginClassPath = new HashSet<>();
// TODO - Pull in transitive dependencies.
addToClasspath(artifact.groupId, artifact.artifactId, artifact.version, artifact.classifier,
pluginClassPath, false);
pluginClassPath.removeAll(ignoreClasspath);
plugins.addAll(pluginClassPath);
}
}
return plugins;
}
protected String findVersionFromPluginArtifacts(String groupId, String artifactId) {
for (Artifact art : pluginArtifacts) {
if (groupId.equals(art.getGroupId()) && artifactId.equals(art.getArtifactId())) {
return art.getVersion();
}
}
throw new IllegalArgumentException(
"Could not locate artifact " + groupId + ":" + artifactId + " in plugin's dependencies");
}
}
|
package edu.wustl.catissuecore.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import edu.wustl.catissuecore.util.global.ApplicationProperties;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* Default implementation of AbstractDAO through JDBC.
* @author gautam_shetty
*/
public class JDBCDAO extends AbstractDAO
{
private PreparedStatement stmt = null;
private Connection connection = null;
public void openSession() throws DAOException
{
}
public void closeSession() throws DAOException
{
}
/**
* Returns a connection to the database.
* @return a connection to the database.
* @throws ClassNotFoundException
* @throws SQLException
*/
private Connection createConnection() throws ClassNotFoundException,
SQLException
{
//Initializes the oracle driver.
Class.forName(ApplicationProperties.getValue("database.driver"));
String database = ApplicationProperties.getValue("database.URL.1");
String loginName = ApplicationProperties
.getValue("database.loginName.1");
String password = ApplicationProperties.getValue("database.password.1");
//Creates a connection.
connection = DriverManager.getConnection(database, loginName, password);
return connection;
}
/**
* Returns the ResultSet containing all the rows in the table represented in sourceObjectName.
* @param sourceObjectName The table name.
* @return The ResultSet containing all the rows in the table represented in sourceObjectName.
* @throws ClassNotFoundException
* @throws SQLException
*/
public List retrieve(String sourceObjectName) throws DAOException
{
return retrieve(sourceObjectName, null, null, null, null, null);
}
/**
* Returns the ResultSet containing all the rows according to the columns specified
* from the table represented in sourceObjectName.
* @param sourceObjectName The table name.
* @param selectColumnName The column names in select clause.
* @return The ResultSet containing all the rows according to the columns specified
* from the table represented in sourceObjectName.
* @throws ClassNotFoundException
* @throws SQLException
*/
public List retrieve(String sourceObjectName, String[] selectColumnName)
throws DAOException
{
return retrieve(sourceObjectName, selectColumnName, null, null, null,
null);
}
/**
* Retrieves the records for class name in sourceObjectName according to field values passed in the passed session.
* @param selectColumnName An array of field names in select clause.
* @param whereColumnName An array of field names in where clause.
* @param whereColumnCondition The comparision condition for the field values.
* @param whereColumnValue An array of field values.
* @param joinCondition The join condition.
* @param The session object.
*/
public List retrieve(String sourceObjectName, String[] selectColumnName,
String[] whereColumnName, String[] whereColumnCondition,
Object[] whereColumnValue, String joinCondition)
throws DAOException
{
List list = null;
try
{
StringBuffer query = new StringBuffer("SELECT ");
if (joinCondition == null)
{
joinCondition = Constants.AND_JOIN_CONDITION;
}
//Prepares the select clause of the query.
if ((selectColumnName != null) && (selectColumnName.length > 0))
{
int i;
for (i = 0; i < (selectColumnName.length - 1); i++)
{
query.append(selectColumnName[i] + " ");
query.append(",");
}
query.append(selectColumnName[i] + " ");
}
else
{
query.append("* ");
}
//Prepares the from clause of the query.
query.append("FROM " + sourceObjectName);
//Prepares the where clause of the query.
if ((whereColumnName != null && whereColumnName.length > 0)
&& (whereColumnCondition != null && whereColumnCondition.length == whereColumnName.length)
&& (whereColumnValue != null && whereColumnName.length == whereColumnValue.length))
{
query.append(" WHERE ");
int i;
for (i = 0; i < (whereColumnName.length - 1); i++)
{
query.append(sourceObjectName + "." + whereColumnName[i]
+ " " + whereColumnCondition[i] + " "
+ whereColumnValue[i]);
query.append(" " + joinCondition + " ");
}
query.append(sourceObjectName + "." + whereColumnName[i] + " "
+ whereColumnCondition[i] + " " + whereColumnValue[i]);
}
//Creates connection.
createConnection();
PreparedStatement stmt = connection.prepareStatement(query
.toString());
ResultSet resultSet = stmt.executeQuery();
list = new ArrayList();
while (resultSet.next())
{
int i = 0;
String[] columnData = new String[resultSet.getFetchSize()];
while (i < selectColumnName.length)
{
columnData[i] = new String(resultSet.getString(selectColumnName[i]));
i++;
}
list.add(columnData);
}
}
catch (SQLException sqlExp)
{
Logger.out.error(sqlExp.getMessage(), sqlExp);
}
catch (ClassNotFoundException classExp)
{
Logger.out.error(classExp.getMessage(), classExp);
}
return list;
}
public List retrieve(String sourceObjectName, String whereColumnName,
Object whereColumnValue) throws DAOException
{
String whereColumnNames[] = {whereColumnName};
String whereColumnConditions[] = {"="};
Object whereColumnValues[] = {whereColumnValue};
return retrieve(sourceObjectName, null, whereColumnNames,
whereColumnConditions, whereColumnValues, Constants.AND_JOIN_CONDITION);
}
/**
* Closes the Connection and PreparedStatement objects.
*/
protected void finalize() throws Throwable
{
try
{
stmt.close();
connection.close();
}
finally
{
super.finalize();
}
}
// public static void main(String[] args)
// JDBCDAO dao = new JDBCDAO();
// String sourceObjectName = "CATISSUE_QUERY_RESULTS";
// String[] selectColumnName = {"PARTICIPANT_ID","ACCESSION_ID","SPECIMEN_ID","SEGMENT_ID","SAMPLE_ID"};
// String[] whereColumnName = null;
// String[] whereColumnCondition = null;
// Object[] whereColumnValue = null;
// String joinCondition = null;
// try{
//// System.out.println(dao.retrieve(sourceObjectName));
//// System.out.println(dao.retrieve(sourceObjectName,selectColumnName,whereColumnName,whereColumnCondition,whereColumnValue,joinCondition));
// ResultSet rs = dao.retrieve(sourceObjectName, selectColumnName);
// System.out.println("Got o/p");
// rs.next();
// System.out.println("PID............"+rs.getString(Constants.QUERY_RESULTS_PARTICIPANT_ID));
// rs.close();
// catch(Exception e){
// e.printStackTrace();
/* (non-Javadoc)
* @see edu.wustl.catissuecore.dao.AbstractDAO#insert(java.lang.Object)
*/
public void insert(Object obj) throws DAOException
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see edu.wustl.catissuecore.dao.AbstractDAO#update(java.lang.Object)
*/
public void update(Object obj) throws DAOException
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see edu.wustl.catissuecore.dao.AbstractDAO#delete(java.lang.Object)
*/
public boolean delete(Object obj) throws DAOException
{
// TODO Auto-generated method stub
return false;
}
// private
}
|
package seedu.tasklist.ui;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.google.common.eventbus.Subscribe;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.StringPropertyBase;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import seedu.tasklist.commons.core.Config;
import seedu.tasklist.commons.core.EventsCenter;
import seedu.tasklist.commons.core.GuiSettings;
import seedu.tasklist.commons.events.ui.ExitAppRequestEvent;
import seedu.tasklist.logic.Logic;
import seedu.tasklist.model.UserPrefs;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart {
private static final String ICON = "/images/smart_scheduler.png";
private static final String FXML = "MainWindow.fxml";
public static final int MIN_HEIGHT = 600;
public static final int MIN_WIDTH = 450;
private Logic logic;
// Independent Ui parts residing in this Ui container
private CategoryPanel categoryPanel;
private TaskListPanel taskListPanel;
private ResultDisplay resultDisplay;
private StatusBarFooter statusBarFooter;
private CommandBox commandBox;
private Config config;
private UserPrefs userPrefs;
// Handles to elements of this Ui container
private VBox rootLayout;
private Scene scene;
private String taskListName;
@FXML
private Label dateTimeLabel;
@FXML
private AnchorPane categoryPanelPlaceholder;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane personListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
//@FXML
//private SplitPane dateTimePlaceholder;
public MainWindow() {
super();
}
@Override
public void setNode(Node node) {
rootLayout = (VBox) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
public static MainWindow load(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
MainWindow mainWindow = UiPartLoader.loadUiPart(primaryStage, new MainWindow());
mainWindow.configure(config.getAppTitle(), config.getTaskListName(), config, prefs, logic);
EventsCenter.getInstance().registerHandler(mainWindow);
return mainWindow;
}
@Subscribe
private void handleTickEvent(TickEvent tickEvent){
dateTimeLabel.setText(new Date().toString());
}
private void configure(String appTitle, String taskListName, Config config, UserPrefs prefs,
Logic logic) {
//Set dependencies
this.logic = logic;
this.taskListName = taskListName;
this.config = config;
this.userPrefs = prefs;
//Configure the UI
setTitle(appTitle);
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
scene = new Scene(rootLayout);
primaryStage.setScene(scene);
setAccelerators();
}
private void setAccelerators() {
helpMenuItem.setAccelerator(KeyCombination.valueOf("F1"));
}
void fillInnerParts() {
categoryPanel = CategoryPanel.load(primaryStage, getCategoryPanelPlaceholder(), logic.getTaskCounter());
taskListPanel = TaskListPanel.load(primaryStage, getTaskListPlaceholder(), logic.getFilteredTaskList());
resultDisplay = ResultDisplay.load(primaryStage, getResultDisplayPlaceholder());
statusBarFooter = StatusBarFooter.load(primaryStage, getStatusbarPlaceholder(), config.getTaskListFilePath());
commandBox = CommandBox.load(primaryStage, getCommandBoxPlaceholder(), resultDisplay, logic);
setLabelText();
System.out.println();
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
public AnchorPane getTaskListPlaceholder() {
return personListPanelPlaceholder;
}
public AnchorPane getCategoryPanelPlaceholder() {
return categoryPanelPlaceholder;
}
public void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the default size based on user preferences.
*/
protected void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
public GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = HelpWindow.load(primaryStage);
helpWindow.show();
}
public void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.taskListPanel;
}
// public void loadTaskPage(ReadOnlyTask task) {
// browserPanel.loadTaskPage(task);
public void releaseResources() {
// browserPanel.freeResources();
}
public void setLabelText() {
assert dateTimeLabel != null;
dateTimeLabel.setText(new Date().toString());
}
}
|
package edu.wustl.catissuecore.domain;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import edu.wustl.catissuecore.actionForm.UserForm;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.util.logger.Logger;
/**
* A person who interacts with the caTISSUE Core data system
* and/or participates in the process of biospecimen collection,
* processing, or utilization.
* @hibernate.class table="CATISSUE_USER"
*/
public class User extends AbstractDomainObject implements Serializable
{
/**
* System generated unique systemIdentifier.
*/
protected Long systemIdentifier;
/**
* A string containing the Last Name of the user.
*/
protected String lastName = "";
/**
* A string containing the First Name of the user.
*/
protected String firstName = "";
/**
* A string containing the login name of the user.
*/
protected String loginName = "";
/**
* EmailAddress of the user.
*/
protected String emailAddress = "";
/**
* Old password of this user.
*/
protected String oldPassword;
// /**
// * EmailAddress Address of the user.
// */
// protected String password;
/**
* Date of user registration.
*/
protected Date startDate;
/**
* Institute of the user.
*/
protected Institution institution = new Institution();
/**
* Department of the user.
*/
protected Department department = new Department();
/**
* Contact address of the User.
*/
protected Address address = new Address();
/**
* Cancer Research Group to which the user belongs.
*/
protected CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
/**
* Activity Status of user, it could be CLOSED, ACTIVE, DISABLED.
*/
protected String activityStatus;
/**
* Comments given by the approver.
*/
protected String comments;
/**
* Role id of the user.
*/
protected String roleId = null;
/**
* Set of collection protocol.
*/
protected Collection collectionProtocolCollection = new HashSet();
protected String pageOf;
/**
* Identifier of this user in csm user table.
*/
protected Long csmUserId;
/**
* Initialize a new User instance.
* Note: Hibernate invokes this constructor through reflection API.
*/
/**
* Set of passwod collection for the user.
*/
protected Collection passwordCollection = new HashSet();
public User()
{
}
/**
* This Constructor Copies the data from an UserForm object to a User object.
* @param user An UserForm object containing the information about the user.
*/
public User(UserForm uform)
{
this();
setAllValues(uform);
}
/**
* Returns the systemIdentifier assigned to user.
* @hibernate.id name="systemIdentifier" column="IDENTIFIER" type="long" length="30"
* unsaved-value="null" generator-class="native"
* @hibernate.generator-param name="sequence" value="CATISSUE_USER_SEQ"
* @return Returns the systemIdentifier.
*/
public Long getSystemIdentifier()
{
return systemIdentifier;
}
/**
* @param systemIdentifier The systemIdentifier to set.
*/
public void setSystemIdentifier(Long systemIdentifier)
{
this.systemIdentifier = systemIdentifier;
}
/**
* Returns the password assigned to user.
* @hibernate.property name="emailAddress" type="string" column="EMAIL_ADDRESS" length="100"
* @return Returns the password.
*/
public String getEmailAddress()
{
return emailAddress;
}
/**
* @param emailAddress The emailAddress to set.
*/
public void setEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
/**
* @return Returns the oldPassword.
*/
public String getOldPassword()
{
return oldPassword;
}
/**
* @param oldPassword The oldPassword to set.
*/
public void setOldPassword(String oldPassword)
{
this.oldPassword = oldPassword;
}
// /**
// * Returns the password assigned to user.
// * @hibernate.property name="password" type="string" column="PASSWORD" length="50"
// * @return Returns the password.
// */
// public String getPassword()
// return password;
// /**
// * @param password The password to set.
// */
// public void setPassword(String password)
// this.password = password;
/**
* Returns the firstname assigned to user.
* @hibernate.property name="firstName" type="string" column="FIRST_NAME" length="50"
* @return Returns the firstName.
*/
public String getFirstName()
{
return firstName;
}
/**
* @param firstName The firstName to set.
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/**
* Returns the lastname assigned to user.
* @hibernate.property name="lastName" type="string" column="LAST_NAME" length="50"
* @return Returns the lastName.
*/
public String getLastName()
{
return lastName;
}
/**
* @param lastName The lastName to set.
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* Returns the loginname assigned to user.
* @hibernate.property name="loginName" type="string" column="LOGIN_NAME" length="50"
* not-null="true" unique="true"
* @return Returns the loginName.
*/
public String getLoginName()
{
return loginName;
}
/**
* @param loginName The loginName to set.
*/
public void setLoginName(String loginName)
{
this.loginName = loginName;
}
/**
* Returns the date when the user is added to the system.
* @hibernate.property name="startDate" type="date" column="START_DATE"
* @return Returns the dateAdded.
*/
public Date getStartDate()
{
return startDate;
}
/**
* @param startDate The startDate to set.
*/
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
/**
* Returns the activitystatus of the user.
* @hibernate.property name="activityStatus" type="string" column="ACTIVITY_STATUS" length="50"
* @return Returns the activityStatus.
*/
public String getActivityStatus()
{
return activityStatus;
}
/**
* @param activityStatus The activityStatus to set.
*/
public void setActivityStatus(String activityStatus)
{
this.activityStatus = activityStatus;
}
/**
* Returns the department of the user.
* @hibernate.many-to-one column="DEPARTMENT_ID" class="edu.wustl.catissuecore.domain.Department"
* constrained="true"
* @return the department of the user.
*/
public Department getDepartment()
{
return department;
}
/**
* @param department The department to set.
*/
public void setDepartment(Department department)
{
this.department = department;
}
/**
* Returns the cancerResearchGroup of the user.
* @hibernate.many-to-one column="CANCER_RESEARCH_GROUP_ID" class="edu.wustl.catissuecore.domain.CancerResearchGroup"
* constrained="true"
* @return the cancerResearchGroup of the user.
*/
public CancerResearchGroup getCancerResearchGroup()
{
return cancerResearchGroup;
}
/**
* @param cancerResearchGroup The cancerResearchGroup to set.
*/
public void setCancerResearchGroup(CancerResearchGroup cancerResearchGroup)
{
this.cancerResearchGroup = cancerResearchGroup;
}
/**
* Returns the institution of the user.
* @hibernate.many-to-one column="INSTITUTION_ID" class="edu.wustl.catissuecore.domain.Institution"
* constrained="true"
* @return the institution of the user.
*/
public Institution getInstitution()
{
return institution;
}
/**
* @param institution The institution to set.
*/
public void setInstitution(Institution institution)
{
this.institution = institution;
}
/**
* Returns the address of the user.
* @hibernate.many-to-one column="ADDRESS_ID" class="edu.wustl.catissuecore.domain.Address"
* constrained="true"
* @return the address of the user.
*/
public Address getAddress()
{
return address;
}
/**
* @param address The address to set.
*/
public void setAddress(Address address)
{
this.address = address;
}
/**
* @return Returns the collectionProtocolCollection.
* @hibernate.set name="collectionProtocolCollection" table="CATISSUE_COLL_COORDINATORS"
* cascade="save-update" inverse="true" lazy="true"
* @hibernate.collection-key column="USER_ID"
* @hibernate.collection-many-to-many class="edu.wustl.catissuecore.domain.CollectionProtocol" column="COLLECTION_PROTOCOL_ID"
*/
public Collection getCollectionProtocolCollection()
{
return collectionProtocolCollection;
}
/**
* @param collectionProtocolCollection The collectionProtocolCollection to set.
*/
public void setCollectionProtocolCollection(
Collection collectionProtocolCollection)
{
this.collectionProtocolCollection = collectionProtocolCollection;
}
/**
* @return Returns the pageOf.
*/
public String getPageOf()
{
return pageOf;
}
/**
* @param pageOf The pageOf to set.
*/
public void setPageOf(String pageOf)
{
this.pageOf = pageOf;
}
/**
* Returns the password assigned to user.
* @hibernate.property name="csmUserId" type="long" column="CSM_USER_ID" length="20"
* @return Returns the password.
*/
public Long getCsmUserId()
{
return csmUserId;
}
/**
* @param csmUserId The csmUserId to set.
*/
public void setCsmUserId(Long csmUserId)
{
this.csmUserId = csmUserId;
}
// /**
// * Returns the comments given by the approver.
// * @return the comments given by the approver.
// * @see #setCommentClob(String)
// */
// public Clob getCommentClob()
// return commentClob;
// /**
// * Sets the comments given by the approver.
// * @param comments the comments given by the approver.
// * @see #getCommentClob()
// */
// public void setCommentClob(Clob commentClob) throws SQLException
// if (commentClob == null)
// comments = "";
// commentClob = null;
// else
// this.commentClob = commentClob;
// this.comments = commentClob.getSubString(1L,(int)commentClob.length());
/**
* Returns the comments given by the approver.
* @hibernate.property name="comments" type="string"
* column="STATUS_COMMENT" length="2000"
* @return the comments given by the approver.
* @see #setComments(String)
*/
public String getComments()
{
return comments;
}
/**
* Sets the comments given by the approver.
* @param comments The comments to set.
* @see #getComments()
*/
public void setComments(String commentString)
{
if (commentString == null)
{
commentString = "";
}
else
{
this.comments = commentString;
}
}
/**
* @return Returns the roleId.
*/
public String getRoleId()
{
return roleId;
}
/**
* @param roleId The roleId to set.
*/
public void setRoleId(String roleId)
{
this.roleId = roleId;
}
/**
* @hibernate.set name="passwordCollection" table="CATISSUE_PASSWORD"
* cascade="save-update" inverse="true" lazy="true"
* @hibernate.collection-key column="USER_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.Password"
*/
public Collection getPasswordCollection()
{
return passwordCollection;
}
/**
* @return Returns the passwordCollection.
*/
public void setPasswordCollection(Collection passwordCollection)
{
this.passwordCollection = passwordCollection;
}
/**
* This function Copies the data from an UserForm object to a User object.
* @param user An UserForm object containing the information about the user.
* */
public void setAllValues(AbstractActionForm abstractForm)
{
try
{
UserForm uform = (UserForm) abstractForm;
this.pageOf = uform.getPageOf();
if (pageOf.equals(Constants.PAGEOF_CHANGE_PASSWORD))
{
// this.password = uform.getNewPassword();
this.oldPassword = uform.getOldPassword();
}
else
{
this.systemIdentifier = new Long(uform.getSystemIdentifier());
this.setLoginName(uform.getEmailAddress());
this.setLastName(uform.getLastName());
this.setFirstName(uform.getFirstName());
this.setEmailAddress(uform.getEmailAddress());
this.institution.setSystemIdentifier(new Long(uform
.getInstitutionId()));
this.department.setSystemIdentifier(new Long(uform
.getDepartmentId()));
this.cancerResearchGroup.setSystemIdentifier(new Long(uform
.getCancerResearchGroupId()));
if (Constants.PAGEOF_USER_PROFILE.equals(pageOf) == false)
{
this.activityStatus = uform.getActivityStatus();
}
if (pageOf.equals(Constants.PAGEOF_SIGNUP))
{
this.setStartDate(Calendar.getInstance().getTime());
}
if (!pageOf.equals(Constants.PAGEOF_SIGNUP)
&& !pageOf.equals(Constants.PAGEOF_USER_PROFILE))
{
this.comments = uform.getComments();
}
if (uform.getPageOf().equals(Constants.PAGEOF_USER_ADMIN)
&& uform.getOperation().equals(Constants.ADD))
{
this.activityStatus = Constants.ACTIVITY_STATUS_ACTIVE;
this.setStartDate(Calendar.getInstance().getTime());
}
if (uform.getPageOf().equals(Constants.PAGEOF_APPROVE_USER))
{
if (uform.getStatus().equals(
Constants.APPROVE_USER_APPROVE_STATUS))
{
this.activityStatus = Constants.ACTIVITY_STATUS_ACTIVE;
}
else if (uform.getStatus().equals(
Constants.APPROVE_USER_REJECT_STATUS))
{
this.activityStatus = Constants.ACTIVITY_STATUS_REJECT;
}
else
{
this.activityStatus = Constants.ACTIVITY_STATUS_PENDING;
}
}
this.roleId = uform.getRole();
this.address.setStreet(uform.getStreet());
this.address.setCity(uform.getCity());
this.address.setState(uform.getState());
this.address.setCountry(uform.getCountry());
this.address.setZipCode(uform.getZipCode());
this.address.setPhoneNumber(uform.getPhoneNumber());
this.address.setFaxNumber(uform.getFaxNumber());
if (Constants.PAGEOF_USER_ADMIN.equals(pageOf))
{
this.csmUserId = uform.getCsmUserId();
}
}
}
catch (Exception excp)
{
Logger.out.error(excp.getMessage());
}
}
}
|
package team.unstudio.udpl.util;
import java.io.File;
import java.util.Locale;
import org.bukkit.configuration.Configuration;
import team.unstudio.udpl.config.ConfigurationHelper;
public class I18n {
public static final Locale LOCAL_LOCALE = Locale.getDefault();
public static final Locale DEFAULT_LOCALE = Locale.US;
private final File path;
private Locale locale = LOCAL_LOCALE;
private Configuration cache = null;
public I18n(File path) {
if(path==null)
throw new IllegalArgumentException("Path can't Null.");
if(!path.exists())
throw new IllegalArgumentException("Path isn't exist.");
if(!path.isDirectory())
throw new IllegalArgumentException("Path isn't directory.");
this.path = path;
}
public File getPath() {
return path;
}
public Locale getSecretLanguage(){
return locale;
}
public String getSecretLanguageTag(){
return locale.toLanguageTag();
}
public void setSecretLanguage(String language) {
locale = Locale.forLanguageTag(language);
reload();
}
public void setSecretLanguage(Locale language) {
locale = language;
reload();
}
private void reload(){
File file = new File(path, getSecretLanguageTag()+".yml");
if(file.exists())
cache = ConfigurationHelper.loadConfiguration(file);
else
loadDefault();
}
private void loadDefault(){
File defaultFile = new File(path, DEFAULT_LOCALE.toLanguageTag()+".yml");
if(defaultFile.exists())
cache = ConfigurationHelper.loadConfiguration(defaultFile);
else
cache = null;
}
public String format(String key, Object... args){
if(cache == null)
return String.format(key, args);
else
return String.format(cache.getString(key, key), args);
}
}
|
package fitnesse.wikitext.widgets;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TodayWidgetTest {
@Before
public void setup() {
TodayWidget.todayForTest = new GregorianCalendar(1952, Calendar.DECEMBER, 5, 1, 13, 23); //GDTH unix date!!! Eleven == Dec
}
@After
public void teardown() {
TodayWidget.todayForTest = null;
}
private boolean matches(String widget) {
return Pattern.matches(TodayWidget.REGEXP, widget);
}
private void assertRenders(String widgetString, String result) throws Exception {
TodayWidget widget = new TodayWidget(new MockWidgetRoot(), widgetString);
Assert.assertEquals(result, widget.render());
}
@Test
public void shouldMatch() throws Exception {
assertTrue(matches("!today"));
assertTrue(matches("!today -t"));
assertTrue(matches("!today -xml"));
assertTrue(matches("!today +3"));
assertTrue(matches("!today -3"));
assertTrue(matches("!today (MMM)"));
assertTrue(matches("!today (MMM) +3"));
}
@Test
public void shouldNotMatch() throws Exception {
assertFalse(matches("!today -p"));
assertFalse(matches("!today 33"));
assertFalse(matches("!today x"));
}
@Test
public void today() throws Exception {
assertRenders("!today", "05 Dec, 1952");
}
@Test
public void withTime() throws Exception {
assertRenders("!today -t", "05 Dec, 1952 01:13");
}
@Test
public void xml() throws Exception {
assertRenders("!today -xml", "1952-12-05T01:13:23");
}
@Test
public void addOneDay() throws Exception {
assertRenders("!today +1", "06 Dec, 1952");
}
@Test
public void subtractOneDay() throws Exception {
assertRenders("!today -1", "04 Dec, 1952");
}
@Test
public void subtractOneWeek() throws Exception {
assertRenders("!today -7", "28 Nov, 1952");
}
@Test
public void addOneYear() throws Exception {
assertRenders("!today +365", "05 Dec, 1953");
}
@Test
public void format() throws Exception {
assertRenders("!today (MMM)", "Dec");
}
@Test
public void formatPlusOneDay() throws Exception {
assertRenders("!today (ddMMM) +1", "06Dec");
}
}
|
package org.micromanager.utils;
import ij.ImagePlus;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.LUT;
import ij.process.ShortProcessor;
import java.awt.Color;
import java.awt.Point;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.TaggedImageStorage;
public class ImageUtils {
private static Class storageClass_ = TaggedImageStorageDiskDefault.class;
public static int BppToImageType(long Bpp) {
int BppInt = (int) Bpp;
switch (BppInt) {
case 1:
return ImagePlus.GRAY8;
case 2:
return ImagePlus.GRAY16;
case 4:
return ImagePlus.COLOR_RGB;
}
return 0;
}
public static int getImageProcessorType(ImageProcessor proc) {
if (proc instanceof ByteProcessor) {
return ImagePlus.GRAY8;
}
if (proc instanceof ShortProcessor) {
return ImagePlus.GRAY16;
}
if (proc instanceof ColorProcessor) {
return ImagePlus.COLOR_RGB;
}
return -1;
}
public static ImageProcessor makeProcessor(CMMCore core) {
return makeProcessor(core, null);
}
public static ImageProcessor makeProcessor(CMMCore core, Object imgArray) {
int w = (int) core.getImageWidth();
int h = (int) core.getImageHeight();
int Bpp = (int) core.getBytesPerPixel();
int type;
switch (Bpp) {
case 1:
type = ImagePlus.GRAY8;
break;
case 2:
type = ImagePlus.GRAY16;
break;
case 4:
type = ImagePlus.COLOR_RGB;
break;
default:
type = 0;
}
return makeProcessor(type, w, h, imgArray);
}
public static ImageProcessor makeProcessor(int type, int w, int h, Object imgArray) {
if (imgArray == null) {
return makeProcessor(type, w, h);
} else {
switch (type) {
case ImagePlus.GRAY8:
return new ByteProcessor(w, h, (byte[]) imgArray, null);
case ImagePlus.GRAY16:
return new ShortProcessor(w, h, (short[]) imgArray, null);
case ImagePlus.GRAY32:
return new FloatProcessor(w,h, (float[]) imgArray, null);
case ImagePlus.COLOR_RGB:
return new ColorProcessor(w, h, (int[]) imgArray);
default:
return null;
}
}
}
public static ImageProcessor makeProcessor(TaggedImage taggedImage) {
final JSONObject tags = taggedImage.tags;
try {
return makeProcessor(MDUtils.getIJType(tags), MDUtils.getWidth(tags),
MDUtils.getHeight(tags), taggedImage.pix);
} catch (Exception e) {
ReportingUtils.logError(e);
}
return null;
}
public static ImageProcessor makeProcessor(int type, int w, int h) {
if (type == ImagePlus.GRAY8) {
return new ByteProcessor(w, h);
} else if (type == ImagePlus.GRAY16) {
return new ShortProcessor(w, h);
} else if (type == ImagePlus.GRAY32) {
return new FloatProcessor(w,h);
} else if (type == ImagePlus.COLOR_RGB) {
return new ColorProcessor(w, h);
} else {
return null;
}
}
public static ImageProcessor subtractImageProcessors(ImageProcessor proc1, ImageProcessor proc2) {
if (proc1 instanceof ByteProcessor) {
return subtractByteProcessors((ByteProcessor) proc1, (ByteProcessor) proc2);
} else if (proc1 instanceof ShortProcessor) {
return subtractShortProcessors((ShortProcessor) proc1, (ShortProcessor) proc2);
}
return null;
}
private static ByteProcessor subtractByteProcessors(ByteProcessor proc1, ByteProcessor proc2) {
return new ByteProcessor(proc1.getWidth(), proc1.getHeight(),
subtractPixelArrays((byte []) proc1.getPixels(), (byte []) proc2.getPixels()),
null);
}
private static ShortProcessor subtractShortProcessors(ShortProcessor proc1, ShortProcessor proc2) {
return new ShortProcessor(proc1.getWidth(), proc1.getHeight(),
subtractPixelArrays((short []) proc1.getPixels(), (short []) proc2.getPixels()),
null);
}
public static byte[] subtractPixelArrays(byte[] array1, byte[] array2) {
int l = array1.length;
byte[] result = new byte[l];
for (int i=0;i<l;++i) {
result[i] = (byte) Math.max(0,array1[i] - array2[i]);
}
return result;
}
public static short[] subtractPixelArrays(short[] array1, short[] array2) {
int l = array1.length;
short[] result = new short[l];
for (int i=0;i<l;++i) {
result[i] = (short) Math.max(0,array1[i] - array2[i]);
}
return result;
}
/*
* Finds the position of the maximum pixel value.
*/
public static Point findMaxPixel(ImagePlus img) {
ImageProcessor proc = img.getProcessor();
float[] pix = (float[]) proc.getPixels();
int width = img.getWidth();
double max = 0;
int imax = -1;
for (int i = 0; i < pix.length; i++) {
if (pix[i] > max) {
max = pix[i];
imax = i;
}
}
int y = imax / width;
int x = imax % width;
return new Point(x, y);
}
public static Point findMaxPixel(ImageProcessor proc) {
int width = proc.getWidth();
int imax = findArrayMax(proc.getPixels());
int y = imax / width;
int x = imax % width;
return new Point(x, y);
}
public static byte[] get8BitData(Object bytesAsObject) {
return (byte[]) bytesAsObject;
}
public static short[] get16BitData(Object shortsAsObject) {
return (short[]) shortsAsObject;
}
public static int[] get32BitData(Object intsAsObject) {
return (int[]) intsAsObject;
}
public static int findArrayMax(Object pix) {
if (pix instanceof byte [])
return findArrayMax((byte []) pix);
if (pix instanceof int [])
return findArrayMax((int []) pix);
if (pix instanceof short [])
return findArrayMax((short []) pix);
if (pix instanceof float [])
return findArrayMax((float []) pix);
else
return -1;
}
public static int findArrayMax(float[] pix) {
float pixel;
int imax = -1;
float max = Float.MIN_VALUE;
for (int i = 0; i < pix.length; ++i) {
pixel = pix[i];
if (pixel > max) {
max = pixel;
imax = i;
}
}
return imax;
}
public static int findArrayMax(short[] pix) {
short pixel;
int imax = -1;
short max = Short.MIN_VALUE;
for (int i = 0; i < pix.length; ++i) {
pixel = pix[i];
if (pixel > max) {
max = pixel;
imax = i;
}
}
return imax;
}
public static int findArrayMax(byte[] pix) {
byte pixel;
int imax = -1;
byte max = Byte.MIN_VALUE;
for (int i = 0; i < pix.length; ++i) {
pixel = pix[i];
if (pixel > max) {
max = pixel;
imax = i;
}
}
return imax;
}
public static int findArrayMax(int[] pix) {
int pixel;
int imax = -1;
int max = Integer.MIN_VALUE;
for (int i = 0; i < pix.length; ++i) {
pixel = pix[i];
if (pixel > max) {
max = pixel;
imax = i;
}
}
return imax;
}
public static byte[] convertRGB32IntToBytes(int [] pixels) {
byte[] bytes = new byte[pixels.length*4];
int j = 0;
for (int i = 0; i<pixels.length;++i) {
bytes[j++] = (byte) (pixels[i] & 0xff);
bytes[j++] = (byte) ((pixels[i] >> 8) & 0xff);
bytes[j++] = (byte) ((pixels[i] >> 16) & 0xff);
bytes[j++] = 0;
}
return bytes;
}
public static byte[] getRGB32PixelsFromColorPanes(byte[][] planes) {
int j=0;
byte[] pixels = new byte[planes.length * 4];
for (int i=0;i<planes.length;++i) {
pixels[j++] = planes[2][i];
pixels[j++] = planes[1][i];
pixels[j++] = planes[0][i];
pixels[j++] = 0; // Empty A byte.
}
return pixels;
}
public static short[] getRGB64PixelsFromColorPlanes(short[][] planes) {
int j=-1;
short[] pixels = new short[planes[0].length * 4];
for (int i=0;i<planes[0].length;++i) {
pixels[++j] = planes[2][i];
pixels[++j] = planes[1][i];
pixels[++j] = planes[0][i];
pixels[++j] = 0; // Empty A (two bytes).
}
return pixels;
}
public static byte[][] getColorPlanesFromRGB32(byte[] pixels) {
byte [] r = new byte[pixels.length/4];
byte [] g = new byte[pixels.length/4];
byte [] b = new byte[pixels.length/4];
int j=0;
for (int i=0;i<pixels.length/4;++i) {
b[i] = pixels[j++];
g[i] = pixels[j++];
r[i] = pixels[j++];
j++; // skip "A" byte.
}
byte[][] planes = {r,g,b};
return planes;
}
public static short[][] getColorPlanesFromRGB64(short[] pixels) {
short [] r = new short[pixels.length/4];
short [] g = new short[pixels.length/4];
short [] b = new short[pixels.length/4];
int j=0;
for (int i=0;i<pixels.length/4;++i) {
b[i] = pixels[j++];
g[i] = pixels[j++];
r[i] = pixels[j++];
j++; // skip "A" (two bytes).
}
short[][] planes = {r,g,b};
return planes;
}
/*
* channel should be 0, 1 or 2.
*/
public static byte[] singleChannelFromRGB32(byte[] pixels, int channel) {
if (channel != 0 && channel != 1 && channel != 2)
return null;
byte [] p = new byte[pixels.length/4];
for (int i=0;i<p.length;++i) {
p[i] = pixels[(2-channel) + 4*i]; //B,G,R
}
return p;
}
/*
* channel should be 0, 1 or 2.
*/
public static short[] singleChannelFromRGB64(short[] pixels, int channel) {
if (channel != 0 && channel != 1 && channel != 2)
return null;
short [] p = new short[pixels.length/4];
for (int i=0;i<p.length;++i) {
p[i] = pixels[(2-channel) + 4*i]; // B,G,R
}
return p;
}
public static LUT makeLUT(Color color, double gamma) {
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
int size = 256;
byte [] rs = new byte[size];
byte [] gs = new byte[size];
byte [] bs = new byte[size];
double xn;
double yn;
for (int x=0;x<size;++x) {
xn = x / (double) (size-1);
yn = Math.pow(xn, gamma);
rs[x] = (byte) (yn * r);
gs[x] = (byte) (yn * g);
bs[x] = (byte) (yn * b);
}
return new LUT(8,size,rs,gs,bs);
}
public static void setImageStorageClass(Class storageClass) {
storageClass_ = storageClass;
}
public static Class getImageStorageClass() {
return storageClass_;
}
public static TaggedImageStorage newImageStorageInstance
(String acqPath, boolean newDataSet, JSONObject summaryMetadata) {
try {
return (TaggedImageStorage) storageClass_
.getConstructor(String.class, Boolean.class, JSONObject.class)
.newInstance(acqPath, new Boolean(newDataSet), summaryMetadata);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
return null;
}
public class MinAndMax {
int min;
int max;
}
private static int unsignedValue(byte b) {
return ((0x100 + b) % 0x100);
}
private static int unsignedValue(short s) {
return ((0x10000 + s) % 0x10000);
}
public static int getMin(final Object pixels) {
if (pixels instanceof byte[]) {
byte[] bytes = (byte []) pixels;
int min = Integer.MAX_VALUE;
for (int i=0;i<bytes.length;++i) {
min = Math.min(min, unsignedValue(bytes[i]));
}
return min;
}
if (pixels instanceof short[]) {
short[] shorts = (short []) pixels;
int min = Integer.MAX_VALUE;
for (int i=0;i<shorts.length;++i) {
min = Math.min(min, unsignedValue(shorts[i]));
}
return min;
}
return -1;
}
public static int getMax(final Object pixels) {
if (pixels instanceof byte[]) {
byte[] bytes = (byte []) pixels;
int max = Integer.MIN_VALUE;
for (int i=0;i<bytes.length;++i) {
max = Math.max(max, unsignedValue(bytes[i]));
}
return max;
}
if (pixels instanceof short[]) {
short[] shorts = (short []) pixels;
int min = Integer.MIN_VALUE;
for (int i=0;i<shorts.length;++i) {
min = Math.max(min, unsignedValue(shorts[i]));
}
return min;
}
return -1;
}
public static int[] getMinMax(final Object pixels) {
int[] result = new int[2];
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
if (pixels instanceof byte[]) {
byte[] bytes = (byte []) pixels;
for (int i=0;i<bytes.length;++i) {
max = Math.max(max, unsignedValue(bytes[i]));
min = Math.min(min, unsignedValue(bytes[i]));
}
result[0] = min;
result[1] = max;
return result;
}
if (pixels instanceof short[]) {
short[] shorts = (short []) pixels;
for (int i=0;i<shorts.length;++i) {
min = Math.min(min, unsignedValue(shorts[i]));
max = Math.max(max, unsignedValue(shorts[i]));
}
result[0] = min;
result[1] = max;
return result;
}
return null;
}
public static TaggedImage makeTaggedImage(ImageProcessor proc) {
JSONObject tags = new JSONObject();
try {
MDUtils.setChannelIndex(tags, 0);
MDUtils.setSliceIndex(tags, 0);
MDUtils.setPositionIndex(tags, 0);
MDUtils.setFrameIndex(tags, 0);
MDUtils.setWidth(tags, proc.getWidth());
MDUtils.setHeight(tags, proc.getHeight());
MDUtils.setPixelType(tags, getImageProcessorType(proc));
} catch (Exception e) {
return null;
}
return new TaggedImage(proc.getPixels(), tags);
}
public static TaggedImage makeTaggedImage(Object pixels, int channelIndex,
int sliceIndex, int positionIndex, int frameIndex, int width,
int height, int numberOfBytesPerPixel) {
JSONObject tags = new JSONObject();
try {
MDUtils.setChannelIndex(tags, channelIndex);
MDUtils.setSliceIndex(tags, sliceIndex);
MDUtils.setPositionIndex(tags, positionIndex);
MDUtils.setFrameIndex(tags, frameIndex);
MDUtils.setWidth(tags, width);
MDUtils.setHeight(tags, height);
MDUtils.setPixelTypeFromByteDepth(tags, numberOfBytesPerPixel);
} catch (Exception e) {
return null;
}
return new TaggedImage(pixels, tags);
}
}
|
package snake;
import java.util.Random;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import snake.Snake.Direction;
/**
* Controls the entire functioning of the game including drawing graphical elements,
* calculating game states, controlling movement and actions and processing
* keyboard input.
* @author Ashley
*/
public class GameController {
private final GraphicsContext gc;
private final int gridWidth, gridHeight, cellSize;
private int score = 0;
private boolean keyPressedThisTick = false;
private boolean paused = false;
private boolean auto = false;
private Snake snake;
private Coordinates apple;
/**
* Initialises a new GameController with the specified parameters and
* immediately creates a new game state.
* @param gc the GraphicsContext that the game will be drawn to
* @param gridWidth the width of the game grid
* @param gridHeight the height of the game grid
* @param cellSize the size in pixels of each cell in the grid
*/
public GameController(GraphicsContext gc, int gridWidth, int gridHeight, int cellSize) {
this.gc = gc;
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
this.cellSize = cellSize;
startGame();
}
/**
* Initialise the game
*/
private void startGame() {
createSnake();
createApple();
score = 0;
}
/**
* Create a new snake at the centre of the game grid
*/
private void createSnake() {
int halfWidth = gridWidth / 2;
int halfHeight = gridHeight / 2;
snake = new Snake(new Coordinates(halfWidth, halfHeight), 5, Direction.WEST);
}
/**
* Create the apple at a random location on the game grid.
* TODO: Fix so it doesn't generate the apple on top of the snake
*/
private void createApple() {
Random rnd = new Random();
apple = new Coordinates(rnd.nextInt(gridWidth), rnd.nextInt(gridHeight));
}
/**
* Draws the game to the GraphicsContext
*/
private void drawGame() {
//For each each cell of the grid if there is a snake draw green,
//an apple draw red or nothing draw white.
for (int x = 0; x < gridWidth; x++) {
for (int y = 0; y < gridHeight; y++) {
if (isSnakeAt(new Coordinates(x, y))) {
drawCell(x, y, Color.GREEN);
} else if (apple.equals(new Coordinates(x, y))) {
drawCell(x, y, Color.RED);
} else {
drawCell(x, y, Color.WHITE);
}
}
}
//Draw a grid around the game grid
gc.strokeRect(0, 0, gridWidth * cellSize, gridHeight * cellSize);
}
private boolean isSnakeAt(Coordinates pos) {
for (int i = 0; i < snake.getLength(); i++) {
if (pos.equals(snake.getBody(i))) {
return true;
}
}
return false;
}
/**
* Draws a cell of the specified colour and x and y coordinates to the game grid
* @param x the x coordinate of the cell to draw
* @param y the y coordinate of the cell to draw
* @param color the Color of the cell to draw
*/
private void drawCell(int x, int y, Color color) {
gc.setFill(color);
gc.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
// /**
// * Calculate which direction the snake should move in when the game is in
// * auto mode.
// * TODO: Make better, snake tends to kill itself as it stands ;)
// */
// private void calculateBestDirection() {
// Point2D snakeHead = snake.get(0);
// double xDif = snakeHead.getX() - apple.getX();
// double yDif = snakeHead.getY() - apple.getY();
// if (Math.abs(xDif) < Math.abs(yDif)) {
// if (yDif < 0) {
// if (direction == Direction.NORTH) {
// direction = Direction.EAST;
// } else {
// direction = Direction.SOUTH;
// } else {
// if (direction == Direction.SOUTH) {
// direction = Direction.EAST;
// } else {
// direction = Direction.NORTH;
// } else {
// if (xDif < 0) {
// if (direction == Direction.WEST) {
// direction = Direction.NORTH;
// } else {
// direction = Direction.EAST;
// } else {
// if (direction == Direction.EAST) {
// direction = Direction.NORTH;
// } else {
// direction = Direction.WEST;
// private boolean wouldCollide() {
// boolean wouldCollide = false;
// List<Point2D> tempSnake = new ArrayList<>(snake);
// moveSnake();
// if (hasCollided()) {
// wouldCollide = true;
// snake = tempSnake;
/**
* Calculates whether the snake has eaten an apple
* @return true if the snake's head is in the same position as the apple
*/
private boolean hasEatenApple() {
return snake.getHead().equals(apple);
}
/**
* Calculates whether the snake has collided
* @return true if the snake has collided with itself or the edge of the
* game grid
*/
private boolean hasCollided() {
//Has the snake collided with itself?
for (int i = 1; i < snake.getLength(); i++) {
if (snake.getHead().equals(snake.getBody(i))) {
return true;
}
}
//Has the snake colided with the edge of the game grid?
return snake.getHead().getX() < 0 || snake.getHead().getX() >= gridWidth || snake.getHead().getY() < 0 || snake.getHead().getY() >= gridHeight;
}
/**
* Calculates the next state of the game. First moves the snake then checks
* for collisions with itself, the edge of the game grid and the apple. Then
* draws the updated game state.
*/
public void tick() {
if (!paused) {
// if (auto) {
// calculateBestDirection();
snake.move();
if (hasEatenApple()) {
snake.eatApple();
createApple();
score++;
}
if (hasCollided()) {
createSnake();
startGame();
}
drawGame();
}
keyPressedThisTick = false;
}
/**
* Handles keyboard input
* @param ke the KeyEvent to handle
*/
public void handleKeyPressed(KeyEvent ke) {
KeyCode keyCode = ke.getCode();
if (!paused) {
if (!keyPressedThisTick) {
switch(keyCode) {
case UP:
snake.changeDirection(Direction.NORTH);
break;
case RIGHT:
snake.changeDirection(Direction.EAST);
break;
case DOWN:
snake.changeDirection(Direction.SOUTH);
break;
case LEFT:
snake.changeDirection(Direction.WEST);
break;
}
keyPressedThisTick = true;
}
if (keyCode == KeyCode.A) {
auto = !auto;
}
}
if (keyCode == KeyCode.P) {
paused = !paused;
}
ke.consume();
}
/**
* Returns the value of score
* @return score
*/
public int getScore() {
return score;
}
/**
* Returns whether the game is paused or not
* @return paused
*/
public boolean isPaused() {
return paused;
}
/**
* Returns whether the game is set to automatic mode
* @return auto
*/
public boolean isAuto() {
return auto;
}
}
|
package sokoban.Elements;
public class Box extends ElementMovable {
String id="B";
/**
* @author 160794
* Constructeur
*
*/
public Box() {
// TODO Auto-generated constructor stub
}
/*
* (getter de id)
* @160794
*/
public String Show()
{
return id;
}
/*
* (Dplace un objet mobil)
* @160794
*/
public void Deplacer() {
// TODO Auto-generated method stub
}
}
|
package mondrian.olap.fun;
import mondrian.olap.*;
import mondrian.util.Format;
import java.util.*;
/**
* <code>BuiltinFunTable</code> contains a list of all built-in MDX functions.
*
* <p>Note: Boolean expressions return {@link Boolean#TRUE},
* {@link Boolean#FALSE} or null. null is returned if the expression can not be
* evaluated because some values have not been loaded from database yet.</p>
*
* @author jhyde
* @since 26 February, 2002
* @version $Id$
**/
public class BuiltinFunTable extends FunTable {
/**
* Maps the upper-case name of a function plus its {@link Syntax} to an
* array of {@link Resolver} objects for that name.
*/
private HashMap mapNameToResolvers;
private static final Resolver[] emptyResolvers = new Resolver[0];
private final Exp.Resolver dummyResolver = Util.createSimpleResolver(this);
private Exp valueFunCall;
private final HashSet reservedWords = new HashSet();
private static final Resolver[] emptyResolverArray = new Resolver[0];
/**
* Creates a <code>BuiltinFunTable</code>. This method should only be
* called from {@link FunTable#instance}.
**/
public BuiltinFunTable() {
init();
valueFunCall = new FunCall("_Value", Syntax.Function, new Exp[0])
.resolve(dummyResolver);
}
private static String makeResolverKey(String name, Syntax syntax) {
return name.toUpperCase() + "$" + syntax;
}
/** Calls {@link #defineFunctions} to load function definitions into a
* List, then indexes that collection. **/
private void init() {
resolvers = new ArrayList();
defineFunctions();
// Map upper-case function names to resolvers.
mapNameToResolvers = new HashMap();
for (int i = 0, n = resolvers.size(); i < n; i++) {
Resolver resolver = (Resolver) resolvers.get(i);
String key = makeResolverKey(resolver.getName(), resolver.getSyntax());
List v2 = (List) mapNameToResolvers.get(key);
if (v2 == null) {
v2 = new ArrayList();
mapNameToResolvers.put(key, v2);
}
v2.add(resolver);
}
// Convert the Lists into arrays.
for (Iterator keys = mapNameToResolvers.keySet().iterator(); keys.hasNext();) {
String key = (String) keys.next();
List v2 = (List) mapNameToResolvers.get(key);
mapNameToResolvers.put(key, v2.toArray(emptyResolverArray));
}
}
protected void define(FunDef funDef) {
define(new SimpleResolver(funDef));
}
protected void define(Resolver resolver) {
resolvers.add(resolver);
}
static Syntax decodeSyntacticType(String flags) {
char c = flags.charAt(0);
switch (c) {
case 'p':
return Syntax.Property;
case 'f':
return Syntax.Function;
case 'm':
return Syntax.Method;
case 'i':
return Syntax.Infix;
case 'P':
return Syntax.Prefix;
case 'I':
return Syntax.Internal;
default:
throw Util.newInternal(
"unknown syntax code '" + c + "' in string '" + flags + "'");
}
}
static int decodeReturnType(String flags) {
final int returnType = decodeType(flags, 1);
if ((returnType & Category.Mask) != returnType) {
throw Util.newInternal("bad return code flag in flags '" + flags + "'");
}
return returnType;
}
static int decodeType(String flags, int offset) {
char c = flags.charAt(offset);
switch (c) {
case 'a':
return Category.Array;
case 'd':
return Category.Dimension;
case 'h':
return Category.Hierarchy;
case 'l':
return Category.Level;
case 'b':
return Category.Logical;
case 'm':
return Category.Member;
case 'N':
return Category.Numeric | Category.Constant;
case 'n':
return Category.Numeric;
case 'x':
return Category.Set;
case '
return Category.String | Category.Constant;
case 'S':
return Category.String;
case 't':
return Category.Tuple;
case 'v':
return Category.Value;
case 'y':
return Category.Symbol;
default:
throw Util.newInternal(
"unknown type code '" + c + "' in string '" + flags + "'");
}
}
/**
* Converts an argument to a parameter type.
*/
public Exp convert(Exp fromExp, int to, Exp.Resolver resolver) {
Exp exp = convert_(fromExp, to);
if (exp == null) {
throw Util.newInternal("cannot convert " + fromExp + " to " + to);
}
return resolver.resolveChild(exp);
}
private static Exp convert_(Exp fromExp, int to) {
int from = fromExp.getType();
if (from == to) {
return fromExp;
}
switch (from) {
case Category.Array:
return null;
case Category.Dimension:
// Seems funny that you can 'downcast' from a dimension, doesn't
// it? But we add an implicit 'CurrentMember', for example,
// '[Time].PrevMember' actually means
// '[Time].CurrentMember.PrevMember'.
switch (to) {
case Category.Hierarchy:
// "<Dimension>.CurrentMember.Hierarchy"
return new FunCall(
"Hierarchy", Syntax.Property, new Exp[]{
new FunCall(
"CurrentMember",
Syntax.Property, new Exp[]{fromExp}
)}
);
case Category.Level:
// "<Dimension>.CurrentMember.Level"
return new FunCall(
"Level", Syntax.Property, new Exp[]{
new FunCall(
"CurrentMember",
Syntax.Property, new Exp[]{fromExp}
)}
);
case Category.Member:
// "<Dimension>.CurrentMember"
return new FunCall("CurrentMember", Syntax.Property, new Exp[]{fromExp});
default:
return null;
}
case Category.Hierarchy:
switch (to) {
case Category.Dimension:
// "<Hierarchy>.Dimension"
return new FunCall("Dimension", Syntax.Property, new Exp[]{fromExp});
default:
return null;
}
case Category.Level:
switch (to) {
case Category.Dimension:
// "<Level>.Dimension"
return new FunCall("Dimension", Syntax.Property, new Exp[]{fromExp});
case Category.Hierarchy:
// "<Level>.Hierarchy"
return new FunCall("Hierarchy", Syntax.Property, new Exp[]{fromExp});
default:
return null;
}
case Category.Logical:
return null;
case Category.Member:
switch (to) {
case Category.Dimension:
// "<Member>.Dimension"
return new FunCall("Dimension", Syntax.Property, new Exp[]{fromExp});
case Category.Hierarchy:
// "<Member>.Hierarchy"
return new FunCall("Hierarchy", Syntax.Property, new Exp[]{fromExp});
case Category.Level:
// "<Member>.Level"
return new FunCall("Level", Syntax.Property, new Exp[]{fromExp});
case Category.Numeric | Category.Constant:
case Category.String | Category.Constant: //todo: assert is a string member
// "<Member>.Value"
return new FunCall("Value", Syntax.Property, new Exp[]{fromExp});
case Category.Value:
case Category.Numeric:
case Category.String:
return fromExp;
default:
return null;
}
case Category.Numeric | Category.Constant:
switch (to) {
case Category.Value:
case Category.Numeric:
return fromExp;
default:
return null;
}
case Category.Numeric:
switch (to) {
case Category.Value:
return fromExp;
case Category.Numeric | Category.Constant:
return new FunCall("_Value", Syntax.Function, new Exp[] {fromExp});
default:
return null;
}
case Category.Set:
return null;
case Category.String | Category.Constant:
switch (to) {
case Category.Value:
case Category.String:
return fromExp;
default:
return null;
}
case Category.String:
switch (to) {
case Category.Value:
return fromExp;
case Category.String | Category.Constant:
return new FunCall("_Value", Syntax.Function, new Exp[] {fromExp});
default:
return null;
}
case Category.Tuple:
switch (to) {
case Category.Value:
return fromExp;
case Category.Numeric:
case Category.String:
return new FunCall("_Value", Syntax.Function, new Exp[] {fromExp});
default:
return null;
}
case Category.Value:
return null;
case Category.Symbol:
return null;
default:
throw Util.newInternal("unknown category " + from);
}
}
/**
* Returns whether we can convert an argument to a parameter tyoe.
* @param fromExp argument type
* @param to parameter type
* @param conversionCount in/out count of number of conversions performed;
* is incremented if the conversion is non-trivial (for
* example, converting a member to a level).
*
* @see FunTable#convert
*/
static boolean canConvert(Exp fromExp, int to, int[] conversionCount) {
int from = fromExp.getType();
if (from == to) {
return true;
}
switch (from) {
case Category.Array:
return false;
case Category.Dimension:
// Seems funny that you can 'downcast' from a dimension, doesn't
// it? But we add an implicit 'CurrentMember', for example,
// '[Time].PrevMember' actually means
// '[Time].CurrentMember.PrevMember'.
if (to == Category.Hierarchy ||
to == Category.Level ||
to == Category.Member) {
conversionCount[0]++;
return true;
} else {
return false;
}
case Category.Hierarchy:
if (to == Category.Dimension) {
conversionCount[0]++;
return true;
} else {
return false;
}
case Category.Level:
if (to == Category.Dimension ||
to == Category.Hierarchy) {
conversionCount[0]++;
return true;
} else {
return false;
}
case Category.Logical:
return false;
case Category.Member:
if (to == Category.Dimension ||
to == Category.Hierarchy ||
to == Category.Level ||
to == Category.Numeric) {
conversionCount[0]++;
return true;
} else if (to == Category.Value ||
to == (Category.Numeric | Category.Expression) ||
to == (Category.String | Category.Expression)) {
return true;
} else {
return false;
}
case Category.Numeric | Category.Constant:
return to == Category.Value ||
to == Category.Numeric;
case Category.Numeric:
return to == Category.Value ||
to == (Category.Numeric | Category.Constant);
case Category.Set:
return false;
case Category.String | Category.Constant:
return to == Category.Value ||
to == Category.String;
case Category.String:
return to == Category.Value ||
to == (Category.String | Category.Constant);
case Category.Tuple:
return to == Category.Value ||
to == Category.Numeric;
case Category.Value:
return false;
case Category.Symbol:
return false;
default:
throw Util.newInternal("unknown category " + from);
}
}
static int[] decodeParameterTypes(String flags) {
int[] parameterTypes = new int[flags.length() - 2];
for (int i = 0; i < parameterTypes.length; i++) {
parameterTypes[i] = decodeType(flags, i + 2);
}
return parameterTypes;
}
public FunDef getDef(FunCall call, Exp.Resolver resolver) {
String key = makeResolverKey(call.getFunName(), call.getSyntax());
// Resolve function by its upper-case name first. If there is only one
// function with that name, stop immediately. If there is more than
// function, use some custom method, which generally involves looking
// at the type of one of its arguments.
String signature = call.getSyntax().getSignature(call.getFunName(),
Category.Unknown, ExpBase.getTypes(call.args));
Resolver[] resolvers = (Resolver[]) mapNameToResolvers.get(key);
if (resolvers == null) {
resolvers = emptyResolvers;
}
int[] conversionCount = new int[1];
int minConversions = Integer.MAX_VALUE;
int matchCount = 0;
FunDef matchDef = null;
for (int i = 0; i < resolvers.length; i++) {
conversionCount[0] = 0;
FunDef def = resolvers[i].resolve(call.args, conversionCount);
if (def != null) {
if (def.getReturnType() == Category.Set &&
resolver.requiresExpression()) {
continue;
}
int conversions = conversionCount[0];
if (conversions < minConversions) {
minConversions = conversions;
matchCount = 1;
matchDef = def;
} else if (conversions == minConversions) {
matchCount++;
} else {
// ignore this match -- it required more coercions than
// other overloadings we've seen
}
}
}
switch (matchCount) {
case 0:
throw MondrianResource.instance().newNoFunctionMatchesSignature(
signature);
case 1:
final String matchKey = makeResolverKey(matchDef.getName(),
matchDef.getSyntax());
Util.assertTrue(matchKey.equals(key), matchKey);
return matchDef;
default:
throw MondrianResource.instance()
.newMoreThanOneFunctionMatchesSignature(signature);
}
}
public boolean requiresExpression(FunCall call, int k,
Exp.Resolver resolver) {
final FunDef funDef = call.getFunDef();
if (funDef != null) {
final int[] parameterTypes = funDef.getParameterTypes();
return parameterTypes[k] != Category.Set;
}
// The function call has not been resolved yet. In fact, this method
// may have been invoked while resolving the child. Consider this:
// CrossJoin([Measures].[Unit Sales] * [Measures].[Store Sales])
// In order to know whether to resolve '*' to the multiplication
// operator (which returns a scalar) or the crossjoin operator (which
// returns a set) we have to know what kind of expression is expected.
String key = makeResolverKey(call.getFunName(), call.getSyntax());
Resolver[] resolvers = (Resolver[]) mapNameToResolvers.get(key);
if (resolvers == null) {
resolvers = emptyResolvers;
}
for (int i = 0; i < resolvers.length; i++) {
Resolver resolver2 = resolvers[i];
if (!resolver2.requiresExpression(k)) {
// This resolver accepts a set in this argument position,
// therefore we don't REQUIRE a scalar expression.
return false;
}
}
return true;
}
public boolean isReserved(String s) {
return reservedWords.contains(s.toUpperCase());
}
/**
* Defines a reserved word.
*/
public void defineReserved(String s) {
reservedWords.add(s.toUpperCase());
}
/**
* Defines a set of reserved words.
*/
public void defineReserved(String[] a) {
for (int i = 0; i < a.length; i++) {
defineReserved(a[i]);
}
}
/**
* Defines every name in an enumeration as a reserved word.
*/
public void defineReserved(EnumeratedValues values) {
defineReserved(values.getNames());
}
/**
* Derived class can override this method to add more functions.
**/
protected void defineFunctions() {
defineReserved("NULL");
// first char: p=Property, m=Method, i=Infix, P=Prefix
// 2nd:
// ARRAY FUNCTIONS
if (false) define(new FunDefBase("SetToArray", "SetToArray(<Set>[, <Set>]...[, <Numeric Expression>])", "Converts one or more sets to an array for use in a user-if (false) defined function.", "fa*"));
// DIMENSION FUNCTIONS
define(new FunDefBase("Dimension", "<Hierarchy>.Dimension", "Returns the dimension that contains a specified hierarchy.", "pdh") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy = getHierarchyArg(evaluator, args, 0, true);
return hierarchy.getDimension();
}
});
//??Had to add this to get <Hierarchy>.Dimension to work?
define(new FunDefBase("Dimension", "<Dimension>.Dimension", "Returns the dimension that contains a specified hierarchy.", "pdd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = getDimensionArg(evaluator, args, 0, true);
return dimension;
}
});
define(new FunDefBase("Dimension", "<Level>.Dimension", "Returns the dimension that contains a specified level.", "pdl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, true);
return level.getDimension();
}
});
define(new FunDefBase("Dimension", "<Member>.Dimension", "Returns the dimension that contains a specified member.", "pdm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.getDimension();
}
});
define(new FunDefBase("Dimensions", "Dimensions(<Numeric Expression>)", "Returns the dimension whose zero-based position within the cube is specified by a numeric expression.", "fdn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Cube cube = evaluator.getCube();
Dimension[] dimensions = cube.getDimensions();
int n = getIntArg(evaluator, args, 0);
if ((n > dimensions.length) || (n < 1)) {
throw newEvalException(
this, "Index '" + n + "' out of bounds");
}
return dimensions[n - 1];
}
});
define(new FunDefBase("Dimensions", "Dimensions(<String Expression>)", "Returns the dimension whose name is specified by a string.", "fdS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String defValue = "Default Value";
String s = getStringArg(evaluator, args, 0, defValue);
if (s.indexOf("[") == -1) {
s = Util.quoteMdxIdentifier(s);
}
OlapElement o = lookupCompound(evaluator.getSchemaReader(),
evaluator.getCube(), explode(s), false, Category.Dimension);
if (o instanceof Dimension) {
return (Dimension) o;
} else if (o == null) {
throw newEvalException(this, "Dimension '" + s + "' not found");
} else {
throw newEvalException(this, "Dimensions(" + s + ") found " + o);
}
}
});
// HIERARCHY FUNCTIONS
define(new FunDefBase("Hierarchy", "<Level>.Hierarchy", "Returns a level's hierarchy.", "phl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, true);
return level.getHierarchy();
}
});
define(new FunDefBase("Hierarchy", "<Member>.Hierarchy", "Returns a member's hierarchy.", "phm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.getHierarchy();
}
});
// LEVEL FUNCTIONS
define(new FunDefBase("Level", "<Member>.Level", "Returns a member's level.", "plm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.getLevel();
}
});
define(new FunDefBase("Levels", "<Hierarchy>.Levels(<Numeric Expression>)", "Returns the level whose position in a hierarchy is specified by a numeric expression.", "mlhn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy = getHierarchyArg(evaluator, args, 0, true);
Level[] levels = hierarchy.getLevels();
int n = getIntArg(evaluator, args, 1);
if ((n >= levels.length) || (n < 0)) {
throw newEvalException(
this, "Index '" + n + "' out of bounds");
}
return levels[n];
}
});
define(new FunDefBase("Levels", "Levels(<String Expression>)", "Returns the level whose name is specified by a string expression.", "flS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String s = getStringArg(evaluator, args, 0, null);
Cube cube = evaluator.getCube();
OlapElement o = null;
if (s.startsWith("[")) {
o = lookupCompound(evaluator.getSchemaReader(), cube, explode(s), false, Category.Level);
} else {
// lookupCompound barfs if "s" doesn't have matching
// brackets, so don't even try
o = null;
}
if (o instanceof Level) {
return (Level) o;
} else if (o == null) {
throw newEvalException(this, "Level '" + s + "' not found");
} else {
throw newEvalException(this, "Levels('" + s + "') found " + o);
}
}
});
// LOGICAL FUNCTIONS
define(new FunkResolver("IsEmpty", "IsEmpty(<Value Expression>)", "Determines if an expression evaluates to the empty cell value.",
new String[] {"fbS", "fbn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Object o = getScalarArg(evaluator, args, 0);
if (o == Util.nullValue) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
}));
define(new FunDefBase("IsEmpty", "IsEmpty(<Value Expression>)", "Determines if an expression evaluates to the empty cell value.", "fbn"));
// MEMBER FUNCTIONS
define(new FunkResolver("Ancestor",
"Ancestor(<Member>, {<Level>|<Numeric Expression>})",
"Returns the ancestor of a member at a specified level.",
new String[] {"fmml", "fmmn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, false);
Object arg2 = getArg(evaluator, args, 1);
Level level = null;
int distance;
if (arg2 instanceof Level) {
level = (Level) arg2;
distance = member.getLevel().getDepth() - level.getDepth();
} else {
distance = ((Number)arg2).intValue();
}
return ancestor(evaluator, member, distance, level);
}
}));
define(new FunDefBase("Cousin", "Cousin(<member>, <ancestor member>)",
"Returns the member with the same relative position under <ancestor member> as the member specified.", "fmmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member ancestorMember = getMemberArg(evaluator, args, 1, true);
Member cousin = cousin(evaluator.getSchemaReader(), member, ancestorMember);
return cousin;
}
});
define(new FunDefBase("CurrentMember", "<Dimension>.CurrentMember", "Returns the current member along a dimension during an iteration.", "pmd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = getDimensionArg(evaluator, args, 0, true);
return evaluator.getContext(dimension);
}
});
define(new FunDefBase("DefaultMember", "<Dimension>.DefaultMember", "Returns the default member of a dimension.", "pmd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = getDimensionArg(evaluator, args, 0, true);
return evaluator.getSchemaReader().getHierarchyDefaultMember(
dimension.getHierarchy());
}
});
define(new FunDefBase("FirstChild", "<Member>.FirstChild", "Returns the first child of a member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member[] children = evaluator.getSchemaReader().getMemberChildren(member);
if (children.length == 0) {
return member.getHierarchy().getNullMember();
} else {
return children[0];
}
}
});
define(new FunDefBase("FirstSibling", "<Member>.FirstSibling", "Returns the first child of the parent of a member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member parent = member.getParentMember();
Member[] children;
if (parent == null) {
if (member.isNull()) {
return member;
}
children = evaluator.getSchemaReader().getHierarchyRootMembers(member.getHierarchy());
} else {
children = evaluator.getSchemaReader().getMemberChildren(parent);
}
return children[0];
}
});
if (false) define(new FunDefBase("Item", "<Tuple>.Item(<Numeric Expression>)", "Returns a member from a tuple.", "mm*"));
define(new FunkResolver(
"Lag", "<Member>.Lag(<Numeric Expression>)", "Returns a member further along the specified member's dimension.",
new String[]{"mmmn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
int n = getIntArg(evaluator, args, 1);
return evaluator.getSchemaReader().getLeadMember(member, -n);
}
}));
define(new FunDefBase("LastChild", "<Member>.LastChild", "Returns the last child of a member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member[] children = evaluator.getSchemaReader().getMemberChildren(member);
if (children.length == 0) {
return member.getHierarchy().getNullMember();
} else {
return children[children.length - 1];
}
}
});
define(new FunDefBase("LastSibling", "<Member>.LastSibling", "Returns the last child of the parent of a member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member parent = member.getParentMember();
Member[] children;
final SchemaReader schemaReader = evaluator.getSchemaReader();
if (parent == null) {
if (member.isNull()) {
return member;
}
children = schemaReader.getHierarchyRootMembers(
member.getHierarchy());
} else {
children = schemaReader.getMemberChildren(parent);
}
return children[children.length - 1];
}
});
define(new FunkResolver(
"Lead", "<Member>.Lead(<Numeric Expression>)", "Returns a member further along the specified member's dimension.",
new String[]{"mmmn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
int n = getIntArg(evaluator, args, 1);
return evaluator.getSchemaReader().getLeadMember(member, n);
}
}));
define(new FunDefBase("Members", "Members(<String Expression>)", "Returns the member whose name is specified by a string expression.", "fmS"));
define(new FunDefBase(
"NextMember", "<Member>.NextMember", "Returns the next member in the level that contains a specified member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return evaluator.getSchemaReader().getLeadMember(member, +1);
}
});
define(new FunkResolver("OpeningPeriod",
"OpeningPeriod([<Level>[, <Member>]])",
"Returns the first descendant of a member at a level.",
new String[] {"fm", "fml", "fmlm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return openingClosingPeriod(evaluator, args, true);
}
}));
define(new FunkResolver("ClosingPeriod",
"ClosingPeriod([<Level>[, <Member>]])",
"Returns the last descendant of a member at a level.",
new String[] {"fm", "fml", "fmlm", "fmm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return openingClosingPeriod(evaluator, args, false);
}
}));
define(new FunkResolver(
"ParallelPeriod", "ParallelPeriod([<Level>[, <Numeric Expression>[, <Member>]]])",
"Returns a member from a prior period in the same relative position as a specified member.",
new String[] {"fm", "fml", "fmln", "fmlnm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
// Member defaults to [Time].currentmember
Member member;
if (args.length == 3) {
member = getMemberArg(evaluator, args, 2, true);
} else {
member = evaluator.getContext(evaluator.getCube().getTimeDimension());
}
// Numeric Expression defaults to 1.
int lagValue;
if (args.length >= 2) {
lagValue = getIntArg(evaluator, args, 1);
} else {
lagValue = 1;
}
Level ancestorLevel;
if (args.length >= 1) {
ancestorLevel = getLevelArg(evaluator, args, 0, true);
}
else {
Member parent = member.getParentMember();
if (parent == null || parent.getType() != Category.Member) {
// The parent isn't a member (it's probably a hierarchy),
// so there is no parallelperiod.
return member.getHierarchy().getNullMember();
}
ancestorLevel = parent.getLevel();
}
// Now do some error checking.
// The ancestorLevel and the member must be from the
// same hierarchy.
if (member.getHierarchy() != ancestorLevel.getHierarchy()) {
MondrianResource.instance().newFunctionMbrAndLevelHierarchyMismatch(
"ParallelPeriod", ancestorLevel.getHierarchy().getUniqueName(),
member.getHierarchy().getUniqueName()
);
}
int distance = member.getLevel().getDepth() - ancestorLevel.getDepth();
Member ancestor = ancestor(evaluator, member, distance, ancestorLevel);
Member inLaw = evaluator.getSchemaReader().getLeadMember(ancestor, -lagValue);
return cousin(evaluator.getSchemaReader(), member, inLaw);
}
}));
define(new FunDefBase("Parent", "<Member>.Parent", "Returns the parent of a member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member parent = evaluator.getSchemaReader().getMemberParent(member);
if (parent == null) {
parent = member.getHierarchy().getNullMember();
}
return parent;
}
});
define(new FunDefBase("PrevMember", "<Member>.PrevMember", "Returns the previous member in the level that contains a specified member.", "pmm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return evaluator.getSchemaReader().getLeadMember(member, -1);
}
});
define(new FunDefBase("StrToMember", "StrToMember(<String Expression>)", "Returns a member from a unique name String in MDX format.", "fmS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String mname = getStringArg(evaluator, args, 0, null);
Cube cube = evaluator.getCube();
SchemaReader schemaReader = evaluator.getSchemaReader();
String[] uniqueNameParts = Util.explode(mname);
Member member = Util.lookupMemberCompound(schemaReader, cube, uniqueNameParts, true);
// Member member = schemaReader.getMemberByUniqueName(uniqueNameParts, false);
return member;
}
});
if (false) define(new FunDefBase("ValidMeasure", "ValidMeasure(<Tuple>)", "Returns a valid measure in a virtual cube by forcing inapplicable dimensions to their top level.", "fm*"));
// NUMERIC FUNCTIONS
define(new FunkResolver("Aggregate", "Aggregate(<Set>[, <Numeric Expression>])", "Returns a calculated value using the appropriate aggregate function, based on the context of the query.",
new String[] {"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
// compute members only if the context has changed
List members = (List) evaluator.getCachedResult(args[0]);
if (members == null) {
members = (List) getArg(evaluator, args, 0);
evaluator.setCachedResult(args[0], members);
}
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
Aggregator aggregator = (Aggregator) evaluator.getProperty(Property.PROPERTY_AGGREGATION_TYPE);
if (aggregator == null) {
throw newEvalException(null, "Could not find an aggregator in the current evaluation context");
}
Aggregator rollup = aggregator.getRollup();
if (rollup == null) {
throw newEvalException(null, "Don't know how to rollup aggregator '" + aggregator + "'");
}
return rollup.aggregate(evaluator.push(), members, exp);
}
}));
define(new FunkResolver("$AggregateChildren", "$AggregateChildren(<Hierarchy>)", "Equivalent to 'Aggregate(<Hierarchy>.CurrentMember.Children); for internal use.",
new String[] {"Inh"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy = getHierarchyArg(evaluator, args, 0, true);
Member member = evaluator.getParent().getContext(hierarchy.getDimension());
List members = (List) member.getPropertyValue(Property.PROPERTY_CONTRIBUTING_CHILDREN);
Aggregator aggregator = (Aggregator) evaluator.getProperty(Property.PROPERTY_AGGREGATION_TYPE);
if (aggregator == null) {
throw newEvalException(null, "Could not find an aggregator in the current evaluation context");
}
Aggregator rollup = aggregator.getRollup();
if (rollup == null) {
throw newEvalException(null, "Don't know how to rollup aggregator '" + aggregator + "'");
}
return rollup.aggregate(evaluator.push(), members, valueFunCall);
}
}));
define(new FunkResolver(
"Avg", "Avg(<Set>[, <Numeric Expression>])", "Returns the average value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return avg(evaluator.push(), members, exp);
}
}));
define(new FunkResolver(
"Correlation", "Correlation(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Returns the correlation of two series evaluated over a set.",
new String[]{"fnxn","fnxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp1 = (ExpBase) getArgNoEval(args, 1);
ExpBase exp2 = (ExpBase) getArgNoEval(args, 2, valueFunCall);
return correlation(evaluator.push(), members, exp1, exp2);
}
}));
defineReserved(new String[] {"EXCLUDEEMPTY","INCLUDEEMPTY"});
define(new FunkResolver(
"Count", "Count(<Set>[, EXCLUDEEMPTY | INCLUDEEMPTY])", "Returns the number of tuples in a set, empty cells included unless the optional EXCLUDEEMPTY flag is used.",
new String[]{"fnx", "fnxy"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
String empties = getLiteralArg(args, 1, "INCLUDEEMPTY", new String[] {"INCLUDEEMPTY", "EXCLUDEEMPTY"}, null);
final boolean includeEmpty = empties.equals("INCLUDEEMPTY");
return count(evaluator, members, includeEmpty);
}
}));
define(new FunDefBase(
"Count", "<Set>.Count", "Returns the number of tuples in a set including empty cells.", "pnx") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
return count(evaluator, members, true);
}
});
define(new FunkResolver(
"Covariance", "Covariance(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Returns the covariance of two series evaluated over a set (biased).",
new String[]{"fnxn","fnxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp1 = (ExpBase) getArgNoEval(args, 1);
ExpBase exp2 = (ExpBase) getArgNoEval(args, 2);
return covariance(evaluator.push(), members, exp1, exp2, true);
}
}));
define(new FunkResolver(
"CovarianceN", "CovarianceN(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Returns the covariance of two series evaluated over a set (unbiased).",
new String[]{"fnxn","fnxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp1 = (ExpBase) getArgNoEval(args, 1);
ExpBase exp2 = (ExpBase) getArgNoEval(args, 2, valueFunCall);
return covariance(evaluator.push(), members, exp1, exp2, false);
}
}));
define(new FunDefBase("IIf", "IIf(<Logical Expression>, <Numeric Expression1>, <Numeric Expression2>)", "Returns one of two numeric values determined by a logical test.", "fnbnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Boolean b = getBooleanArg(evaluator, args, 0);
if (b == null) {
// The result of the logical expression is not known,
// probably because some necessary value is not in the
// cache yet. Evaluate both expressions so that the cache
// gets populated as soon as possible.
getDoubleArg(evaluator, args, 1, null);
getDoubleArg(evaluator, args, 2, null);
return new Double(Double.NaN);
}
if (b.booleanValue())
return getDoubleArg(evaluator, args, 1, null);
else
return getDoubleArg(evaluator, args, 2, null);
}
});
if (false) define(new FunDefBase("LinRegIntercept", "LinRegIntercept(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Calculates the linear regression of a set and returns the value of b in the regression line y = ax + b.", "fn*"));
if (false) define(new FunDefBase("LinRegPoint", "LinRegPoint(<Numeric Expression>, <Set>, <Numeric Expression>[, <Numeric Expression>])", "Calculates the linear regression of a set and returns the value of y in the regression line y = ax + b.", "fn*"));
if (false) define(new FunDefBase("LinRegR2", "LinRegR2(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Calculates the linear regression of a set and returns R2 (the coefficient of determination).", "fn*"));
if (false) define(new FunDefBase("LinRegSlope", "LinRegSlope(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Calculates the linear regression of a set and returns the value of a in the regression line y = ax + b.", "fn*"));
if (false) define(new FunDefBase("LinRegVariance", "LinRegVariance(<Set>, <Numeric Expression>[, <Numeric Expression>])", "Calculates the linear regression of a set and returns the variance associated with the regression line y = ax + b.", "fn*"));
define(new FunkResolver(
"Max", "Max(<Set>[, <Numeric Expression>])", "Returns the maximum value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return max(evaluator.push(), members, exp);
}
}));
define(new FunkResolver(
"Median", "Median(<Set>[, <Numeric Expression>])", "Returns the median value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
//todo: ignore nulls, do we need to ignore the List?
return median(evaluator.push(), members, exp);
}
}));
define(new FunkResolver(
"Min", "Min(<Set>[, <Numeric Expression>])", "Returns the minimum value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return min(evaluator.push(), members, exp);
}
}));
define(new FunDefBase("Ordinal", "<Level>.Ordinal", "Returns the zero-based ordinal value associated with a level.", "pnl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, false);
return new Double(level.getDepth());
}
});
if (false) define(new FunDefBase("Rank", "Rank(<Tuple>, <Set>)", "Returns the one-based rank of a tuple in a set.", "fn*"));
define(new FunkResolver(
"Stddev", "Stddev(<Set>[, <Numeric Expression>])", "Alias for Stdev.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return stdev(evaluator.push(), members, exp, false);
}
}));
define(new FunkResolver(
"Stdev", "Stdev(<Set>[, <Numeric Expression>])", "Returns the standard deviation of a numeric expression evaluated over a set (unbiased).",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return stdev(evaluator.push(), members, exp, false);
}
}));
define(new FunkResolver(
"StddevP", "StddevP(<Set>[, <Numeric Expression>])", "Alias for StdevP.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return stdev(evaluator.push(), members, exp, true);
}
}));
define(new FunkResolver(
"StdevP", "StdevP(<Set>[, <Numeric Expression>])", "Returns the standard deviation of a numeric expression evaluated over a set (biased).",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return stdev(evaluator.push(), members, exp, true);
}
}));
define(new FunkResolver(
"Sum", "Sum(<Set>[, <Numeric Expression>])", "Returns the sum of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return sum(evaluator.push(), members, exp);
}
}));
define(new FunDefBase("Value", "<Measure>.Value", "Returns the value of a measure.", "pnm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.evaluateScalar(evaluator);
}
});
define(new FunDefBase("_Value", "_Value(<Tuple>)", "Returns the value of the current measure within the context of a tuple.", "fnt") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member[] members = getTupleArg(evaluator, args, 0);
Evaluator evaluator2 = evaluator.push(members);
return evaluator2.evaluateCurrent();
}
});
define(new FunDefBase("_Value", "_Value()", "Returns the value of the current measure.", "fn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return evaluator.evaluateCurrent();
}
});
// _Value is a pseudo-function which evaluates a tuple to a number.
// It needs a custom resolver.
if (false)
define(new ResolverBase("_Value", null, null, Syntax.Parentheses) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
if (args.length == 1 &&
args[0].getType() == Category.Tuple) {
return new ValueFunDef(new int[] {Category.Tuple});
}
for (int i = 0; i < args.length; i++) {
Exp arg = args[i];
if (!canConvert(arg, Category.Member, conversionCount)) {
return null;
}
}
int[] argTypes = new int[args.length];
for (int i = 0; i < argTypes.length; i++) {
argTypes[i] = Category.Member;
}
return new ValueFunDef(argTypes);
}
});
define(new FunkResolver(
"Var", "Var(<Set>[, <Numeric Expression>])", "Returns the variance of a numeric expression evaluated over a set (unbiased).",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return var(evaluator.push(), members, exp, false);
}
}));
define(new FunkResolver(
"Variance", "Variance(<Set>[, <Numeric Expression>])", "Alias for Var.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return var(evaluator.push(), members, exp, false);
}
}));
define(new FunkResolver(
"VarianceP", "VarianceP(<Set>[, <Numeric Expression>])", "Alias for VarP.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return var(evaluator.push(), members, exp, true);
}
}));
define(new FunkResolver(
"VarP", "VarP(<Set>[, <Numeric Expression>])", "Returns the variance of a numeric expression evaluated over a set (biased).",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 1, valueFunCall);
return var(evaluator.push(), members, exp, true);
}
}));
// SET FUNCTIONS
if (false) define(new FunDefBase("AddCalculatedMembers", "AddCalculatedMembers(<Set>)", "Adds calculated members to a set.", "fx*"));
define(new FunDefBase("Ascendants", "Ascendants(<Member>)", "Returns the set of the ascendants of a specified member.", "fxm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, false);
if (member.isNull()) {
return new ArrayList();
}
Member[] members = member.getAncestorMembers();
final ArrayList result = new ArrayList(members.length + 1);
result.add(member);
addAll(result, members);
return result;
}
});
define(new FunkResolver(
"BottomCount",
"BottomCount(<Set>, <Count>[, <Numeric Expression>])",
"Returns a specified number of items from the bottom of a set, optionally ordering the set first.",
new String[]{"fxxnn", "fxxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List list = (List) getArg(evaluator, args, 0);
int n = getIntArg(evaluator, args, 1);
ExpBase exp = (ExpBase) getArgNoEval(args, 2, null);
if (exp != null) {
boolean desc = false, brk = true;
sort(evaluator, list, exp, desc, brk);
}
if (n < list.size()) {
list = list.subList(0, n);
}
return list;
}
}));
define(new FunkResolver(
"BottomPercent", "BottomPercent(<Set>, <Percentage>, <Numeric Expression>)", "Sorts a set and returns the bottom N elements whose cumulative total is at least a specified percentage.",
new String[]{"fxxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 2);
Double n = getDoubleArg(evaluator, args, 1);
return topOrBottom(evaluator.push(), members, exp, false, true, n.doubleValue());
}
}));
define(new FunkResolver(
"BottomSum", "BottomSum(<Set>, <Value>, <Numeric Expression>)", "Sorts a set and returns the bottom N elements whose cumulative total is at least a specified value.",
new String[]{"fxxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 2);
Double n = getDoubleArg(evaluator, args, 1);
return topOrBottom(evaluator.push(), members, exp, false, false, n.doubleValue());
}
}));
define(new FunDefBase("Children", "<Member>.Children", "Returns the children of a member.", "pxm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member[] children = evaluator.getSchemaReader().getMemberChildren(member);
return Arrays.asList(children);
}
});
define(new MultiResolver(
"Crossjoin", "Crossjoin(<Set1>, <Set2>)", "Returns the cross product of two sets.",
new String[]{"fxxx"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
return new CrossJoinFunDef(dummyFunDef);
}
});
define(new MultiResolver(
"*", "<Set1> * <Set2>", "Returns the cross product of two sets.",
new String[]{"ixxx", "ixmx", "ixxm", "ixmm"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
return new CrossJoinFunDef(dummyFunDef);
}
});
defineReserved(DescendantsFunDef.Flags.instance);
define(new DescendantsFunDef.Resolver());
define(new FunDefBase("Distinct", "Distinct(<Set>)", "Eliminates duplicate tuples from a set.", "fxx"){
// implement FunDef
public Object evaluate(Evaluator evaluator, Exp[] args) {
List list = (List) getArg(evaluator, args, 0);
HashSet hashSet = new HashSet(list.size());
Iterator iter = list.iterator();
List result = new ArrayList();
while (iter.hasNext()) {
Object element = iter.next();
MemberHelper lookupObj = new MemberHelper(element);
if (hashSet.add(lookupObj)) {
result.add(element);
}
}
return result;
}
});
define(new FunkResolver("DrilldownLevel", "DrilldownLevel(<Set>[, <Level>]) or DrilldownLevel(<Set>, , <Index>)", "Drills down the members of a set, at a specified level, to one level below. Alternatively, drills down on a specified dimension in the set.",
new String[]{"fxx", "fxxl"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
//todo add fssl functionality
List set0 = (List) getArg(evaluator, args, 0);
if (set0.size() == 0) {
return set0;
}
int searchDepth = -1;
Level level = getLevelArg(evaluator, args, 1, false);
if (level != null) {
searchDepth = level.getDepth();
}
if (searchDepth == -1) {
searchDepth = ((Member)set0.get(0)).getLevel().getDepth();
for (int i = 1, m = set0.size(); i < m; i++) {
Member member = (Member) set0.get(i);
int memberDepth = member.getLevel().getDepth();
if (memberDepth > searchDepth) {
searchDepth = memberDepth;
}
}
}
List drilledSet = new ArrayList();
for (int i = 0, m = set0.size(); i < m; i++) {
Member member = (Member) set0.get(i);
drilledSet.add(member);
Member nextMember = i == m - 1 ? null : (Member) set0.get(i + 1);
// This member is drilled if it's at the correct depth
// and if it isn't drilled yet. A member is considered
// to be "drilled" if it is immediately followed by
// at least one descendant
if (member.getLevel().getDepth() == searchDepth
&& !isAncestorOf(member, nextMember, true)) {
Member[] childMembers = evaluator.getSchemaReader().getMemberChildren(member);
for (int j = 0; j < childMembers.length; j++) {
drilledSet.add(childMembers[j]);
}
}
}
return drilledSet;
}
}
));
if (false) define(new FunDefBase("DrilldownLevelBottom", "DrilldownLevelBottom(<Set>, <Count>[, [<Level>][, <Numeric Expression>]])", "Drills down the bottom N members of a set, at a specified level, to one level below.", "fx*"));
if (false) define(new FunDefBase("DrilldownLevelTop", "DrilldownLevelTop(<Set>, <Count>[, [<Level>][, <Numeric Expression>]])", "Drills down the top N members of a set, at a specified level, to one level below.", "fx*"));
defineReserved(DrilldownMemberFunDef.reservedNames);
define(new DrilldownMemberFunDef.Resolver());
if (false) define(new FunDefBase("DrilldownMemberBottom", "DrilldownMemberBottom(<Set1>, <Set2>, <Count>[, [<Numeric Expression>][, RECURSIVE]])", "Like DrilldownMember except that it includes only the bottom N children.", "fx*"));
if (false) define(new FunDefBase("DrilldownMemberTop", "DrilldownMemberTop(<Set1>, <Set2>, <Count>[, [<Numeric Expression>][, RECURSIVE]])", "Like DrilldownMember except that it includes only the top N children.", "fx*"));
if (false) define(new FunDefBase("DrillupLevel", "DrillupLevel(<Set>[, <Level>])", "Drills up the members of a set that are below a specified level.", "fx*"));
if (false) define(new FunDefBase("DrillupMember", "DrillupMember(<Set1>, <Set2>)", "Drills up the members in a set that are present in a second specified set.", "fx*"));
define(new FunkResolver(
"Except", "Except(<Set1>, <Set2>[, ALL])", "Finds the difference between two sets, optionally retaining duplicates.",
new String[]{"fxxx", "fxxxs"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
// todo: implement ALL
HashSet set = new HashSet();
set.addAll((List) getArg(evaluator, args, 1));
List set1 = (List) getArg(evaluator, args, 0);
List result = new ArrayList();
for (int i = 0, count = set1.size(); i < count; i++) {
Object o = set1.get(i);
if (!set.contains(o)) {
result.add(o);
}
}
return result;
}
}));
if (false) define(new FunDefBase("Extract", "Extract(<Set>, <Dimension>[, <Dimension>...])", "Returns a set of tuples from extracted dimension elements. The opposite of Crossjoin.", "fx*"));
define(new FunDefBase("Filter", "Filter(<Set>, <Search Condition>)", "Returns the set resulting from filtering a set based on a search condition.", "fxxb") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
Exp exp = args[1];
List result = new ArrayList();
Evaluator evaluator2 = evaluator.push();
for (int i = 0, count = members.size(); i < count; i++) {
Object o = members.get(i);
if (o instanceof Member) {
evaluator2.setContext((Member) o);
} else if (o instanceof Member[]) {
evaluator2.setContext((Member[]) o);
} else {
throw Util.newInternal(
"unexpected type in set: " + o.getClass());
}
Boolean b = (Boolean) exp.evaluateScalar(evaluator2);
if (b != null && b.booleanValue()) {
result.add(o);
}
}
return result;
}
public boolean dependsOn(Exp[] args, Dimension dimension) {
return dependsOnIntersection(args, dimension);
}
});
define(new MultiResolver(
"Generate", "Generate(<Set1>, <Set2>[, ALL])", "Applies a set to each member of another set and joins the resulting sets by union.",
new String[] {"fxxx", "fxxxy"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
final boolean all = getLiteralArg(args, 2, "", new String[] {"ALL"}, dummyFunDef).equalsIgnoreCase("ALL");
return new FunDefBase(dummyFunDef) {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
List result = new ArrayList();
HashSet emitted = all ? null : new HashSet();
for (int i = 0; i < members.size(); i++) {
Object o = members.get(i);
if (o instanceof Member) {
evaluator.setContext((Member) o);
} else {
evaluator.setContext((Member[]) o);
}
final List result2 = (List) args[1].evaluate(evaluator);
if (all) {
result.addAll(result2);
} else {
for (int j = 0; j < result2.size(); j++) {
Object row = result2.get(j);
if (emitted.add(row)) {
result.add(row);
}
}
}
}
return result;
}
};
}
});
define(new FunkResolver(
"Head", "Head(<Set>[, < Numeric Expression >])", "Returns the first specified number of elements in a set.",
new String[] {"fxx", "fxxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
final int count = args.length < 2 ? 1 :
getIntArg(evaluator, args, 1);
if (count >= members.size()) {
return members;
}
if (count <= 0) {
return new ArrayList();
}
return members.subList(0, count);
}
}));
defineReserved(new String[] {"PRE","POST"});
define(new MultiResolver(
"Hierarchize", "Hierarchize(<Set>[, POST])", "Orders the members of a set in a hierarchy.",
new String[] {"fxx", "fxxy"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
String order = getLiteralArg(args, 1, "PRE", new String[] {"PRE", "POST"}, dummyFunDef);
final boolean post = order.equals("POST");
return new FunDefBase(dummyFunDef) {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
hierarchize(members, post);
return members;
}
};
}
});
define(new MultiResolver(
"Intersect", "Intersect(<Set1>, <Set2>[, ALL])", "Returns the intersection of two input sets, optionally retaining duplicates.",
new String[] {"fxxxy", "fxxx"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
final boolean all = getLiteralArg(args, 2, "", new String[] {"ALL"}, dummyFunDef).equalsIgnoreCase("ALL");
return new IntersectFunDef(dummyFunDef, all);
}
});
if (false) define(new FunDefBase("LastPeriods", "LastPeriods(<Index>[, <Member>])", "Returns a set of members prior to and including a specified member.", "fx*"));
define(new FunDefBase("Members", "<Dimension>.Members", "Returns the set of all members in a dimension.", "pxd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = (Dimension) getArg(evaluator, args, 0);
Hierarchy hierarchy = dimension.getHierarchy();
return addMembers(evaluator.getSchemaReader(), new ArrayList(), hierarchy);
}
});
define(new FunDefBase("Members", "<Hierarchy>.Members", "Returns the set of all members in a hierarchy.", "pxh") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy =
(Hierarchy) getArg(evaluator, args, 0);
return addMembers(evaluator.getSchemaReader(), new ArrayList(), hierarchy);
}
});
define(new FunDefBase("Members", "<Level>.Members", "Returns the set of all members in a level.", "pxl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = (Level) getArg(evaluator, args, 0);
return Arrays.asList(evaluator.getSchemaReader().getLevelMembers(level));
}
});
define(new FunkResolver(
"Mtd", "Mtd([<Member>])", "A shortcut function for the PeriodsToDate function that specifies the level to be Month.",
new String[]{"fx", "fxm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return periodsToDate(
evaluator,
evaluator.getCube().getMonthLevel(),
getMemberArg(evaluator, args, 0, false));
}
}));
defineReserved(OrderFunDef.Flags.instance);
define(new OrderFunDef.OrderResolver());
define(new FunkResolver(
"PeriodsToDate", "PeriodsToDate([<Level>[, <Member>]])", "Returns a set of periods (members) from a specified level starting with the first period and ending with a specified member.",
new String[]{"fx", "fxl", "fxlm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, false);
Member member = getMemberArg(evaluator, args, 1, false);
return periodsToDate(evaluator, level, member);
}
}));
define(new FunkResolver(
"Qtd", "Qtd([<Member>])", "A shortcut function for the PeriodsToDate function that specifies the level to be Quarter.",
new String[]{"fx", "fxm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return periodsToDate(
evaluator,
evaluator.getCube().getQuarterLevel(),
getMemberArg(evaluator, args, 0, false));
}
}));
if (false) define(new FunDefBase("StripCalculatedMembers", "StripCalculatedMembers(<Set>)", "Removes calculated members from a set.", "fx*"));
// "Siblings" is not a standard MDX function.
define(new FunDefBase("Siblings", "<Member>.Siblings", "Returns the set of siblings of the specified member.", "pxm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
Member parent = member.getParentMember();
final SchemaReader schemaReader = evaluator.getSchemaReader();
Member[] siblings;
if (parent == null) {
siblings = schemaReader.getHierarchyRootMembers(member.getHierarchy());
} else {
siblings = schemaReader.getMemberChildren(parent);
}
return Arrays.asList(siblings);
}
});
define(new FunDefBase("StrToSet", "StrToSet(<String Expression>)", "Constructs a set from a string expression.", "fxS") {
public Hierarchy getHierarchy(Exp[] args) {
// StrToSet(s, <Hie1>, ... <HieN>) is of type [Hie1] x ... x [HieN];
// so, for example, So StrToTuple("[Time].[1997]", [Time]) is of type
// [Time]. But if n > 1, we cannot represent the compound type, and we
// return null.
return (args.length == 2) ?
(Hierarchy) args[1] :
null;
}
});
define(new FunkResolver(
"Subset", "Subset(<Set>, <Start>[, <Count>])", "Returns a subset of elements from a set.",
new String[] {"fxxn", "fxxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
final int start = getIntArg(evaluator, args, 1);
final int end;
if (args.length < 3) {
end = members.size();
} else {
final int count = getIntArg(evaluator, args, 2);
end = start + count;
}
if (start >= end || start < 0) {
return new ArrayList();
}
if (start == 0 && end >= members.size()) {
return members;
}
return members.subList(start, end);
}
}));
define(new FunkResolver(
"Tail", "Tail(<Set>[, <Count>])", "Returns a subset from the end of a set.",
new String[] {"fxx", "fxxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
final int count = args.length < 2 ? 1 :
getIntArg(evaluator, args, 1);
if (count >= members.size()) {
return members;
}
if (count <= 0) {
return new ArrayList();
}
return members.subList(members.size() - count, members.size());
}
}));
defineReserved("RECURSIVE");
define(new FunkResolver(
"ToggleDrillState", "ToggleDrillState(<Set1>, <Set2>[, RECURSIVE])", "Toggles the drill state of members. This function is a combination of DrillupMember and DrilldownMember.",
new String[]{"fxxx", "fxxxy"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List v0 = (List) getArg(evaluator, args, 0),
v1 = (List) getArg(evaluator, args, 1);
if (args.length > 2) {
throw MondrianResource.instance().newToggleDrillStateRecursiveNotSupported();
}
if (v1.isEmpty()) {
return v0;
}
if (v0.isEmpty()) {
return v0;
}
HashSet set = new HashSet();
set.addAll(v1);
HashSet set1 = set;
List result = new ArrayList();
int i = 0, n = v0.size();
while (i < n) {
Object o = v0.get(i++);
result.add(o);
Member m = null;
int k = -1;
if (o instanceof Member) {
if (!set1.contains(o)) {
continue;
}
m = (Member) o;
k = -1;
} else {
Util.assertTrue(o instanceof Member[]);
Member[] members = (Member[]) o;
for (int j = 0; j < members.length; j++) {
Member member = members[j];
if (set1.contains(member)) {
k = j;
m = member;
break;
}
}
if (k == -1) {
continue;
}
}
boolean isDrilledDown = false;
if (i < n) {
Object next = v0.get(i);
Member nextMember = (k < 0) ? (Member) next :
((Member[]) next)[k];
boolean strict = true;
if (isAncestorOf(m, nextMember, strict)) {
isDrilledDown = true;
}
}
if (isDrilledDown) {
// skip descendants of this member
do {
Object next = v0.get(i);
Member nextMember = (k < 0) ? (Member) next :
((Member[]) next)[k];
boolean strict = true;
if (isAncestorOf(m, nextMember, strict)) {
i++;
} else {
break;
}
} while (i < n);
} else {
Member[] children = evaluator.getSchemaReader().getMemberChildren(m);
for (int j = 0; j < children.length; j++) {
if (k < 0) {
result.add(children[j]);
} else {
Member[] members = (Member[]) ((Member[]) o).clone();
members[k] = children[j];
result.add(members);
}
}
}
}
return result;
}
}));
define(new FunkResolver(
"TopCount",
"TopCount(<Set>, <Count>[, <Numeric Expression>])",
"Returns a specified number of items from the top of a set, optionally ordering the set first.",
new String[]{"fxxnn", "fxxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List list = (List) getArg(evaluator, args, 0);
int n = getIntArg(evaluator, args, 1);
ExpBase exp = (ExpBase) getArgNoEval(args, 2, null);
if (exp != null) {
boolean desc = true, brk = true;
sort(evaluator, list, exp, desc, brk);
}
if (n < list.size()) {
list = list.subList(0, n);
}
return list;
}
}));
define(new FunkResolver(
"TopPercent", "TopPercent(<Set>, <Percentage>, <Numeric Expression>)", "Sorts a set and returns the top N elements whose cumulative total is at least a specified percentage.",
new String[]{"fxxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 2);
Double n = getDoubleArg(evaluator, args, 1);
return topOrBottom(evaluator.push(), members, exp, true, true, n.doubleValue());
}
}));
define(new FunkResolver(
"TopSum", "TopSum(<Set>, <Value>, <Numeric Expression>)", "Sorts a set and returns the top N elements whose cumulative total is at least a specified value.",
new String[]{"fxxnn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArgNoEval(args, 2);
Double n = getDoubleArg(evaluator, args, 1);
return topOrBottom(evaluator.push(), members, exp, true, false, n.doubleValue());
}
}));
defineReserved(new String[] {"ALL", "DISTINCT"});
define(new MultiResolver(
"Union", "Union(<Set1>, <Set2>[, ALL])", "Returns the union of two sets, optionally retaining duplicates.",
new String[] {"fxxx", "fxxxy"}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
String allString = getLiteralArg(args, 2, "DISTINCT", new String[] {"ALL", "DISTINCT"}, dummyFunDef);
final boolean all = allString.equalsIgnoreCase("ALL");
checkCompatible(args[0], args[1], dummyFunDef);
return new FunDefBase(dummyFunDef) {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List left = (List) getArg(evaluator, args, 0),
right = (List) getArg(evaluator, args, 1);
if (all) {
if (left == null || left.isEmpty()) {
return right;
}
left.addAll(right);
return left;
} else {
HashSet added = new HashSet();
List result = new ArrayList();
addUnique(result, left, added);
addUnique(result, right, added);
return result;
}
}
};
}
});
if (false) define(new FunDefBase("VisualTotals", "VisualTotals(<Set>, <Pattern>)", "Dynamically totals child members specified in a set using a pattern for the total label in the result set.", "fx*"));
define(new FunkResolver(
"Wtd", "Wtd([<Member>])", "A shortcut function for the PeriodsToDate function that specifies the level to be Week.",
new String[]{"fx", "fxm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return periodsToDate(
evaluator,
evaluator.getCube().getWeekLevel(),
getMemberArg(evaluator, args, 0, false));
}
}));
define(new FunkResolver(
"Ytd", "Ytd([<Member>])", "A shortcut function for the PeriodsToDate function that specifies the level to be Year.",
new String[]{"fx", "fxm"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
return periodsToDate(
evaluator,
evaluator.getCube().getYearLevel(),
getMemberArg(evaluator, args, 0, false));
}
}));
define(new FunDefBase(
":", "<Member>:<Member>", "Infix colon operator returns the set of members between a given pair of members.", "ixmm") {
// implement FunDef
public Object evaluate(Evaluator evaluator, Exp[] args) {
final Member member0 = getMemberArg(evaluator, args, 0, true);
final Member member1 = getMemberArg(evaluator, args, 1, true);
if (member0.isNull() || member1.isNull()) {
return Collections.EMPTY_LIST;
}
if (member0.getLevel() != member1.getLevel()) {
throw newEvalException(this, "Members must belong to the same level");
}
return FunUtil.memberRange(evaluator, member0, member1);
}
});
// special resolver for the "{...}" operator
define(new ResolverBase(
"{}",
"{<Member> [, <Member>]...}",
"Brace operator constructs a set.",
Syntax.Braces) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
int[] parameterTypes = new int[args.length];
for (int i = 0; i < args.length; i++) {
if (canConvert(
args[i], Category.Member, conversionCount)) {
parameterTypes[i] = Category.Member;
continue;
}
if (canConvert(
args[i], Category.Set, conversionCount)) {
parameterTypes[i] = Category.Set;
continue;
}
if (canConvert(
args[i], Category.Tuple, conversionCount)) {
parameterTypes[i] = Category.Tuple;
continue;
}
return null;
}
return new SetFunDef(this, parameterTypes);
}
});
// STRING FUNCTIONS
define(new MultiResolver("Format", "Format(<Numeric Expression>, <String Expression>)", "Formats a number to string.", new String[] { "fSmS", "fSnS" }) {
protected FunDef createFunDef(final Exp[] args, final FunDef dummyFunDef) {
final Locale locale = Locale.getDefault(); // todo: use connection's locale
if (args[1] instanceof Literal) {
// Constant string expression: optimize by compiling
// format string.
String formatString = (String) ((Literal) args[1]).getValue();
final Format format = new Format(formatString, locale);
return new FunDefBase(dummyFunDef) {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o = getDoubleArg(evaluator, args, 0);
return format.format(o);
}
};
} else {
// Variable string expression
return new FunDefBase(dummyFunDef) {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o = getDoubleArg(evaluator, args, 0);
String formatString = getStringArg(evaluator, args, 1, null);
final Format format = new Format(formatString, locale);
return format.format(o);
}
};
}
}
});
define(new FunDefBase("IIf", "IIf(<Logical Expression>, <String Expression1>, <String Expression2>)", "Returns one of two string values determined by a logical test.", "fSbSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Boolean b = getBooleanArg(evaluator, args, 0);
if (b == null) {
// The result of the logical expression is not known,
// probably because some necessary value is not in the
// cache yet. Evaluate both expressions so that the cache
// gets populated as soon as possible.
getStringArg(evaluator, args, 1, null);
getStringArg(evaluator, args, 2, null);
return null;
}
if (b.booleanValue())
return getStringArg(evaluator, args, 1, null);
else
return getStringArg(evaluator, args, 2, null);
}
});
define(new FunDefBase("Name", "<Dimension>.Name", "Returns the name of a dimension.", "pSd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = getDimensionArg(evaluator, args, 0, true);
return dimension.getName();
}
});
define(new FunDefBase("Name", "<Hierarchy>.Name", "Returns the name of a hierarchy.", "pSh") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy = getHierarchyArg(evaluator, args, 0, true);
return hierarchy.getName();
}
});
define(new FunDefBase("Name", "<Level>.Name", "Returns the name of a level.", "pSl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, true);
return level.getName();
}
});
define(new FunDefBase("Name", "<Member>.Name", "Returns the name of a member.", "pSm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.getName();
}
});
define(new FunDefBase("SetToStr", "SetToStr(<Set>)", "Constructs a string from a set.", "fSx"));
define(new FunDefBase("TupleToStr", "TupleToStr(<Tuple>)", "Constructs a string from a tuple.", "fSt"));
define(new FunDefBase("UniqueName", "<Dimension>.UniqueName", "Returns the unique name of a dimension.", "pSd") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Dimension dimension = getDimensionArg(evaluator, args, 0, true);
return dimension.getUniqueName();
}
});
define(new FunDefBase("UniqueName", "<Hierarchy>.UniqueName", "Returns the unique name of a hierarchy.", "pSh") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Hierarchy hierarchy = getHierarchyArg(evaluator, args, 0, true);
return hierarchy.getUniqueName();
}
});
define(new FunDefBase("UniqueName", "<Level>.UniqueName", "Returns the unique name of a level.", "pSl") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Level level = getLevelArg(evaluator, args, 0, true);
return level.getUniqueName();
}
});
define(new FunDefBase("UniqueName", "<Member>.UniqueName", "Returns the unique name of a member.", "pSm") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Member member = getMemberArg(evaluator, args, 0, true);
return member.getUniqueName();
}
});
// TUPLE FUNCTIONS
define(new FunDefBase("Current", "<Set>.Current", "Returns the current tuple from a set during an iteration.", "ptx"));
if (false) {
// we do not support the <String expression> arguments
define(new FunDefBase("Item", "<Set>.Item(<String Expression>[, <String Expression>...] | <Index>)", "Returns a tuple from a set.", "mx*"));
}
define (new FunkResolver("Item", "<Set>.Item(<Index>)", "Returns the <Index>th element in the set, or ", new String[] {"mtxn", "mmtn"},
new FunkBase() {
// Returns the item specified from the set.
public Object evaluate(Evaluator evaluator, Exp[] args) {
Object arg0 = getArg(evaluator, args, 0);
int index = getIntArg(evaluator, args, 1);
int setSize;
if (arg0 instanceof List) {
List theSet = (List)arg0;
setSize = theSet.size();
if (index < setSize && index >= 0) {
return theSet.get(index);
}
}
else {
// You'll get a member in the following case:
// {[member]}.item(0).item(0), even though the first invocation of
// item returned a tuple.
assert ((arg0 instanceof Member[]) || (arg0 instanceof Member));
if (arg0 instanceof Member) {
if (index == 0) {
return arg0;
}
setSize = 0;
}
else {
Member[] tuple = (Member[]) arg0;
if (index < tuple.length && index >= 0) {
return tuple[index];
}
setSize = tuple.length;
}
}
throw MondrianResource.instance().newItemIndexOutOfBounds(Integer.toString(index), Integer.toString(setSize - 1));
}
}));
define(new FunDefBase("StrToTuple", "StrToTuple(<String Expression>)", "Constructs a tuple from a string.", "ftS") {
public Hierarchy getHierarchy(Exp[] args) {
// StrToTuple(s, <Hie1>, ... <HieN>) is of type [Hie1] x
// ... x [HieN]; so, for example, So
// StrToTuple("[Time].[1997]", [Time]) is of type [Time].
// But if n > 1, we cannot represent the compound type, and
// we return null.
return (args.length == 2) ?
(Hierarchy) args[1] :
null;
}
});
// special resolver for "()"
define(new ResolverBase("()", null, null, Syntax.Parentheses) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
// Compare with TupleFunDef.getReturnType(). For example,
// ([Gender].members) is a set,
// ([Gender].[M]) is a member,
// (1 + 2) is a numeric,
// but
// ([Gender].[M], [Marital Status].[S]) is a tuple.
if (args.length == 1) {
return new ParenthesesFunDef(args[0].getType());
} else {
return new TupleFunDef(ExpBase.getTypes(args));
}
}
});
// GENERIC VALUE FUNCTIONS
define(new ResolverBase(
"CoalesceEmpty",
"CoalesceEmpty(<Value Expression>[, <Value Expression>]...)",
"Coalesces an empty cell value to a different value. All of the expressions must be of the same type (number or string).",
Syntax.Function) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
if (args.length < 1) {
return null;
}
final int[] types = {Category.Numeric, Category.String};
for (int j = 0; j < types.length; j++) {
int type = types[j];
int matchingArgs = 0;
conversionCount[0] = 0;
for (int i = 0; i < args.length; i++) {
if (canConvert(args[i], type, conversionCount)) {
matchingArgs++;
}
}
if (matchingArgs == args.length) {
return new CoalesceEmptyFunDef(this, type, ExpBase.getTypes(args));
}
}
return null;
}
public boolean requiresExpression(int k) {
return true;
}
});
define(new ResolverBase(
"_CaseTest",
"Case When <Logical Expression> Then <Expression> [...] [Else <Expression>] End",
"Evaluates various conditions, and returns the corresponding expression for the first which evaluates to true.",
Syntax.Case) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
if (args.length < 1) {
return null;
}
int j = 0,
clauseCount = args.length / 2,
mismatchingArgs = 0;
int returnType = args[1].getType();
for (int i = 0; i < clauseCount; i++) {
if (!canConvert(args[j++], Category.Logical, conversionCount)) {
mismatchingArgs++;
}
if (!canConvert(args[j++], returnType, conversionCount)) {
mismatchingArgs++;
}
}
if (j < args.length) {
if (!canConvert(args[j++], returnType, conversionCount)) {
mismatchingArgs++;
}
}
Util.assertTrue(j == args.length);
if (mismatchingArgs == 0) {
return new FunDefBase(this, returnType, ExpBase.getTypes(args)) {
// implement FunDef
public Object evaluate(Evaluator evaluator, Exp[] args) {
return evaluateCaseTest(evaluator, args);
}
};
} else {
return null;
}
}
public boolean requiresExpression(int k) {
return true;
}
Object evaluateCaseTest(Evaluator evaluator, Exp[] args) {
int clauseCount = args.length / 2,
j = 0;
for (int i = 0; i < clauseCount; i++) {
boolean logical = getBooleanArg(evaluator, args, j++, false);
if (logical) {
return getArg(evaluator, args, j);
} else {
j++;
}
}
if (j < args.length) {
return getArg(evaluator, args, j); // ELSE
} else {
return null;
}
}
});
define(new ResolverBase(
"_CaseMatch",
"Case <Expression> When <Expression> Then <Expression> [...] [Else <Expression>] End",
"Evaluates various expressions, and returns the corresponding expression for the first which matches a particular value.",
Syntax.Case) {
public FunDef resolve(Exp[] args, int[] conversionCount) {
if (args.length < 3) {
return null;
}
int valueType = args[0].getType();
int returnType = args[2].getType();
int j = 0,
clauseCount = (args.length - 1) / 2,
mismatchingArgs = 0;
if (!canConvert(args[j++], valueType, conversionCount)) {
mismatchingArgs++;
}
for (int i = 0; i < clauseCount; i++) {
if (!canConvert(args[j++], valueType, conversionCount)) {
mismatchingArgs++;
}
if (!canConvert(args[j++], returnType, conversionCount)) {
mismatchingArgs++;
}
}
if (j < args.length) {
if (!canConvert(args[j++], returnType, conversionCount)) {
mismatchingArgs++;
}
}
Util.assertTrue(j == args.length);
if (mismatchingArgs == 0) {
return new FunDefBase(this, returnType, ExpBase.getTypes(args)) {
// implement FunDef
public Object evaluate(Evaluator evaluator, Exp[] args) {
return evaluateCaseMatch(evaluator, args);
}
};
} else {
return null;
}
}
public boolean requiresExpression(int k) {
return true;
}
Object evaluateCaseMatch(Evaluator evaluator, Exp[] args) {
int clauseCount = (args.length - 1)/ 2,
j = 0;
Object value = getArg(evaluator, args, j++);
for (int i = 0; i < clauseCount; i++) {
Object match = getArg(evaluator, args, j++);
if (match.equals(value)) {
return getArg(evaluator, args, j);
} else {
j++;
}
}
if (j < args.length) {
return getArg(evaluator, args, j); // ELSE
} else {
return null;
}
}
});
define(new PropertiesFunDef.Resolver());
// PARAMETER FUNCTIONS
defineReserved(new String[] {"NUMERIC","STRING"});
define(new MultiResolver("Parameter", "Parameter(<Name>, <Type>, <DefaultValue>, <Description>)", "Returns default value of parameter.",
new String[] {
"fS#yS#", "fs#yS", // Parameter(string const, symbol, string[, string const]): string
"fn#yn#", "fn#yn", // Parameter(string const, symbol, numeric[, string const]): numeric
"fm#hm#", "fm#hm", // Parameter(string const, hierarchy constant, member[, string const]): member
}) {
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
String parameterName;
if (args[0] instanceof Literal &&
args[0].getType() == Category.String) {
parameterName = (String) ((Literal) args[0]).getValue();
} else {
throw newEvalException(dummyFunDef, "Parameter name must be a string constant");
}
Exp typeArg = args[1];
Hierarchy hierarchy;
int type;
switch (typeArg.getType()) {
case Category.Hierarchy:
case Category.Dimension:
hierarchy = typeArg.getHierarchy();
if (hierarchy == null || !isConstantHierarchy(typeArg)) {
throw newEvalException(dummyFunDef, "Invalid hierarchy for parameter '" + parameterName + "'");
}
type = Category.Member;
break;
case Category.Symbol:
hierarchy = null;
String s = (String) ((Literal) typeArg).getValue();
if (s.equalsIgnoreCase("NUMERIC")) {
type = Category.Numeric;
break;
} else if (s.equalsIgnoreCase("STRING")) {
type = Category.String;
break;
}
// fall through and throw error
default:
// Error is internal because the function call has already been
// type-checked.
throw newEvalException(dummyFunDef,
"Invalid type for parameter '" + parameterName + "'; expecting NUMERIC, STRING or a hierarchy");
}
Exp exp = args[2];
if (exp.getType() != type) {
String typeName = Category.instance.getName(type).toUpperCase();
throw newEvalException(dummyFunDef, "Default value of parameter '" + parameterName + "' is inconsistent with its type, " + typeName);
}
if (type == Category.Member) {
Hierarchy expHierarchy = exp.getHierarchy();
if (expHierarchy != hierarchy) {
throw newEvalException(dummyFunDef, "Default value of parameter '" + parameterName + "' must belong to the hierarchy " + hierarchy);
}
}
String parameterDescription = null;
if (args.length > 3) {
if (args[3] instanceof Literal &&
args[3].getType() == Category.String) {
parameterDescription = (String) ((Literal) args[3]).getValue();
} else {
throw newEvalException(dummyFunDef, "Description of parameter '" + parameterName + "' must be a string constant");
}
}
return new ParameterFunDef(dummyFunDef, parameterName, hierarchy, type, exp, parameterDescription);
}
});
define(new MultiResolver("ParamRef", "ParamRef(<Name>)", "Returns current value of parameter. If it's null, returns default.",
new String[] {"fv
protected FunDef createFunDef(Exp[] args, FunDef dummyFunDef) {
String parameterName;
if (args[0] instanceof Literal &&
args[0].getType() == Category.String) {
parameterName = (String) ((Literal) args[0]).getValue();
} else {
throw newEvalException(dummyFunDef, "Parameter name must be a string constant");
}
return new ParameterFunDef(dummyFunDef, parameterName, null, Category.Unknown, null, null);
}
});
// OPERATORS
define(new FunDefBase("+", "<Numeric Expression> + <Numeric Expression>", "Adds two numbers.", "innn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0, null),
o1 = getDoubleArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return new Double(o0.doubleValue() + o1.doubleValue());
}
});
define(new FunDefBase("-", "<Numeric Expression> - <Numeric Expression>", "Subtracts two numbers.", "innn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0, null),
o1 = getDoubleArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return new Double(o0.doubleValue() - o1.doubleValue());
}
});
define(new FunDefBase("*", "<Numeric Expression> * <Numeric Expression>", "Multiplies two numbers.", "innn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0, null),
o1 = getDoubleArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return new Double(o0.doubleValue() * o1.doubleValue());
}
});
define(new FunDefBase("/", "<Numeric Expression> / <Numeric Expression>", "Divides two numbers.", "innn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0, null),
o1 = getDoubleArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return new Double(o0.doubleValue() / o1.doubleValue());
}
// todo: use this, via reflection
public double evaluate(double d1, double d2) {
return d1 / d2;
}
});
define(new FunDefBase("-", "- <Numeric Expression>", "Returns the negative of a number.", "Pnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0, null);
if (o0 == null)
return null;
return new Double(- o0.doubleValue());
}
});
define(new FunDefBase("||", "<String Expression> || <String Expression>", "Concatenates two strings.", "iSSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
return o0 + o1;
}
});
define(new FunDefBase("AND", "<Logical Expression> AND <Logical Expression>", "Returns the conjunction of two conditions.", "ibbb") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
// if the first arg is known and false, we dont evaluate the second
Boolean b1 = getBooleanArg(evaluator, args, 0);
if (b1 != null && !b1.booleanValue())
return Boolean.FALSE;
Boolean b2 = getBooleanArg(evaluator, args, 1);
if (b2 != null && !b2.booleanValue())
return Boolean.FALSE;
if (b1 == null || b2 == null)
return null;
return toBoolean(b1.booleanValue() && b2.booleanValue());
}
});
define(new FunDefBase("OR", "<Logical Expression> OR <Logical Expression>", "Returns the disjunction of two conditions.", "ibbb") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
// if the first arg is known and true, we dont evaluate the second
Boolean b1 = getBooleanArg(evaluator, args, 0);
if (b1 != null && b1.booleanValue())
return Boolean.TRUE;
Boolean b2 = getBooleanArg(evaluator, args, 1);
if (b2 != null && b2.booleanValue())
return Boolean.TRUE;
if (b1 == null || b2 == null)
return null;
return toBoolean(b1.booleanValue() || b2.booleanValue());
}
});
define(new FunDefBase("XOR", "<Logical Expression> XOR <Logical Expression>", "Returns whether two conditions are mutually exclusive.", "ibbb") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Boolean b1 = getBooleanArg(evaluator, args, 0);
Boolean b2 = getBooleanArg(evaluator, args, 1);
if (b1 == null || b2 == null)
return null;
return toBoolean(b1.booleanValue() != b2.booleanValue());
}
});
define(new FunDefBase("NOT", "NOT <Logical Expression>", "Returns the negation of a condition.", "Pbb") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Boolean b = getBooleanArg(evaluator, args, 0);
if (b == null)
return null;
return toBoolean(!b.booleanValue());
}
});
define(new FunDefBase("=", "<String Expression> = <String Expression>", "Returns whether two expressions are equal.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(o0.equals(o1));
}
});
define(new FunDefBase("=", "<Numeric Expression> = <Numeric Expression>", "Returns whether two expressions are equal.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(o0.equals(o1));
}
});
define(new FunDefBase("<>", "<String Expression> <> <String Expression>", "Returns whether two expressions are not equal.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(!o0.equals(o1));
}
});
define(new FunDefBase("<>", "<Numeric Expression> <> <Numeric Expression>", "Returns whether two expressions are not equal.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(!o0.equals(o1));
}
});
define(new FunDefBase("<", "<Numeric Expression> < <Numeric Expression>", "Returns whether an expression is less than another.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(o0.compareTo(o1) < 0);
}
});
define(new FunDefBase("<", "<String Expression> < <String Expression>", "Returns whether an expression is less than another.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(o0.compareTo(o1) < 0);
}
});
define(new FunDefBase("<=", "<Numeric Expression> <= <Numeric Expression>", "Returns whether an expression is less than or equal to another.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(o0.compareTo(o1) <= 0);
}
});
define(new FunDefBase("<=", "<String Expression> <= <String Expression>", "Returns whether an expression is less than or equal to another.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(o0.compareTo(o1) <= 0);
}
});
define(new FunDefBase(">", "<Numeric Expression> > <Numeric Expression>", "Returns whether an expression is greater than another.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(o0.compareTo(o1) > 0);
}
});
define(new FunDefBase(">", "<String Expression> > <String Expression>", "Returns whether an expression is greater than another.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(o0.compareTo(o1) > 0);
}
});
define(new FunDefBase(">=", "<Numeric Expression> >= <Numeric Expression>", "Returns whether an expression is greater than or equal to another.", "ibnn") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
Double o0 = getDoubleArg(evaluator, args, 0),
o1 = getDoubleArg(evaluator, args, 1);
if (o0.isNaN() || o1.isNaN())
return null;
return toBoolean(o0.compareTo(o1) >= 0);
}
});
define(new FunDefBase(">=", "<String Expression> >= <String Expression>", "Returns whether an expression is greater than or equal to another.", "ibSS") {
public Object evaluate(Evaluator evaluator, Exp[] args) {
String o0 = getStringArg(evaluator, args, 0, null),
o1 = getStringArg(evaluator, args, 1, null);
if (o0 == null || o1 == null)
return null;
return toBoolean(o0.compareTo(o1) >= 0);
}
});
// NON-STANDARD FUNCTIONS
define(new FunkResolver(
"FirstQ", "FirstQ(<Set>[, <Numeric Expression>])", "Returns the 1st quartile value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArg(evaluator, args, 1, valueFunCall);
//todo: ignore nulls, do we need to ignore the List?
return quartile(evaluator.push(), members, exp, 1);
}
}));
define(new FunkResolver(
"ThirdQ", "ThirdQ(<Set>[, <Numeric Expression>])", "Returns the 3rd quartile value of a numeric expression evaluated over a set.",
new String[]{"fnx", "fnxn"},
new FunkBase() {
public Object evaluate(Evaluator evaluator, Exp[] args) {
List members = (List) getArg(evaluator, args, 0);
ExpBase exp = (ExpBase) getArg(evaluator, args, 1, valueFunCall);
//todo: ignore nulls, do we need to ignore the List?
return quartile(evaluator.push(), members, exp, 3);
}
}));
}
private static boolean isConstantHierarchy(Exp typeArg) {
if (typeArg instanceof Hierarchy) {
// e.g. "[Time].[By Week]"
return true;
}
if (typeArg instanceof Dimension) {
// e.g. "[Time]"
return true;
}
if (typeArg instanceof FunCall) {
// e.g. "[Time].CurrentMember.Hierarchy". They probably wrote
// "[Time]", and the automatic type conversion did the rest.
FunCall hierarchyCall = (FunCall) typeArg;
if (hierarchyCall.getFunName().equals("Hierarchy") &&
hierarchyCall.args.length > 0 &&
hierarchyCall.args[0] instanceof FunCall) {
FunCall currentMemberCall = (FunCall) hierarchyCall.args[0];
if (currentMemberCall.getFunName().equals("CurrentMember") &&
currentMemberCall.args.length > 0 &&
currentMemberCall.args[0] instanceof Dimension) {
return true;
}
}
}
return false;
}
/**
* Returns a read-only version of the name-to-resolvers map. Used by the
* testing framework.
*/
protected static Map getNameToResolversMap() {
return Collections.unmodifiableMap(((BuiltinFunTable)instance()).mapNameToResolvers);
}
}
// End BuiltinFunTable.java
|
package net.fortuna.ical4j.model;
import java.text.ParseException;
import java.util.Calendar;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.fortuna.ical4j.util.TimeZones;
public class DateTest extends TestCase {
private Date date;
private java.util.Date date2;
private String expectedString;
/**
* @param date
* @param expectedString
*/
public DateTest(Date date, String expectedString) {
super("testToString");
this.date = date;
this.expectedString = expectedString;
}
/**
* @param date
* @param date2
*/
public DateTest(Date date, java.util.Date date2) {
super("testEquals");
this.date = date;
this.date2 = date2;
}
public void testToString() {
assertEquals(expectedString, date.toString());
}
public void testEquals() {
assertEquals(date2, date);
}
/* (non-Javadoc)
* @see junit.framework.TestCase#getName()
*/
public String getName() {
return super.getName() + " [" + date.toString() + "]";
}
/**
* @return
* @throws ParseException
*/
public static TestSuite suite() throws ParseException {
TestSuite suite = new TestSuite();
suite.addTest(new DateTest(new Date(0l), "19700101"));
Calendar cal = Calendar.getInstance(java.util.TimeZone.getTimeZone(TimeZones.GMT_ID));
cal.clear();
cal.set(Calendar.YEAR, 1984);
// months are zero-based..
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.DAY_OF_MONTH, 17);
suite.addTest(new DateTest(new Date(cal.getTime()), "19840417"));
suite.addTest(new DateTest(new Date("20050630"), "20050630"));
// Test equality of Date instances created using different constructors..
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(TimeZones.GMT_ID));
calendar.clear();
calendar.set(2005, 0, 1);
calendar.set(Calendar.MILLISECOND, 1);
suite.addTest(new DateTest(new Date(calendar.getTime()), new Date("20050101").toString()));
suite.addTest(new DateTest(new Date(calendar.getTime()), new Date("20050101")));
calendar = Calendar.getInstance(TimeZone.getTimeZone(TimeZones.GMT_ID));
calendar.clear();
calendar.set(2005, 0, 1);
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
suite.addTest(new DateTest(new Date("20050101"), calendar.getTime()));
return suite;
}
}
|
package kernitus.plugin.OldCombatMechanics;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Team;
import java.util.Collection;
import java.util.List;
public class OCMTask extends BukkitRunnable {
OCMMain plugin;
public OCMTask(OCMMain instance) {
this.plugin = instance;
}
@Override
public void run() {
Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers();
for (Player p : players) {
addPlayerToScoreboard(p);
}
}
public void addPlayerToScoreboard(Player p) {
String name = p.getName();
if (p.getScoreboard().getEntryTeam(p.getName()) != null) return;
World w = p.getWorld();
List<?> worlds = Config.getWorlds("disable-player-collisions");
if (worlds.isEmpty() || worlds.contains(w.getName())) {
Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam("ocmInternal");
if (!team.getEntries().contains(name)) {
team.addEntry(name);
}
} else if (!worlds.contains(w.getName())) {
removePlayerFromScoreboard(p);
}
}
public void removePlayerFromScoreboard(Player p) {
if (p.getScoreboard().getEntryTeam(p.getName()) != null) return;
Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam("ocmInternal");
if (team.getEntries().contains(p.getName())) {
team.removeEntry(p.getName());
}
}
}
|
package hu.pazsitz.pacuse.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class GeneralWidgetImpl extends AbstractWidget {
private WebElement container;
public GeneralWidgetImpl(WebDriver webDriver, WebElement element) {
super(webDriver);
this.container = element;
}
public GeneralWidgetImpl(WebDriver webDriver, By by) {
super(webDriver);
this.container = getWebDriver().findElement(by);
}
@Override
public WebElement getContainer() {
return container;
}
}
|
package ibis.impl.nameServer.tcp;
import ibis.impl.nameServer.NSProps;
import ibis.io.DummyInputStream;
import ibis.io.DummyOutputStream;
import ibis.ipl.ConnectionRefusedException;
import ibis.ipl.ConnectionTimedOutException;
import ibis.ipl.Ibis;
import ibis.ipl.IbisConfigurationException;
import ibis.ipl.IbisIdentifier;
import ibis.ipl.IbisRuntimeException;
import ibis.ipl.ReceivePortIdentifier;
import ibis.ipl.StaticProperties;
import ibis.util.IPUtils;
import ibis.util.IbisSocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
public class NameServerClient extends ibis.impl.nameServer.NameServer implements Runnable, Protocol {
static final boolean DEBUG = false;
private PortTypeNameServerClient portTypeNameServerClient;
private ReceivePortNameServerClient receivePortNameServerClient;
private ElectionClient electionClient;
private ServerSocket serverSocket;
private Ibis ibisImpl;
private IbisIdentifier id;
private volatile boolean stop = false;
private InetAddress serverAddress;
private String server;
private int port;
private String poolName;
private InetAddress myAddress;
static IbisSocketFactory socketFactory =
IbisSocketFactory.createFactory();
public NameServerClient() {
/* do nothing */
}
protected void init(Ibis ibisImpl) throws IOException, IbisConfigurationException {
this.ibisImpl = ibisImpl;
this.id = ibisImpl.identifier();
Properties p = System.getProperties();
myAddress = IPUtils.getAlternateLocalHostAddress();
server = p.getProperty(NSProps.s_host);
if (server == null) {
throw new IbisConfigurationException("property ibis.name_server.host is not specified");
}
if (server.equals("localhost")) {
server = myAddress.getHostName();
}
poolName = p.getProperty(NSProps.s_key);
if (poolName == null) {
throw new IbisConfigurationException("property ibis.name_server.key is not specified");
}
String nameServerPortString = p.getProperty(NSProps.s_port);
port = NameServer.TCP_IBIS_NAME_SERVER_PORT_NR;
if (nameServerPortString != null) {
try {
port = Integer.parseInt(nameServerPortString);
if(DEBUG) {
System.err.println("Using nameserver port: " + port);
}
} catch (Exception e) {
System.err.println("illegal nameserver port: " + nameServerPortString + ", using default");
}
}
serverAddress = InetAddress.getByName(server);
if (myAddress.equals(serverAddress)) {
// Try and start a nameserver ...
NameServer n = NameServer.createNameServer(true, false, true, false);
if (n != null) {
n.start();
}
}
if(DEBUG) {
System.err.println("Found nameServerInet " + serverAddress);
}
Socket s = null;
int cnt = 0;
while(s == null) {
try {
cnt++;
s = socketFactory.createSocket(serverAddress,
port, myAddress, -1);
// myAddress = s.getLocalAddress();
} catch (ConnectionTimedOutException e) {
if(cnt == 10) {
// Rather arbitrary, 10 seconds, print warning
System.err.println("Nameserver client failed"
+ " to connect to nameserver\n at "
+ serverAddress + ":" + port
+ ", will keep trying");
}
else if(cnt == 60) {
// Rather arbitrary, 1 minute
System.err.println("Nameserver client failed"
+ " to connect to nameserver\n at "
+ serverAddress + ":" + port);
System.err.println("Gave up after 60 seconds");
throw e;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
// don't care
}
}
}
serverSocket = socketFactory.createServerSocket(0, myAddress, true);
DummyOutputStream dos = new DummyOutputStream(s.getOutputStream());
ObjectOutputStream out =
new ObjectOutputStream(new BufferedOutputStream(dos));
if (DEBUG) {
System.out.println("NameServerClient: contacting nameserver");
}
out.writeByte(IBIS_JOIN);
out.writeUTF(poolName);
out.writeObject(id);
out.writeObject(myAddress);
out.writeInt(serverSocket.getLocalPort());
out.flush();
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
int opcode = in.readByte();
if (DEBUG) {
System.out.println("NameServerClient: nameserver reply, opcode " + opcode);
}
switch (opcode) {
case IBIS_REFUSED:
socketFactory.close(in, out, s);
throw new ConnectionRefusedException("NameServerClient: " + id.name() + " is not unique!");
case IBIS_ACCEPTED:
// read the ports for the other name servers and start the receiver thread...
int temp = in.readInt(); /* Port for the PortTypeNameServer */
portTypeNameServerClient = new PortTypeNameServerClient(myAddress, serverAddress, temp);
temp = in.readInt(); /* Port for the ReceivePortNameServer */
receivePortNameServerClient = new ReceivePortNameServerClient(myAddress, serverAddress, temp);
temp = in.readInt(); /* Port for the ElectionServer */
electionClient = new ElectionClient(myAddress, serverAddress, temp);
int poolSize = in.readInt();
if (DEBUG) {
System.out.println("NameServerClient: accepted by nameserver, poolsize " + poolSize);
}
for(int i=0; i<poolSize; i++) {
IbisIdentifier newid;
try {
newid = (IbisIdentifier) in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("Receive IbisIdent of unknown class " + e);
}
if(DEBUG) {
System.out.println("NameServerClient: join of " + newid);
}
ibisImpl.join(newid);
if(DEBUG) {
System.out.println("NameServerClient: join of " + newid + " DONE");
}
}
// at least read the tobedeleted stuff!
int tmp = in.readInt();
for (int i = 0; i < tmp; i++) {
try {
in.readObject();
} catch(ClassNotFoundException e) {
throw new IOException("Receive IbisIdent of unknown class " + e);
}
}
// Should we join ourselves?
ibisImpl.join(id);
socketFactory.close(in, out, s);
Thread t = new Thread(this, "NameServerClient accept thread");
t.setDaemon(true);
t.start();
break;
default:
socketFactory.close(in, out, s);
throw new StreamCorruptedException("NameServerClient: got illegal opcode " + opcode);
}
}
public boolean newPortType(String name, StaticProperties p) throws IOException {
return portTypeNameServerClient.newPortType(name, p);
}
public long getSeqno(String name) throws IOException {
return portTypeNameServerClient.getSeqno(name);
}
public void leave() throws IOException {
if(DEBUG) {
System.err.println("NS client: leave");
}
Socket s = socketFactory.createSocket(serverAddress, port, myAddress, 0 /* retry */);
DummyOutputStream dos = new DummyOutputStream(s.getOutputStream());
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(dos));
out.writeByte(IBIS_LEAVE);
out.writeUTF(poolName);
out.writeObject(id);
out.flush();
if(DEBUG) {
System.err.println("NS client: leave sent");
}
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
int temp = in.readByte();
if(DEBUG) {
System.err.println("NS client: leave ack received");
}
socketFactory.close(in, out, s);
// stop = true;
// this.interrupt();
if(DEBUG) {
System.err.println("NS client: leave DONE");
}
}
public void run() {
if (DEBUG) {
System.out.println("NameServerClient: stread started");
}
while (true) { // !stop
Socket s;
IbisIdentifier id;
try {
s = socketFactory.accept(serverSocket);
if (DEBUG) {
System.out.println("NameServerClient: incoming connection from " + s.toString());
}
} catch (Exception e) {
if (stop) {
if (DEBUG) {
System.out.println("NameServerClient: thread dying");
}
try {
serverSocket.close();
} catch (IOException e1) {
/* do nothing */
}
return;
}
throw new IbisRuntimeException("NameServerClient: got an error", e);
}
int opcode = 666;
try {
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
opcode = in.readByte();
if (DEBUG) {
System.out.println("NameServerClient: opcode " + opcode);
}
switch (opcode) {
case (IBIS_PING): {
DummyOutputStream dos = new DummyOutputStream(s.getOutputStream());
DataOutputStream out =
new DataOutputStream(new BufferedOutputStream(dos));
out.writeUTF(poolName);
socketFactory.close(in, out, s);
}
break;
case (IBIS_JOIN):
id = (IbisIdentifier) in.readObject();
if (DEBUG) {
System.out.println("NameServerClient: receive join request " + id);
}
socketFactory.close(in, null, s);
ibisImpl.join(id);
break;
case (IBIS_LEAVE):
id = (IbisIdentifier) in.readObject();
socketFactory.close(in, null, s);
if(id.equals(this.id)) {
// received an ack from the nameserver that I left.
if (DEBUG) {
System.out.println("NameServerClient: thread dying");
}
return;
} else {
ibisImpl.leave(id);
}
break;
default:
System.out.println("NameServerClient: got an illegal opcode " + opcode);
}
} catch (Exception e1) {
System.out.println("Got an exception in NameServerClient.run (opcode = " + opcode + ") " + e1.toString());
if(stop) return;
e1.printStackTrace();
if (s != null) {
socketFactory.close(null, null, s);
}
}
}
}
public ReceivePortIdentifier lookupReceivePort(String name) throws IOException {
return lookupReceivePort(name, 0);
}
public ReceivePortIdentifier lookupReceivePort(String name, long timeout) throws IOException {
return receivePortNameServerClient.lookup(name, timeout);
}
public IbisIdentifier lookupIbis(String name) throws IOException {
return lookupIbis(name, 0);
}
public IbisIdentifier lookupIbis(String name, long timeout) throws IOException {
/* not implemented yet */
return null;
}
public ReceivePortIdentifier [] listReceivePorts(IbisIdentifier ident) throws IOException, ClassNotFoundException {
/* not implemented yet */
return new ReceivePortIdentifier[0];
}
public Object elect(String election, Object candidate) throws IOException, ClassNotFoundException {
return electionClient.elect(election, candidate);
}
//gosia
public Object reelect(String election, Object candidate, Object formerRuler) throws IOException, ClassNotFoundException {
return electionClient.reelect(election, candidate, formerRuler);
}
public void bind(String name, ReceivePortIdentifier rpi) throws IOException {
receivePortNameServerClient.bind(name, rpi);
}
public void rebind(String name, ReceivePortIdentifier rpi) throws IOException {
receivePortNameServerClient.rebind(name, rpi);
}
public void unbind(String name) throws IOException {
receivePortNameServerClient.unbind(name);
}
public String[] listNames(String pattern) throws IOException {
return receivePortNameServerClient.list(pattern);
}
//end gosia
}
|
package io.github.lordjbs.ConCore.Console;
import io.github.lordjbs.ConCore.ConCore;
public class LogMore
{
static void Log(String log, int mode)
{
if(mode == 1)
{
System.out.println("MineCordBot > CodeName: Log -> ");
}else if(mode == 2)
{
System.out.println("MineCordBot > CodeName: Warn -> ");
}else if(mode == 3)
{
System.out.println("MineCordBot > CodeName: Error -> ");
}else{
System.out.println("Error: Unknown mode.");
}
}
}
|
package it.unimi.dsi.sux4j.test;
import it.unimi.dsi.Util;
import it.unimi.dsi.fastutil.io.BinIO;
import it.unimi.dsi.fastutil.io.FastByteArrayInputStream;
import it.unimi.dsi.fastutil.io.FastByteArrayOutputStream;
import it.unimi.dsi.fastutil.objects.Object2LongFunction;
import it.unimi.dsi.io.FileLinesCollection;
import it.unimi.dsi.lang.MutableString;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Parameter;
import com.martiansoftware.jsap.SimpleJSAP;
import com.martiansoftware.jsap.Switch;
import com.martiansoftware.jsap.UnflaggedOption;
import com.martiansoftware.jsap.stringparsers.ForNameStringParser;
public class FunctionSpeedTest {
public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException, ClassNotFoundException {
final SimpleJSAP jsap = new SimpleJSAP( FunctionSpeedTest.class.getName(), "Test the speed of a function. Performs thirteen repetitions: the first three ones are warmup, and the average of the remaining ten is printed on standard output. The detailed results are logged to standard error.",
new Parameter[] {
new FlaggedOption( "bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b', "buffer-size", "The size of the I/O buffer used to read terms." ),
new FlaggedOption( "n", JSAP.INTSIZE_PARSER, "1000000", JSAP.NOT_REQUIRED, 'n', "number-of-strings", "The (maximum) number of strings used for random testing." ),
new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The term file encoding." ),
new FlaggedOption( "save", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 's', "save", "In case of a random test, save to this file the strings used." ),
new Switch( "zipped", 'z', "zipped", "The term list is compressed in gzip format." ),
new Switch( "random", 'r', "random", "Test a shuffled subset of strings." ),
new Switch( "check", 'c', "check", "Check that the term list is mapped to its ordinal position." ),
new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised function." ),
new UnflaggedOption( "termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "Read terms from this file." ),
});
JSAPResult jsapResult = jsap.parse( arg );
if ( jsap.messagePrinted() ) return;
final String functionName = jsapResult.getString( "function" );
final String termFile = jsapResult.getString( "termFile" );
final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
final boolean zipped = jsapResult.getBoolean( "zipped" );
final boolean check = jsapResult.getBoolean( "check" );
final boolean random = jsapResult.getBoolean( "random" );
final String save = jsapResult.getString( "save" );
final int maxStrings = jsapResult.getInt( "n" );
if ( jsapResult.userSpecified( "n" ) && ! random ) throw new IllegalArgumentException( "The number of string is meaningful for random tests only" );
if ( save != null && ! random ) throw new IllegalArgumentException( "You can save test string only for random tests" );
@SuppressWarnings("unchecked")
final Object2LongFunction<? extends CharSequence> function = (Object2LongFunction<? extends CharSequence>)BinIO.loadObject( functionName );
final FileLinesCollection flc = new FileLinesCollection( termFile, encoding.name(), zipped );
final long size = flc.size();
if ( random ) {
final int n = (int)Math.min( maxStrings, size );
MutableString[] test = new MutableString[ n ];
final int step = (int)( size / n ) - 1;
final Iterator<? extends CharSequence> iterator = flc.iterator();
for( int i = 0; i < n; i++ ) {
test[ i ] = new MutableString( iterator.next() );
for( int j = step; j-- != 0; ) iterator.next();
}
Collections.shuffle( Arrays.asList( test ) );
if ( save != null ) {
final PrintStream ps = new PrintStream( save, encoding.name() );
for( MutableString s: test ) s.println( ps );
ps.close();
}
FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
for( MutableString s: test ) s.writeSelfDelimUTF8( fbaos );
fbaos.close();
test = null;
final FastByteArrayInputStream fbais = new FastByteArrayInputStream( fbaos.array, 0, fbaos.length );
final MutableString s = new MutableString();
System.gc();
System.gc();
long total = 0, t = -1;
for( int k = 13; k
fbais.position( 0 );
long time = -System.nanoTime();
for( int i = 0; i < n; i++ ) {
t ^= function.getLong( s.readSelfDelimUTF8( fbais ) );
if ( ( i % 0xFFFFF ) == 0 ) System.out.print('.');
}
System.out.println();
time += System.nanoTime();
if ( k < 10 ) total += time;
System.out.println( Util.format( time / 1E9 ) + "s, " + Util.format( (double)time / n ) + " ns/item" );
}
System.out.println( "Average: " + Util.format( total / 1E10 ) + "s, " + Util.format( total / ( 10. * n ) ) + " ns/item" );
if ( t == 0 ) System.err.println( t );
}
else {
System.gc();
System.gc();
long total = 0, t = -1;
for( int k = 13; k
final Iterator<? extends CharSequence> iterator = flc.iterator();
long time = -System.nanoTime();
long index;
for( long i = 0; i < size; i++ ) {
index = function.getLong( iterator.next() );
t ^= index;
if ( check && index != i ) throw new AssertionError( index + " != " + i );
if ( ( i & 0xFFFFF ) == 0 ) System.err.print('.');
}
System.err.println();
time += System.nanoTime();
if ( k < 10 ) total += time;
System.err.println( Util.format( time / 1E9 ) + "s, " + Util.format( (double)time / size ) + " ns/item" );
}
System.out.println( "Average: " + Util.format( total / 1E10 ) + "s, " + Util.format( total / ( 10. * size ) ) + " ns/item" );
if ( t == 0 ) System.err.println( t );
}
}
}
|
package org.lockss.kbart;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class replaces unknown publisher names in a tab-separated input
* file with actual publisher names in a tab-separated mod file, using
* issn/eissn as a matching key.
*
* @author Philip Gust
*
*/
public class FillInUnknownNames {
static List<String[]> inList = new ArrayList<String[]>();
static List<String[]> modList = new ArrayList<String[]>();
static int modPissn = 0; // mod file column for print issn
static int modEissn=1; // mod file column for eissn
static int modPublisher = 2; // mod file column for publisher
static int inPissn = 1; // input column for print issn
static int inEissn = 2; // input column for eissn
static int inPublisher = 4; // input column for publisher
/**
* Read a tab-separated rows of input into a list string arrays.
* @param fname the file name
* @param list the list to fill
* @throws IOException if an error occurred reading the file
*/
static void readList(String fname, List<String[]> list)
throws IOException {
BufferedReader rdr = new java.io.BufferedReader(new FileReader(fname));
String line;
while ((line = rdr.readLine()) != null) {
String[] fields = line.split("\t");
list.add(fields);
}
}
/**
* Write a list of string arrays to a stdout as tab-separated lines.
* @param list the list to write
*/
static void writeList(List<String[]> list) {
PrintStream ps = System.out;
for (String[] fields : list) {
for (int i = 0; i < fields.length; i++) {
if (i > 0) {
ps.print("\t");
}
ps.print(fields[i]);
}
ps.println();
}
}
/**
* This method reads two files specified by command line arguments.
* The first file contains tab-separated lines of fields including
* issn, eissn, and publisher. The second file contans tab-separated
* lines of fields containing pissn, eissn, and corresponding correct
* publisher names. The output is a version of the input file with
* gensym publisher names replaced by correct publisher names, using
* the issn and eissn as keys.
*
* @param args the names of the input and modification files
* @throws IOException if an IO error occurs.
*/
// PJG: TODO: Should accept input as comma-separated lists with
// quotes around fields that contain embedded commas. KBART files
// are comma-separated rather than tab-separated.
static public void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("Need two file names");
System.exit(1);
}
// read input and mod lists
readList(args[0], inList);
readList(args[1], modList);
// build a map if issn/eissn to publisher title
Map<String,String> modMap = new HashMap<String,String>();
for (String[] modFields : modList) {
if (modFields[modPissn].length() > 0) {
modMap.put(modFields[modPissn], modFields[modPublisher]);
}
if (modFields[modEissn].length() > 0) {
modMap.put(modFields[modEissn], modFields[modPublisher]);
}
}
for (String[] inFields : inList) {
// validate row
if (inFields.length <= inPublisher) {
continue;
}
// get publisher name from the mod map based on print issn
String modPub = modMap.get(inFields[inPissn]);
if (modPub == null) {
// get publisher name from the mod map based on eissn
modPub = modMap.get(inFields[inEissn]);
}
if (modPub != null) {
// replace the publisher name in the input map
inFields[inPublisher] = modPub;
}
}
writeList(inList);
}
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.dobj;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import org.apache.commons.lang.StringUtils;
import com.samskivert.util.ListUtil;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.util.TrackedObject;
import com.threerings.presents.Log;
/**
* The distributed object forms the foundation of the Presents system. All
* information shared among users of the system is done via distributed
* objects. A distributed object has a set of listeners. These listeners
* have access to the object or a proxy of the object and therefore have
* access to the data stored in the object's members at all times.
*
* <p> Additionally, an object as a set of subscribers. Subscribers manage
* the lifespan of the object; while a subscriber is subscribed, the
* listeners registered with an object will be notified of events. When
* the subscriber unsubscribes, the object becomes non-live and the
* listeners are no longer notified. <em>Note:</em> on the server, object
* subscription is merely a formality as all objects remain live all the
* time, so <em>do not</em> depend on event notifications ceasing when a
* subscriber has relinquished its subscription. Always unregister all
* listeners when they no longer need to hear from an object.
*
* <p> When there is any change to the the object's fields data, an event
* is generated which is dispatched to all listeners of the object,
* notifying them of that change and effecting that change to the copy of
* the object maintained at each client. In this way, both a respository
* of shared information and a mechanism for asynchronous notification are
* made available as a fundamental application building blocks.
*
* <p> To define what information is shared, an application creates a
* distributed object declaration which is much like a class declaration
* except that it is transformed into a proper derived class of
* <code>DObject</code> by a script. A declaration looks something like
* this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the
* proper attribute change events being generated and dispatched.
*
* <p> Note that distributed object fields can be any of the following set
* of primitive types:
*
* <code><pre>
* boolean, byte, short, int, long, float, double
* Boolean, Byte, Short, Integer, Long, Float, Double, String
* boolean[], byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*
* Fields of type {@link Streamable} can also be used.
*/
public class DObject extends TrackedObject
implements Streamable
{
public DObject ()
{
_fields = (Field[])_ftable.get(getClass());
if (_fields == null) {
_fields = getClass().getFields();
Arrays.sort(_fields, FIELD_COMP);
_ftable.put(getClass(), _fields);
}
}
/**
* Returns the object id of this object. All objects in the system
* have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Returns the dobject manager under the auspices of which this object
* operates. This could be <code>null</code> if the object is not
* active.
*/
public DObjectManager getManager ()
{
return _omgr;
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber sub)
{
// only add the subscriber if they're not already there
Object[] subs = ListUtil.testAndAddRef(_subs, sub);
if (subs != null) {
// Log.info("Adding subscriber " + which() + ": " + sub + ".");
_subs = subs;
_scount++;
} else {
Log.warning("Refusing subscriber that's already in the list " +
"[dobj=" + which() + ", subscriber=" + sub + "]");
Thread.dumpStack();
}
}
/**
* Don't call this function! Go through the distributed object manager
* instead to ensure that everything is done on the proper thread.
* This function can only safely be called directly when you know you
* are operating on the omgr thread (you are in the middle of a call
* to <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber sub)
{
if (ListUtil.clearRef(_subs, sub) != null) {
// if we removed something, check to see if we just removed
// the last subscriber from our list; we also want to be sure
// that we're still active otherwise there's no need to notify
// our objmgr because we don't have one
if (--_scount == 0 && _omgr != null) {
_omgr.removedLastSubscriber(this, _deathWish);
}
}
}
/**
* Instructs this object to request to have a fork stuck in it when
* its last subscriber is removed.
*/
public void setDestroyOnLastSubscriberRemoved (boolean deathWish)
{
_deathWish = deathWish;
}
/**
* Adds an event listener to this object. The listener will be
* notified when any events are dispatched on this object that match
* their particular listener interface.
*
* <p> Note that the entity adding itself as a listener should have
* obtained the object reference by subscribing to it or should be
* acting on behalf of some other entity that subscribed to the
* object, <em>and</em> that it must be sure to remove itself from the
* listener list (via {@link #removeListener}) when it is done because
* unsubscribing from the object (done by whatever entity subscribed
* in the first place) is not guaranteed to result in the listeners
* added through that subscription being automatically removed (in
* most cases, they definitely will not be removed).
*
* @param listener the listener to be added.
*
* @see EventListener
* @see AttributeChangeListener
* @see SetListener
* @see OidListListener
*/
public void addListener (ChangeListener listener)
{
// only add the listener if they're not already there
Object[] els = ListUtil.testAndAddRef(_listeners, listener);
if (els != null) {
_listeners = els;
} else {
Log.warning("Refusing repeat listener registration " +
"[dobj=" + which() + ", list=" + listener + "]");
Thread.dumpStack();
}
}
/**
* Removes an event listener from this object. The listener will no
* longer be notified when events are dispatched on this object.
*
* @param listener the listener to be removed.
*/
public void removeListener (ChangeListener listener)
{
ListUtil.clearRef(_listeners, listener);
}
/**
* Provides this object with an entity that can be used to validate
* subscription requests and events before they are processed. The
* access controller is handy for ensuring that clients are behaving
* as expected and for preventing impermissible modifications or event
* dispatches on a distributed object.
*/
public void setAccessController (AccessController controller)
{
_controller = controller;
}
/**
* Returns a reference to the access controller in use by this object
* or null if none has been configured.
*/
public AccessController getAccessController ()
{
return _controller;
}
/**
* Get the DSet with the specified name.
*/
public final DSet getSet (String setName)
{
try {
return (DSet) getField(setName).get(this);
} catch (Exception e) {
throw new IllegalArgumentException("No such set: " + setName);
}
}
/**
* Request to have the specified item added to the specified DSet.
*/
public void addToSet (String setName, DSet.Entry entry)
{
requestEntryAdd(setName, getSet(setName), entry);
}
/**
* Request to have the specified item updated in the specified DSet.
*/
public void updateSet (String setName, DSet.Entry entry)
{
requestEntryUpdate(setName, getSet(setName), entry);
}
/**
* Request to have the specified key removed from the specified DSet.
*/
public void removeFromSet (String setName, Comparable key)
{
requestEntryRemove(setName, getSet(setName), key);
}
/**
* At times, an entity on the server may need to ensure that events it
* has queued up have made it through the event queue and are applied
* to their respective objects before a service may safely be
* undertaken again. To make this possible, it can acquire a lock on a
* distributed object, generate the events in question and then
* release the lock (via a call to <code>releaseLock</code>) which
* will queue up a final event, the processing of which will release
* the lock. Thus the lock will not be released until all of the
* previously generated events have been processed. If the service is
* invoked again before that lock is released, the associated call to
* <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as
* long as they each have a unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not
* acquired because it has not yet been released from a previous
* acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// check for the existence of the lock in the list and add it if
// it's not already there
Object[] list = ListUtil.testAndAdd(_locks, name);
if (list == null) {
// a null list means the object was already in the list
return false;
} else {
// a non-null list means the object was added
_locks = list;
return true;
}
}
/**
* Queues up an event that when processed will release the lock of the
* specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
postEvent(new ReleaseLockEvent(_oid, name));
}
/**
* Don't call this function! It is called by a remove lock event when
* that event is processed and shouldn't be called at any other time.
* If you mean to release a lock that was acquired with
* <code>acquireLock</code> you should be using
* <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// clear the lock from the list
if (ListUtil.clear(_locks, name) == null) {
// complain if we didn't find the lock
Log.info("Unable to clear non-existent lock [lock=" + name +
", dobj=" + this + "].");
}
}
/**
* Requests that this distributed object be destroyed. It does so by
* queueing up an object destroyed event which the server will
* validate and process.
*/
public void destroy ()
{
postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this
* object. This will be called before satisfying a subscription
* request. If an {@link AccessController} has been specified for this
* object, it will be used to determine whether or not to allow the
* subscription request. If no controller is set, the subscription
* will be allowed.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if
* they do not.
*/
public boolean checkPermissions (Subscriber sub)
{
if (_controller != null) {
return _controller.allowSubscribe(this, sub);
} else {
return true;
}
}
public boolean checkPermissions (DEvent event)
{
if (_controller != null) {
return _controller.allowDispatch(this, event);
} else {
return true;
}
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the listeners registered with this object.
*
* @param event the event that was just applied.
*/
public void notifyListeners (DEvent event)
{
if (_listeners == null) {
return;
}
int llength = _listeners.length;
for (int i = 0; i < llength; i++) {
Object listener = _listeners[i];
if (listener == null) {
continue;
}
try {
// do any event specific notifications
event.notifyListener(listener);
// and notify them if they are listening for all events
if (listener instanceof EventListener) {
((EventListener)listener).eventReceived(event);
}
} catch (Exception e) {
Log.warning("Listener choked during notification " +
"[list=" + listener + ", event=" + event + "].");
Log.logStackTrace(e);
}
}
}
/**
* Called by the distributed object manager after it has applied an
* event to this object. This dispatches an event notification to all
* of the proxy listeners registered with this object.
*
* @param event the event that was just applied.
*/
public void notifyProxies (DEvent event)
{
if (_subs == null || event.isPrivate()) {
return;
}
for (int ii = 0, ll = _subs.length; ii < ll; ii++) {
Object sub = _subs[ii];
try {
if (sub != null && sub instanceof ProxySubscriber) {
((ProxySubscriber)sub).eventReceived(event);
}
} catch (Exception e) {
Log.warning("Proxy choked during notification " +
"[sub=" + sub + ", event=" + event + "].");
Log.logStackTrace(e);
}
}
}
/**
* Requests that the specified attribute be changed to the specified
* value. Normally the generated setter methods should be used but in
* rare cases a caller may wish to update distributed fields in a
* generic manner.
*/
public void changeAttribute (String name, Object value)
throws ObjectAccessException
{
try {
Field f = getField(name);
requestAttributeChange(name, value, f.get(this));
f.set(this, value);
} catch (Exception e) {
String errmsg = "changeAttribute() failure [name=" + name +
", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Sets the named attribute to the specified value. This is only used
* by the internals of the event dispatch mechanism and should not be
* called directly by users. Use the generated attribute setter
* methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "setAttribute() failure [name=" + name +
", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Looks up the named attribute and returns a reference to it. This
* should only be used by the internals of the event dispatch
* mechanism and should not be called directly by users. Use the
* generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getField(name).get(this);
} catch (Exception e) {
String errmsg = "getAttribute() failure [name=" + name + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Posts a message event on this distrubuted object.
*/
public void postMessage (String name, Object[] args)
{
postEvent(new MessageEvent(_oid, name, args));
}
/**
* Posts the specified event either to our dobject manager or to the
* compound event for which we are currently transacting.
*/
public void postEvent (DEvent event)
{
if (_tevent != null) {
_tevent.postEvent(event);
} else if (_omgr != null) {
_omgr.postEvent(event);
} else {
Log.warning("Unable to post event, object has no omgr " +
"[oid=" + getOid() + ", class=" + getClass().getName() +
", event=" + event + "].");
}
}
/**
* Returns true if this object is active and registered with the
* distributed object system. If an object is created via
* <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public final boolean isActive ()
{
return _omgr != null;
}
/**
* Don't call this function! It initializes this distributed object
* with the supplied distributed object manager. This is called by the
* distributed object manager when an object is created and registered
* with the system.
*
* @see DObjectManager#createObject
*/
public void setManager (DObjectManager omgr)
{
_omgr = omgr;
}
/**
* Don't call this function. It is called by the distributed object
* manager when an object is created and registered with the system.
*
* @see DObjectManager#createObject
*/
public void setOid (int oid)
{
_oid = oid;
}
/**
* Generates a concise string representation of this object.
*/
public String which ()
{
StringBuffer buf = new StringBuffer();
which(buf);
return buf.toString();
}
/**
* Used to briefly describe this distributed object.
*/
protected void which (StringBuffer buf)
{
buf.append(StringUtil.shortClassName(this));
buf.append(":").append(_oid);
}
/**
* Generates a string representation of this object.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer();
toString(buf);
return buf.append("]").toString();
}
/**
* Generates a string representation of this object.
*/
protected void toString (StringBuffer buf)
{
StringUtil.fieldsToString(buf, this, "\n");
if (buf.length() > 0) {
buf.insert(0, "\n");
}
buf.insert(0, _oid);
buf.insert(0, "[oid=");
}
/**
* Begins a transaction on this distributed object. In some
* situations, it is desirable to cause multiple changes to
* distributed object fields in one unified operation. Starting a
* transaction causes all subsequent field modifications to be stored
* in a single compound event which can then be committed, dispatching
* and applying all included events in a single group. Additionally,
* the events are dispatched over the network in a single unit which
* can significantly enhance network efficiency.
*
* <p> When the transaction is complete, the caller must call {@link
* #commitTransaction} or {@link CompoundEvent#commit} to commit the
* transaction and release the object back to its normal
* non-transacting state. If the caller decides not to commit their
* transaction, they must call {@link #cancelTransaction} or {@link
* CompoundEvent#cancel} to cancel the transaction. Failure to do so
* will cause the pooch to be totally screwed.
*
* <p> Note: like all other distributed object operations,
* transactions are not thread safe. It is expected that a single
* thread will handle all distributed object operations and that
* thread will begin and complete a transaction before giving up
* control to unknown code which might try to operate on the
* transacting distributed object.
*
* <p> Note also: if the object is already engaged in a transaction, a
* transaction participant count will be incremented to note that an
* additional call to {@link #commitTransaction} is required before
* the transaction should actually be committed. Thus <em>every</em>
* call to {@link #startTransaction} must be accompanied by a call to
* either {@link #commitTransaction} or {@link
* #cancelTransaction}. Additionally, if any transaction participant
* cancels the transaction, the entire transaction is cancelled for
* all participants, regardless of whether the other participants
* attempted to commit the transaction.
*/
public void startTransaction ()
{
// sanity check
if (!isActive()) {
String errmsg = "Refusing to start transaction on inactive " +
"object [dobj=" + this + "]";
throw new IllegalArgumentException(errmsg);
} else if (_tevent != null) {
_tcount++;
} else {
_tevent = new CompoundEvent(this, _omgr);
}
}
/**
* Commits the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#commit
*/
public void commitTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot commit: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we are nested, we decrement our nesting count rather than
// committing the transaction
if (_tcount > 0) {
_tcount
} else {
// we may actually be doing our final commit after someone
// already cancelled this transaction, so we need to perform
// the appropriate action at this point
if (_tcancelled) {
_tevent.cancel();
} else {
_tevent.commit();
}
}
}
/**
* Returns true if this object is in the middle of a transaction or
* false if it is not.
*/
public boolean inTransaction ()
{
return (_tevent != null);
}
/**
* Cancels the transaction in which this distributed object is
* involved.
*
* @see CompoundEvent#cancel
*/
public void cancelTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot cancel: not involved in a transaction " +
"[dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we're in a nested transaction, make a note that it is to be
// cancelled when all parties commit and decrement the nest count
if (_tcount > 0) {
_tcancelled = true;
_tcount
} else {
_tevent.cancel();
}
}
/**
* Removes this object from participation in any transaction in which
* it might be taking part.
*/
protected void clearTransaction ()
{
// sanity check
if (_tcount != 0) {
Log.warning("Transaction cleared with non-zero nesting count " +
"[dobj=" + this + "].");
_tcount = 0;
}
// clear our transaction state
_tevent = null;
_tcancelled = false;
}
/**
* Called by derived instances when an attribute setter method was
* called.
*/
protected void requestAttributeChange (
String name, Object value, Object oldValue)
{
// dispatch an attribute changed event
postEvent(new AttributeChangedEvent(_oid, name, value, oldValue));
}
/**
* Called by derived instances when an element updater method was
* called.
*/
protected void requestElementUpdate (
String name, int index, Object value, Object oldValue)
{
// dispatch an attribute changed event
postEvent(new ElementUpdatedEvent(
_oid, name, value, oldValue, index));
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// dispatch an object added event
postEvent(new ObjectAddedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// dispatch an object removed event
postEvent(new ObjectRemovedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when a set adder method was called.
*/
protected void requestEntryAdd (String name, DSet set, DSet.Entry entry)
{
// if we're on the authoritative server, we update the set immediately
boolean alreadyApplied = false;
if (_omgr != null && _omgr.isManager(this)) {
if (!set.add(entry)) {
Thread.dumpStack();
}
alreadyApplied = true;
}
// dispatch an entry added event
postEvent(new EntryAddedEvent(_oid, name, entry, alreadyApplied));
}
/**
* Calls by derived instances when a set remover method was called.
*/
protected void requestEntryRemove (String name, DSet set, Comparable key)
{
// if we're on the authoritative server, we update the set immediately
DSet.Entry oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
oldEntry = set.get(key);
set.removeKey(key);
}
// dispatch an entry removed event
postEvent(new EntryRemovedEvent(_oid, name, key, oldEntry));
}
/**
* Calls by derived instances when a set updater method was called.
*/
protected void requestEntryUpdate (String name, DSet set, DSet.Entry entry)
{
// if we're on the authoritative server, we update the set immediately
DSet.Entry oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
oldEntry = set.get(entry.getKey());
set.update(entry);
}
// dispatch an entry updated event
postEvent(new EntryUpdatedEvent(_oid, name, entry, oldEntry));
}
/**
* Returns the {@link Field} with the specified name or null if there
* is none such.
*/
protected final Field getField (String name)
{
int low = 0, high = _fields.length-1;
while (low <= high) {
int mid = (low + high) >> 1;
Field midVal = _fields[mid];
int cmp = midVal.getName().compareTo(name);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return midVal; // key found
}
}
return null; // key not found.
}
/** Our object id. */
protected int _oid;
/** An array of our fields, sorted for efficient lookup. */
protected transient Field[] _fields;
/** A reference to our object manager. */
protected transient DObjectManager _omgr;
/** The entity that tells us if an event or subscription request
* should be allowed. */
protected transient AccessController _controller;
/** A list of outstanding locks. */
protected transient Object[] _locks;
/** Our subscribers list. */
protected transient Object[] _subs;
/** Our event listeners list. */
protected transient Object[] _listeners;
/** Our subscriber count. */
protected transient int _scount;
/** The compound event associated with our transaction, if we're
* currently in a transaction. */
protected transient CompoundEvent _tevent;
/** The nesting depth of our current transaction. */
protected transient int _tcount;
/** Whether or not our nested transaction has been cancelled. */
protected transient boolean _tcancelled;
/** Indicates whether we want to be destroyed when our last subscriber
* is removed. */
protected transient boolean _deathWish = false;
/** Maintains a mapping of sorted field arrays for each distributed
* object class. */
protected static HashMap _ftable = new HashMap();
/** Used to sort and search {@link #_fields}. */
protected static final Comparator FIELD_COMP = new Comparator() {
public int compare (Object o1, Object o2) {
return ((Field)o1).getName().compareTo(((Field)o2).getName());
}
};
/** Used when calling set methods dynamically. */
protected static final Class[] ENTRY_CLASS_ARGS =
new Class[] { DSet.Entry.class };
/** Used when calling set methods dynamically. */
protected static final Class[] KEY_CLASS_ARGS =
new Class[] { Comparable.class };
}
|
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.dobj;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.samskivert.util.ArrayUtil;
import com.samskivert.util.ListUtil;
import com.samskivert.util.StringUtil;
import com.threerings.io.Streamable;
import com.threerings.presents.net.Transport;
import static com.threerings.presents.Log.log;
/**
* The distributed object forms the foundation of the Presents system. All information shared among
* users of the system is done via distributed objects. A distributed object has a set of
* listeners. These listeners have access to the object or a proxy of the object and therefore have
* access to the data stored in the object's members at all times.
*
* <p> Additionally, an object has a set of subscribers. Subscribers manage the lifespan of the
* object; while a subscriber is subscribed, the listeners registered with an object will be
* notified of events. When the subscriber unsubscribes, the object becomes non-live and the
* listeners are no longer notified. <em>Note:</em> on the server, object subscription is merely a
* formality as all objects remain live all the time, so <em>do not</em> depend on event
* notifications ceasing when a subscriber has relinquished its subscription. Always unregister all
* listeners when they no longer need to hear from an object.
*
* <p> When there is any change to the the object's fields data, an event is generated which is
* dispatched to all listeners of the object, notifying them of that change and effecting that
* change to the copy of the object maintained at each client. In this way, both a repository of
* shared information and a mechanism for asynchronous notification are made available as a
* fundamental application building blocks.
*
* <p> To define what information is shared, an application creates a distributed object
* declaration which is much like a class declaration except that it is transformed into a proper
* derived class of <code>DObject</code> by a script. A declaration looks something like this:
*
* <pre>
* public dclass RoomObject
* {
* public String description;
* public int[] occupants;
* }
* </pre>
*
* which is converted into an actual Java class that looks like this:
*
* <pre>
* public class RoomObject extends DObject
* {
* public String getDescription ()
* {
* // ...
* }
*
* public void setDescription (String description)
* {
* // ...
* }
*
* public int[] getOccupants ()
* {
* // ...
* }
*
* public void setOccupants (int[] occupants)
* {
* // ...
* }
*
* public void setOccupantsAt (int index, int value)
* {
* // ...
* }
* }
* </pre>
*
* These method calls on the actual distributed object will result in the proper attribute change
* events being generated and dispatched.
*
* <p> Note that distributed object fields can be any of the following set of primitive types:
*
* <code><pre>
* boolean, byte, short, int, long, float, double
* Boolean, Byte, Short, Integer, Long, Float, Double, String
* boolean[], byte[], short[], int[], long[], float[], double[], String[]
* </pre></code>
*
* Fields of type {@link Streamable} can also be used.
*/
public class DObject
implements Streamable
{
public DObject ()
{
_fields = _ftable.get(getClass());
if (_fields == null) {
_fields = getClass().getFields();
Arrays.sort(_fields, FIELD_COMP);
_ftable.put(getClass(), _fields);
}
}
/**
* Returns the object id of this object. All objects in the system have a unique object id.
*/
public int getOid ()
{
return _oid;
}
/**
* Returns the dobject manager under the auspices of which this object operates. This could be
* <code>null</code> if the object is not active.
*/
public DObjectManager getManager ()
{
return _omgr;
}
/**
* Don't call this function! Go through the distributed object manager instead to ensure that
* everything is done on the proper thread. This function can only safely be called directly
* when you know you are operating on the omgr thread (you are in the middle of a call to
* <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#subscribeToObject
*/
public void addSubscriber (Subscriber<?> sub)
{
// only add the subscriber if they're not already there
Object[] subs = ListUtil.testAndAddRef(_subs, sub);
if (subs != null) {
// Log.info("Adding subscriber " + which() + ": " + sub + ".");
_subs = subs;
_scount++;
} else {
log.warning("Refusing subscriber that's already in the list", "dobj", which(),
"subscriber", sub, new Exception());
}
}
/**
* Don't call this function! Go through the distributed object manager instead to ensure that
* everything is done on the proper thread. This function can only safely be called directly
* when you know you are operating on the omgr thread (you are in the middle of a call to
* <code>objectAvailable</code> or to a listener callback).
*
* @see DObjectManager#unsubscribeFromObject
*/
public void removeSubscriber (Subscriber<?> sub)
{
if (ListUtil.clearRef(_subs, sub) != null) {
// if we removed something, check to see if we just removed the last subscriber from
// our list; we also want to be sure that we're still active otherwise there's no need
// to notify our objmgr because we don't have one
if (--_scount == 0 && _omgr != null) {
_omgr.removedLastSubscriber(this, _deathWish);
}
}
}
/**
* Instructs this object to request to have a fork stuck in it when its last subscriber is
* removed.
*/
public void setDestroyOnLastSubscriberRemoved (boolean deathWish)
{
_deathWish = deathWish;
}
/**
* Adds an event listener to this object. The listener will be notified when any events are
* dispatched on this object that match their particular listener interface.
*
* <p> Note that the entity adding itself as a listener should have obtained the object
* reference by subscribing to it or should be acting on behalf of some other entity that
* subscribed to the object, <em>and</em> that it must be sure to remove itself from the
* listener list (via {@link #removeListener}) when it is done because unsubscribing from the
* object (done by whatever entity subscribed in the first place) is not guaranteed to result
* in the listeners added through that subscription being automatically removed (in most cases,
* they definitely will not be removed).
*
* @param listener the listener to be added.
*
* @see EventListener
* @see AttributeChangeListener
* @see SetListener
* @see OidListListener
*/
public void addListener (ChangeListener listener)
{
addListener(listener, false);
}
/**
* Adds an event listener to this object. The listener will be notified when any events are
* dispatched on this object that match their particular listener interface.
*
* <p> Note that the entity adding itself as a listener should have obtained the object
* reference by subscribing to it or should be acting on behalf of some other entity that
* subscribed to the object, <em>and</em> that it must be sure to remove itself from the
* listener list (via {@link #removeListener}) when it is done because unsubscribing from the
* object (done by whatever entity subscribed in the first place) is not guaranteed to result
* in the listeners added through that subscription being automatically removed (in most cases,
* they definitely will not be removed).
*
* @param listener the listener to be added.
* @param weak if true, retain only a weak reference to the listener (do not prevent the
* listener from being garbage-collected).
*
* @see EventListener
* @see AttributeChangeListener
* @see SetListener
* @see OidListListener
*/
public void addListener (ChangeListener listener, boolean weak)
{
// only add the listener if they're not already there
int idx = getListenerIndex(listener);
if (idx == -1) {
_listeners = ListUtil.add(_listeners,
weak ? new WeakListenerWrapper(listener) : listener);
return;
}
boolean oweak = _listeners[idx] instanceof WeakListenerWrapper;
if (weak == oweak) {
log.warning("Refusing repeat listener registration",
"dobj", which(), "list", listener, new Exception());
} else {
log.warning("Updating listener registered under different strength.",
"dobj", which(), "list", listener, "oweak", oweak, "nweak", weak, new Exception());
_listeners[idx] = weak ? new WeakListenerWrapper(listener) : listener;
}
}
/**
* Removes an event listener from this object. The listener will no longer be notified when
* events are dispatched on this object.
*
* @param listener the listener to be removed.
*/
public void removeListener (ChangeListener listener)
{
int idx = getListenerIndex(listener);
if (idx != -1) {
_listeners[idx] = null;
}
}
/**
* Provides this object with an entity that can be used to validate subscription requests and
* events before they are processed. The access controller is handy for ensuring that clients
* are behaving as expected and for preventing impermissible modifications or event dispatches
* on a distributed object.
*/
public void setAccessController (AccessController controller)
{
_controller = controller;
}
/**
* Returns a reference to the access controller in use by this object or null if none has been
* configured.
*/
public AccessController getAccessController ()
{
return _controller;
}
/**
* Get the DSet with the specified name.
*/
public final <T extends DSet.Entry> DSet<T> getSet (String setName)
{
try {
@SuppressWarnings("unchecked") DSet<T> casted = (DSet<T>)getField(setName).get(this);
return casted;
} catch (Exception e) {
throw new IllegalArgumentException("No such set: " + setName);
}
}
/**
* Request to have the specified item added to the specified DSet.
*/
public <T extends DSet.Entry> void addToSet (String setName, T entry)
{
requestEntryAdd(setName, getSet(setName), entry);
}
/**
* Request to have the specified item updated in the specified DSet.
*/
public void updateSet (String setName, DSet.Entry entry)
{
requestEntryUpdate(setName, getSet(setName), entry);
}
/**
* Request to have the specified key removed from the specified DSet.
*/
public void removeFromSet (String setName, Comparable<?> key)
{
requestEntryRemove(setName, getSet(setName), key);
}
/**
* At times, an entity on the server may need to ensure that events it has queued up have made
* it through the event queue and are applied to their respective objects before a service may
* safely be undertaken again. To make this possible, it can acquire a lock on a distributed
* object, generate the events in question and then release the lock (via a call to
* <code>releaseLock</code>) which will queue up a final event, the processing of which will
* release the lock. Thus the lock will not be released until all of the previously generated
* events have been processed. If the service is invoked again before that lock is released,
* the associated call to <code>acquireLock</code> will fail and the code can respond
* accordingly. An object may have any number of outstanding locks as long as they each have a
* unique name.
*
* @param name the name of the lock to acquire.
*
* @return true if the lock was acquired, false if the lock was not acquired because it has not
* yet been released from a previous acquisition.
*
* @see #releaseLock
*/
public boolean acquireLock (String name)
{
// check for the existence of the lock in the list and add it if it's not already there
Object[] list = ListUtil.testAndAdd(_locks, name);
if (list == null) {
// a null list means the object was already in the list
return false;
} else {
// a non-null list means the object was added
_locks = list;
return true;
}
}
/**
* Queues up an event that when processed will release the lock of the specified name.
*
* @see #acquireLock
*/
public void releaseLock (String name)
{
// queue up a release lock event
postEvent(new ReleaseLockEvent(_oid, name));
}
/**
* Don't call this function! It is called by a remove lock event when that event is processed
* and shouldn't be called at any other time. If you mean to release a lock that was acquired
* with <code>acquireLock</code> you should be using <code>releaseLock</code>.
*
* @see #acquireLock
* @see #releaseLock
*/
protected void clearLock (String name)
{
// clear the lock from the list
if (ListUtil.clear(_locks, name) == null) {
// complain if we didn't find the lock
log.info("Unable to clear non-existent lock", "lock", name, "dobj", this);
}
}
/**
* Requests that this distributed object be destroyed. It does so by queueing up an object
* destroyed event which the server will validate and process.
*/
public void destroy ()
{
if (_oid == 0) {
log.warning("Denying request to destroy an uninitialized object!", new Exception());
return;
}
postEvent(new ObjectDestroyedEvent(_oid));
}
/**
* Checks to ensure that the specified subscriber has access to this object. This will be
* called before satisfying a subscription request. If an {@link AccessController} has been
* specified for this object, it will be used to determine whether or not to allow the
* subscription request. If no controller is set, the subscription will be allowed.
*
* @param sub the subscriber that will subscribe to this object.
*
* @return true if the subscriber has access to the object, false if they do not.
*/
public boolean checkPermissions (Subscriber<?> sub)
{
if (_controller != null) {
return _controller.allowSubscribe(this, sub);
} else {
return true;
}
}
public boolean checkPermissions (DEvent event)
{
if (_controller != null) {
return _controller.allowDispatch(this, event);
} else {
return true;
}
}
/**
* Called by the distributed object manager after it has applied an event to this object. This
* dispatches an event notification to all of the listeners registered with this object.
*
* @param event the event that was just applied.
*/
public void notifyListeners (DEvent event)
{
if (_listeners == null) {
return;
}
int llength = _listeners.length;
for (int i = 0; i < llength; i++) {
Object listener = _listeners[i];
if (listener == null) {
continue;
}
try {
// do any event specific notifications
event.notifyListener(listener);
// and notify them if they are listening for all events
if (listener instanceof EventListener) {
((EventListener)listener).eventReceived(event);
}
} catch (Exception e) {
log.warning("Listener choked during notification", "list", listener,
"event", event, e);
}
}
}
/**
* Called by the distributed object manager after it has applied an event to this object. This
* dispatches an event notification to all of the proxy listeners registered with this object.
*
* @param event the event that was just applied.
*/
public void notifyProxies (DEvent event)
{
if (_subs == null || event.isPrivate()) {
return;
}
for (Object sub : _subs) {
try {
if (sub != null && sub instanceof ProxySubscriber) {
((ProxySubscriber)sub).eventReceived(event);
}
} catch (Exception e) {
log.warning("Proxy choked during notification", "sub", sub, "event", event, e);
}
}
}
/**
* Requests that the specified attribute be changed to the specified value. Normally the
* generated setter methods should be used but in rare cases a caller may wish to update
* distributed fields in a generic manner.
*/
public void changeAttribute (String name, Object value)
throws ObjectAccessException
{
try {
Field f = getField(name);
requestAttributeChange(name, value, f.get(this));
f.set(this, value);
} catch (Exception e) {
String errmsg = "changeAttribute() failure [name=" + name + ", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Sets the named attribute to the specified value. This is only used by the internals of the
* event dispatch mechanism and should not be called directly by users. Use the generated
* attribute setter methods instead.
*/
public void setAttribute (String name, Object value)
throws ObjectAccessException
{
try {
getField(name).set(this, value);
} catch (Exception e) {
String errmsg = "setAttribute() failure [name=" + name + ", value=" + value +
", vclass=" + value.getClass().getName() + "].";
throw new ObjectAccessException(errmsg, e);
}
}
/**
* Looks up the named attribute and returns a reference to it. This should only be used by the
* internals of the event dispatch mechanism and should not be called directly by users. Use
* the generated attribute getter methods instead.
*/
public Object getAttribute (String name)
throws ObjectAccessException
{
try {
return getField(name).get(this);
} catch (Exception e) {
throw new ObjectAccessException("getAttribute() failure [name=" + name + "].", e);
}
}
/**
* Posts a message event on this distributed object.
*/
public void postMessage (String name, Object... args)
{
postMessage(Transport.DEFAULT, name, args);
}
/**
* Posts a message event on this distributed object.
*
* @param transport a hint as to the type of transport desired for the message.
*/
public void postMessage (Transport transport, String name, Object... args)
{
postEvent(new MessageEvent(_oid, name, args, transport));
}
/**
* Posts the specified event either to our dobject manager or to the compound event for which
* we are currently transacting.
*/
public void postEvent (DEvent event)
{
if (_tevent != null) {
_tevent.postEvent(event);
} else if (_omgr != null) {
_omgr.postEvent(event);
} else {
log.info("Dropping event for non- or no longer managed object", "oid", getOid(),
"class", getClass().getName(), "event", event);
}
}
/**
* Returns true if this object is active and registered with the distributed object system. If
* an object is created via <code>DObjectManager.createObject</code> it will be active until
* such time as it is destroyed.
*/
public final boolean isActive ()
{
return _omgr != null;
}
/**
* Don't call this function! It initializes this distributed object with the supplied
* distributed object manager. This is called by the distributed object manager when an object
* is created and registered with the system.
*
* @see RootDObjectManager#registerObject(DObject)
*/
public void setManager (DObjectManager omgr)
{
_omgr = omgr;
}
/**
* Don't call this function. It is called by the distributed object manager when an object is
* created and registered with the system.
*
* @see RootDObjectManager#registerObject(DObject)
*/
public void setOid (int oid)
{
_oid = oid;
}
public <T> void setLocal (Class<T> key, T attr)
{
// locate any existing attribute that matches our key
for (int ii = 0, ll = _locattrs.length; ii < ll; ii++) {
if (key.isInstance(_locattrs[ii])) {
if (attr != null) {
throw new IllegalStateException(
"Attribute already exists that matches the supplied key " +
"[key=" + key + ", have=" + _locattrs[ii].getClass());
}
_locattrs = ArrayUtil.splice(_locattrs, ii, 1);
return;
}
}
// if we were trying to clear out an attribute but didn't find it, then stop here
if (attr == null) {
return;
}
// otherwise append our attribute to the end of the list
_locattrs = ArrayUtil.append(_locattrs, attr);
}
/**
* Retrieves a local attribute for the supplied key. See {@link #setLocal} for
* information on key polymorphism. Returns null if no attribute is found that matches the
* supplied key.
*/
public <T> T getLocal (Class<T> key)
{
for (Object attr : _locattrs) {
if (key.isInstance(attr)) {
@SuppressWarnings("unchecked") T casted = (T)attr;
return casted;
}
}
return null;
}
/**
* Returns an array containing our local attributes.
*/
public List<Object> getLocals ()
{
return ImmutableList.copyOf(_locattrs);
}
/**
* Generates a concise string representation of this object.
*/
public String which ()
{
StringBuilder buf = new StringBuilder();
which(buf);
return buf.toString();
}
@Override // from Object
public String toString ()
{
StringBuilder buf = new StringBuilder();
toString(buf);
return buf.append("]").toString();
}
/**
* Used to briefly describe this distributed object.
*/
protected void which (StringBuilder buf)
{
buf.append(StringUtil.shortClassName(this));
buf.append(":").append(_oid);
}
/**
* Generates a string representation of this object.
*/
protected void toString (StringBuilder buf)
{
StringUtil.fieldsToString(buf, this, "\n");
if (buf.length() > 0) {
buf.insert(0, "\n");
}
buf.insert(0, _oid);
buf.insert(0, "[oid=");
}
/**
* Begins a transaction on this distributed object. In some situations, it is desirable to
* cause multiple changes to distributed object fields in one unified operation. Starting a
* transaction causes all subsequent field modifications to be stored in a single compound
* event which can then be committed, dispatching and applying all included events in a single
* group. Additionally, the events are dispatched over the network in a single unit which can
* significantly enhance network efficiency.
*
* <p> When the transaction is complete, the caller must call {@link #commitTransaction} or
* {@link CompoundEvent#commit} to commit the transaction and release the object back to its
* normal non-transacting state. If the caller decides not to commit their transaction, they
* must call {@link #cancelTransaction} or {@link CompoundEvent#cancel} to cancel the
* transaction. Failure to do so will cause the pooch to be totally screwed.
*
* <p> Note: like all other distributed object operations, transactions are not thread safe. It
* is expected that a single thread will handle all distributed object operations and that
* thread will begin and complete a transaction before giving up control to unknown code which
* might try to operate on the transacting distributed object.
*
* <p> Note also: if the object is already engaged in a transaction, a transaction participant
* count will be incremented to note that an additional call to {@link #commitTransaction} is
* required before the transaction should actually be committed. Thus <em>every</em> call to
* {@link #startTransaction} must be accompanied by a call to either {@link #commitTransaction}
* or {@link #cancelTransaction}. Additionally, if any transaction participant cancels the
* transaction, the entire transaction is cancelled for all participants, regardless of whether
* the other participants attempted to commit the transaction.
*/
public void startTransaction ()
{
if (_tevent != null) {
_tcount++;
} else {
_tevent = new CompoundEvent(this, _omgr);
}
}
/**
* Commits the transaction in which this distributed object is involved.
*
* @see CompoundEvent#commit
*/
public void commitTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot commit: not involved in a transaction [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we are nested, we decrement our nesting count rather than committing the transaction
if (_tcount > 0) {
_tcount
} else {
// we may actually be doing our final commit after someone already cancelled this
// transaction, so we need to perform the appropriate action at this point
if (_tcancelled) {
_tevent.cancel();
} else {
_tevent.commit();
}
}
}
/**
* Returns true if this object is in the middle of a transaction or false if it is not.
*/
public boolean inTransaction ()
{
return (_tevent != null);
}
/**
* Cancels the transaction in which this distributed object is involved.
*
* @see CompoundEvent#cancel
*/
public void cancelTransaction ()
{
if (_tevent == null) {
String errmsg = "Cannot cancel: not involved in a transaction [dobj=" + this + "]";
throw new IllegalStateException(errmsg);
}
// if we're in a nested transaction, make a note that it is to be cancelled when all
// parties commit and decrement the nest count
if (_tcount > 0) {
_tcancelled = true;
_tcount
} else {
_tevent.cancel();
}
}
/**
* Removes this object from participation in any transaction in which it might be taking part.
*/
protected void clearTransaction ()
{
// sanity check
if (_tcount != 0) {
log.warning("Transaction cleared with non-zero nesting count", "dobj", this);
_tcount = 0;
}
// clear our transaction state
_tevent = null;
_tcancelled = false;
}
/**
* Called by derived instances when an attribute setter method was called.
*/
protected void requestAttributeChange (String name, Object value, Object oldValue)
{
requestAttributeChange(name, value, oldValue, Transport.DEFAULT);
}
/**
* Called by derived instances when an attribute setter method was called.
*/
protected void requestAttributeChange (
String name, Object value, Object oldValue, Transport transport)
{
// dispatch an attribute changed event
postEvent(new AttributeChangedEvent(_oid, name, value, oldValue, transport));
}
/**
* Called by derived instances when an element updater method was called.
*/
protected void requestElementUpdate (String name, int index, Object value, Object oldValue)
{
requestElementUpdate(name, index, value, oldValue, Transport.DEFAULT);
}
/**
* Called by derived instances when an element updater method was called.
*/
protected void requestElementUpdate (
String name, int index, Object value, Object oldValue, Transport transport)
{
// dispatch an attribute changed event
postEvent(new ElementUpdatedEvent(
_oid, name, value, oldValue, index, transport));
}
/**
* Calls by derived instances when an oid adder method was called.
*/
protected void requestOidAdd (String name, int oid)
{
// dispatch an object added event
postEvent(new ObjectAddedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when an oid remover method was called.
*/
protected void requestOidRemove (String name, int oid)
{
// dispatch an object removed event
postEvent(new ObjectRemovedEvent(_oid, name, oid));
}
/**
* Calls by derived instances when a set adder method was called.
*/
protected <T extends DSet.Entry> void requestEntryAdd (String name, DSet<T> set, T entry)
{
// if we're on the authoritative server, we update the set immediately
boolean alreadyApplied = false;
if (_omgr != null && _omgr.isManager(this)) {
set.add(entry);
alreadyApplied = true;
}
// dispatch an entry added event
postEvent(new EntryAddedEvent<T>(_oid, name, entry, alreadyApplied));
}
/**
* Calls by derived instances when a set remover method was called.
*/
protected <T extends DSet.Entry> void requestEntryRemove (
String name, DSet<T> set, Comparable<?> key)
{
// if we're on the authoritative server, we update the set immediately
T oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
oldEntry = set.removeKey(key);
if (oldEntry == null) {
log.warning("Requested to remove non-element", "set", name, "key", key,
new Exception());
}
}
// dispatch an entry removed event
postEvent(new EntryRemovedEvent<T>(_oid, name, key, oldEntry));
}
/**
* Calls by derived instances when a set updater method was called.
*/
protected <T extends DSet.Entry> void requestEntryUpdate (String name, DSet<T> set, T entry)
{
requestEntryUpdate(name, set, entry, Transport.DEFAULT);
}
/**
* Calls by derived instances when a set updater method was called.
*/
protected <T extends DSet.Entry> void requestEntryUpdate (
String name, DSet<T> set, T entry, Transport transport)
{
// if we're on the authoritative server, we update the set immediately
T oldEntry = null;
if (_omgr != null && _omgr.isManager(this)) {
oldEntry = set.update(entry);
if (oldEntry == null) {
log.warning("Set update had no old entry", "name", name, "entry", entry,
new Exception());
}
}
// dispatch an entry updated event
postEvent(new EntryUpdatedEvent<T>(_oid, name, entry, oldEntry, transport));
}
/**
* Returns the {@link Field} with the specified name or null if there is none such.
*/
protected final Field getField (String name)
{
int low = 0, high = _fields.length-1;
while (low <= high) {
int mid = (low + high) >> 1;
Field midVal = _fields[mid];
int cmp = midVal.getName().compareTo(name);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return midVal; // key found
}
}
return null; // key not found.
}
/**
* Returns the index of the identified listener, or -1 if not found.
*/
protected int getListenerIndex (ChangeListener listener)
{
if (_listeners == null) {
return -1;
}
for (int ii = 0, ll = _listeners.length; ii < ll; ii++) {
Object olistener = _listeners[ii];
if (olistener == listener || (olistener instanceof WeakListenerWrapper &&
((WeakListenerWrapper)olistener).ref.get() == listener)) {
return ii;
}
}
return -1;
}
/**
* A listener that wraps a weak reference to another listener.
*/
protected class WeakListenerWrapper
implements EventListener
{
/** The weak reference to our underlying listener. */
public final WeakReference<ChangeListener> ref;
/**
* Creates a new weak listener wrapper.
*/
public WeakListenerWrapper (ChangeListener listener)
{
ref = new WeakReference<ChangeListener>(listener);
}
// documentation inherited from interface EventListener
public void eventReceived (DEvent event)
{
ChangeListener listener = ref.get();
if (listener == null) {
ListUtil.clearRef(_listeners, this);
} else {
event.notifyListener(listener);
if (listener instanceof EventListener) {
((EventListener)listener).eventReceived(event);
}
}
}
}
/** Our object id. */
protected int _oid;
/** An array of our fields, sorted for efficient lookup. */
protected transient Field[] _fields;
/** A reference to our object manager. */
protected transient DObjectManager _omgr;
/** The entity that tells us if an event or subscription request should be allowed. */
protected transient AccessController _controller;
/** A list of outstanding locks. */
protected transient Object[] _locks;
/** Our subscribers list. */
protected transient Object[] _subs;
/** Our event listeners list. */
protected transient Object[] _listeners;
/** Our subscriber count. */
protected transient int _scount;
/** The compound event associated with our transaction, if we're currently in a transaction. */
protected transient CompoundEvent _tevent;
/** The nesting depth of our current transaction. */
protected transient int _tcount;
/** Whether or not our nested transaction has been cancelled. */
protected transient boolean _tcancelled;
/** Indicates whether we want to be destroyed when our last subscriber is removed. */
protected transient boolean _deathWish = false;
/** Any local attributes configured on this object or null. */
protected transient Object[] _locattrs = NO_ATTRS;
/** Maintains a mapping of sorted field arrays for each distributed object class. */
protected static Map<Class<?>, Field[]> _ftable = Maps.newHashMap();
/** Used to sort and search {@link #_fields}. */
protected static final Comparator<Field> FIELD_COMP = new Comparator<Field>() {
public int compare (Field f1, Field f2) {
return f1.getName().compareTo(f2.getName());
}
};
/** Simplifies code for objects that have no local attributes. */
protected static final Object[] NO_ATTRS = {};
}
|
// $Id: Invoker.java,v 1.12 2003/10/08 04:10:29 mdb Exp $
package com.threerings.presents.util;
import java.util.HashMap;
import java.util.Iterator;
import com.samskivert.util.Histogram;
import com.samskivert.util.LoopingThread;
import com.samskivert.util.Queue;
import com.samskivert.util.StringUtil;
import com.threerings.presents.Log;
import com.threerings.presents.server.PresentsDObjectMgr;
import com.threerings.presents.server.PresentsServer.Reporter;
import com.threerings.presents.server.PresentsServer;
/**
* The invoker is used to invoke self-contained units of code on an
* invoking thread. Each invoker is associated with its own thread and
* that thread is used to invoke all of the units posted to that invoker
* in the order in which they were posted. The invoker also provides a
* convenient mechanism for processing the result of an invocation back on
* the dobjmgr thread.
*
* <p> The invoker is a useful tool for services that need to block and
* therefore cannot be run on the distributed object thread. For example,
* a user of the Presents system might provide an invoker on which to run
* database queries.
*
* <p> Bear in mind that each invoker instance runs units on its own
* thread and care must be taken to ensure that code running on separate
* invokers properly synchronizes access to shared information. Where
* possible, complete isolation of the services provided by a particular
* invoker is desirable.
*/
public class Invoker extends LoopingThread
implements Reporter
{
/**
* The unit encapsulates a unit of executable code that will be run on
* the invoker thread. It also provides facilities for additional code
* to be run on the dobjmgr thread once the primary code has completed
* on the invoker thread.
*/
public static abstract class Unit implements Runnable
{
/**
* This method is called on the invoker thread and should be used
* to perform the primary function of the unit. It can return true
* to cause the <code>handleResult</code> method to be
* subsequently invoked on the dobjmgr thread (generally to allow
* the results of the invocation to be acted upon back in the
* context of the distributed object world) or false to indicate
* that no further processing should be performed.
*
* <p> Note that an invocation unit can do things like post events
* from the invoker thread (which includes modification of
* distributed object fields) and need not jump over to the
* dobjmgr thread to do so. However, it cannot <em>read</em>
* distributed object fields from the invoker thread. Any field
* values needed during the course of the invocation should be
* provided from the dobjmgr thread at the time that the
* invocation unit is created and posted.
*
* @return true if the <code>handleResult</code> method should be
* invoked on the dobjmgr thread, false if not.
*/
public abstract boolean invoke ();
/**
* Invocation unit implementations can implement this function to
* perform any post-unit-invocation processing back on the dobjmgr
* thread. It will be invoked if <code>invoke</code> returns true.
*/
public void handleResult ()
{
// do nothing by default
}
// we want to be a runnable to make the dobjmgr happy, but we'd
// like for invocation unit implementations to be able to put
// their result handling code into an aptly named method
public void run ()
{
handleResult();
}
}
/**
* Creates an invoker that will post results to the supplied
* distributed object manager.
*/
public Invoker (PresentsDObjectMgr omgr)
{
super("presents.Invoker");
_omgr = omgr;
if (PERF_TRACK) {
PresentsServer.registerReporter(this);
}
}
/**
* Posts a unit to this invoker for subsequent invocation on the
* invoker's thread.
*/
public void postUnit (Unit unit)
{
// simply append it to the queue
_queue.append(unit);
}
// documentation inherited
public void iterate ()
{
// pop the next item off of the queue
Unit unit = (Unit) _queue.get();
long start;
if (PERF_TRACK) {
start = System.currentTimeMillis();
_unitsRun++;
}
try {
if (unit.invoke()) {
// if it returned true, we post it to the dobjmgr
// thread to invoke the result processing
_omgr.postUnit(unit);
}
// track some performance metrics
if (PERF_TRACK) {
long duration = System.currentTimeMillis() - start;
Object key = unit.getClass();
Histogram histo = (Histogram)_tracker.get(key);
if (histo == null) {
// track in buckets of 50ms up to 500ms
_tracker.put(key, histo = new Histogram(0, 50, 10));
}
histo.addValue((int)duration);
// report long runners
if (duration > 500L) {
Log.warning("Invoker unit ran for '" + duration + "ms: " +
unit + "' (" + key + ").");
}
}
} catch (Exception e) {
Log.warning("Invocation unit failed [unit=" + unit + "].");
Log.logStackTrace(e);
}
}
/**
* Will do a sophisticated shutdown of both itself and the DObjectManager
* thread.
*/
public void shutdown ()
{
_queue.append(new ShutdownUnit());
}
// documentation inherited from interface
public void appendReport (StringBuffer buffer, long now, long sinceLast)
{
buffer.append("* presents.util.Invoker:\n");
buffer.append("- Units executed: ").append(_unitsRun).append("\n");
_unitsRun = 0;
for (Iterator iter = _tracker.keySet().iterator(); iter.hasNext(); ) {
Class key = (Class)iter.next();
Histogram histo = (Histogram)_tracker.get(key);
buffer.append(" ");
buffer.append(StringUtil.shortClassName(key)).append(": ");
buffer.append(histo.summarize()).append("\n");
histo.clear();
}
}
/**
* This unit gets posted back and forth between the invoker and DObjectMgr
* until both of their queues are empty and they can both be safely
* shutdown.
*/
protected class ShutdownUnit extends Unit
{
// run on the invoker thread
public boolean invoke ()
{
if (checkLoops()) {
return false;
// if the invoker queue is not empty, we put ourselves back on it
} else if (_queue.hasElements()) {
_loopCount++;
postUnit(this);
return false;
} else {
// the invoker is empty, let's go over to the omgr
_loopCount = 0;
_passCount++;
return true;
}
}
// run on the dobj thread
public void handleResult ()
{
if (checkLoops()) {
return;
// if the queue isn't empty, re-post
} else if (!_omgr.queueIsEmpty()) {
_loopCount++;
_omgr.postUnit(this);
// if the invoker still has stuff and we're still under the pass
// limit, go ahead and pass it back to the invoker
} else if (_queue.hasElements() && (_passCount < MAX_PASSES)) {
// pass the buck back to the invoker
_loopCount = 0;
postUnit(this);
} else {
// otherwise end it, and complain if we're ending it
// because of passes
if (_passCount >= MAX_PASSES) {
Log.warning("Shutdown Unit passed 50 times without " +
"finishing, shutting down harshly.");
}
doShutdown();
}
}
/**
* Check to make sure we haven't looped too many times.
*/
protected boolean checkLoops ()
{
if (_loopCount > MAX_LOOPS) {
Log.warning("Shutdown Unit looped on one thread 100 times " +
"without finishing, shutting down harshly.");
doShutdown();
return true;
}
return false;
}
/**
* Do the actual shutdown.
*/
protected void doShutdown ()
{
_omgr.harshShutdown(); // end the dobj thread
// end the invoker thread
postUnit(new Unit() {
public boolean invoke () {
_running = false;
return false;
}
});
}
/** The number of times we've been passed to the object manager. */
protected int _passCount = 0;
/** How many times we've looped on the thread we're currently on. */
protected int _loopCount = 0;
/** The maximum number of passes we allow before just ending things. */
protected static final int MAX_PASSES = 50;
/** The maximum number of loops we allow before just ending things. */
protected static final int MAX_LOOPS = 100;
}
/** The invoker's queue of units to be executed. */
protected Queue _queue = new Queue();
/** The object manager with which we're working. */
protected PresentsDObjectMgr _omgr;
/** Tracks the counts of invocations by unit's class. */
protected HashMap _tracker = new HashMap();
/** The total number of invoker units run since the last report. */
protected int _unitsRun;
/** Whether or not to track invoker unit performance. */
protected static final boolean PERF_TRACK = true;
}
|
package org.jaxen.util;
public class SelfAxisIterator extends SingleObjectIterator
{
public SelfAxisIterator(Object node)
{
super(node);
}
}
|
package org.apache.commons.digester;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogSource;
import org.apache.commons.logging.NoOpLog;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class Digester extends DefaultHandler {
/**
* Construct a new Digester with default properties.
*/
public Digester() {
super();
}
/**
* Construct a new Digester, allowing a SAXParser to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to
* James House (james@interobjective.com). This may help in places where
* you are able to load JAXP 1.1 classes yourself.
*/
public Digester(SAXParser parser) {
super();
this.parser = parser;
}
/**
* Construct a new Digester, allowing an XMLReader to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you
* have to configure namespace and validation support yourself, as these
* properties only affect the SAXParser and emtpy constructor.
*/
public Digester(XMLReader reader) {
super();
this.reader = reader;
}
/**
* The body text of the current element.
*/
protected StringBuffer bodyText = new StringBuffer();
/**
* The stack of body text string buffers for surrounding elements.
*/
protected ArrayStack bodyTexts = new ArrayStack();
/**
* The class loader to use for instantiating application objects.
* If not specified, the context class loader, or the class loader
* used to load Digester itself, is used, based on the value of the
* <code>useContextClassLoader</code> variable.
*/
protected ClassLoader classLoader = null;
/**
* Has this Digester been configured yet?
*/
protected boolean configured = false;
/**
* The URLs of DTDs that have been registered, keyed by the public
* identifier that corresponds.
*/
protected HashMap dtds = new HashMap();
/**
* The application-supplied error handler that is notified when parsing
* warnings, errors, or fatal errors occur.
*/
protected ErrorHandler errorHandler = null;
/**
* The SAXParserFactory that is created the first time we need it.
*/
protected static SAXParserFactory factory = null;
/**
* The Locator associated with our parser.
*/
protected Locator locator = null;
/**
* The current match pattern for nested element processing.
*/
protected String match = "";
/**
* Do we want a "namespace aware" parser?
*/
protected boolean namespaceAware = false;
/**
* Registered namespaces we are currently processing. The key is the
* namespace prefix that was declared in the document. The value is an
* ArrayStack of the namespace URIs this prefix has been mapped to --
* the top Stack element is the most current one. (This architecture
* is required because documents can declare nested uses of the same
* prefix for different Namespace URIs).
*/
protected HashMap namespaces = new HashMap();
/**
* The parameters stack being utilized by CallMethodRule and
* CallParamRule rules.
*/
protected ArrayStack params = new ArrayStack();
/**
* The SAXParser we will use to parse the input stream.
*/
protected SAXParser parser = null;
/**
* The public identifier of the DTD we are currently parsing under
* (if any).
*/
protected String publicId = null;
/**
* The XMLReader used to parse digester rules.
*/
protected XMLReader reader = null;
/**
* The "root" element of the stack (in other words, the last object
* that was popped.
*/
protected Object root = null;
/**
* The <code>Rules</code> implementation containing our collection of
* <code>Rule</code> instances and associated matching policy. If not
* established before the first rule is added, a default implementation
* will be provided.
*/
protected Rules rules = null;
/**
* The object stack being constructed.
*/
protected ArrayStack stack = new ArrayStack();
/**
* Do we want to use the Context ClassLoader when loading classes
* for instantiating new objects? Default is <code>false</code>.
*/
protected boolean useContextClassLoader = false;
/**
* Do we want to use a validating parser?
*/
protected boolean validating = false;
/**
* The Log to which all logging calls will be made. By default a NoOpLog
* is used, which means no output is done at all.
*/
protected Log log = new NoOpLog();
/**
* Return the currently mapped namespace URI for the specified prefix,
* if any; otherwise return <code>null</code>. These mappings come and
* go dynamically as the document is parsed.
*
* @param prefix Prefix to look up
*/
public String findNamespaceURI(String prefix) {
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null)
return (null);
try {
return ((String) stack.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the class loader to be used for instantiating application objects
* when required. This is determined based upon the following rules:
* <ul>
* <li>The class loader set by <code>setClassLoader()</code>, if any</li>
* <li>The thread context class loader, if it exists and the
* <code>useContextClassLoader</code> property is set to true</li>
* <li>The class loader used to load the Digester class itself.
* </ul>
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null)
return (this.classLoader);
if (this.useContextClassLoader) {
ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader != null)
return (classLoader);
}
return (this.getClass().getClassLoader());
}
/**
* Set the class loader to be used for instantiating application objects
* when required.
*
* @param classLoader The new class loader to use, or <code>null</code>
* to revert to the standard rules
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the current depth of the element stack.
*/
public int getCount() {
return (stack.size());
}
/**
* Return the name of the XML element that is currently being processed.
*/
public String getCurrentElementName() {
String elementName = match;
int lastSlash = elementName.lastIndexOf('/');
if (lastSlash >= 0)
elementName = elementName.substring(lastSlash + 1);
return (elementName);
}
/**
* Return the debugging detail level of our currently enabled logger.
*
* @deprecated Call getLogger() and use it's getLevel() method
*/
public int getDebug() {
return (log.getLevel());
}
/**
* Set the debugging detail level of our currently enabled logger.
*
* @param debug New debugging detail level (0=off, increasing integers
* for more detail)
*
* @deprecated Call getLogger() and use its setLevel() method
*/
public void setDebug(int debug) {
// Compute an appropriate level value
int level = Log.INFO;
if (debug >= 1) {
level = Log.DEBUG;
}
// Tell our Log to use the new level
log.setLevel(level);
}
/**
* Return the error handler for this Digester.
*/
public ErrorHandler getErrorHandler() {
return (this.errorHandler);
}
/**
* Set the error handler for this Digester.
*
* @param errorHandler The new error handler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the current Logger associated with this instance of the Digester
*/
public Log getLogger() {
return log;
}
/**
* Set the current logger for this Digester.
*/
public void setLogger(Log log) {
this.log = log;
}
/**
* Return the "namespace aware" flag for parsers we create.
*/
public boolean getNamespaceAware() {
return (this.namespaceAware);
}
/**
* Set the "namespace aware" flag for parsers we create.
*
* @param namespaceAware The new "namespace aware" flag
*/
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/**
* Return the public identifier of the DTD we are currently
* parsing under, if any.
*/
public String getPublicId() {
return (this.publicId);
}
/**
* Return the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*/
public String getRuleNamespaceURI() {
return (getRules().getNamespaceURI());
}
/**
* Set the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*
* @param ruleNamespaceURI Namespace URI that must match on all
* subsequently added rules, or <code>null</code> for matching
* regardless of the current namespace URI
*/
public void setRuleNamespaceURI(String ruleNamespaceURI) {
getRules().setNamespaceURI(ruleNamespaceURI);
}
/**
* Return the SAXParser we will use to parse the input stream. If there
* is a problem creating the parser, return <code>null</code>.
*/
public SAXParser getParser() {
// Return the parser we already created (if any)
if (parser != null)
return (parser);
// Create and return a new parser
synchronized (this) {
try {
if (factory == null)
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setValidating(validating);
parser = factory.newSAXParser();
return (parser);
} catch (Exception e) {
log.error("Digester.getParser: ", e);
return (null);
}
}
}
/**
* By setting the reader in the constructor, you can bypass JAXP and be able
* to use digester in Weblogic 6.0.
*/
public synchronized XMLReader getReader() {
if (reader == null) {
try {
reader = getParser().getXMLReader();
} catch (SAXException se) {
return null;
}
}
//set up the parse
reader.setContentHandler(this);
reader.setDTDHandler(this);
reader.setEntityResolver(this);
reader.setErrorHandler(this);
return reader;
}
/**
* Return the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy. If none has been
* established, a default implementation will be created and returned.
*/
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return (this.rules);
}
/**
* Set the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy.
*
* @param rules New Rules implementation
*/
public void setRules(Rules rules) {
this.rules = rules;
this.rules.setDigester(this);
}
/**
* Return the validating parser flag.
*/
public boolean getValidating() {
return (this.validating);
}
/**
* Set the validating parser flag. This must be called before
* <code>parse()</code> is called the first time.
*
* @param validating The new validating parser flag.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Return the boolean as to whether the context classloader should be used.
*/
public boolean getUseContextClassLoader() {
return useContextClassLoader;
}
/**
* Determine whether to use the Context ClassLoader (the one found by
* calling <code>Thread.currentThread().getContextClassLoader()</code>)
* to resolve/load classes that are defined in various rules. If not
* using Context ClassLoader, then the class-loading defaults to
* using the calling-class' ClassLoader.
*
* @param boolean determines whether to use Context ClassLoader.
*/
public void setUseContextClassLoader(boolean use) {
useContextClassLoader = use;
}
/**
* Process notification of character data received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void characters(char buffer[], int start, int length)
throws SAXException {
if (log.isInfoEnabled()) {
log.info("characters(" + new String(buffer, start, length) + ")");
}
bodyText.append(buffer, start, length);
}
/**
* Process notification of the end of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void endDocument() throws SAXException {
boolean info = log.isInfoEnabled();
if (info) {
log.info("endDocument()");
}
if (getCount() > 1 && info) {
log.info("endDocument(): " + getCount() + " elements left");
}
while (getCount() > 1)
pop();
// Fire "finish" events for all defined rules
Iterator rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = (Rule) rules.next();
try {
rule.finish();
} catch (Exception e) {
log.error("Finish event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log.error("Finish event threw exception", t);
throw createSAXException(t.getMessage());
}
}
// Perform final cleanup
clear();
}
/**
* Process notification of the end of an XML element being reached.
*
* @param uri - The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace processing is not
* being performed.
* @param localName - The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName - The qualified XML 1.0 name (with prefix), or the
* empty string if qualified names are not available.
* @exception SAXException if a parsing error is to be reported
*/
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
boolean info = log.isInfoEnabled();
boolean debug = log.isDebugEnabled();
if (info) {
log.info("endElement(" + namespaceURI + "," + localName +
"," + qName + ")");
log.info(" match='" + match + "'");
log.info(" bodyText='" + bodyText + "'");
}
// Fire "body" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString().trim();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug)
log.debug(" Fire body() for " + rule);
rule.body(bodyText);
} catch (Exception e) {
log.error("Body event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log.error("Body event threw exception", t);
throw createSAXException(t.getMessage());
}
}
} else {
if (info)
log.info(" No rules found matching '" + match + "'.");
}
// Recover the body text from the surrounding element
bodyText = (StringBuffer) bodyTexts.pop();
if (debug)
log.debug(" Popping body text '" + bodyText.toString() + "'");
// Fire "end" events for all relevant rules in reverse order
if (rules != null) {
for (int i = 0; i < rules.size(); i++) {
int j = (rules.size() - i) - 1;
try {
Rule rule = (Rule) rules.get(j);
if (debug)
log.debug(" Fire end() for " + rule);
rule.end();
} catch (Exception e) {
log.error("End event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log.error("End event threw exception", t);
throw createSAXException(t.getMessage());
}
}
}
// Recover the previous match expression
int slash = match.lastIndexOf('/');
if (slash >= 0)
match = match.substring(0, slash);
else
match = "";
}
/**
* Process notification that a namespace prefix is going out of scope.
*
* @param prefix Prefix that is going out of scope
*
* @exception SAXException if a parsing error is to be reported
*/
public void endPrefixMapping(String prefix) throws SAXException {
if (log.isInfoEnabled()) {
log.info("endPrefixMapping(" + prefix + ")");
}
// Deregister this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null)
return;
try {
stack.pop();
if (stack.empty())
namespaces.remove(prefix);
} catch (EmptyStackException e) {
throw createSAXException("endPrefixMapping popped too many times");
}
}
/**
* Process notification of ignorable whitespace received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void ignorableWhitespace(char buffer[], int start, int len)
throws SAXException {
if (log.isInfoEnabled()) {
log.info("ignorableWhitespace(" +
new String(buffer, start, len) + ")");
}
; // No processing required
}
/**
* Process notification of a processing instruction that was encountered.
*
* @param target The processing instruction target
* @param data The processing instruction data (if any)
*
* @exception SAXException if a parsing error is to be reported
*/
public void processingInstruction(String target, String data)
throws SAXException {
if (log.isInfoEnabled()) {
log.info("processingInstruction('" + target + "','" + data + "')");
}
; // No processing is required
}
/**
* Set the document locator associated with our parser.
*
* @param locator The new locator
*/
public void setDocumentLocator(Locator locator) {
if (log.isInfoEnabled()) {
log.info("setDocumentLocator(" + locator + ")");
}
this.locator = locator;
}
/**
* Process notification of a skipped entity.
*
* @param name Name of the skipped entity
*
* @exception SAXException if a parsing error is to be reported
*/
public void skippedEntity(String name) throws SAXException {
if (log.isInfoEnabled()) {
log.info("skippedEntity(" + name + ")");
}
; // No processing required
}
/**
* Process notification of the beginning of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void startDocument() throws SAXException {
if (log.isInfoEnabled()) {
log.info("startDocument()");
}
; // No processing required
}
/**
* Process notification of the start of an XML element being reached.
*
* @param uri The Namespace URI, or the empty string if the element
* has no Namespace URI or if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName The qualified name (with prefix), or the empty
* string if qualified names are not available.\
* @param list The attributes attached to the element. If there are
* no attributes, it shall be an empty Attributes object.
* @exception SAXException if a parsing error is to be reported
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
boolean info = log.isInfoEnabled();
boolean debug = log.isDebugEnabled();
if (info) {
log.info("startElement(" + namespaceURI + "," + localName + "," +
qName + ")");
}
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText);
if (debug) {
log.debug(" Pushing body text '" + bodyText.toString() + "'");
}
bodyText = new StringBuffer();
// Compute the current matching rule
StringBuffer sb = new StringBuffer(match);
if (match.length() > 0)
sb.append('/');
if ((localName == null) || (localName.length() < 1))
sb.append(qName);
else
sb.append(localName);
match = sb.toString();
if (info) {
log.info(" New match='" + match + "'");
}
// Fire "begin" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug) {
log.debug(" Fire begin() for " + rule);
}
rule.begin(list);
} catch (Exception e) {
log.error("Begin event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log.error("Begin event threw exception", t);
throw createSAXException(t.getMessage());
}
}
} else {
if (info) {
log.info(" No rules found matching '" + match + "'.");
}
}
}
/**
* Process notification that a namespace prefix is coming in to scope.
*
* @param prefix Prefix that is being declared
* @param namespaceURI Corresponding namespace URI being mapped to
*
* @exception SAXException if a parsing error is to be reported
*/
public void startPrefixMapping(String prefix, String namespaceURI)
throws SAXException {
if (log.isInfoEnabled()) {
log.info("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
}
// Register this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
stack = new ArrayStack();
namespaces.put(prefix, stack);
}
stack.push(namespaceURI);
}
/**
* Receive notification of a notation declaration event.
*
* @param name The notation name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
*/
public void notationDecl(String name, String publicId, String systemId) {
if (log.isInfoEnabled()) {
log.info("notationDecl(" + name + "," + publicId + "," +
systemId + ")");
}
}
/**
* Receive notification of an unparsed entity declaration event.
*
* @param name The unparsed entity name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
* @param notation The name of the associated notation
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notation) {
if (log.isInfoEnabled()) {
log.info("unparsedEntityDecl(" + name + "," + publicId + "," +
systemId + "," + notation + ")");
}
}
/**
* Resolve the requested external entity.
*
* @param publicId The public identifier of the entity being referenced
* @param systemId The system identifier of the entity being referenced
*
* @exception SAXException if a parsing exception occurs
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
log.info("resolveEntity('" + publicId + "', '" + systemId + "')");
this.publicId = publicId;
// Has this system identifier been registered?
String dtdURL = null;
if (publicId != null)
dtdURL = (String) dtds.get(publicId);
if (dtdURL == null) {
log.info(" Not registered, use system identifier");
return (null);
}
// Return an input source to our alternative URL
log.info(" Resolving to alternate DTD '" + dtdURL + "'");
try {
URL url = new URL(dtdURL);
InputStream stream = url.openStream();
return (new InputSource(stream));
} catch (Exception e) {
throw createSAXException(e);
}
}
/**
* Forward notification of a parsing error to the application supplied
* error handler (if any).
*
* @param exception The error information
*
* @exception SAXException if a parsing exception occurs
*/
public void error(SAXParseException exception) throws SAXException {
log.error("Parse Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.error(exception);
}
/**
* Forward notification of a fatal parsing error to the application
* supplied error handler (if any).
*
* @param exception The fatal error information
*
* @exception SAXException if a parsing exception occurs
*/
public void fatalError(SAXParseException exception) throws SAXException {
log.error("Parse Fatal Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.fatalError(exception);
}
/**
* Forward notification of a parse warning to the application supplied
* error handler (if any).
*
* @param exception The warning information
*
* @exception SAXException if a parsing exception occurs
*/
public void warning(SAXParseException exception) throws SAXException {
log.error("Parse Warning at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.warning(exception);
}
/**
* Parse the content of the specified file using this Digester. Returns
* the root element from the object stack (if any).
*
* @param file File containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(File file) throws IOException, SAXException {
configure();
getReader().parse(new InputSource(new FileReader(file)));
return (root);
}
/**
* Parse the content of the specified input source using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input source containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputSource input) throws IOException, SAXException {
configure();
getReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input stream using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input stream containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputStream input) throws IOException, SAXException {
configure();
getReader().parse(new InputSource(input));
return (root);
}
/**
* Parse the content of the specified reader using this Digester.
* Returns the root element from the object stack (if any).
*
* @param reader Reader containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(Reader reader) throws IOException, SAXException {
configure();
getReader().parse(new InputSource(reader));
return (root);
}
/**
* Parse the content of the specified URI using this Digester.
* Returns the root element from the object stack (if any).
*
* @param uri URI containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(String uri) throws IOException, SAXException {
configure();
getReader().parse(uri);
return (root);
}
/**
* Register the specified DTD URL for the specified public identifier.
* This must be called before the first call to <code>parse()</code>.
*
* @param publicId Public identifier of the DTD to be resolved
* @param dtdURL The URL to use for reading this DTD
*/
public void register(String publicId, String dtdURL) {
log.info("register('" + publicId + "', '" + dtdURL + "'");
dtds.put(publicId, dtdURL);
}
/**
* Register a new Rule matching the specified pattern.
*
* @param pattern Element matching pattern
* @param rule Rule to be registered
*/
public void addRule(String pattern, Rule rule) {
getRules().add(pattern, rule);
}
/**
* Register a set of Rule instances defined in a RuleSet.
*
* @param ruleSet The RuleSet instance to configure from
*/
public void addRuleSet(RuleSet ruleSet) {
String oldNamespaceURI = getRuleNamespaceURI();
String newNamespaceURI = ruleSet.getNamespaceURI();
if (log.isDebugEnabled()) {
if (newNamespaceURI == null)
log.debug("addRuleSet() with no namespace URI");
else
log.debug("addRuleSet() with namespace URI " + newNamespaceURI);
}
setRuleNamespaceURI(newNamespaceURI);
ruleSet.addRuleInstances(this);
setRuleNamespaceURI(oldNamespaceURI);
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addBeanPropertySetter(String pattern) {
addRule(pattern,
new BeanPropertySetterRule(this));
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param propertyName Name of property to set
*/
public void addBeanPropertySetter(String pattern,
String propertyName) {
addRule(pattern,
new BeanPropertySetterRule(this, propertyName));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount) {
addRule(pattern,
new CallMethodRule(this, methodName, paramCount));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes Set of Java class names for the types
* of the expected parameters
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, String paramTypes[]) {
addRule(pattern,
new CallMethodRule(this, methodName,
paramCount, paramTypes));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes The Java class names of the arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, Class paramTypes[]) {
addRule(pattern,
new CallMethodRule(this, methodName,
paramCount, paramTypes));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the body of this element)
*/
public void addCallParam(String pattern, int paramIndex) {
addRule(pattern,
new CallParamRule(this, paramIndex));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the specified attribute)
* @param attributeName Attribute whose value is used as the
* parameter value
*/
public void addCallParam(String pattern, int paramIndex,
String attributeName) {
addRule(pattern,
new CallParamRule(this, paramIndex, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
*/
public void addFactoryCreate(String pattern, String className) {
addRule(pattern,
new FactoryCreateRule(this, className));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
*/
public void addFactoryCreate(String pattern, Class clazz) {
addRule(pattern,
new FactoryCreateRule(this, clazz));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
*/
public void addFactoryCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new FactoryCreateRule(this, className, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
*/
public void addFactoryCreate(String pattern, Class clazz,
String attributeName) {
addRule(pattern,
new FactoryCreateRule(this, clazz, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param creationFactory Previously instantiated ObjectCreationFactory
* to be utilized
*/
public void addFactoryCreate(String pattern,
ObjectCreationFactory creationFactory) {
creationFactory.setDigester(this);
addRule(pattern,
new FactoryCreateRule(this, creationFactory));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name to be created
*/
public void addObjectCreate(String pattern, String className) {
addRule(pattern,
new ObjectCreateRule(this, className));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class to be created
*/
public void addObjectCreate(String pattern, Class clazz) {
addRule(pattern,
new ObjectCreateRule(this, clazz));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Default Java class name to be created
* @param attributeName Attribute name that optionally overrides
* the default Java class name to be created
*/
public void addObjectCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(this, className, attributeName));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Default Java class to be created
* @param attributeName Attribute name that optionally overrides
* the default Java class name to be created
*/
public void addObjectCreate(String pattern, Class clazz,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(this, clazz, attributeName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetNext(String pattern, String methodName) {
addRule(pattern,
new SetNextRule(this, methodName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetNext(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetNextRule(this, methodName, paramType));
}
/**
* Add a "set properties" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addSetProperties(String pattern) {
addRule(pattern,
new SetPropertiesRule(this));
}
/**
* Add a "set property" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param name Attribute name containing the property name to be set
* @param value Attribute name containing the property value to set
*/
public void addSetProperty(String pattern, String name, String value) {
addRule(pattern,
new SetPropertyRule(this, name, value));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetTop(String pattern, String methodName) {
addRule(pattern,
new SetTopRule(this, methodName));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetTop(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetTopRule(this, methodName, paramType));
}
/**
* Clear the current contents of the object stack.
*/
public void clear() {
match = "";
bodyTexts.clear();
params.clear();
publicId = null;
stack.clear();
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object peek() {
try {
return (stack.peek());
} catch (EmptyStackException e) {
log.info("Empty stack (returning null)");
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
public Object peek(int n) {
try {
return (stack.peek(n));
} catch (EmptyStackException e) {
log.info("Empty stack (returning null)");
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object pop() {
try {
return (stack.pop());
} catch (EmptyStackException e) {
log.info("Empty stack (returning null)");
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
public void push(Object object) {
if (stack.size() == 0)
root = object;
stack.push(object);
}
/**
* Provide a hook for lazy configuration of this <code>Digester</code>
* instance. The default implementation does nothing, but subclasses
* can override as needed.
*/
protected void configure() {
// Do not configure more than once
if (configured)
return;
// Perform lazy configuration as needed
; // Nothing required by default
// Set the configuration flag to avoid repeating
configured = true;
}
/**
* Return the set of DTD URL registrations, keyed by public identifier.
*/
Map getRegistrations() {
return (dtds);
}
/**
* Return the set of rules that apply to the specified match position.
* The selected rules are those that match exactly, or those rules
* that specify a suffix match and the tail of the rule matches the
* current match position. Exact matches have precedence over
* suffix matches, then (among suffix matches) the longest match
* is preferred.
*
* @param match The current match position
*
* @deprecated Call <code>match()</code> on the <code>Rules</code>
* implementation returned by <code>getRules()</code>
*/
List getRules(String match) {
return (getRules().match(match));
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
Object peekParams() {
try {
return (params.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
Object peekParams(int n) {
try {
return (params.peek(n));
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
Object popParams() {
try {
return (params.pop());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
void pushParams(Object object) {
params.push(object);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message, Exception e) {
if (locator != null) {
String error = "Error at (" + locator.getLineNumber() + ", "
+ locator.getColumnNumber() + ": " + message;
if (e != null) {
return new SAXParseException(error, locator, e);
} else {
return new SAXParseException(error, locator);
}
}
log.error("No Locator!");
if (e != null) {
return new SAXException(message, e);
} else {
return new SAXException(message);
}
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(Exception e) {
return createSAXException(e.getMessage(), e);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message) {
return createSAXException(message, null);
}
}
|
package visualizer;
import java.awt.Color;
import java.awt.Paint;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import edu.uci.ics.jung.graph.util.Pair;
public class Edge {
private float weight;
private Pair<Vertex> endpointsSave;
public Edge() {
this(0.f);
}
public Edge(float weight) {
this.weight = weight;
}
public static Factory<Edge> getFactory() {
return new Factory<Edge>() {
public Edge create() {
return new Edge();
}
};
}
public static Transformer<Edge, Paint> getColorTransformer() {
// We only plot edges with strong weight
return new Transformer<Edge, Paint>() {
public Paint transform(Edge i) {
return Color.BLACK;
}
};
}
public float getWeight() {
return weight;
}
public void setWeight(float floatValue) {
weight = floatValue;
}
public Pair<Vertex> getEndpointsSave() {
return endpointsSave;
}
public void setEndpointsSave(Pair<Vertex> endpointsSave) {
this.endpointsSave = endpointsSave;
}
}
|
package org.orbeon.oxf.xforms;
import org.dom4j.Element;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsControlFactory;
import org.orbeon.oxf.xforms.control.XFormsSingleNodeControl;
import org.orbeon.oxf.xforms.control.controls.*;
import org.orbeon.oxf.xforms.event.XFormsEventTarget;
import org.orbeon.oxf.xforms.event.events.XFormsDeselectEvent;
import org.orbeon.oxf.xforms.event.events.XFormsSelectEvent;
import org.orbeon.oxf.xforms.processor.XFormsServer;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.saxon.om.NodeInfo;
import org.xml.sax.Locator;
import java.util.*;
/**
* Represents all this XForms containing document controls and the context in which they operate.
*/
public class XFormsControls {
private Locator locator;
private boolean initialized;
private ControlsState initialControlsState;
private ControlsState currentControlsState;
private SwitchState initialSwitchState;
private SwitchState currentSwitchState;
private DialogState initialDialogState;
private DialogState currentDialogState;
private boolean dirtySinceLastRequest;
private XFormsContainingDocument containingDocument;
private XFormsContextStack contextStack;
//private Map eventsMap;// TODO: this must go into XFormsStaticState
private Map constantItems;
// private Map
public static final Map groupingControls = new HashMap();
private static final Map valueControls = new HashMap();
private static final Map noValueControls = new HashMap();
private static final Map leafControls = new HashMap();
private static final Map actualControls = new HashMap();
public static final Map mandatorySingleNodeControls = new HashMap();
private static final Map optionalSingleNodeControls = new HashMap();
public static final Map noSingleNodeControls = new HashMap();
public static final Map mandatoryNodesetControls = new HashMap();
public static final Map noNodesetControls = new HashMap();
public static final Map singleNodeOrValueControls = new HashMap();
static {
groupingControls.put("group", "");
groupingControls.put("repeat", "");
groupingControls.put("switch", "");
groupingControls.put("case", "");
groupingControls.put("dialog", "");
valueControls.put("input", "");
valueControls.put("secret", "");
valueControls.put("textarea", "");
valueControls.put("output", "");
valueControls.put("upload", "");
valueControls.put("range", "");
valueControls.put("select", "");
valueControls.put("select1", "");
valueControls.put("attribute", "");// xxforms:attribute extension
noValueControls.put("submit", "");
noValueControls.put("trigger", "");
leafControls.putAll(valueControls);
leafControls.putAll(noValueControls);
actualControls.putAll(groupingControls);
actualControls.putAll(leafControls);
mandatorySingleNodeControls.putAll(valueControls);
mandatorySingleNodeControls.remove("output");
mandatorySingleNodeControls.put("filename", "");
mandatorySingleNodeControls.put("mediatype", "");
mandatorySingleNodeControls.put("setvalue", "");
singleNodeOrValueControls.put("output", "");
optionalSingleNodeControls.putAll(noValueControls);
optionalSingleNodeControls.put("output", ""); // can have @value attribute
optionalSingleNodeControls.put("value", ""); // can have inline text
optionalSingleNodeControls.put("label", ""); // can have linking or inline text
optionalSingleNodeControls.put("help", ""); // can have linking or inline text
optionalSingleNodeControls.put("hint", ""); // can have linking or inline text
optionalSingleNodeControls.put("alert", ""); // can have linking or inline text
optionalSingleNodeControls.put("copy", "");
optionalSingleNodeControls.put("load", ""); // can have linking
optionalSingleNodeControls.put("message", ""); // can have linking or inline text
optionalSingleNodeControls.put("group", "");
optionalSingleNodeControls.put("switch", "");
noSingleNodeControls.put("choices", "");
noSingleNodeControls.put("item", "");
noSingleNodeControls.put("case", "");
noSingleNodeControls.put("toggle", "");
mandatoryNodesetControls.put("repeat", "");
mandatoryNodesetControls.put("itemset", "");
mandatoryNodesetControls.put("delete", "");
noNodesetControls.putAll(mandatorySingleNodeControls);
noNodesetControls.putAll(optionalSingleNodeControls);
noNodesetControls.putAll(noSingleNodeControls);
}
public XFormsControls(XFormsContainingDocument containingDocument, XFormsStaticState xformsStaticState, Element repeatIndexesElement) {
this.containingDocument = containingDocument;
this.contextStack = new XFormsContextStack(containingDocument);
// Perform minimal initialization
if (xformsStaticState != null) {
// Set default repeat index information only
final ControlsState result = new ControlsState();
result.setDefaultRepeatIdToIndex(xformsStaticState.getDefaultRepeatIdToIndex());
initialControlsState = result;
currentControlsState = initialControlsState;
// Set incoming repeat index state if any
setRepeatIndexState(repeatIndexesElement);
}
}
public boolean isDirtySinceLastRequest() {
return dirtySinceLastRequest;
}
public void markDirtySinceLastRequest() {
dirtySinceLastRequest = true;
if (this.currentControlsState != null)// can be null for legacy XForms engine
this.currentControlsState.markDirty();
}
/**
* Returns whether there is any event handler registered anywhere in the controls for the given event name.
*
* @param eventName event name, like xforms-value-changed
* @return true if there is a handler, false otherwise
*/
public boolean hasHandlerForEvent(String eventName) {
return containingDocument.getStaticState().getEventNamesMap().get(eventName) != null;
}
/**
* Initialize the controls if needed. This is called upon initial creation of the engine OR when new exernal events
* arrive.
*
* TODO: this is called in XFormsContainingDocument.prepareForExternalEventsSequence() but it is not really an
* initialization in that case.
*
* @param pipelineContext current PipelineContext
*/
public void initialize(PipelineContext pipelineContext) {
initializeState(pipelineContext, null, null, false);
}
/**
* Initialize the controls if needed, passing initial state information. This is called if the state of the engine
* needs to be rebuilt.
*
* @param pipelineContext current PipelineContext
* @param divsElement current div elements, or null
* @param repeatIndexesElement current repeat indexes, or null
*/
public void initializeState(PipelineContext pipelineContext, Element divsElement, Element repeatIndexesElement, boolean evaluateItemsets) {
final XFormsStaticState staticState = containingDocument.getStaticState();
if (staticState != null && staticState.getControlsDocument() != null) {
if (initialized) {
// Use existing controls state
initialControlsState = currentControlsState;
initialSwitchState = currentSwitchState;
initialDialogState = currentDialogState;
} else {
// Build controls state
// Get initial controls state information
initialControlsState = buildControlsState(pipelineContext, evaluateItemsets);
currentControlsState = initialControlsState;
initialSwitchState = new SwitchState(initialControlsState.getSwitchIdToSelectedCaseIdMap());
currentSwitchState = initialSwitchState;
initialDialogState = new DialogState(initialControlsState.getDialogIdToVisibleMap());
currentDialogState = initialDialogState;
// Set switch state if necessary
if (divsElement != null) {
for (Iterator i = divsElement.elements().iterator(); i.hasNext();) {
final Element divElement = (Element) i.next();
final String dialogId = divElement.attributeValue("dialog-id");
final boolean isShow;
{
final String visibilityString = divElement.attributeValue("visibility");
isShow = "visible".equals(visibilityString);
}
if (dialogId != null) {
// xxforms:dialog
final String neighbor = divElement.attributeValue("neighbor");
final boolean constrainToViewport = "true".equals(divElement.attributeValue("constrain"));
currentDialogState.showHide(dialogId, isShow, isShow ? neighbor : null, constrainToViewport);
} else {
// xforms:switch/xforms:case
final String switchId = divElement.attributeValue("switch-id");
final String caseId = divElement.attributeValue("case-id");
currentSwitchState.initializeState(switchId, caseId, isShow);
}
}
}
// Handle repeat indexes if needed
final boolean hasRepeat = staticState.hasControlByName("repeat");
if (hasRepeat) {
// Set default repeat index information
initialControlsState.setDefaultRepeatIdToIndex(containingDocument.getStaticState().getDefaultRepeatIdToIndex());
// Set external updates
setRepeatIndexState(repeatIndexesElement);
// Adjust repeat indexes
XFormsIndexUtils.adjustIndexes(initialControlsState);
}
}
// We are now clean
containingDocument.markCleanSinceLastRequest();
dirtySinceLastRequest = false;
initialControlsState.dirty = false;
}
contextStack.resetBindingContext(pipelineContext);// not sure we actually need to do this
initialized = true;
}
private void setRepeatIndexState(Element repeatIndexesElement) {
if (repeatIndexesElement != null) {
for (Iterator i = repeatIndexesElement.elements().iterator(); i.hasNext();) {
final Element repeatIndexElement = (Element) i.next();
final String repeatId = repeatIndexElement.attributeValue("id");
final String index = repeatIndexElement.attributeValue("index");
initialControlsState.updateRepeatIndex(repeatId, Integer.parseInt(index));
}
}
}
public XFormsContainingDocument getContainingDocument() {
return containingDocument;
}
public XFormsContextStack getContextStack() {
return contextStack;
}
public static boolean isValueControl(String controlName) {
return valueControls.get(controlName) != null;
}
public static boolean isGroupingControl(String controlName) {
return groupingControls.get(controlName) != null;
}
public static boolean isLeafControl(String controlName) {
return leafControls.get(controlName) != null;
}
public static boolean isActualControl(String controlName) {
return actualControls.get(controlName) != null;
}
/**
* For the given control id and the current binding, try to find an effective control id.
*
* @param caseId a control id
* @return an effective control id if possible
*/
public String findEffectiveControlId(String caseId) {
return getCurrentControlsState().findEffectiveControlId(caseId);
}
private ControlsState buildControlsState(final PipelineContext pipelineContext, final boolean evaluateItemsets) {
final long startTime;
if (XFormsServer.logger.isDebugEnabled()) {
containingDocument.logDebug("controls", "start building");
startTime = System.currentTimeMillis();
} else {
startTime = 0;
}
containingDocument.startHandleOperation();
final ControlsState result = new ControlsState();
final XFormsControl rootXFormsControl = new RootControl(containingDocument);// this is temporary and won't be stored
final Map idsToXFormsControls = new HashMap();
final Map switchIdToSelectedCaseIdMap = new HashMap();
final Map dialogIdToVisibleMap = new HashMap();
visitAllControlsHandleRepeat(pipelineContext, new XFormsControls.ControlElementVisitorListener() {
private XFormsControl currentControlsContainer = rootXFormsControl;
public boolean startVisitControl(Element controlElement, String effectiveControlId) {
if (effectiveControlId == null)
throw new ValidationException("Control element doesn't have an id", new ExtendedLocationData((LocationData) controlElement.getData(),
"analyzing control element", controlElement));
final String controlName = controlElement.getName();
// Create XFormsControl with basic information
final XFormsControl xformsControl = XFormsControlFactory.createXFormsControl(containingDocument, currentControlsContainer, controlElement, controlName, effectiveControlId);
idsToXFormsControls.put(effectiveControlId, xformsControl);
// Control type-specific handling
{
if (controlName.equals("case")) {
// Handle xforms:case
if (!(currentControlsContainer.getName().equals("switch")))
throw new ValidationException("xforms:case with id '" + effectiveControlId + "' is not directly within an xforms:switch container.", xformsControl.getLocationData());
final String switchId = currentControlsContainer.getEffectiveId();
if (switchIdToSelectedCaseIdMap.get(switchId) == null) {
// If case is not already selected for this switch and there is a select attribute, set it
final String selectedAttribute = controlElement.attributeValue("selected");
if ("true".equals(selectedAttribute))
switchIdToSelectedCaseIdMap.put(switchId, effectiveControlId);
}
} else if (controlName.equals("dialog")) {
// Handle xxforms:dialog
// TODO: Handle initial visibility. Do this here?
// final XXFormsDialogControl dialogControl = (XXFormsDialogControl) xformsControl;
dialogIdToVisibleMap.put(effectiveControlId, new DialogState.DialogInfo(false, null, false));
} else if (xformsControl instanceof XFormsSelectControl || xformsControl instanceof XFormsSelect1Control) {
// Handle xforms:itemset
final XFormsSelect1Control select1Control = ((XFormsSelect1Control) xformsControl);
// Evaluate itemsets only if specified (case of restoring dynamic state)
if (evaluateItemsets)
select1Control.getItemset(pipelineContext, false);
} else if (xformsControl instanceof XFormsUploadControl) {
// Handle xforms:upload
result.addUploadControl((XFormsUploadControl) xformsControl);
} else if (xformsControl instanceof XXFormsAttributeControl) {
// Handle xxforms:attribute
result.addAttributeControl((XXFormsAttributeControl) xformsControl);
}
}
// Set current binding for control element
final XFormsContextStack.BindingContext currentBindingContext = contextStack.getCurrentBindingContext();
xformsControl.setBindingContext(currentBindingContext);
// Add to current controls container
currentControlsContainer.addChild(xformsControl);
// Current grouping control becomes the current controls container
if (isGroupingControl(controlName)) {
currentControlsContainer = xformsControl;
}
return true;
}
public boolean endVisitControl(Element controlElement, String effectiveControlId) {
final String controlName = controlElement.getName();
if (isGroupingControl(controlName)) {
// Handle grouping controls
if (controlName.equals("switch")) {
// Handle xforms:switch
if (switchIdToSelectedCaseIdMap.get(effectiveControlId) == null) {
// No case was selected, select first case id
final List children = currentControlsContainer.getChildren();
if (children != null && children.size() > 0)
switchIdToSelectedCaseIdMap.put(effectiveControlId, ((XFormsControl) children.get(0)).getEffectiveId());
}
} else if (controlName.equals("repeat")) {
// Handle xforms:repeat
// Store number of repeat iterations for the effective id
final List children = currentControlsContainer.getChildren();
if (children == null || children.size() == 0) {
// Current index is 0
result.setRepeatIterations(effectiveControlId, 0);
} else {
// Number of iterations is number of children
result.setRepeatIterations(effectiveControlId, children.size());
}
}
// Go back up to parent
currentControlsContainer = currentControlsContainer.getParent();
}
return true;
}
public void startRepeatIteration(int iteration, String effectiveIterationId) {
final XFormsControl repeatIterationControl = new RepeatIterationControl(containingDocument, currentControlsContainer, iteration, effectiveIterationId);
idsToXFormsControls.put(effectiveIterationId, repeatIterationControl);
currentControlsContainer.addChild(repeatIterationControl);
currentControlsContainer = repeatIterationControl;
// Set current binding for control
final XFormsContextStack.BindingContext currentBindingContext = contextStack.getCurrentBindingContext();
repeatIterationControl.setBindingContext(currentBindingContext);
}
public void endRepeatIteration(int iteration) {
currentControlsContainer = currentControlsContainer.getParent();
}
});
// Make it so that all the root XFormsControl don't have a parent
final List rootChildren = rootXFormsControl.getChildren();
if (rootChildren != null) {
for (Iterator i = rootChildren.iterator(); i.hasNext();) {
final XFormsControl currentXFormsControl = (XFormsControl) i.next();
currentXFormsControl.detach();
}
}
result.setChildren(rootChildren);
result.setIdsToXFormsControls(idsToXFormsControls);
result.setSwitchIdToSelectedCaseIdMap(switchIdToSelectedCaseIdMap);
result.setDialogIdToVisibleMap(dialogIdToVisibleMap);
containingDocument.endHandleOperation();
if (XFormsServer.logger.isDebugEnabled()) {
containingDocument.logDebug("controls", "end building", new String[] { "time (ms)", Long.toString((System.currentTimeMillis() - startTime)) });
}
return result;
}
/**
* Evaluate all the controls if needed. Should be used before output initial XHTML and before computing differences
* in XFormsServer.
*
* @param pipelineContext current PipelineContext
*/
public void evaluateAllControlsIfNeeded(PipelineContext pipelineContext) {
final long startTime;
if (XFormsServer.logger.isDebugEnabled()) {
containingDocument.logDebug("controls", "start evaluating");
startTime = System.currentTimeMillis();
} else {
startTime = 0;
}
final Map idsToXFormsControls = getCurrentControlsState().getIdsToXFormsControls();
// Evaluate all controls
for (Iterator i = idsToXFormsControls.entrySet().iterator(); i.hasNext();) {
final Map.Entry currentEntry = (Map.Entry) i.next();
final XFormsControl currentControl = (XFormsControl) currentEntry.getValue();
currentControl.evaluateIfNeeded(pipelineContext);
}
if (XFormsServer.logger.isDebugEnabled()) {
containingDocument.logDebug("controls", "end evaluating",
new String[] { "time (ms)", Long.toString(System.currentTimeMillis() - startTime)});
}
}
/**
* Get the ControlsState computed in the initialize() method.
*/
public ControlsState getInitialControlsState() {
return initialControlsState;
}
/**
* Get the last computed ControlsState.
*/
public ControlsState getCurrentControlsState() {
return currentControlsState;
}
/**
* Get the SwitchState computed in the initialize() method.
*/
public SwitchState getInitialSwitchState() {
return initialSwitchState;
}
/**
* Get the last computed SwitchState.
*/
public SwitchState getCurrentSwitchState() {
return currentSwitchState;
}
public DialogState getInitialDialogState() {
return initialDialogState;
}
public DialogState getCurrentDialogState() {
return currentDialogState;
}
/**
* Activate a switch case by case id.
*
* @param pipelineContext current PipelineContext
* @param caseId case id to activate
*/
public void activateCase(PipelineContext pipelineContext, String caseId) {
if (initialSwitchState == currentSwitchState)
currentSwitchState = new SwitchState(new HashMap(initialSwitchState.getSwitchIdToSelectedCaseIdMap()));
// TODO: if switch state changes AND we optimize relevance, then mark controls as dirty
getCurrentSwitchState().updateSwitchInfo(pipelineContext, containingDocument, getCurrentControlsState(), caseId);
containingDocument.markDirtySinceLastRequest();
}
public void showHideDialog(String dialogId, boolean show, String neighbor, boolean constrainToViewport) {
// Make sure the id refers to an existing xxforms:dialog
final Object object = getObjectById(dialogId);
if (object == null || !(object instanceof XXFormsDialogControl))
return;
// Update state
if (initialDialogState == currentDialogState)
currentDialogState = new DialogState(new HashMap(initialDialogState.getDialogIdToVisibleMap()));
currentDialogState.showHide(dialogId, show, neighbor, constrainToViewport);
containingDocument.markDirtySinceLastRequest();
}
/**
* Rebuild the current controls state information if needed.
*/
public boolean rebuildCurrentControlsStateIfNeeded(PipelineContext pipelineContext) {
if (!initialized) {
return false;
} else {
// This is the regular case
// Don't do anything if we are clean
if (!currentControlsState.isDirty())
return false;
// Rebuild
rebuildCurrentControlsState(pipelineContext);
// Everything is clean
initialControlsState.dirty = false;
currentControlsState.dirty = false;
return true;
}
}
/**
* Rebuild the current controls state information.
*/
public void rebuildCurrentControlsState(PipelineContext pipelineContext) {
// If we haven't been initialized yet, don't do anything
if (!initialized)
return;
// Remember current state
final ControlsState currentControlsState = this.currentControlsState;
// Create new controls state
final ControlsState result = buildControlsState(pipelineContext, false);
// Transfer some of the previous information
final Map currentRepeatIdToIndex = currentControlsState.getRepeatIdToIndex();
if (currentRepeatIdToIndex.size() != 0) {
// Keep repeat index information
result.setRepeatIdToIndex(currentRepeatIdToIndex);
// Adjust repeat indexes if necessary
XFormsIndexUtils.adjustIndexes(result);
}
// Update xforms;switch information: use new values, except where old values are available
final Map oldSwitchIdToSelectedCaseIdMap = getCurrentSwitchState().getSwitchIdToSelectedCaseIdMap();
final Map newSwitchIdToSelectedCaseIdMap = result.getSwitchIdToSelectedCaseIdMap();
{
for (Iterator i = newSwitchIdToSelectedCaseIdMap.entrySet().iterator(); i.hasNext();) {
final Map.Entry entry = (Map.Entry) i.next();
final String switchId = (String) entry.getKey();
// Keep old switch state
final String oldSelectedCaseId = (String) oldSwitchIdToSelectedCaseIdMap.get(switchId);
if (oldSelectedCaseId != null) {
entry.setValue(oldSelectedCaseId);
}
}
this.currentSwitchState = new SwitchState(newSwitchIdToSelectedCaseIdMap);
}
// Update xxforms:dialog information
// NOP!
// Update current state
this.currentControlsState = result;
// Handle relevance of controls that are no longer bound to instance data nodes
final Map[] eventsToDispatch = new Map[] { currentControlsState.getEventsToDispatch() } ;
findSpecialRelevanceChanges(currentControlsState.getChildren(), result.getChildren(), eventsToDispatch);
this.currentControlsState.setEventsToDispatch(eventsToDispatch[0]);
}
/**
* Perform a refresh of the controls for a given model
*/
// public void refreshForModel(final PipelineContext pipelineContext, final XFormsModel model) {
// // NOP
/**
* Return the current repeat index for the given xforms:repeat id, -1 if the id is not found.
*/
public int getRepeatIdIndex(String repeatId) {
final Map repeatIdToIndex = currentControlsState.getRepeatIdToIndex();
final Integer currentIndex = (Integer) repeatIdToIndex.get(repeatId);
if (currentIndex != null) {
return currentIndex.intValue();
} else {
// If the controls are not initialized, then we give the caller a chance and return 0. This will make sure
// that index() used in a calculate MIP will return something during the recalculate at the end of
// xforms-model-construct, instead of throwing an exception. Ideally, we should still return -1 if there is
// no xforms:repeat with the id provided.
return (initialized) ? -1 : 0;
}
}
public Locator getLocator() {
return locator;
}
public void setLocator(Locator locator) {
this.locator = locator;
}
/**
* Get the object with the id specified, null if not found.
*/
public Object getObjectById(String controlId) {
// Until xforms-ready is dispatched, ids map may be null
final Map idsToXFormsControls = currentControlsState.getIdsToXFormsControls();
return (idsToXFormsControls != null) ? idsToXFormsControls.get(controlId) : null;
}
/**
* Visit all the effective controls elements.
*/
public void visitAllControlsHandleRepeat(PipelineContext pipelineContext, ControlElementVisitorListener controlElementVisitorListener) {
contextStack.resetBindingContext(pipelineContext);
final boolean isOptimizeRelevance = XFormsProperties.isOptimizeRelevance(containingDocument);
handleControls(pipelineContext, controlElementVisitorListener, isOptimizeRelevance, containingDocument.getStaticState().getControlsDocument().getRootElement(), "");
}
private boolean handleControls(PipelineContext pipelineContext, ControlElementVisitorListener controlElementVisitorListener,
boolean isOptimizeRelevance, Element containerElement, String idPostfix) {
boolean doContinue = true;
int variablesCount = 0;
for (Iterator i = containerElement.elements().iterator(); i.hasNext();) {
final Element currentControlElement = (Element) i.next();
final String currentControlName = currentControlElement.getName();
final String controlId = currentControlElement.attributeValue("id");
final String effectiveControlId = controlId + (idPostfix.equals("") ? "" : XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 + idPostfix);
if (currentControlName.equals("repeat")) {
// Handle xforms:repeat
contextStack.pushBinding(pipelineContext, currentControlElement);
// Visit xforms:repeat element
doContinue = controlElementVisitorListener.startVisitControl(currentControlElement, effectiveControlId);
// Iterate over current xforms:repeat nodeset
final List currentNodeSet = contextStack.getCurrentNodeset();
if (currentNodeSet != null) {
for (int currentPosition = 1; currentPosition <= currentNodeSet.size(); currentPosition++) {
// Push "artificial" binding with just current node in nodeset
contextStack.pushIteration(currentPosition);
{
// Handle children of xforms:repeat
if (doContinue) {
// TODO: handle isOptimizeRelevance()
// Compute repeat iteration id
final String iterationEffectiveId = effectiveControlId
+ (idPostfix.equals("") ? XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1 : XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_2)
+ currentPosition;
controlElementVisitorListener.startRepeatIteration(currentPosition, iterationEffectiveId);
final String newIdPostfix = idPostfix.equals("") ? Integer.toString(currentPosition) : (idPostfix + XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_2 + currentPosition);
doContinue = handleControls(pipelineContext, controlElementVisitorListener, isOptimizeRelevance, currentControlElement, newIdPostfix);
controlElementVisitorListener.endRepeatIteration(currentPosition);
}
}
contextStack.popBinding();
if (!doContinue)
break;
}
}
doContinue = doContinue && controlElementVisitorListener.endVisitControl(currentControlElement, effectiveControlId);
contextStack.popBinding();
} else if (isGroupingControl(currentControlName)) {
// Handle XForms grouping controls
contextStack.pushBinding(pipelineContext, currentControlElement);
doContinue = controlElementVisitorListener.startVisitControl(currentControlElement, effectiveControlId);
final XFormsContextStack.BindingContext currentBindingContext = contextStack.getCurrentBindingContext();
if (doContinue) {
// Recurse into grouping control if we don't optimize relevance, OR if we do optimize and we are
// not bound to a node OR we are bound to a relevant node
// NOTE: Simply excluding non-selected cases with the expression below doesn't work. So for
// now, we don't consider hidden cases as non-relevant. In the future, we might want to improve
// this.
// && (!controlName.equals("case") || isCaseSelectedByControlElement(controlElement, effectiveControlId, idPostfix))
if (!isOptimizeRelevance
|| (!currentBindingContext.isNewBind()
|| (currentBindingContext.getSingleNode() != null && InstanceData.getInheritedRelevant(currentBindingContext.getSingleNode())))) {
doContinue = handleControls(pipelineContext, controlElementVisitorListener, isOptimizeRelevance, currentControlElement, idPostfix);
}
}
doContinue = doContinue && controlElementVisitorListener.endVisitControl(currentControlElement, effectiveControlId);
contextStack.popBinding();
} else if (isLeafControl(currentControlName)) {
// Handle leaf control
contextStack.pushBinding(pipelineContext, currentControlElement);
doContinue = controlElementVisitorListener.startVisitControl(currentControlElement, effectiveControlId);
doContinue = doContinue && controlElementVisitorListener.endVisitControl(currentControlElement, effectiveControlId);
contextStack.popBinding();
} else if (currentControlName.equals("variable")) {
// Handle xxforms:variable specifically
// Create variable object
final Variable variable = new Variable(containingDocument, contextStack, currentControlElement);
// Push the variable on the context stack. Note that we do as if each variable was a "parent" of the following controls and variables.
// NOTE: The value is computed immediately. We should use Expression objects and do lazy evaluation in the future.
contextStack.pushVariable(currentControlElement, variable.getVariableName(), variable.getVariableValue(pipelineContext, true));
variablesCount++;
}
if (!doContinue)
break;
}
// Unscope all variables
for (int i = 0; i < variablesCount; i++)
contextStack.popBinding();
return doContinue;
}
/**
* Visit all the current XFormsControls.
*/
public void visitAllControls(XFormsControlVisitorListener xformsControlVisitorListener) {
handleControl(xformsControlVisitorListener, currentControlsState.getChildren());
}
/**
* Visit all the children of the given XFormsControl.
*/
public void visitAllControls(XFormsControlVisitorListener xformsControlVisitorListener, XFormsControl currentXFormsControl) {
handleControl(xformsControlVisitorListener, currentXFormsControl.getChildren());
}
private void handleControl(XFormsControlVisitorListener xformsControlVisitorListener, List children) {
if (children != null && children.size() > 0) {
for (Iterator i = children.iterator(); i.hasNext();) {
final XFormsControl XFormsControl = (XFormsControl) i.next();
xformsControlVisitorListener.startVisitControl(XFormsControl);
handleControl(xformsControlVisitorListener, XFormsControl.getChildren());
xformsControlVisitorListener.endVisitControl(XFormsControl);
}
}
}
private static interface ControlElementVisitorListener {
public boolean startVisitControl(Element controlElement, String effectiveControlId);
public boolean endVisitControl(Element controlElement, String effectiveControlId);
public void startRepeatIteration(int iteration, String effectiveIterationId);
public void endRepeatIteration(int iteration);
}
public static interface XFormsControlVisitorListener {
public void startVisitControl(XFormsControl control);
public void endVisitControl(XFormsControl control);
}
/**
* Represents the state of repeat indexes.
*/
// public static class RepeatIndexesState {
// public RepeatIndexesState() {
/**
* Represents the state of switches.
*/
public static class SwitchState {
private Map switchIdToSelectedCaseIdMap;
public SwitchState(Map switchIdToSelectedCaseIdMap) {
this.switchIdToSelectedCaseIdMap = switchIdToSelectedCaseIdMap;
}
public Map getSwitchIdToSelectedCaseIdMap() {
return switchIdToSelectedCaseIdMap;
}
/**
* Update xforms:switch/xforms:case information with newly selected case id.
*/
public void updateSwitchInfo(PipelineContext pipelineContext, XFormsContainingDocument containingDocument, ControlsState controlsState, String selectedCaseId) {
// Find SwitchXFormsControl
final XFormsControl caseXFormsControl = (XFormsControl) controlsState.getIdsToXFormsControls().get(selectedCaseId);
if (caseXFormsControl == null) {
// NOTE: we used to throw here, but really we mustn't
if (XFormsServer.logger.isDebugEnabled()) {
XFormsServer.logger.debug("No XFormsControl found for case id '" + selectedCaseId + "'.");
}
return;
}
final XFormsControl switchXFormsControl = (XFormsControl) caseXFormsControl.getParent();
if (switchXFormsControl == null) {
// NOTE: we used to throw here, but really we mustn't
if (XFormsServer.logger.isDebugEnabled()) {
XFormsServer.logger.debug("No XFormsControl found for case id '" + selectedCaseId + "'.");
}
return;
}
final String currentSelectedCaseId = (String) getSwitchIdToSelectedCaseIdMap().get(switchXFormsControl.getEffectiveId());
if (!selectedCaseId.equals(currentSelectedCaseId)) {
// A new selection occurred on this switch
// "This action adjusts all selected attributes on the affected cases to reflect the
// new state, and then performs the following:"
getSwitchIdToSelectedCaseIdMap().put(switchXFormsControl.getEffectiveId(), selectedCaseId);
// "1. Dispatching an xforms-deselect event to the currently selected case."
containingDocument.dispatchEvent(pipelineContext, new XFormsDeselectEvent((XFormsEventTarget) controlsState.getIdsToXFormsControls().get(currentSelectedCaseId)));
// "2. Dispatching an xform-select event to the case to be selected."
containingDocument.dispatchEvent(pipelineContext, new XFormsSelectEvent((XFormsEventTarget) controlsState.getIdsToXFormsControls().get(selectedCaseId)));
}
}
/**
* Update switch info state for the given case id.
*/
public void initializeState(String switchId, String caseId, boolean visible) {
// Update currently selected case id
if (visible) {
getSwitchIdToSelectedCaseIdMap().put(switchId, caseId);
}
}
}
/**
* Represents the state of dialogs.
*/
public static class DialogState {
private Map dialogIdToVisibleMap;
public DialogState(Map dialogIdToVisibleMap) {
this.dialogIdToVisibleMap = dialogIdToVisibleMap;
}
public Map getDialogIdToVisibleMap() {
return dialogIdToVisibleMap;
}
public void showHide(String dialogId, boolean show, String neighbor, boolean constrainToViewport) {
dialogIdToVisibleMap.put(dialogId, new DialogInfo(show, neighbor, constrainToViewport));
}
public static class DialogInfo {
public boolean show;
public String neighbor;
public boolean constrainToViewport;
public DialogInfo(boolean show, String neighbor, boolean constrainToViewport) {
this.show = show;
this.neighbor = neighbor;
this.constrainToViewport = constrainToViewport;
}
public boolean isShow() {
return show;
}
public String getNeighbor() {
return neighbor;
}
public boolean isConstrainToViewport() {
return constrainToViewport;
}
}
}
/**
* Represents the state of a tree of XForms controls.
*/
public static class ControlsState {
private List children;
private Map idsToXFormsControls;
private Map defaultRepeatIdToIndex;
private Map repeatIdToIndex;
private Map effectiveRepeatIdToIterations;
private Map switchIdToSelectedCaseIdMap;
private Map dialogIdToVisibleMap;
private List uploadControlsList;
private boolean dirty;
private Map eventsToDispatch;
public ControlsState() {
}
public boolean isDirty() {
return dirty;
}
public void markDirty() {
this.dirty = true;
}
public Map getEventsToDispatch() {
return eventsToDispatch;
}
public void setEventsToDispatch(Map eventsToDispatch) {
this.eventsToDispatch = eventsToDispatch;
}
public void setChildren(List children) {
this.children = children;
}
public void setIdsToXFormsControls(Map idsToXFormsControls) {
this.idsToXFormsControls = idsToXFormsControls;
}
public Map getDefaultRepeatIdToIndex() {
return defaultRepeatIdToIndex;
}
public void setDefaultRepeatIdToIndex(Map defaultRepeatIdToIndex) {
this.defaultRepeatIdToIndex = defaultRepeatIdToIndex;
}
public void updateRepeatIndex(String controlId, int index) {
if (controlId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1)
throw new OXFException("Invalid repeat id provided: " + controlId);
if (repeatIdToIndex == null)
repeatIdToIndex = new HashMap(defaultRepeatIdToIndex);
repeatIdToIndex.put(controlId, new Integer(index));
}
public void setRepeatIdToIndex(Map repeatIdToIndex) {
this.repeatIdToIndex = new HashMap(repeatIdToIndex);
}
public void setRepeatIterations(String effectiveControlId, int iterations) {
if (effectiveRepeatIdToIterations == null)
effectiveRepeatIdToIterations = new HashMap();
effectiveRepeatIdToIterations.put(effectiveControlId, new Integer(iterations));
}
public List getChildren() {
return children;
}
public Map getIdsToXFormsControls() {
return idsToXFormsControls;
}
public Map getRepeatIdToIndex() {
if (repeatIdToIndex == null){
if (defaultRepeatIdToIndex != null)
repeatIdToIndex = new HashMap(defaultRepeatIdToIndex);
else // In this case there is no repeat
return Collections.EMPTY_MAP;
}
return repeatIdToIndex;
}
public Map getEffectiveRepeatIdToIterations() {
return effectiveRepeatIdToIterations;
}
public Map getSwitchIdToSelectedCaseIdMap() {
return switchIdToSelectedCaseIdMap;
}
public void setSwitchIdToSelectedCaseIdMap(Map switchIdToSelectedCaseIdMap) {
this.switchIdToSelectedCaseIdMap = switchIdToSelectedCaseIdMap;
}
public Map getDialogIdToVisibleMap() {
return dialogIdToVisibleMap;
}
public void setDialogIdToVisibleMap(Map dialogIdToVisibleMap) {
this.dialogIdToVisibleMap = dialogIdToVisibleMap;
}
public void addUploadControl(XFormsUploadControl uploadControl) {
if (uploadControlsList == null)
uploadControlsList = new ArrayList();
uploadControlsList.add(uploadControl);
}
public List getUploadControls() {
return uploadControlsList;
}
private Map attributeControls;
public void addAttributeControl(XXFormsAttributeControl attributeControl) {
final String effectiveForAttribute = attributeControl.getEffectiveForAttribute();
if (attributeControls == null) {
attributeControls = new HashMap();
final Map mapForId = new HashMap();
attributeControls.put(effectiveForAttribute, mapForId);
mapForId.put(attributeControl.getNameAttribute(), attributeControl);
} else {
Map mapForId = (Map) attributeControls.get(effectiveForAttribute);
if (mapForId == null) {
mapForId = new HashMap();
attributeControls.put(effectiveForAttribute, mapForId);
}
mapForId.put(attributeControl.getNameAttribute(), attributeControl);
}
}
public boolean hasAttributeControl(String effectiveForAttribute) {
return attributeControls != null && attributeControls.get(effectiveForAttribute) != null;
}
public XXFormsAttributeControl getAttributeControl(String effectiveForAttribute, String attributeName) {
final Map mapForId = (Map) attributeControls.get(effectiveForAttribute);
return (mapForId != null) ? (XXFormsAttributeControl) mapForId.get(attributeName) : null;
}
/**
* Return a map of repeat ids -> RepeatXFormsControl objects, following the branches of the
* current indexes of the repeat elements.
*/
public Map getRepeatIdToRepeatXFormsControl() {
final Map result = new HashMap();
visitRepeatHierarchy(result, this.children);
return result;
}
private void visitRepeatHierarchy(Map result, List children) {
if (children != null) {
for (Iterator i = children.iterator(); i.hasNext();) {
final XFormsControl currentXFormsControl = (XFormsControl) i.next();
if (currentXFormsControl instanceof XFormsRepeatControl) {
final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl;
final String repeatId = currentRepeatXFormsControl.getRepeatId();
final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue();
result.put(repeatId, currentXFormsControl);
if (index > 0) {
final List newChildren = currentXFormsControl.getChildren();
if (newChildren != null && newChildren.size() > 0)
visitRepeatHierarchy(result, Collections.singletonList(newChildren.get(index - 1)));
}
} else {
visitRepeatHierarchy(result, currentXFormsControl.getChildren());
}
}
}
}
/**
* Visit all the XFormsControl elements by following the current repeat indexes.
*/
public void visitControlsFollowRepeats(XFormsControlVisitorListener xformsControlVisitorListener) {
// Don't iterate if we don't have controls
if (this.children == null)
return;
visitControlsFollowRepeats(this.children, xformsControlVisitorListener);
}
private void visitControlsFollowRepeats(List children, XFormsControlVisitorListener xformsControlVisitorListener) {
for (Iterator i = children.iterator(); i.hasNext();) {
final XFormsControl currentXFormsControl = (XFormsControl) i.next();
xformsControlVisitorListener.startVisitControl(currentXFormsControl);
{
if (currentXFormsControl instanceof XFormsRepeatControl) {
final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl;
final String repeatId = currentRepeatXFormsControl.getRepeatId();
final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue();
if (index > 0) {
final List newChildren = currentXFormsControl.getChildren();
if (newChildren != null && newChildren.size() > 0)
visitControlsFollowRepeats(Collections.singletonList(newChildren.get(index - 1)), xformsControlVisitorListener);
}
} else {
final List newChildren = currentXFormsControl.getChildren();
if (newChildren != null)
visitControlsFollowRepeats(newChildren, xformsControlVisitorListener);
}
}
xformsControlVisitorListener.endVisitControl(currentXFormsControl);
}
}
/**
* Find an effective control id based on a control id, following the branches of the
* current indexes of the repeat elements.
*/
public String findEffectiveControlId(String controlId) {
// Don't iterate if we don't have controls
if (this.children == null)
return null;
return findEffectiveControlId(controlId, this.children);
}
private String findEffectiveControlId(String controlId, List children) {
for (Iterator i = children.iterator(); i.hasNext();) {
final XFormsControl currentXFormsControl = (XFormsControl) i.next();
final String originalControlId = currentXFormsControl.getId();
if (controlId.equals(originalControlId)) {
return currentXFormsControl.getEffectiveId();
} else if (currentXFormsControl instanceof XFormsRepeatControl) {
final XFormsRepeatControl currentRepeatXFormsControl = (XFormsRepeatControl) currentXFormsControl;
final String repeatId = currentRepeatXFormsControl.getRepeatId();
final int index = ((Integer) getRepeatIdToIndex().get(repeatId)).intValue();
if (index > 0) {
final List newChildren = currentXFormsControl.getChildren();
if (newChildren != null && newChildren.size() > 0) {
final String result = findEffectiveControlId(controlId, Collections.singletonList(newChildren.get(index - 1)));
if (result != null)
return result;
}
}
} else {
final List newChildren = currentXFormsControl.getChildren();
if (newChildren != null) {
final String result = findEffectiveControlId(controlId, newChildren);
if (result != null)
return result;
}
}
}
// Not found
return null;
}
}
/**
* Analyze differences of relevance for controls getting bound and unbound to nodes.
*/
private void findSpecialRelevanceChanges(List state1, List state2, Map[] eventsToDispatch) {
// Trivial case
if (state1 == null && state2 == null)
return;
// Both lists must have the same size if present; state1 can be null
if (state1 != null && state2 != null && state1.size() != state2.size()) {
throw new IllegalStateException("Illegal state when comparing controls.");
}
final Iterator j = (state1 == null) ? null : state1.iterator();
final Iterator i = (state2 == null) ? null : state2.iterator();
final Iterator leadingIterator = (i != null) ? i : j;
while (leadingIterator.hasNext()) {
final XFormsControl xformsControl1 = (state1 == null) ? null : (XFormsControl) j.next();
final XFormsControl xformsControl2 = (state2 == null) ? null : (XFormsControl) i.next();
final XFormsControl leadingControl = (xformsControl2 != null) ? xformsControl2 : xformsControl1; // never null
// 1: Check current control
if (leadingControl instanceof XFormsSingleNodeControl) {
// xforms:repeat doesn't need to be handled independently, iterations do it
final XFormsSingleNodeControl xformsSingleNodeControl1 = (XFormsSingleNodeControl) xformsControl1;
final XFormsSingleNodeControl xformsSingleNodeControl2 = (XFormsSingleNodeControl) xformsControl2;
String foundControlId = null;
XFormsControl targetControl = null;
int eventType = 0;
if (xformsControl1 != null && xformsControl2 != null) {
final NodeInfo boundNode1 = xformsControl1.getBoundNode();
final NodeInfo boundNode2 = xformsControl2.getBoundNode();
if (boundNode1 != null && xformsSingleNodeControl1.isRelevant() && boundNode2 == null) {
// A control was bound to a node and relevant, but has become no longer bound to a node
foundControlId = xformsControl2.getEffectiveId();
eventType = XFormsModel.EventSchedule.RELEVANT_BINDING;
} else if (boundNode1 == null && boundNode2 != null && xformsSingleNodeControl2.isRelevant()) {
// A control was not bound to a node, but has now become bound and relevant
foundControlId = xformsControl2.getEffectiveId();
eventType = XFormsModel.EventSchedule.RELEVANT_BINDING;
} else if (boundNode1 != null && boundNode2 != null && !boundNode1.isSameNodeInfo(boundNode2)) {
// The control is now bound to a different node
// In this case, we schedule the control to dispatch all the events
// NOTE: This is not really proper according to the spec, but it does help applications to
// force dispatching in such cases
foundControlId = xformsControl2.getEffectiveId();
eventType = XFormsModel.EventSchedule.ALL;
}
} else if (xformsControl2 != null) {
final NodeInfo boundNode2 = xformsControl2.getBoundNode();
if (boundNode2 != null && xformsSingleNodeControl2.isRelevant()) {
// A control was not bound to a node, but has now become bound and relevant
foundControlId = xformsControl2.getEffectiveId();
eventType = XFormsModel.EventSchedule.RELEVANT_BINDING;
}
} else if (xformsControl1 != null) {
final NodeInfo boundNode1 = xformsControl1.getBoundNode();
if (boundNode1 != null && xformsSingleNodeControl1.isRelevant()) {
// A control was bound to a node and relevant, but has become no longer bound to a node
foundControlId = xformsControl1.getEffectiveId();
// NOTE: This is the only case where we must dispatch the event to an obsolete control
targetControl = xformsControl1;
eventType = XFormsModel.EventSchedule.RELEVANT_BINDING;
}
}
// Remember that we need to dispatch information about this control
if (foundControlId != null) {
if (eventsToDispatch[0] == null)
eventsToDispatch[0] = new HashMap();
eventsToDispatch[0].put(foundControlId,
new XFormsModel.EventSchedule(foundControlId, eventType, targetControl));
}
}
// 2: Check children if any
if (XFormsControls.isGroupingControl(leadingControl.getName()) || leadingControl instanceof RepeatIterationControl) {
final List children1 = (xformsControl1 == null) ? null : xformsControl1.getChildren();
final List children2 = (xformsControl2 == null) ? null : xformsControl2.getChildren();
final int size1 = children1 == null ? 0 : children1.size();
final int size2 = children2 == null ? 0 : children2.size();
if (leadingControl instanceof XFormsRepeatControl) {
// Special case of repeat update
if (size1 == size2) {
// No add or remove of children
findSpecialRelevanceChanges(children1, children2, eventsToDispatch);
} else if (size2 > size1) {
// Size has grown
// Diff the common subset
findSpecialRelevanceChanges(children1, children2.subList(0, size1), eventsToDispatch);
// Issue new values for new iterations
findSpecialRelevanceChanges(null, children2.subList(size1, size2), eventsToDispatch);
} else if (size2 < size1) {
// Size has shrunk
// Diff the common subset
findSpecialRelevanceChanges(children1.subList(0, size2), children2, eventsToDispatch);
// Issue new values for new iterations
findSpecialRelevanceChanges(children1.subList(size2, size1), null, eventsToDispatch);
}
} else {
// Other grouping controls
findSpecialRelevanceChanges(size1 == 0 ? null : children1, size2 == 0 ? null : children2, eventsToDispatch);
}
}
}
}
/**
* Get the items for a given control id. This is not an effective id, but an original control id.
*
* @param controlId original control id
* @return List of Item
*/
public List getConstantItems(String controlId) {
if (constantItems == null)
return null;
else
return (List) constantItems.get(controlId);
}
/**
* Set the items for a given control id. This is not an effective id, but an original control id.
*
* @param controlId original control id
* @param items List of Item
*/
public void setConstantItems(String controlId, List items) {
if (constantItems == null)
constantItems = new HashMap();
constantItems.put(controlId, items);
}
}
|
package jsaf.provider.unix.io.driver;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.slf4j.cal10n.LocLogger;
import jsaf.Message;
import jsaf.intf.io.IFile;
import jsaf.intf.io.IFileMetadata;
import jsaf.intf.io.IFilesystem;
import jsaf.intf.io.IReader;
import jsaf.intf.unix.io.IUnixFileInfo;
import jsaf.intf.unix.io.IUnixFilesystem;
import jsaf.intf.unix.io.IUnixFilesystemDriver;
import jsaf.intf.unix.system.IUnixSession;
import jsaf.intf.util.ISearchable;
import jsaf.io.PerishableReader;
import jsaf.provider.unix.io.UnixFileInfo;
import jsaf.util.SafeCLI;
import jsaf.util.StringTools;
/**
* IUnixFilesystemDriver implementation for Mac OS X.
*
* @author David A. Solin
* @version %I% %G%
*/
public class MacOSXDriver extends AbstractDriver {
private static final String STAT = "ls -ldnT";
public MacOSXDriver(IUnixSession session) {
super(session);
}
static final String OPEN = "(";
static final String CLOSE = ")";
void getMounts() throws Exception {
mounts = new ArrayList<IFilesystem.IMount>();
for (String line : SafeCLI.multiLine("mount", session, IUnixSession.Timeout.S)) {
if (line.trim().length() == 0) continue;
int ptr = line.indexOf(" on ");
String device = line.substring(0, ptr);
int begin = ptr + 4;
ptr = line.indexOf(OPEN);
String path = line.substring(begin, ptr).trim();
begin = ptr;
ptr = line.indexOf(CLOSE, begin);
StringTokenizer tok = new StringTokenizer(line.substring(begin, ptr), ",");
String fsType = null;
while(tok.hasMoreTokens()) {
String attr = tok.nextToken().trim();
if (attr.endsWith("fs")) {
fsType = attr;
break;
}
}
if (fsType != null && path.startsWith(IUnixFilesystem.DELIM_STR)) {
mounts.add(new Mount(path, fsType));
}
}
}
// Implement IUnixFilesystemDriver
public String getFindCommand(List<ISearchable.ICondition> conditions) {
String from = null;
boolean dirOnly = false;
boolean followLinks = false;
boolean xdev = false;
Pattern path = null, dirname = null, basename = null;
String literalBasename = null, antiBasename = null, fsType = null;
int depth = ISearchable.DEPTH_UNLIMITED;
for (ISearchable.ICondition condition : conditions) {
switch(condition.getField()) {
case IUnixFilesystem.FIELD_FOLLOW_LINKS:
followLinks = true;
break;
case IUnixFilesystem.FIELD_XDEV:
xdev = true;
break;
case IFilesystem.FIELD_FILETYPE:
if (IFilesystem.FILETYPE_DIR.equals(condition.getValue())) {
dirOnly = true;
}
break;
case IFilesystem.FIELD_PATH:
path = (Pattern)condition.getValue();
break;
case IFilesystem.FIELD_DIRNAME:
dirname = (Pattern)condition.getValue();
break;
case IFilesystem.FIELD_BASENAME:
switch(condition.getType()) {
case ISearchable.TYPE_INEQUALITY:
antiBasename = (String)condition.getValue();
break;
case ISearchable.TYPE_EQUALITY:
literalBasename = (String)condition.getValue();
break;
case ISearchable.TYPE_PATTERN:
basename = (Pattern)condition.getValue();
break;
}
break;
case IFilesystem.FIELD_FSTYPE:
fsType = (String)condition.getValue();
break;
case ISearchable.FIELD_DEPTH:
depth = ((Integer)condition.getValue()).intValue();
break;
case ISearchable.FIELD_FROM:
from = ((String)condition.getValue()).replace(" ", "\\ ");
break;
}
}
StringBuffer sb = new StringBuffer("find");
if (followLinks) {
sb.append(" -L");
}
String FIND = sb.toString();
StringBuffer cmd = new StringBuffer(FIND).append(" -E");
if (xdev) {
cmd.append("x");
}
cmd.append(" ").append(from);
if (fsType != null) {
cmd.append(" -fstype ").append(fsType);
}
if (depth != ISearchable.DEPTH_UNLIMITED) {
cmd.append(" -maxdepth ").append(Integer.toString(depth));
}
if (dirOnly) {
cmd.append(" -type d");
if (dirname != null && !dirname.pattern().equals(WILDCARD)) {
cmd.append(" -regex '").append(dirname.pattern()).append("'");
}
} else {
if (path != null && !path.pattern().equals(WILDCARD)) {
cmd.append(" -regex '").append(path.pattern()).append("'");
} else {
if (dirname != null) {
cmd.append(" -type d");
if (!dirname.pattern().equals(WILDCARD)) {
cmd.append(" -regex '").append(dirname.pattern()).append("'");
}
cmd.append(" -print0 | xargs -0 -I{} ").append(FIND).append(" '{}' -maxdepth 1");
}
cmd.append(" -type f");
if (basename != null) {
cmd.append(" | awk -F/ '$NF ~ /");
cmd.append(basename.pattern());
cmd.append("/'");
} else if (antiBasename != null) {
cmd.append(" ! -name '").append(antiBasename).append("'");
} else if (literalBasename != null) {
cmd.append(" -name '").append(literalBasename).append("'");
}
}
}
cmd.append(" | xargs -I{} ").append(STAT).append(" '{}'");
return cmd.toString();
}
public String getStatCommand(String path) {
return new StringBuffer(STAT).append(" '").append(path).append("'").toString();
}
public UnixFileInfo nextFileInfo(Iterator<String> lines) {
String line = null;
if (lines.hasNext()) {
line = lines.next();
} else {
return null;
}
if (line.trim().length() == 0) {
return nextFileInfo(lines);
}
char unixType = line.charAt(0);
String perms = line.substring(1, 10);
Boolean hasAcl = Boolean.FALSE;
if (line.charAt(10) == '+') {
hasAcl = true;
}
StringTokenizer tok = new StringTokenizer(line.substring(11));
String linkCount = tok.nextToken();
int uid = -1;
try {
uid = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
}
int gid = -1;
try {
gid = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
}
IFileMetadata.Type type = IFileMetadata.Type.FILE;
switch(unixType) {
case IUnixFileInfo.DIR_TYPE:
type = IFileMetadata.Type.DIRECTORY;
break;
case IUnixFileInfo.LINK_TYPE:
type = IFileMetadata.Type.LINK;
break;
case IUnixFileInfo.CHAR_TYPE:
case IUnixFileInfo.BLOCK_TYPE:
int ptr = -1;
if ((ptr = line.indexOf(",")) > 11) {
tok = new StringTokenizer(line.substring(ptr+1));
}
break;
}
long length = 0;
try {
length = Long.parseLong(tok.nextToken());
} catch (NumberFormatException e) {
}
Date mtime = null;
String dateStr = tok.nextToken("/").trim();
try {
mtime = new SimpleDateFormat("MMM dd HH:mm:ss yyyy").parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
String path = null, linkPath = null;
int begin = line.indexOf(session.getFilesystem().getDelimiter());
if (begin > 0) {
int end = line.indexOf("->");
if (end == -1) {
path = line.substring(begin).trim();
} else if (end > begin) {
path = line.substring(begin, end).trim();
linkPath = line.substring(end+2).trim();
}
}
return new UnixFileInfo(type, path, linkPath, null, mtime, null, length, unixType, perms, uid, gid, hasAcl, null);
}
}
|
package lama.tablegen.sqlite3;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import lama.Expression;
import lama.Main;
import lama.Main.StateToReproduce;
import lama.Randomly;
import lama.schema.Schema.Column;
import lama.schema.Schema.Table;
import lama.sqlite3.SQLite3Visitor;
public class Sqlite3RowGenerator {
public static void insertRows(Table table, Connection con, StateToReproduce state) throws SQLException {
for (int i = 0; i < Main.NR_INSERT_ROW_TRIES; i++) {
String query = insertRow(table);
try (Statement s = con.createStatement()) {
state.statements.add(query);
s.execute(query);
}
}
}
private static String insertRow(Table table) {
StringBuilder sb = new StringBuilder();
boolean upsert = false; // Randomly.getBooleanWithSmallProbability(); TODO enable after fixed
sb.append("INSERT ");
if (!upsert || Randomly.getBoolean()) {
sb.append("OR IGNORE ");
}
sb.append("INTO " + table.getName());
if (Randomly.getBooleanWithSmallProbability()) {
sb.append(" DEFAULT VALUES");
} else {
sb.append("(");
List<Column> columns = appendColumnNames(table, sb);
sb.append(")");
sb.append(" VALUES ");
int nrValues = 1 + Randomly.smallNumber();
appendNrValues(sb, columns, nrValues);
}
if (upsert) {
sb.append(" ON CONFLICT DO NOTHING");
}
return sb.toString();
}
private static void appendNrValues(StringBuilder sb, List<Column> columns, int nrValues) {
for (int i = 0; i < nrValues; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append("(");
appendValue(sb, columns);
sb.append(")");
}
}
private static void appendValue(StringBuilder sb, List<Column> columns) {
for (int i = 0; i < columns.size(); i++) {
if (i != 0) {
sb.append(", ");
}
Expression randomLiteral = SQLite3ExpressionGenerator.getRandomLiteralValue(false);
SQLite3Visitor visitor = new SQLite3Visitor();
visitor.visit(randomLiteral);
sb.append(visitor.get());
}
}
private static List<Column> appendColumnNames(Table table, StringBuilder sb) {
List<Column> columns = table.getColumns();
for (int i = 0; i < columns.size(); i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(columns.get(i).getName());
}
return columns;
}
}
|
package java.awt;
import java.io.File;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.videolan.Logger;
public class BDFontMetrics extends FontMetrics {
static final long serialVersionUID = -4956160226949100590L;
private static long ftLib = 0;
private static long fcLib = 0;
private static Map systemFontNameMap = null;
private static final Logger logger = Logger.getLogger(BDFontMetrics.class.getName());
private static native long initN();
private static native void destroyN(long ftLib);
private static native String[] getFontFamilyAndStyleN(long ftLib, String fontName);
protected synchronized static String[] getFontFamilyAndStyle(String fontFile) {
return getFontFamilyAndStyleN(ftLib, fontFile);
}
private native static String resolveFontN(String fontFamily, int fontStyle);
private native static void unloadFontConfigN();
private static void addSystemFont(String alias, int style, String family, String defaultPath) {
alias = alias + "." + style;
/* default to jre fonts, if available */
if (new File(defaultPath).exists()) {
logger.info("mapping " + alias + " (" + family + ") to " + defaultPath);
systemFontNameMap.put(alias, defaultPath);
return;
}
/* try fontconfig */
String path = resolveFontN(family, style);
if (path != null) {
logger.info("fontconfig: mapping " + alias + " (" + family + ") to " + path);
systemFontNameMap.put(alias, path);
return;
}
logger.error("Can't resolve font " + alias + ": file " + defaultPath + " does not exist");
/* useless ? font file does not exist ... */
systemFontNameMap.put(alias, defaultPath);
}
private static void initSystemFonts() {
String javaHome = (String) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return System.getProperty("java.home");
}
}
);
File f = new File(javaHome, "lib" + File.separator + "fonts");
String defaultFontPath = f.getAbsolutePath() + File.separator;
final Object[][] sfd = {
{ "serif", "Arial", new String[] {"LucidaBrightRegular.ttf", "LucidaBrightDemiBold.ttf", "LucidaBrightItalic.ttf", "LucidaBrightDemiItalic.ttf"}},
{ "sansserif", "Times New Roman", new String[] {"LucidaSansRegular.ttf", "LucidaSansDemiBold.ttf", "LucidaSansOblique.ttf", "LucidaSansDemiOblique.ttf"}},
{ "monospaced", "Courier New", new String[] {"LucidaTypewriterRegular.ttf", "LucidaTypewriterBold.ttf", "LucidaTypewriterOblique.ttf", "LucidaTypewriterBoldOblique.ttf"}},
{ "dialog", "Times New Roman", new String[] {"LucidaSansRegular.ttf", "LucidaSansDemiBold.ttf", "LucidaSansOblique.ttf", "LucidaSansDemiOblique.ttf"}},
{ "dialoginput", "Courier New", new String[] {"LucidaTypewriterRegular.ttf", "LucidaTypewriterBold.ttf", "LucidaTypewriterOblique.ttf", "LucidaTypewriterBoldOblique.ttf"}},
{ "default", "Times New Roman", new String[] {"LucidaSansRegular.ttf", "LucidaSansDemiBold.ttf", "LucidaSansOblique.ttf", "LucidaSansDemiOblique.ttf"}},
};
systemFontNameMap = new HashMap(24);
for (int type = 0; type < sfd.length; type++) {
for (int style = 0; style < 4; style++) {
addSystemFont((String)sfd[type][0], style, (String)sfd[type][1],
defaultFontPath + ((String[])sfd[type][2])[style]);
}
}
unloadFontConfigN();
}
public synchronized static void init() {
if (ftLib == 0) {
ftLib = initN();
}
if (ftLib == 0) {
logger.error("freetype library not loaded");
throw new AWTError("freetype lib not loaded");
}
if (systemFontNameMap == null) {
initSystemFonts();
}
}
public synchronized static void shutdown() {
Iterator it = fontMetricsMap.values().iterator();
while (it.hasNext()) {
try {
WeakReference ref = (WeakReference)it.next();
BDFontMetrics fm = (BDFontMetrics)ref.get();
it.remove();
if (fm != null) {
fm.destroy();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
destroyN(BDFontMetrics.ftLib);
ftLib = 0;
}
/** A map which maps a native font name and size to a font metrics object. This is used
as a cache to prevent loading the same fonts multiple times. */
private static Map fontMetricsMap = new HashMap();
/** Gets the BDFontMetrics object for the supplied font. This method caches font metrics
to ensure native fonts are not loaded twice for the same font. */
static synchronized BDFontMetrics getFontMetrics(Font font) {
/* See if metrics has been stored in font already. */
BDFontMetrics fm = (BDFontMetrics)font.metrics;
if (fm == null || fm.ftFace == 0) {
/* See if a font metrics of the same native name and size has already been loaded.
If it has then we use that one. */
String nativeName;
if (font.fontFile != null) {
nativeName = font.fontFile.getPath();
} else {
nativeName = (String)systemFontNameMap.get(font.getName().toLowerCase() + "." + font.getStyle());
if (nativeName == null) {
nativeName = (String)systemFontNameMap.get("default." + font.getStyle());
}
}
String key = nativeName + "." + font.getSize();
WeakReference ref = (WeakReference)fontMetricsMap.get(key);
if (ref != null) {
fm = (BDFontMetrics)ref.get();
}
if (fm == null) {
fm = new BDFontMetrics(font, nativeName);
fontMetricsMap.put(key, new WeakReference(fm));
}
font.metrics = fm;
}
return fm;
}
static String stripAttributes(String fontname) {
int dotidx;
if ((dotidx = fontname.indexOf('.')) == -1)
return fontname;
return fontname.substring(0, dotidx);
}
static synchronized String[] getFontList() {
init();
ArrayList fontNames = new ArrayList();
Iterator fonts = systemFontNameMap.keySet().iterator();
while (fonts.hasNext()) {
String fontname = stripAttributes((String)fonts.next());
if (!fontNames.contains(fontname))
fontNames.add(fontname);
}
return (String[])fontNames.toArray(new String[fontNames.size()]);
}
private long ftFace = 0;
private int ascent = 0;
private int descent = 0;
private int leading = 0;
private int maxAdvance = 0;
/** Cache of first 256 Unicode characters as these map to ASCII characters and are often used. */
private int[] widths;
/**
* Creates a font metrics for the supplied font. To get a font metrics for a font
* use the static method getFontMetrics instead which does caching.
*/
private BDFontMetrics(Font font, String nativeName) {
super(font);
ftFace = loadFontN(ftLib, nativeName, font.getSize());
if (ftFace == 0)
throw new AWTError("font face:" + nativeName + " not loaded");
widths = null;
}
private native long loadFontN(long ftLib, String fontName, int size);
private native void destroyFontN(long ftFace);
private native int charWidthN(long ftFace, char c);
private native int stringWidthN(long ftFace, String string);
private native int charsWidthN(long ftFace, char chars[], int offset, int len);
private synchronized void loadWidths() {
/* Cache first 256 char widths for use by the getWidths method and for faster metric
calculation as they are commonly used (ASCII) characters. */
if (widths == null) {
widths = new int[256];
for (int i = 0; i < 256; i++) {
widths[i] = charWidthN(ftFace, (char)i);
}
}
}
protected synchronized void drawString(BDGraphics g, String string, int x, int y, int rgb) {
g.drawStringN(ftFace, string, x, y, rgb);
}
public int getAscent() {
return ascent;
}
public int getDescent() {
return descent;
}
public int getLeading() {
return leading;
}
public int getMaxAdvance() {
return maxAdvance;
}
/**
* Fast lookup of first 256 chars as these are always the same eg. ASCII charset.
*/
public synchronized int charWidth(char c) {
if (c < 256) {
loadWidths();
return widths[c];
}
return charWidthN(ftFace, c);
}
/**
* Return the width of the specified string in this Font.
*/
public synchronized int stringWidth(String string) {
return stringWidthN(ftFace, string);
}
/**
* Return the width of the specified char[] in this Font.
*/
public synchronized int charsWidth(char chars[], int offset, int length) {
return charsWidthN(ftFace, chars, offset, length);
}
/**
* Get the widths of the first 256 characters in the font.
*/
public int[] getWidths() {
loadWidths();
int[] newWidths = new int[widths.length];
System.arraycopy(widths, 0, newWidths, 0, widths.length);
return newWidths;
}
private void destroy() {
if (ftFace != 0) {
destroyFontN(ftFace);
ftFace = 0;
}
}
protected void finalize() throws Throwable {
try {
destroy();
} catch (Throwable t) {
throw t;
} finally {
super.finalize();
}
}
}
|
package io.mangoo.core;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.quartz.CronExpression;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.reflections.Reflections;
import org.yaml.snakeyaml.Yaml;
import com.google.common.io.Resources;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import io.mangoo.admin.AdminController;
import io.mangoo.annotations.Schedule;
import io.mangoo.configuration.Config;
import io.mangoo.enums.AdminRoute;
import io.mangoo.enums.Default;
import io.mangoo.enums.Key;
import io.mangoo.enums.Mode;
import io.mangoo.enums.RouteType;
import io.mangoo.interfaces.MangooLifecycle;
import io.mangoo.routing.Route;
import io.mangoo.routing.Router;
import io.mangoo.routing.handlers.DispatcherHandler;
import io.mangoo.routing.handlers.ExceptionHandler;
import io.mangoo.routing.handlers.FallbackHandler;
import io.mangoo.routing.handlers.ServerSentEventHandler;
import io.mangoo.routing.handlers.WebSocketHandler;
import io.mangoo.scheduler.Scheduler;
import io.mangoo.utils.BootstrapUtils;
import io.mangoo.utils.SchedulerUtils;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
/**
* Convenient methods for everything to start up a mangoo I/O application
*
* @author svenkubiak
* @author William Dunne
*
*/
public class Bootstrap {
private static volatile Logger LOG; //NOSONAR
private static final int INITIAL_SIZE = 255;
private final LocalDateTime start = LocalDateTime.now();
private final ResourceHandler pathResourceHandler;
private PathHandler pathHandler;
private Config config;
private String host;
private Mode mode;
private Injector injector;
private boolean error;
private int port;
public Bootstrap() {
this.pathResourceHandler = new ResourceHandler(
new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + "/"));
}
public Mode prepareMode() {
final String applicationMode = System.getProperty(Key.APPLICATION_MODE.toString());
if (StringUtils.isNotBlank(applicationMode)) {
switch (applicationMode.toLowerCase(Locale.ENGLISH)) {
case "dev" : this.mode = Mode.DEV;
break;
case "test" : this.mode = Mode.TEST;
break;
default : this.mode = Mode.PROD;
break;
}
} else {
this.mode = Mode.PROD;
}
return this.mode;
}
@SuppressWarnings("all")
public void prepareLogger() {
final String configurationFile = "log4j2." + this.mode.toString() + ".xml";
if (Thread.currentThread().getContextClassLoader().getResource(configurationFile) == null) {
LOG = LogManager.getLogger(Bootstrap.class); //NOSONAR
} else {
try {
final URL resource = Thread.currentThread().getContextClassLoader().getResource(configurationFile);
final LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.setConfigLocation(resource.toURI());
} catch (final URISyntaxException e) {
e.printStackTrace(); //NOSONAR
this.error = true;
}
if (!hasError()) {
LOG = LogManager.getLogger(Bootstrap.class); //NOSONAR
LOG.info("Found environment specific Log4j2 configuration. Using configuration file: " + configurationFile);
}
}
}
public Injector prepareInjector() {
this.injector = Guice.createInjector(Stage.PRODUCTION, getModules());
return this.injector;
}
public void applicationInitialized() {
this.injector.getInstance(MangooLifecycle.class).applicationInitialized();
}
public void prepareConfig() {
this.config = this.injector.getInstance(Config.class);
if (!this.config.hasValidSecret()) {
LOG.error("Please make sure that your application.yaml has an application.secret property which has at least 16 characters");
this.error = true;
}
}
@SuppressWarnings("all")
public void parseRoutes() {
if (!hasError()) {
try (InputStream inputStream = Resources.getResource(Default.ROUTES_FILE.toString()).openStream()) {
final List<Map<String, String>> routes = (List<Map<String, String>>) new Yaml().load(inputStream);
for (final Map<String, String> routing : routes) {
for (final Entry<String, String> entry : routing.entrySet()) {
final String method = entry.getKey().trim();
final String mapping = entry.getValue();
final String [] mappings = mapping
.replace(Default.AUTHENTICATION.toString(), "")
.replace(Default.BLOCKING.toString(), "")
.split("->");
if (mappings != null && mappings.length > 0) {
final String url = mappings[0].trim();
final Route route = new Route(BootstrapUtils.getRouteType(method));
route.toUrl(url);
route.withRequest(HttpString.tryFromString(method));
route.withAuthentication(BootstrapUtils.hasAuthentication(mapping));
route.allowBlocking(BootstrapUtils.hasBlocking(mapping));
try {
if (mappings.length == 2) {
final String [] classMethod = mappings[1].split("\\.");
if (classMethod != null && classMethod.length > 0) {
route.withClass(Class.forName(validPackage(this.config.getControllerPackage()) + classMethod[0].trim()));
if (classMethod.length == 2) {
String controllerMethod = classMethod[1].trim();
if (methodExists(controllerMethod, route.getControllerClass())) {
route.withMethod(controllerMethod);
}
}
}
}
Router.addRoute(route);
} catch (final Exception e) {
LOG.error("Failed to parse routing: " + routing);
LOG.error("Please check, that your routes.yaml syntax is correct", e);
this.error = true;
throw new Exception();
}
}
}
}
} catch (final Exception e) {
LOG.error("Failed to load routes.yaml Please check, that routes.yaml exists in your application resource folder", e);
this.error = true;
}
if (!hasError()) {
createRoutes();
}
}
}
private boolean methodExists(String controllerMethod, Class<?> controllerClass) {
boolean exists = false;
for (final Method method : controllerClass.getMethods()) {
if (method.getName().equals(controllerMethod)) {
exists = true;
break;
}
}
if (!exists) {
LOG.error("Could not find controller method '" + controllerMethod + "' in controller class '" + controllerClass.getSimpleName() + "'");
this.error = true;
}
return exists;
}
private void createRoutes() {
this.pathHandler = new PathHandler(getRoutingHandler());
for (Route route : Router.getRoutes()) {
if (RouteType.WEBSOCKET.equals(route.getRouteType())) {
this.pathHandler.addExactPath(route.getUrl(), Handlers.websocket(new WebSocketHandler(route.getControllerClass(), route.isAuthenticationRequired())));
} else if (RouteType.SERVER_SENT_EVENT.equals(route.getRouteType())) {
this.pathHandler.addExactPath(route.getUrl(), Handlers.serverSentEvents(new ServerSentEventHandler(route.isAuthenticationRequired())));
} else if (RouteType.RESOURCE_PATH.equals(route.getRouteType())) {
this.pathHandler.addPrefixPath(route.getUrl(), new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + route.getUrl())));
}
}
}
private RoutingHandler getRoutingHandler() {
final RoutingHandler routingHandler = Handlers.routing();
routingHandler.setFallbackHandler(new FallbackHandler());
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.ROUTES.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("routes"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.CONFIG.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("config"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.HEALTH.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("health"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.CACHE.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("cache"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.METRICS.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("metrics"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.SCHEDULER.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("scheduler"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.SYSTEM.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("system"));
Router.addRoute(new Route(RouteType.REQUEST).toUrl(AdminRoute.MEMORY.toString()).withRequest(Methods.GET).withClass(AdminController.class).withMethod("memory"));
Router.getRoutes().parallelStream().forEach(route -> {
if (RouteType.REQUEST.equals(route.getRouteType())) {
routingHandler.add(route.getRequestMethod(), route.getUrl(), new DispatcherHandler(route.getControllerClass(), route.getControllerMethod(), route.isBlockingAllowed()));
} else if (RouteType.RESOURCE_FILE.equals(route.getRouteType())) {
routingHandler.add(Methods.GET, route.getUrl(), this.pathResourceHandler);
}
});
return routingHandler;
}
public void startUndertow() {
if (!hasError()) {
this.host = this.config.getString(Key.APPLICATION_HOST, Default.APPLICATION_HOST.toString());
this.port = this.config.getInt(Key.APPLICATION_PORT, Default.APPLICATION_PORT.toInt());
final Undertow server = Undertow.builder()
.addHttpListener(this.port, this.host)
.setHandler(Handlers.exceptionHandler(this.pathHandler).addExceptionHandler(Throwable.class, new ExceptionHandler()))
.build();
server.start();
}
}
private List<Module> getModules() {
final List<Module> modules = new ArrayList<>();
if (!hasError()) {
try {
final Class<?> module = Class.forName(Default.MODULE_CLASS.toString());
AbstractModule abstractModule;
abstractModule = (AbstractModule) module.getConstructor().newInstance();
modules.add(abstractModule);
modules.add(new Modules());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
LOG.error("Failed to load modules. Check that conf/Module.java exists in your application", e);
this.error = true;
}
}
return modules;
}
public void showLogo() {
if (!hasError()) {
final StringBuilder buffer = new StringBuilder(INITIAL_SIZE);
buffer.append('\n')
.append(BootstrapUtils.getLogo())
.append("\n\nhttps://mangoo.io | @mangoo_io | ")
.append(BootstrapUtils.getVersion())
.append('\n');
LOG.info(buffer.toString());
LOG.info("mangoo I/O application started @{}:{} in {} ms in {} mode. Enjoy.", this.host, this.port, ChronoUnit.MILLIS.between(this.start, LocalDateTime.now()), this.mode.toString());
}
}
public void applicationStarted() {
this.injector.getInstance(MangooLifecycle.class).applicationStarted();
}
public void startQuartzScheduler() {
if (!hasError()) {
final Set<Class<?>> jobs = new Reflections(this.config.getSchedulerPackage()).getTypesAnnotatedWith(Schedule.class);
if (jobs != null && !jobs.isEmpty() && this.config.isSchedulerAutostart()) {
final Scheduler mangooScheduler = this.injector.getInstance(Scheduler.class);
jobs.forEach(clazz -> {
final Schedule schedule = clazz.getDeclaredAnnotation(Schedule.class);
if (CronExpression.isValidExpression(schedule.cron())) {
final JobDetail jobDetail = SchedulerUtils.createJobDetail(clazz.getName(), Default.SCHEDULER_JOB_GROUP.toString(), clazz.asSubclass(Job.class));
final Trigger trigger = SchedulerUtils.createTrigger(clazz.getName() + "-trigger", Default.SCHEDULER_TRIGGER_GROUP.toString(), schedule.description(), schedule.cron());
mangooScheduler.schedule(jobDetail, trigger);
LOG.info("Successfully scheduled job " + clazz.getName() + " with cron " + schedule.cron());
} else {
LOG.error("Invalid or missing cron expression for job: " + clazz.getName());
this.error = true;
}
});
if (!hasError()) {
mangooScheduler.start();
}
}
}
}
public boolean isBootstrapSuccessful() {
return !this.error;
}
private boolean hasError() {
return this.error;
}
public LocalDateTime getStart() {
return this.start;
}
private String validPackage(String package) {
if(!package.endsWith(".")) {
return package + '.';
}
return package;
}
}
|
package magpie.data.materials.util;
import java.util.*;
import magpie.data.BaseEntry;
import magpie.data.materials.CompositionDataset;
import magpie.data.materials.CompositionEntry;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.optim.linear.*;
public class GCLPCalculator {
/**
* Phases to consider for equilibria and their energy. Only contains
* the lowest-energy phase at each entry
*/
protected Map<CompositionEntry, Double> Phases = new TreeMap<>();
/**
* Composition for which equilibrium is currently computed.
*/
protected CompositionEntry CurrentComposition = null;
/**
* Final phase equilibrium. Maps composition to fraction
*/
protected Map<CompositionEntry, Double> Equilibrium = new TreeMap<>();
/**
* Ground state energy at this composition.
*/
protected double GroundStateEnergy;
/**
* Initialize a GCLP calculator. Sets the chemical potential of each
* element to be 0.
*/
public GCLPCalculator() {
// Add for each element
int[] elem = new int[1];
double[] frac = new double[1];
frac[0] = 1.0;
for (int i=0; i<LookupData.ElementNames.length; i++) {
elem[0] = i;
CompositionEntry entry = new CompositionEntry(elem, frac);
Phases.put(entry, 0.0);
}
}
/**
* Define the chemical potential of an element
* @param elem Abbreviation of element
* @param mu Desired chemical potential
* @throws Exception
*/
public void setMu(String elem, double mu) throws Exception {
CompositionEntry entry = new CompositionEntry(elem);
if (entry.getElements().length != 1) {
throw new Exception("Not an element: " + elem);
}
Phases.put(entry, mu);
}
/**
* Set many phase energies. Assumes that measured class values are the
* energy of interest.
* @param phases Dataset containing energy values
*/
public void addPhases(CompositionDataset phases) {
for (BaseEntry ptr : phases.getEntries()) {
CompositionEntry entry = (CompositionEntry) ptr;
if (ptr.hasMeasurement()) {
addPhase(entry, entry.getMeasuredClass());
}
}
}
/**
* Add new phase to the list of phases to consider.
* @param composition Composition of phase
* @param energy Energy of phase
*/
public void addPhase(CompositionEntry composition, double energy) {
Double curEnergy = Phases.get(composition);
if (curEnergy == null) {
// Add if there is no current entry at this composition
Phases.put(composition, energy);
} else if (curEnergy > energy) {
// If there is a phase, update only if new energy is lower than current
Phases.put(composition, energy);
}
}
/**
* Get the number of phases being considered for GCLP
* @return Number of phases
*/
public int numPhases() {
return Phases.size();
}
/**
* Compute the ground state phase equilibria for a certain composition.
* @param composition Composition to be considered
* @throws java.lang.Exception
*/
public void doGCLP(CompositionEntry composition) throws Exception {
// Set the composition and pull up lookup data
CurrentComposition = composition.clone();
int[] curElems = CurrentComposition.getElements();
double[] curFrac = CurrentComposition.getFractions();
// Get the current possible phases (i.e., those that contain exclusively
// the elements in the current compound).
List<CompositionEntry> components = new LinkedList<>();
List<Double> energies = new LinkedList<>();
for (Map.Entry<CompositionEntry, Double> phase : Phases.entrySet()) {
CompositionEntry component = phase.getKey();
Double energy = phase.getValue();
// Check whether this entry is in the target phase diagram
int[] thisElems = component.getElements();
boolean isIn = true;
for (int thisElem : thisElems) {
if (! ArrayUtils.contains(curElems, thisElem)) {
isIn = false;
break;
}
}
// If it is, add it to the list
if (isIn) {
components.add(component);
energies.add(energy);
}
}
// Set up constraints
// Type #1 : Mass Conservation
List<LinearConstraint> constraints = new ArrayList<>(curElems.length);
for (int e=0; e<curElems.length; e++) {
double[] coeff = new double[components.size()];
for (int i=0; i<components.size(); i++) {
coeff[i] = components.get(i).getElementFraction(curElems[e]);
}
constraints.add(new LinearConstraint(coeff, Relationship.EQ, curFrac[e]));
}
// Type #2 : Normalization
double[] coeff = new double[components.size()];
Arrays.fill(coeff, 1.0);
constraints.add(new LinearConstraint(coeff, Relationship.EQ, 1.0));
// Make the constratint set object
LinearConstraintSet constraintSet = new LinearConstraintSet(constraints);
// Set up objective function
double[] energyTerms = new double[energies.size()];
for (int i=0; i<energyTerms.length; i++) {
energyTerms[i] = energies.get(i);
}
LinearObjectiveFunction objFun = new LinearObjectiveFunction(energyTerms, 0);
// Call LP solver
SimplexSolver solver = new SimplexSolver();
PointValuePair result = solver.optimize(objFun,
constraintSet,
new NonNegativeConstraint(true));
// Store result
Equilibrium.clear();
double[] equilFracs = result.getPoint();
for (int i=0; i<components.size(); i++) {
if (equilFracs[i] > 1e-6) {
Equilibrium.put(components.get(i), equilFracs[i]);
}
}
GroundStateEnergy = result.getValue();
}
/**
* Get computed ground state energy of last composition computed with this solver.
* @return Ground state energy
* @throws java.lang.Exception
*/
public double getGroundStateEnergy() throws Exception {
if (Equilibrium.isEmpty()) {
throw new Exception("GCLP has not yet been run");
}
return GroundStateEnergy;
}
/**
* Get computed phase equilibria of last composition computed with this solver.
* @return Ground state phase equilibrium (compositions) and their relative fractions
* @throws java.lang.Exception
*/
public Map<CompositionEntry, Double> getPhaseEquilibria() throws Exception {
if (Equilibrium.isEmpty()) {
throw new Exception("GCLP has not yet been run");
}
return new TreeMap<>(Equilibrium);
}
}
|
package battlecode.world;
import static battlecode.common.GameConstants.BYTECODE_LIMIT_BASE;
import static battlecode.common.GameConstants.NUMBER_OF_INDICATOR_STRINGS;
import static battlecode.common.GameConstants.YIELD_BONUS;
import static battlecode.common.GameActionExceptionType.*;
import battlecode.common.*;
import battlecode.engine.GenericController;
import battlecode.engine.instrumenter.RobotMonitor;
import battlecode.engine.instrumenter.RobotDeathException;
import battlecode.engine.signal.Signal;
import battlecode.world.signal.*;
/*
TODO:
- tweak player
-specs & software page?
- performance tips
- figure out why it's not deterministic
- optimize
- non-constant java.util costs
- player's navigation class, and specs about it
- fix execute action hack w/ robotmonitor ??
- fix playerfactory/spawnsignal hack??
- better suicide() ??
- pare down GW, GWviewer methods; add engine.getallsignals?
- TEST energon transfer every round, with cap
- TEST better println tagging
- TEST optimized silencing
- TEST "control ints"
- TEST indicator strings
- TEST map offsets
- TEST tiebreaking conditions
- TEST senseNearbyUpgrades
- TEST no battery freeze
- TEST upgrades
- TEST upgrades on map
- TEST only one energonchangesignal / round / robot
- TEST exception polling for action queue
- TEST fix action timing
- TEST action queue
- TEST broadcast queue
- TEST emp detonate
- TEST locating enemy batteries -- return direction
- TEST InternalArchon
- TEST energon decay
- TEST new energon transfer
- TEST map parsing
- TEST run perl script to get robottypes
- TEST serializable stuff
- TEST getNextMessage arrays
- TEST responding to signals
- TEST clock
*/
public class RobotControllerImpl extends ControllerShared implements RobotController, GenericController {
protected MapLocation locThisTurn;
protected Direction dirThisTurn;
public RobotControllerImpl(GameWorld gw, InternalRobot r) {
super(gw, r);
r.setRC(this);
}
/**
* {@inheritDoc}
*/
public Direction getDirection() {
return dirThisTurn;
}
/**
* {@inheritDoc}
*/
public double getHitpoints() {
return robot.getEnergonLevel();
}
public double getTeamResources() {
return gameWorld.resources(getTeam());
}
/**
* {@inheritDoc}
*/
public double getMaxHp() {
return robot.getMaxEnergon();
}
/**
* {@inheritDoc}
*/
public MapLocation getLocation() {
return locThisTurn;
}
/**
* {@inheritDoc}
*/
public Message getNextMessage() {
return robot.dequeueIncomingMessage();
}
/**
* {@inheritDoc}
*/
public Message[] getAllMessages() {
return robot.dequeueIncomingMessages();
}
/**
* {@inheritDoc}
*/
public Team getTeam() {
return robot.getTeam();
}
public int getBytecodeLimit() {
return robot.getBytecodeLimit();
}
public int getMapMinPoints() {
return gameWorld.getGameMap().getMinPoints();
}
public Chassis getChassis() {
return robot.getChassis();
}
public ComponentController[] components() {
return robot.getComponentControllers();
}
public ComponentController[] newComponents() {
return robot.getNewComponentControllers();
}
public ComponentController[] components(ComponentType type) {
return robot.getComponentControllers(type);
}
public ComponentController[] components(ComponentClass cls) {
return robot.getComponentControllers(cls);
}
/**
* {@inheritDoc}
*/
public void yield() {
int bytecodesBelowBase = BYTECODE_LIMIT_BASE - RobotMonitor.getBytecodesUsed();
if(bytecodesBelowBase>0)
gameWorld.adjustResources(robot.getTeam(),YIELD_BONUS*bytecodesBelowBase/BYTECODE_LIMIT_BASE*robot.chassis.upkeep);
RobotMonitor.endRunner();
}
/**
* {@inheritDoc}
*/
public void suicide() {
throw new RobotDeathException();
}
/**
* {@inheritDoc}
*/
public void breakpoint() {
gameWorld.notifyBreakpoint();
}
/**
* {@inheritDoc}
*/
public TerrainTile senseTerrainTile(MapLocation loc) {
assertNotNull(loc);
return robot.getMapMemory().recallTerrain(loc);
}
/**
* {@inheritDoc}
*/
public void setIndicatorString(int stringIndex, String newString) {
if (stringIndex >= 0 && stringIndex < NUMBER_OF_INDICATOR_STRINGS)
(new IndicatorStringSignal(robot, stringIndex, newString)).accept(gameWorld);
}
public void setIndicatorStringFormat(int stringIndex, String format, Object... args) {
setIndicatorString(stringIndex, String.format(format, args));
}
/**
* {@inheritDoc}
*/
public long getControlBits() {
return robot.getControlBits();
}
/**
* {@inheritDoc}
*/
public void addMatchObservation(String observation) {
(new MatchObservationSignal(robot, observation)).accept(gameWorld);
}
/**
* {@inheritDoc}
*/
public void setTeamMemory(int index, long value) {
gameWorld.setArchonMemory(robot.getTeam(), index, value);
}
public void setTeamMemory(int index, long value, long mask) {
gameWorld.setArchonMemory(robot.getTeam(), index, value, mask);
}
public long[] getTeamMemory() {
return gameWorld.getOldArchonMemory()[robot.getTeam().ordinal()];
}
public int hashCode() {
return robot.getID();
}
public void processBeginningOfTurn() {
if (!(robot.getLocation().equals(locThisTurn) && robot.getDirection().equals(dirThisTurn))) {
robot.saveMapMemory(locThisTurn, robot.getLocation(), false);
locThisTurn = robot.getLocation();
dirThisTurn = robot.getDirection();
}
}
}
|
package ahuglajbclajep.linebot;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.DateTimeException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.EnumMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
@WebServlet("/callback")
public class CallBack extends HttpServlet {
private static final String APP_NAME = System.getenv("APP_NAME");
private static final String SECRET_KEY = System.getenv("LINE_BOT_CHANNEL_SECRET");
private static final String TOKEN = System.getenv("LINE_BOT_CHANNEL_TOKEN");
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) {
String sig = req.getHeader("X-Line-Signature");
byte[] reqAll;
try (InputStream in = req.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
while (true) {
int i = in.read();
if (i == -1) {
reqAll = out.toByteArray();
break;
}
out.write(i);
}
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA256"));
String csig = Base64.getEncoder().encodeToString(mac.doFinal(reqAll));
if (!csig.equals(sig)) throw(new IOException());
} catch (IOException | NullPointerException | NoSuchAlgorithmException | InvalidKeyException e) {
res.setStatus(HttpServletResponse.SC_OK);
return;
}
ObjectMapper mapper = new ObjectMapper();
JsonNode events;
try {
events = mapper.readTree(reqAll).path("events");
} catch (IOException e) {
res.setStatus(HttpServletResponse.SC_OK);
return;
}
String replyMess;
if ("message".equals(events.path(0).path("type").asText())) {
replyMess = createReply(events.path(0).path("message"));
} else if ("join".equals(events.path(0).path("type").asText())){
replyMess = "\"messages\":[{\"type\":\"text\", \"text\":\"\"}]";
} else {
res.setStatus(HttpServletResponse.SC_OK);
return;
}
HttpPost httpPost = new HttpPost("https://api.line.me/v2/bot/message/reply");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + TOKEN);
StringBuffer replyBody = new StringBuffer("{\"replyToken\":\"")
.append(events.path(0).path("replyToken").asText())
.append("\",")
.append(replyMess)
.append("}");
httpPost.setEntity(new StringEntity(replyBody.toString(), StandardCharsets.UTF_8));
try (CloseableHttpResponse resp = HttpClients.createDefault().execute(httpPost)) {
} catch (IOException e) {}
res.setStatus(HttpServletResponse.SC_OK);
}
private String GetData(String sVal){
String sTmp;
String sX;
String sY;
int iPos;
iPos=sVal.indexOf("?lat=");
if(iPos>0) {
sTmp = sVal.substring(iPos);
}
else
{
sTmp=sVal;
}
sTmp=sTmp.replace("?lat=","");
sTmp=sTmp.replace("&lng=",",");
sTmp=sTmp.replace("&g=2","");
iPos=sTmp.indexOf(",");
if(iPos>0) {
sX = sTmp.substring(0, iPos);
sY = sTmp.substring(iPos + 1);
if(sX.length()>10) {
sX = sX.substring(0, 10);
}
if(sY.length()>10) {
sY = sY.substring(0, 10);
}
sTmp = sX + ',' + sY;
}
return sTmp;
}
private String createReply(JsonNode message){
StringBuffer replyMessages = new StringBuffer("\"messages\":[");
String type = message.path("type").asText();
if ("text".equals(type)) {
String[] args;
args = message.path("text").asText().split(" ", 2);
if ("@qr".equals(args[0])) {
replyMessages.append("{\"type\":\"text\",\"text\":\"")
.append("")
.append("\"},");
try {
String url = createQR(args[1], message.path("id").asText()); // /tmp/hoge.jpg
replyMessages.append("{\"type\":\"image\",\"originalContentUrl\":\"")
.append("https://").append(APP_NAME).append(".herokuapp.com")
.append(url)
.append("\",\"previewImageUrl\":\"")
.append("https://").append(APP_NAME).append(".herokuapp.com")
.append(url);
} catch (ArrayIndexOutOfBoundsException | IOException | WriterException e) {
replyMessages.append("{\"type\":\"text\",\"text\":\"")
.append("");
}
} else if ("@time".equals(args[0])) {
replyMessages.append("{\"type\":\"text\",\"text\":\"")
.append("")
.append("\"},")
.append("{\"type\":\"text\",\"text\":\"");
try {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of(args[1]));
replyMessages.append(now.format(DateTimeFormatter.ofPattern("MM/dd HH:mm")));
} catch (ArrayIndexOutOfBoundsException | DateTimeException e) {
replyMessages.append("")
.append(System.getProperty("line.separator"))
.append("https://git.io/vyqDP");
}
} else {
replyMessages=GetData(message.path("text").asText());
/*
replyMessages.append("{\"type\":\"text\",\"text\":\"")
.append("");
*/
}
}
replyMessages.append("\"}]");
return replyMessages.toString();
}
private String createQR(String arg, String id) throws WriterException, IOException {
EnumMap<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(arg, BarcodeFormat.QR_CODE, 185, 185, hints);
// 4,40171x171, MARGIN4
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
StringBuffer fileName = new StringBuffer("/tmp/").append(id).append(".jpg");
ImageIO.write(image, "JPEG", new File(fileName.toString())); // tmp
return fileName.toString();
}
}
|
package backend.resource;
import java.time.LocalDate;
import java.util.Optional;
import org.eclipse.egit.github.core.Milestone;
import backend.resource.serialization.SerializableMilestone;
import util.Utility;
@SuppressWarnings("unused")
public class TurboMilestone {
private static final String STATE_CLOSED = "closed";
private static final String STATE_OPEN = "open";
private void ______SERIALIZED_FIELDS______() {
}
private final int id;
private String title;
private Optional<LocalDate> dueDate;
private String description;
private boolean isOpen;
private int openIssues;
private int closedIssues;
private void ______TRANSIENT_FIELDS______() {
}
private final String repoId;
private void ______CONSTRUCTORS______() {
}
public TurboMilestone(String repoId, int id, String title) {
this.id = id;
this.title = title;
this.dueDate = Optional.empty();
this.description = "";
this.isOpen = true;
this.openIssues = 0;
this.closedIssues = 0;
this.repoId = repoId;
}
public TurboMilestone(String repoId, Milestone milestone) {
this.id = milestone.getNumber();
this.title = milestone.getTitle();
this.dueDate = milestone.getDueOn() == null
? Optional.empty()
: Optional.of(Utility.dateToLocalDateTime(milestone.getDueOn()).toLocalDate());
this.description = milestone.getDescription() == null ? "" : milestone.getDescription();
this.isOpen = milestone.getState().equals(STATE_OPEN);
this.openIssues = milestone.getOpenIssues();
this.closedIssues = milestone.getClosedIssues();
this.repoId = repoId;
}
public TurboMilestone(String repoId, SerializableMilestone milestone) {
this.id = milestone.getId();
this.title = milestone.getTitle();
this.dueDate = milestone.getDueDate();
this.description = milestone.getDescription();
this.isOpen = milestone.isOpen();
this.openIssues = milestone.getOpenIssues();
this.closedIssues = milestone.getClosedIssues();
this.repoId = repoId;
}
private void ______METHODS______() {
}
@Override
public String toString() {
return title;
}
private void ______BOILERPLATE______() {
}
public String getRepoId() {
return repoId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Optional<LocalDate> getDueDate() {
return dueDate;
}
public void setDueDate(Optional<LocalDate> dueDate) {
this.dueDate = dueDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean isOpen) {
this.isOpen = isOpen;
}
public int getOpenIssues() {
return openIssues;
}
public void setOpenIssues(int openIssues) {
this.openIssues = openIssues;
}
public int getClosedIssues() {
return closedIssues;
}
public void setClosedIssues(int closedIssues) {
this.closedIssues = closedIssues;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TurboMilestone that = (TurboMilestone) o;
return closedIssues == that.closedIssues &&
id == that.id && isOpen == that.isOpen &&
openIssues == that.openIssues &&
description.equals(that.description) &&
dueDate.equals(that.dueDate) &&
title.equals(that.title);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + title.hashCode();
result = 31 * result + dueDate.hashCode();
result = 31 * result + description.hashCode();
result = 31 * result + (isOpen ? 1 : 0);
result = 31 * result + openIssues;
result = 31 * result + closedIssues;
return result;
}
}
|
package com.Acrobot.ChestShop;
import com.Acrobot.Breeze.Configuration.Configuration;
import com.Acrobot.ChestShop.Commands.Give;
import com.Acrobot.ChestShop.Commands.ItemInfo;
import com.Acrobot.ChestShop.Commands.Toggle;
import com.Acrobot.ChestShop.Commands.Version;
import com.Acrobot.ChestShop.Configuration.Messages;
import com.Acrobot.ChestShop.Configuration.Properties;
import com.Acrobot.ChestShop.Database.Migrations;
import com.Acrobot.ChestShop.Listeners.Block.BlockPlace;
import com.Acrobot.ChestShop.Listeners.Block.Break.ChestBreak;
import com.Acrobot.ChestShop.Listeners.Block.Break.SignBreak;
import com.Acrobot.ChestShop.Listeners.Block.SignCreate;
import com.Acrobot.ChestShop.Listeners.Economy.ServerAccountCorrector;
import com.Acrobot.ChestShop.Listeners.Economy.TaxModule;
import com.Acrobot.ChestShop.Listeners.AuthMeChestShopListener;
import com.Acrobot.ChestShop.Listeners.GarbageTextListener;
import com.Acrobot.ChestShop.Listeners.Item.ItemMoveListener;
import com.Acrobot.ChestShop.Listeners.ItemInfoListener;
import com.Acrobot.ChestShop.Listeners.Modules.DiscountModule;
import com.Acrobot.ChestShop.Listeners.Modules.PriceRestrictionModule;
import com.Acrobot.ChestShop.Listeners.Player.*;
import com.Acrobot.ChestShop.Listeners.PostShopCreation.CreationFeeGetter;
import com.Acrobot.ChestShop.Listeners.PostShopCreation.MessageSender;
import com.Acrobot.ChestShop.Listeners.PostShopCreation.ShopCreationLogger;
import com.Acrobot.ChestShop.Listeners.PostShopCreation.SignSticker;
import com.Acrobot.ChestShop.Listeners.PostTransaction.*;
import com.Acrobot.ChestShop.Listeners.PreShopCreation.*;
import com.Acrobot.ChestShop.Listeners.PreTransaction.*;
import com.Acrobot.ChestShop.Listeners.PreTransaction.ErrorMessageSender;
import com.Acrobot.ChestShop.Listeners.PreTransaction.PermissionChecker;
import com.Acrobot.ChestShop.Listeners.ShopRemoval.ShopRefundListener;
import com.Acrobot.ChestShop.Listeners.ShopRemoval.ShopRemovalLogger;
import com.Acrobot.ChestShop.Logging.FileFormatter;
import com.Acrobot.ChestShop.Metadata.ItemDatabase;
import com.Acrobot.ChestShop.Signs.RestrictedSign;
import com.Acrobot.ChestShop.UUIDs.NameManager;
import com.Acrobot.ChestShop.Updater.Updater;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.Message;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.Metrics;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* Main file of the plugin
*
* @author Acrobot
*/
public class ChestShop extends JavaPlugin {
private static ChestShop plugin;
private static Server server;
private static PluginDescriptionFile description;
private static File dataFolder;
private static ItemDatabase itemDatabase;
private static Logger logger;
private FileHandler handler;
public ChestShop() {
dataFolder = getDataFolder();
logger = getLogger();
description = getDescription();
server = getServer();
plugin = this;
}
public void onEnable() {
Configuration.pairFileAndClass(loadFile("config.yml"), Properties.class);
Configuration.pairFileAndClass(loadFile("local.yml"), Messages.class);
turnOffDatabaseLogging();
handleMigrations();
itemDatabase = new ItemDatabase();
NameManager.load();
Dependencies.loadPlugins();
registerEvents();
if (Properties.LOG_TO_FILE) {
File log = loadFile("ChestShop.log");
FileHandler handler = loadHandler(log.getAbsolutePath());
handler.setFormatter(new FileFormatter());
this.handler = handler;
logger.addHandler(handler);
}
if (!Properties.LOG_TO_CONSOLE) {
logger.setUseParentHandlers(false);
}
getCommand("iteminfo").setExecutor(new ItemInfo());
getCommand("csVersion").setExecutor(new Version());
getCommand("csGive").setExecutor(new Give());
getCommand("cstoggle").setExecutor(new Toggle());
startStatistics();
startUpdater();
}
private void turnOffDatabaseLogging() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
org.apache.logging.log4j.core.config.Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig("");
loggerConfig.addFilter(new AbstractFilter() {
@Override
public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, String msg, Object... params) {
return filter(logger.getName(), level);
}
@Override
public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, Object msg, Throwable t) {
return filter(logger.getName(), level);
}
@Override
public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, Message msg, Throwable t) {
return filter(logger.getName(), level);
}
@Override
public Result filter(LogEvent event) {
return filter(event.getLoggerName(), event.getLevel());
}
private Result filter(String classname, Level level) {
if (level.isAtLeastAsSpecificAs(Level.ERROR) && !classname.contains("SqliteDatabaseType")) {
return Result.NEUTRAL;
}
if (classname.contains("SqliteDatabaseType") || classname.contains("TableUtils")) {
return Result.DENY;
} else {
return Result.NEUTRAL;
}
}
});
}
private void handleMigrations() {
File versionFile = loadFile("version");
YamlConfiguration previousVersion = YamlConfiguration.loadConfiguration(versionFile);
if (previousVersion.get("version") == null) {
previousVersion.set("version", Migrations.CURRENT_DATABASE_VERSION);
try {
previousVersion.save(versionFile);
} catch (IOException e) {
e.printStackTrace();
}
}
int lastVersion = previousVersion.getInt("version");
int newVersion = Migrations.migrate(lastVersion);
if (lastVersion != newVersion) {
previousVersion.set("version", newVersion);
try {
previousVersion.save(versionFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static File loadFile(String string) {
File file = new File(dataFolder, string);
return loadFile(file);
}
private static File loadFile(File file) {
if (!file.exists()) {
try {
if (file.getParent() != null) {
file.getParentFile().mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private static FileHandler loadHandler(String path) {
FileHandler handler = null;
try {
handler = new FileHandler(path, true);
} catch (IOException ex) {
ex.printStackTrace();
}
return handler;
}
public void onDisable() {
getServer().getScheduler().cancelTasks(this);
Toggle.clearToggledPlayers();
if (handler != null) {
handler.close();
getLogger().removeHandler(handler);
}
}
////////////////// REGISTER EVENTS, SCHEDULER & STATS ///////////////////////////
private void registerEvents() {
registerEvent(new com.Acrobot.ChestShop.Plugins.ChestShop()); //Chest protection
registerPreShopCreationEvents();
registerPreTransactionEvents();
registerPostShopCreationEvents();
registerPostTransactionEvents();
registerShopRemovalEvents();
registerModules();
registerEvent(new SignBreak());
registerEvent(new SignCreate());
registerEvent(new ChestBreak());
registerEvent(new BlockPlace());
registerEvent(new PlayerConnect());
registerEvent(new PlayerInteract());
registerEvent(new PlayerInventory());
registerEvent(new PlayerLeave());
registerEvent(new PlayerTeleport());
registerEvent(new ItemInfoListener());
registerEvent(new GarbageTextListener());
Plugin authMe = getServer().getPluginManager().getPlugin("AuthMe");
if (authMe != null && authMe.isEnabled()){
registerEvent(new AuthMeChestShopListener());
}
registerEvent(new RestrictedSign());
if (!Properties.TURN_OFF_HOPPER_PROTECTION) {
registerEvent(new ItemMoveListener());
}
}
private void registerShopRemovalEvents() {
registerEvent(new ShopRefundListener());
registerEvent(new ShopRemovalLogger());
}
private void registerPreShopCreationEvents() {
if (Properties.BLOCK_SHOPS_WITH_SELL_PRICE_HIGHER_THAN_BUY_PRICE) {
registerEvent(new PriceRatioChecker());
}
registerEvent(new ChestChecker());
registerEvent(new ItemChecker());
registerEvent(new MoneyChecker());
registerEvent(new NameChecker());
registerEvent(new com.Acrobot.ChestShop.Listeners.PreShopCreation.PermissionChecker());
registerEvent(new com.Acrobot.ChestShop.Listeners.PreShopCreation.ErrorMessageSender());
registerEvent(new PriceChecker());
registerEvent(new QuantityChecker());
registerEvent(new TerrainChecker());
}
private void registerPostShopCreationEvents() {
registerEvent(new CreationFeeGetter());
registerEvent(new MessageSender());
registerEvent(new SignSticker());
registerEvent(new ShopCreationLogger());
}
private void registerPreTransactionEvents() {
if (Properties.ALLOW_PARTIAL_TRANSACTIONS) {
registerEvent(new PartialTransactionModule());
} else {
registerEvent(new AmountAndPriceChecker());
}
registerEvent(new CreativeModeIgnorer());
registerEvent(new ErrorMessageSender());
registerEvent(new PermissionChecker());
registerEvent(new PriceValidator());
registerEvent(new ShopValidator());
registerEvent(new SpamClickProtector());
registerEvent(new StockFittingChecker());
}
private void registerPostTransactionEvents() {
registerEvent(new EconomicModule());
registerEvent(new EmptyShopDeleter());
registerEvent(new ItemManager());
registerEvent(new TransactionLogger());
registerEvent(new TransactionMessageSender());
}
private void registerModules() {
registerEvent(new DiscountModule());
registerEvent(new PriceRestrictionModule());
registerEconomicalModules();
}
private void registerEconomicalModules() {
registerEvent(new ServerAccountCorrector());
registerEvent(new TaxModule());
}
public void registerEvent(Listener listener) {
getServer().getPluginManager().registerEvents(listener, this);
}
private void startStatistics() {
try {
new Metrics(this).start();
} catch (IOException ex) {
ChestShop.getBukkitLogger().severe("There was an error while submitting statistics.");
}
}
private static final int PROJECT_BUKKITDEV_ID = 31263;
private void startUpdater() {
if (Properties.TURN_OFF_UPDATES) {
return;
}
new Updater(this, PROJECT_BUKKITDEV_ID, this.getFile(), Updater.UpdateType.DEFAULT, true);
}
public static ItemDatabase getItemDatabase() {
return itemDatabase;
}
public static File getFolder() {
return dataFolder;
}
public static Logger getBukkitLogger() {
return logger;
}
public static Server getBukkitServer() {
return server;
}
public static String getVersion() {
return description.getVersion();
}
public static String getPluginName() {
return description.getName();
}
public static List<String> getDependencies() {
return description.getSoftDepend();
}
public static ChestShop getPlugin() {
return plugin;
}
public static void registerListener(Listener listener) {
plugin.registerEvent(listener);
}
public static void callEvent(Event event) {
Bukkit.getPluginManager().callEvent(event);
}
}
|
package com.contained.game.ui;
import java.awt.Color;
import java.text.DecimalFormat;
import org.lwjgl.opengl.GL11;
import codechicken.lib.packet.PacketCustom;
import com.contained.game.network.ServerPacketHandler;
import com.contained.game.user.PlayerTeamIndividual;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.util.ResourceLocation;
public class GuiSurvey extends GuiScreen {
private static final ResourceLocation bookGuiTextures = new ResourceLocation("minecraft", "textures/gui/book.png");
private int disableTime = 0;
private int bookImageWidth = 192;
private int bookImageHeight = 192;
public int lastProgress;
private GuiButton buttonFinish;
private GuiButton buttonStart;
private GuiButton buttonNext;
private GuiButton buttonMale;
private GuiButton buttonFemale;
private GuiButton buttonOptionA;
private GuiButton buttonOptionB;
private GuiButton buttonOptionC;
private GuiButton buttonOptionD;
private GuiButton buttonOptionE;
private GuiTextField textResponseA;
private GuiTextField textResponseB;
private PlayerTeamIndividual playerCopy;
public static final int PAGE_GENDER = 1;
public static final int PAGE_AGE = 2;
public static final int PAGE_ETHNICITY = 3;
public static final int PAGE_MINECRAFT = 4;
public static final int PAGE_PERSONALITY = 5;
public GuiSurvey(PlayerTeamIndividual pdata) {
playerCopy = new PlayerTeamIndividual(pdata);
lastProgress = pdata.surveyResponses.progress;
}
@Override
public void initGui()
{
super.initGui();
int bottomMargin = -42;
int leftMargin = -6;
this.buttonFinish = new GuiButton(0, this.width / 2 - 100, 4 + this.bookImageHeight, 200, 20, "Done");
this.buttonStart = new GuiButton(1, this.width / 2 - 50 + leftMargin, bottomMargin + this.bookImageHeight, 100, 20, "Begin!");
this.buttonOptionA = new GuiButton(2, this.width / 2 - 50 + leftMargin, bottomMargin-(20*4) + this.bookImageHeight, 100, 16, "Strongly Agree");
this.buttonOptionB = new GuiButton(3, this.width / 2 - 50 + leftMargin, bottomMargin-(20*3) + this.bookImageHeight, 100, 16, "Agree");
this.buttonOptionC = new GuiButton(4, this.width / 2 - 50 + leftMargin, bottomMargin-(20*2) + this.bookImageHeight, 100, 16, "Neutral");
this.buttonOptionD = new GuiButton(5, this.width / 2 - 50 + leftMargin, bottomMargin-(20*1) + this.bookImageHeight, 100, 16, "Disagree");
this.buttonOptionE = new GuiButton(6, this.width / 2 - 50 + leftMargin, bottomMargin-(20*0) + this.bookImageHeight, 100, 16, "Strongly Disagree");
this.buttonNext = new GuiButton(1, this.width / 2 - 50 + leftMargin, bottomMargin + this.bookImageHeight, 100, 20, "Next");
this.buttonMale = new GuiButton(7, this.width / 2 - 50 + leftMargin, bottomMargin-(24*3) + this.bookImageHeight, 100, 20, "Male");
this.buttonFemale = new GuiButton(8, this.width / 2 - 50 + leftMargin, bottomMargin-(24*2) + this.bookImageHeight, 100, 20, "Female");
this.textResponseA = new GuiTextField(this.fontRendererObj, this.width / 2 - 50 + leftMargin, bottomMargin-(24*3) + this.bookImageHeight, 100, 20);
this.textResponseA.setTextColor(Color.WHITE.hashCode());
this.textResponseA.setEnableBackgroundDrawing(true);
this.textResponseA.setMaxStringLength(25);
this.textResponseA.setText("");
this.textResponseA.setFocused(false);
this.textResponseB = new GuiTextField(this.fontRendererObj, this.width / 2 - 50 + leftMargin, bottomMargin-(int)(24.0*1.5) + this.bookImageHeight, 100, 20);
this.textResponseB.setTextColor(Color.WHITE.hashCode());
this.textResponseB.setEnableBackgroundDrawing(true);
this.textResponseB.setMaxStringLength(25);
this.textResponseB.setText("");
this.textResponseB.setFocused(false);
this.updateButtons();
}
public boolean isTextFieldAEnabled() {
int page = playerCopy.surveyResponses.progress;
if (page == PAGE_AGE || page == PAGE_ETHNICITY || page == PAGE_MINECRAFT)
return true;
return false;
}
public boolean isTextFieldBEnabled() {
int page = playerCopy.surveyResponses.progress;
if (page == PAGE_MINECRAFT)
return true;
return false;
}
@Override
public void updateScreen()
{
super.updateScreen();
if (!this.buttonOptionA.enabled) {
this.disableTime
if (this.disableTime <= 0) {
this.buttonOptionA.enabled = true;
this.buttonOptionB.enabled = true;
this.buttonOptionC.enabled = true;
this.buttonOptionD.enabled = true;
this.buttonOptionE.enabled = true;
}
}
// For pages that require numerical textfield inputs, disable the
// next button until the text field contains a valid number.
this.buttonNext.enabled = true;
if (playerCopy.surveyResponses.progress == PAGE_AGE
|| playerCopy.surveyResponses.progress == PAGE_MINECRAFT) {
try {
int val = Integer.parseInt(this.textResponseA.getText().trim());
if (val < 0 || val > 150)
this.buttonNext.enabled = false;
if (playerCopy.surveyResponses.progress == PAGE_MINECRAFT && val > 12)
this.buttonNext.enabled = false;
} catch (Exception e) {
this.buttonNext.enabled = false;
}
}
if (playerCopy.surveyResponses.progress == PAGE_MINECRAFT) {
try {
int val = Integer.parseInt(this.textResponseB.getText().trim());
if (val < 0)
this.buttonNext.enabled = false;
} catch (Exception e) {
this.buttonNext.enabled = false;
}
}
if (playerCopy.surveyResponses.progress == PAGE_ETHNICITY
&& this.textResponseA.getText().trim().length() == 0)
this.buttonNext.enabled = false;
}
@Override
public void mouseClicked(int i , int j, int k){
super.mouseClicked(i, j, k);
if (isTextFieldAEnabled())
this.textResponseA.mouseClicked(i, j, k);
if (isTextFieldBEnabled())
this.textResponseB.mouseClicked(i, j, k);
}
@Override
public void keyTyped(char c, int i){
super.keyTyped(c, i);
if (isTextFieldAEnabled() && this.textResponseA.isFocused())
this.textResponseA.textboxKeyTyped(c, i);
if (isTextFieldBEnabled() && this.textResponseB.isFocused())
this.textResponseB.textboxKeyTyped(c, i);
}
private void updateButtons() {
this.buttonList.clear();
this.textResponseA.setText("");
this.textResponseB.setText("");
if (playerCopy.surveyResponses.progress == 0) {
//Intro Page
this.buttonList.add(this.buttonStart);
} else if (playerCopy.surveyResponses.progress == PAGE_GENDER) {
//Gender Page
this.buttonList.add(this.buttonMale);
this.buttonList.add(this.buttonFemale);
}
else if (playerCopy.surveyResponses.progress <= SurveyData.getSurveyLength()
&& playerCopy.surveyResponses.progress >= PAGE_PERSONALITY) {
//Personality Question Page
this.buttonList.add(this.buttonOptionA);
this.buttonList.add(this.buttonOptionB);
this.buttonList.add(this.buttonOptionC);
this.buttonList.add(this.buttonOptionD);
this.buttonList.add(this.buttonOptionE);
} else if (playerCopy.surveyResponses.progress <= SurveyData.getSurveyLength()) {
this.buttonList.add(this.buttonNext);
}
this.buttonList.add(this.buttonFinish);
}
@Override
protected void actionPerformed(GuiButton b)
{
super.actionPerformed(b);
if (b.enabled) {
if (b.id == 7) //Male Button
playerCopy.surveyResponses.isMale = true;
else if (b.id == 8) //Female Button
playerCopy.surveyResponses.isMale = false;
if (b.id == 0) //Done Button
this.mc.displayGuiScreen(null);
else if (b.id == 1 || b.id == 7 || b.id == 8) //Start/Next Button
{
if (playerCopy.surveyResponses.progress == PAGE_AGE)
playerCopy.surveyResponses.age = Integer.parseInt(this.textResponseA.getText().trim());
else if (playerCopy.surveyResponses.progress == PAGE_ETHNICITY)
playerCopy.surveyResponses.ethnicity = this.textResponseA.getText().trim();
else if (playerCopy.surveyResponses.progress == PAGE_MINECRAFT) {
playerCopy.surveyResponses.mcMonths = Integer.parseInt(this.textResponseA.getText().trim());
playerCopy.surveyResponses.mcYears = Integer.parseInt(this.textResponseB.getText().trim());
}
playerCopy.surveyResponses.progress++;
if (playerCopy.surveyResponses.progress == PAGE_PERSONALITY) {
//Disable the survey buttons for a brief period to prevent
//the button click from being double-counted.
this.disableTime = 10;
this.buttonOptionA.enabled = false;
this.buttonOptionB.enabled = false;
this.buttonOptionC.enabled = false;
this.buttonOptionD.enabled = false;
this.buttonOptionE.enabled = false;
}
updateButtons();
}
else if (b.id >= 2 && b.id <= 6) //Option buttons
{
playerCopy.surveyResponses.personality[playerCopy.surveyResponses.progress-PAGE_PERSONALITY] = b.id-2;
playerCopy.surveyResponses.progress++;
updateButtons();
}
}
}
@Override
public void onGuiClosed() {
super.onGuiClosed();
if (this.lastProgress != playerCopy.surveyResponses.progress) {
PacketCustom packet = ServerPacketHandler.packetUpdateSurvey(playerCopy);
ServerPacketHandler.sendToServer(packet.toPacket());
PlayerTeamIndividual localPData = PlayerTeamIndividual.get(playerCopy.playerName);
localPData.surveyResponses = playerCopy.surveyResponses;
}
}
@Override
public boolean doesGuiPauseGame(){
return false;
}
public void drawScreen(int par1, int par2, float par3)
{
super.drawScreen(par1, par2, par3);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(bookGuiTextures);
int x = (this.width - this.bookImageWidth) / 2;
byte y = 2;
this.drawTexturedModalRect(x, y, 0, 0, this.bookImageWidth, this.bookImageHeight);
if (playerCopy.surveyResponses.progress == 0) {
//Intro Page
String title = "Personality Survey";
String body = "Please take a moment to answer this brief personality survey. For each statement, state how much you feel it reflects yourself. Your responses will be visible only to the server administrators.";
this.fontRendererObj.drawString("§l§n"+title, x - this.fontRendererObj.getStringWidth(title)/2 + (this.bookImageWidth-36)/2 + 7, y + 16, 0);
this.fontRendererObj.drawSplitString(body, x + 36, y + 16 + 16, 116, 0);
}
else if (playerCopy.surveyResponses.progress <= SurveyData.getSurveyLength()) {
//Question Page
String headerStr = "== "+playerCopy.surveyResponses.progress+" of "+SurveyData.getSurveyLength()+" ==";
this.fontRendererObj.drawString(headerStr, x - this.fontRendererObj.getStringWidth(headerStr) + this.bookImageWidth - 44, y + 16, 0);
String question = "";
if (playerCopy.surveyResponses.progress >= PAGE_PERSONALITY)
question = SurveyData.data[playerCopy.surveyResponses.progress-PAGE_PERSONALITY].question;
else if (playerCopy.surveyResponses.progress == PAGE_AGE)
question = "How old are you?";
else if (playerCopy.surveyResponses.progress == PAGE_ETHNICITY)
question = "What is your ethnicity?";
else if (playerCopy.surveyResponses.progress == PAGE_GENDER)
question = "Which gender do you identify as?";
else if (playerCopy.surveyResponses.progress == PAGE_MINECRAFT)
question = "How long have you been playing Minecraft?";
this.fontRendererObj.drawSplitString(question, x + 36, y + 16 + 16, 116, 0);
if (playerCopy.surveyResponses.progress == PAGE_MINECRAFT) {
this.fontRendererObj.drawString("§nMonths:", x+36, y+16+16*3, 0);
this.fontRendererObj.drawString("§nYears:", x+36, y+16+(int)(16.0*5.25), 0);
}
if (isTextFieldAEnabled())
this.textResponseA.drawTextBox();
if (isTextFieldBEnabled())
this.textResponseB.drawTextBox();
}
else {
//Survey Complete Page
String title = "Survey Complete!";
String body = "Your results:";
this.fontRendererObj.drawString("§l§n"+title, x - this.fontRendererObj.getStringWidth(title)/2 + (this.bookImageWidth-36)/2 + 7, y + 16, 0);
this.fontRendererObj.drawString(body, x + 36, y + 16 + 16, 0);
this.fontRendererObj.drawString("Openness: "+signedFormat(
SurveyData.scoreResponses(SurveyData.Q.OPENNESS, playerCopy.surveyResponses.personality)), x + 36, y + 16 + 16*2, 0);
this.fontRendererObj.drawString("Conscientious: "+signedFormat(
SurveyData.scoreResponses(SurveyData.Q.CONSCIENTIOUSNESS, playerCopy.surveyResponses.personality)), x + 36, y + 16 + 16*3, 0);
this.fontRendererObj.drawString("Extraversion: "+signedFormat(
SurveyData.scoreResponses(SurveyData.Q.EXTRAVERSION, playerCopy.surveyResponses.personality)), x + 36, y + 16 + 16*4, 0);
this.fontRendererObj.drawString("Agreeableness: "+signedFormat(
SurveyData.scoreResponses(SurveyData.Q.AGREEABLENESS, playerCopy.surveyResponses.personality)), x + 36, y + 16 + 16*5, 0);
this.fontRendererObj.drawString("Neuroticism: "+signedFormat(
SurveyData.scoreResponses(SurveyData.Q.NEUROTICISM, playerCopy.surveyResponses.personality)), x + 36, y + 16 + 16*6, 0);
}
super.drawScreen(par1, par2, par3);
}
public String signedFormat(float value) {
if (value >= 0)
return "+"+(new DecimalFormat("0.00").format(value));
else
return ""+(new DecimalFormat("0.00").format(value));
}
}
|
package com.conveyal.gtfs;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.index.strtree.STRtree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.List;
import java.util.function.BiConsumer;
/**
* Cache STRTree spatial indexes of geometries of a particular type, with each spatial index keyed on a String
* (typically the bundle-scoped feed ID of the GTFS feed the geometries are drawn from). This is based on a Caffeine
* LoadingCache so should be thread safe and provide granular per-key locking, which is convenient when serving up
* lots of simultaneous vector tile requests.
*
* This is currently used only for looking up geomertries when producing Mapbox vector map tiles, hence the single
* set of hard-wired cache eviction parameters. For more general use we'd want another constructor to change them.
*/
public class GeometryCache<T extends Geometry> {
private static final Logger LOG = LoggerFactory.getLogger(GeometryCache.class);
/** How long after it was last accessed to keep a spatial index in memory. */
private static final Duration EXPIRE_AFTER_ACCESS = Duration.ofMinutes(10);
/** The maximum number of spatial indexes to keep in memory at once. */
private static final int MAX_SPATIAL_INDEXES = 4;
/** A cache of spatial indexes, usually keyed on a feed ID. */
private final LoadingCache<String, STRtree> cache;
public GeometryCache(BiConsumer<String, STRtree> loader) {
this.cache = Caffeine.newBuilder()
.maximumSize(MAX_SPATIAL_INDEXES)
.expireAfterAccess(EXPIRE_AFTER_ACCESS)
.removalListener(this::logCacheEviction)
.build((key) -> {
var tree = new STRtree();
loader.accept(key, tree);
tree.build();
return tree;
});
}
/** RemovalListener triggered when a spatial index is evicted from the cache. */
private void logCacheEviction (String feedId, STRtree value, RemovalCause cause) {
LOG.info("Spatial index removed. Feed {}, cause {}.", feedId, cause);
}
/**
* Return a List including all geometries that intersect a given envelope.
* Note that this overselects (can and will return some geometries outside the envelope).
* It could make sense to move some of the clipping logic in here if this class remains vector tile specific.
*/
public List<T> queryEnvelope(String key, Envelope envelope) {
return cache.get(key).query(envelope);
}
}
|
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class _1086 {
public static class Solution1 {
public int[][] highFive(int[][] items) {
TreeMap<Integer, List<Integer>> map = new TreeMap<>();
for (int[] studentToScore : items) {
if (map.containsKey(studentToScore[0])) {
map.get(studentToScore[0]).add(studentToScore[1]);
} else {
List<Integer> list = new ArrayList<>();
list.add(studentToScore[1]);
map.put(studentToScore[0], list);
}
}
int[][] result = new int[map.size()][2];
for (int id : map.keySet()) {
List<Integer> scores = map.get(id);
Collections.sort(scores);
int sum = 0;
for (int i = scores.size() - 1; i >= scores.size() - 5 && i >= 0; i
sum += scores.get(i);
}
result[id - 1][0] = id;
result[id - 1][1] = sum / 5;
}
return result;
}
}
public static class Solution2 {
public int[][] highFive(int[][] items) {
TreeMap<Integer, PriorityQueue<Integer>> treeMap = new TreeMap<>();
for (int[] studentToScores : items) {
if (treeMap.containsKey(studentToScores[0])) {
PriorityQueue<Integer> maxHeap = treeMap.get(studentToScores[0]);
maxHeap.offer(studentToScores[1]);
if (maxHeap.size() > 5) {
maxHeap.poll();
}
treeMap.put(studentToScores[0], maxHeap);
} else {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
maxHeap.offer(studentToScores[1]);
treeMap.put(studentToScores[0], maxHeap);
}
}
int[][] result = new int[treeMap.size()][2];
for (int id : treeMap.keySet()) {
result[id - 1][0] = id;
int sum = 0;
PriorityQueue<Integer> maxHeap = treeMap.get(id);
while (!maxHeap.isEmpty()) {
sum += maxHeap.poll();
}
result[id - 1][1] = sum / 5;
}
return result;
}
}
}
|
package com.github.fjdbc.op;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.logging.Logger;
import com.github.fjdbc.FjdbcException;
import com.github.fjdbc.util.FjdbcUtil;
/**
* Represents a sequence of statements that must be executed in a single transaction.
*/
public class CompositeOp implements DbOp {
private final DbOp[] operations;
public static Logger logger = Logger.getLogger(CompositeOp.class.getName());
public CompositeOp(DbOp... operations) {
this.operations = operations;
}
public CompositeOp(Collection<DbOp> operations) {
this(operations.toArray(new DbOp[0]));
}
@Override
public int executeAndCommit(Connection cnx) {
if (operations.length == 0) return 0;
try {
final int modifiedRows = execute(cnx);
cnx.commit();
return modifiedRows;
} catch (final Exception e) {
FjdbcUtil.rollbackConnection(cnx);
throw new FjdbcException(e);
} finally {
FjdbcUtil.closeConnection(cnx);
}
}
@Override
public int execute(Connection cnx) throws SQLException {
int modifiedRows = 0;
for (int i = 0; i < operations.length; i++) {
final DbOp t = operations[i];
try {
modifiedRows += t.execute(cnx);
} catch (final Exception e) {
throw new FjdbcException("DB Operation " + (i + 1) + "/" + operations.length + " failed", e);
}
}
return modifiedRows;
}
}
|
package com.jaamsim.events;
import java.util.ArrayList;
/**
* Class EventManager - Sandwell Discrete Event Simulation
* <p>
* The EventManager is responsible for scheduling future events, controlling
* conditional event evaluation, and advancing the simulation time. Events are
* scheduled in based on:
* <ul>
* <li>1 - The execution time scheduled for the event
* <li>2 - The priority of the event (if scheduled to occur at the same time)
* <li>3 - If both 1) and 2) are equal, the order in which the event was
* scheduled (FILO - Stack ordering)
* </ul>
* <p>
* The event time is scheduled using a backing long value. Double valued time is
* taken in by the scheduleWait function and scaled to the nearest long value
* using the simTimeFactor.
* <p>
* The EventManager thread is always the bottom thread on the threadStack, so
* that after each event has finished, along with any spawned events, the
* program control will pass back to the EventManager.
* <p>
* The runnable interface is implemented so that the eventManager runs as a
* separate thread.
* <p>
* EventManager is held as a static member of class entity, this ensures that
* all entities will schedule themselves with the same event manager.
*/
public final class EventManager {
public final String name;
private final Object lockObject; // Object used as global lock for synchronization
private EventTree eventTree;
private volatile boolean executeEvents;
private boolean processRunning;
private final ArrayList<Process> conditionalList; // List of all conditionally waiting processes
private final ArrayList<ConditionalHandle> conditionalHandles; // List of any handles tracking conditional events
private long currentTick; // Master simulation time (long)
private long nextTick; // The next tick to execute events at
private long targetTick; // the largest time we will execute events for (run to time)
private double ticksPerSecond; // The number of discrete ticks per simulated second
private double secsPerTick; // The length of time in seconds each tick represents
// Real time execution state
private long realTimeTick; // the simulation tick corresponding to the wall-clock millis value
private long realTimeMillis; // the wall-clock time in millis
private volatile boolean executeRealTime; // TRUE if the simulation is to be executed in Real Time mode
private volatile boolean rebaseRealTime; // TRUE if the time keeping for Real Time model needs re-basing
private volatile int realTimeFactor; // target ratio of elapsed simulation time to elapsed wall clock time
private EventTimeListener timelistener;
private EventErrorListener errListener;
private EventTraceListener trcListener;
/**
* Allocates a new EventManager with the given parent and name
*
* @param parent the connection point for this EventManager in the tree
* @param name the name this EventManager should use
*/
public EventManager(String name) {
// Basic initialization
this.name = name;
lockObject = new Object();
// Initialize and event lists and timekeeping variables
currentTick = 0;
nextTick = 0;
ticksPerSecond = 1000000.0d;
secsPerTick = 1.0d / ticksPerSecond;
eventTree = new EventTree();
conditionalList = new ArrayList<Process>();
conditionalHandles = new ArrayList<ConditionalHandle>();
executeEvents = false;
processRunning = false;
executeRealTime = false;
realTimeFactor = 1;
rebaseRealTime = true;
setTimeListener(null);
setErrorListener(null);
}
public final void setTimeListener(EventTimeListener l) {
synchronized (lockObject) {
if (l != null)
timelistener = l;
else
timelistener = new DefaultTimeListener();
timelistener.tickUpdate(currentTick);
}
}
public final void setErrorListener(EventErrorListener l) {
synchronized (lockObject) {
if (l != null)
errListener = l;
else
errListener = new DefaultErrorListener();
}
}
public final void setTraceListener(EventTraceListener l) {
synchronized (lockObject) {
trcListener = l;
}
}
public void clear() {
synchronized (lockObject) {
currentTick = 0;
nextTick = 0;
targetTick = Long.MAX_VALUE;
timelistener.tickUpdate(currentTick);
rebaseRealTime = true;
eventTree.runOnAllNodes(new KillAllEvents());
eventTree.reset();
// Kill conditional threads
for (int i = 0; i < conditionalList.size(); i++) {
conditionalList.get(i).kill();
if (conditionalHandles.get(i) != null) {
conditionalHandles.get(i).proc = null;
}
}
conditionalList.clear();
conditionalHandles.clear();
}
}
private static class KillAllEvents implements EventNode.Runner {
@Override
public void runOnNode(EventNode node) {
Event each = node.head;
while (each != null) {
if (each.handle != null) {
each.handle.event = null;
each.handle = null;
}
Process proc = each.target.getProcess();
if (proc != null)
proc.kill();
each = each.next;
}
}
}
private boolean executeTarget(Process cur, ProcessTarget t) {
try {
// If the event has a captured process, pass control to it
Process p = t.getProcess();
if (p != null) {
p.setNextProcess(cur);
p.wake();
threadWait(cur);
return true;
}
// Execute the method
t.process();
assertNotWaitUntil(cur);
// Notify the event manager that the process has been completed
if (trcListener != null) trcListener.traceProcessEnd(this);
return !cur.wakeNextProcess();
}
catch (Throwable e) {
// This is how kill() is implemented for sleeping processes.
if (e instanceof ThreadKilledException)
return false;
// Tear down any threads waiting for this to finish
Process next = cur.forceKillNext();
while (next != null) {
next = next.forceKillNext();
}
executeEvents = false;
processRunning = false;
errListener.handleError(this, e, currentTick);
return false;
}
}
/**
* Main event execution method the eventManager, this is the only entrypoint
* for Process objects taken out of the pool.
*/
final void execute(Process cur, ProcessTarget t) {
synchronized (lockObject) {
// This occurs in the startProcess or interrupt case where we start
// a process with a target already assigned
if (t != null) {
executeTarget(cur, t);
return;
}
if (processRunning)
return;
processRunning = true;
timelistener.timeRunning(true);
// Loop continuously
while (true) {
EventNode nextNode = eventTree.getNextNode();
if (nextNode == null ||
currentTick >= targetTick) {
executeEvents = false;
}
if (!executeEvents) {
processRunning = false;
timelistener.timeRunning(false);
return;
}
// If the next event is at the current tick, execute it
if (nextNode.schedTick == currentTick) {
// Remove the event from the future events
Event nextEvent = nextNode.head;
nextNode.head = nextEvent.next;
// check for an empty node
if (nextEvent.next == null) {
nextNode.tail = null;
eventTree.removeNode(nextNode.schedTick, nextNode.priority);
}
if (trcListener != null) trcListener.traceEvent(this, nextEvent);
if (nextEvent.handle != null) {
nextEvent.handle.event = null;
nextEvent.handle = null;
}
nextEvent.next = null;
// the return from execute target informs whether or not this
// thread should grab an new Event, or return to the pool
if (executeTarget(cur, nextEvent.target))
continue;
else
return;
}
// If the next event would require us to advance the time, check the
// conditonal events
if (eventTree.getNextNode().schedTick > nextTick) {
if (conditionalList.size() > 0) {
// Loop through the conditions in reverse order and add to the linked
// list of active threads
for (int i = 0; i < conditionalList.size() - 1; i++) {
conditionalList.get(i).setNextProcess(conditionalList.get(i + 1));
}
conditionalList.get(conditionalList.size() - 1).setNextProcess(cur);
// Wake up the first conditional thread to be tested
// at this point, nextThread == conditionalList.get(0)
conditionalList.get(0).wake();
// TODO: the error handing for errors received during conditional
// execution still needs to be done
threadWait(cur);
}
// If a conditional event was satisfied, we will have a new event at the
// beginning of the eventStack for the current tick, go back to the
// beginning, otherwise fall through to the time-advance
nextTick = eventTree.getNextNode().schedTick;
if (nextTick == currentTick)
continue;
}
// Advance to the next event time
if (executeRealTime) {
// Loop until the next event time is reached
long realTick = this.calcRealTimeTick();
if (realTick < nextTick && realTick < targetTick) {
// Update the displayed simulation time
currentTick = realTick;
timelistener.tickUpdate(currentTick);
//Halt the thread for 20ms and then reevaluate the loop
try { lockObject.wait(20); } catch( InterruptedException e ) {}
continue;
}
}
// advance time
if (targetTick < nextTick)
currentTick = targetTick;
else
currentTick = nextTick;
timelistener.tickUpdate(currentTick);
}
}
}
/**
* Return the simulation time corresponding the given wall clock time
* @param simTime = the current simulation time used when setting a real-time basis
* @return simulation time in seconds
*/
private long calcRealTimeTick() {
long curMS = System.currentTimeMillis();
if (rebaseRealTime) {
realTimeTick = currentTick;
realTimeMillis = curMS;
rebaseRealTime = false;
}
double simElapsedsec = ((curMS - realTimeMillis) * realTimeFactor) / 1000.0d;
long simElapsedTicks = secondsToNearestTick(simElapsedsec);
return realTimeTick + simElapsedTicks;
}
/**
// Pause the current active thread and restart the next thread on the
// active thread list. For this case, a future event or conditional event
// has been created for the current thread. Called by
// eventManager.scheduleWait() and related methods, and by
// eventManager.waitUntil().
// restorePreviousActiveThread()
* Must hold the lockObject when calling this method.
*/
private void captureProcess(Process cur) {
// if we don't wake a new process, take one from the pool
if (!cur.wakeNextProcess()) {
processRunning = false;
Process.allocate(this, null, null).wake();
}
threadWait(cur);
cur.setActive();
}
/**
* Calculate the time for an event taking into account numeric overflow.
* Must hold the lockObject when calling this method
*/
private long calculateEventTime(long waitLength) {
// Test for negative duration schedule wait length
if(waitLength < 0)
throw new ProcessError("Negative duration wait is invalid, waitLength = " + waitLength);
// Check for numeric overflow of internal time
long nextEventTime = currentTick + waitLength;
if (nextEventTime < 0)
nextEventTime = Long.MAX_VALUE;
return nextEventTime;
}
/**
* Schedules a future event to occur with a given priority. Lower priority
* events will be executed preferentially over higher priority. This is
* by lower priority events being placed higher on the event stack.
* @param ticks the number of discrete ticks from now to schedule the event.
* @param priority the priority of the scheduled event: 1 is the highest priority (default is priority 5)
*/
public void waitTicks(long ticks, int priority, boolean fifo, EventHandle handle) {
synchronized (lockObject) {
Process cur = Process.current();
assertNotWaitUntil(cur);
long nextEventTime = calculateEventTime(ticks);
WaitTarget t = new WaitTarget(cur);
EventNode node = getEventNode(nextEventTime, priority);
Event temp = new Event(node, t, handle);
if (trcListener != null) trcListener.traceWait(this, temp);
node.addEvent(temp, fifo);
captureProcess(cur);
}
}
/**
* Find an eventNode in the list, if a node is not found, create one and
* insert it.
*/
private EventNode getEventNode(long tick, int prio) {
return eventTree.createOrFindNode(tick, prio);
}
/**
* Debugging aid to test that we are not executing a conditional event, useful
* to try and catch places where a waitUntil was missing a waitUntilEnded.
* While not fatal, it will print out a stack dump to try and find where the
* waitUntilEnded was missed.
* @return the current model Process
*/
private void assertNotWaitUntil(Process cur) {
if (!cur.isCondWait())
return;
System.out.println("AUDIT - waitUntil without waitUntilEnded " + this);
for (StackTraceElement elem : cur.getStackTrace()) {
System.out.println(elem.toString());
}
}
public static final void waitUntil(Conditional cond) {
waitUntil(cond, null);
}
public static final void waitUntil(Conditional cond, ConditionalHandle handle) {
Process cur = Process.current();
while (!cond.evaluate()) {
cur.evt().waitUntil(cur, handle);
}
cur.evt().waitUntilEnded(cur);
}
/**
* Used to achieve conditional waits in the simulation. Adds the calling
* thread to the conditional stack, then wakes the next waiting thread on
* the thread stack.
*/
private void waitUntil(Process cur, ConditionalHandle handle) {
synchronized (lockObject) {
if (!conditionalList.contains(cur)) {
if (handle != null) {
if (handle.proc != null)
throw new ProcessError("Tried to waitUntil using a handle already in use");
handle.proc = cur;
}
if (trcListener != null) trcListener.traceWaitUntil(this);
cur.setCondWait(true);
conditionalList.add(cur);
conditionalHandles.add(handle);
}
captureProcess(cur);
}
}
private void waitUntilEnded(Process cur) {
synchronized (lockObject) {
// Do not wait at all if we never actually were on the waitUntilStack
// ie. we never called waitUntil
int index = conditionalList.indexOf(cur);
if (index == -1)
return;
conditionalList.remove(index);
ConditionalHandle handle = conditionalHandles.remove(index);
if (handle != null) handle.proc = null;
cur.setCondWait(false);
WaitTarget t = new WaitTarget(cur);
EventNode node = getEventNode(currentTick, 0);
Event temp = new Event(node, t, null);
if (trcListener != null) trcListener.traceWaitUntilEnded(this, temp);
node.addEvent(temp, true);
captureProcess(cur);
}
}
public static final void startProcess(ProcessTarget t) {
Process cur = Process.current();
cur.evt().start(cur, t);
}
private void start(Process cur, ProcessTarget t) {
Process newProcess = Process.allocate(this, cur, t);
// Notify the eventManager that a new process has been started
synchronized (lockObject) {
if (trcListener != null) trcListener.traceProcessStart(this, t);
// Transfer control to the new process
newProcess.wake();
threadWait(cur);
}
}
/**
* Remove an event from the eventList, must hold the lockObject.
* @param idx
* @return
*/
private void removeEvent(Event evt) {
EventNode node = evt.node;
evt.handle.event = null;
evt.handle = null;
// quick case where we are the head event
if (node.head == evt) {
node.head = evt.next;
if (evt.next == null) {
node.tail = null;
removeNode(node);
}
evt.next = null;
return;
}
Event prev = node.head;
while (prev.next != evt) {
prev = prev.next;
}
prev.next = evt.next;
if (evt.next == null)
node.tail = prev;
evt.next = null;
}
private void removeNode(EventNode node) {
boolean removed = eventTree.removeNode(node.schedTick, node.priority);
if (!removed) {
throw new ProcessError("Tried to remove an event that could not be found");
}
}
public static final void killEvent(ConditionalHandle handle) {
Process cur = Process.current();
cur.evt().killEvent(cur, handle);
}
private void killEvent(Process cur, ConditionalHandle handle) {
synchronized (lockObject) {
assertNotWaitUntil(cur);
Process p = handle.proc;
if (p == null)
return;
int index = conditionalList.indexOf(p);
if (index == -1)
throw new ProcessError("Tried to terminate a waitUntil that couldn't be found");
conditionalList.remove(index);
conditionalHandles.remove(index);
handle.proc = null;
p.kill();
}
}
public static final void interruptEvent(ConditionalHandle handle) {
Process cur = Process.current();
cur.evt().interruptEvent(cur, handle);
}
/**
* Causes a conditional event to be evaluated immediately..
*/
private void interruptEvent(Process cur, ConditionalHandle handle) {
synchronized (lockObject) {
assertNotWaitUntil(cur);
Process p = handle.proc;
if (p == null)
return;
int index = conditionalList.indexOf(p);
if (index == -1)
throw new ProcessError("Tried to interrupt a waitUntil that couldn't be found");
p.setNextProcess(cur);
p.wake();
threadWait(cur);
}
}
public static final void killEvent(EventHandle handle) {
Process cur = Process.current();
cur.evt().killEvent(cur, handle);
}
/**
* Removes an event from the pending list without executing it.
*/
private void killEvent(Process cur, EventHandle handle) {
synchronized (lockObject) {
assertNotWaitUntil(cur);
Event evt = handle.event;
if (evt == null)
return;
removeEvent(evt);
Process proc = evt.target.getProcess();
if (proc != null)
proc.kill();
if (trcListener != null) trcListener.traceKill(this, evt);
}
}
public static final void interruptEvent(EventHandle handle) {
Process cur = Process.current();
cur.evt().interruptEvent(cur, handle);
}
/**
* Removes an event from the pending list and executes it.
*/
private void interruptEvent(Process cur, EventHandle handle) {
synchronized (lockObject) {
assertNotWaitUntil(cur);
Event evt = handle.event;
if (evt == null)
return;
removeEvent(evt);
if (trcListener != null) trcListener.traceInterrupt(this, evt);
Process proc = evt.target.getProcess();
if (proc == null)
proc = Process.allocate(this, cur, evt.target);
proc.setNextProcess(cur);
proc.wake();
threadWait(cur);
}
}
public long getSimTicks() {
synchronized (lockObject) {
return currentTick;
}
}
public double getSimSeconds() {
synchronized (lockObject) {
return currentTick * secsPerTick;
}
}
public void setExecuteRealTime(boolean useRealTime, int factor) {
executeRealTime = useRealTime;
realTimeFactor = factor;
if (useRealTime)
rebaseRealTime = true;
}
/**
* Locks the calling thread in an inactive state to the global lock.
* When a new thread is created, and the current thread has been pushed
* onto the inactive thread stack it must be put to sleep to preserve
* program ordering.
* <p>
* The function takes no parameters, it puts the calling thread to sleep.
* This method is NOT static as it requires the use of wait() which cannot
* be called from a static context
* <p>
* There is a synchronized block of code that will acquire the global lock
* and then wait() the current thread.
*/
private void threadWait(Process cur) {
// Ensure that the thread owns the global thread lock
try {
/*
* Halt the thread and only wake up by being interrupted.
*
* The infinite loop is _absolutely_ necessary to prevent
* spurious wakeups from waking us early....which causes the
* model to get into an inconsistent state causing crashes.
*/
while (true) { lockObject.wait(); }
}
// Catch the exception when the thread is interrupted
catch( InterruptedException e ) {}
if (cur.shouldDie())
throw new ThreadKilledException("Thread killed");
}
public void scheduleProcess(long waitLength, int eventPriority, boolean fifo, ProcessTarget t, EventHandle handle) {
synchronized (lockObject) {
long schedTick = calculateEventTime(waitLength);
EventNode node = getEventNode(schedTick, eventPriority);
Event e = new Event(node, t, handle);
if (trcListener != null) trcListener.traceSchedProcess(this, e);
node.addEvent(e, fifo);
}
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. If set to false, the eventManager will
* execute a threadWait() and wait until an interrupt is generated. It is
* guaranteed in this state that there is an empty thread stack and the
* thread referenced in activeThread is the eventManager thread.
*/
public void pause() {
executeEvents = false;
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. Generates an interrupt of activeThread
* in case the eventManager thread has already been paused and needs to
* resume the event execution loop. This prevents the model being resumed
* from an inconsistent state.
*/
public void resume(long targetTicks) {
synchronized (lockObject) {
targetTick = targetTicks;
rebaseRealTime = true;
if (executeEvents)
return;
executeEvents = true;
Process.allocate(this, null, null).wake();
}
}
@Override
public String toString() {
return name;
}
/**
* Returns true if the calling thread has a current eventManager (ie. it is inside a model)
* @return
*/
public static final boolean hasCurrent() {
return (Thread.currentThread() instanceof Process);
}
/**
* Returns the eventManager that is currently executing events for this thread.
*/
public static final EventManager current() {
return Process.current().evt();
}
public final void setSimTimeScale(double scale) {
ticksPerSecond = scale / 3600.0d;
secsPerTick = 3600.0d / scale;
}
/**
* Convert the number of seconds rounded to the nearest tick.
*/
public final long secondsToNearestTick(double seconds) {
return Math.round(seconds * ticksPerSecond);
}
/**
* Convert the number of ticks into a value in seconds.
*/
public final double ticksToSeconds(long ticks) {
return ticks * secsPerTick;
}
private static class DefaultTimeListener implements EventTimeListener {
@Override
public void tickUpdate(long tick) {}
@Override
public void timeRunning(boolean running) {}
}
private static class DefaultErrorListener implements EventErrorListener {
@Override
public void handleError(EventManager evt, Throwable t, long currentTick) {}
}
}
|
package com.justjournal.core;
import com.justjournal.db.SQLHelper;
import org.apache.cayenne.CayenneRuntimeException;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.query.SelectQuery;
import org.apache.log4j.Logger;
import java.sql.ResultSet;
import java.util.List;
/**
* Track the number of users, entry and comment statistics, and other information.
*
* @author Lucas Holt
* @version $Id: Statistics.java,v 1.8 2012/06/23 18:15:31 laffer1 Exp $
*/
public class Statistics {
private static Logger log = Logger.getLogger(Statistics.class.getName());
/**
* Determine the number of users registered.
*
* @return The number of users or -1 on an error.
*/
public int getUsers() {
int count = -1;
try {
ObjectContext dataContext = DataContext.getThreadObjectContext();
SelectQuery query = new SelectQuery(com.justjournal.model.User.class);
List list = dataContext.performQuery(query);
count = list.size();
} catch (Exception e) {
log.error("users(): " + e.getMessage());
}
return count;
}
/**
* Determine the number of journal entries posted.
*
* @return The number of entries or -1 on error.
*/
public int getEntries() {
try {
ObjectContext dataContext = DataContext.getThreadObjectContext();
SelectQuery query = new SelectQuery(com.justjournal.model.Entry.class);
List list = dataContext.performQuery(query);
return list.size();
} catch (CayenneRuntimeException ce) {
log.error(ce);
}
return -1;
}
/**
* Percentage of public entries as compared to total.
*
* @return public entries as %
*/
public float getPublicEntries() {
float percent;
String sql = "SELECT count(*) FROM entry WHERE security='2';";
percent = (((float) sqlCount(sql) / (float) getEntries()) * 100);
if (log.isDebugEnabled())
log.debug("publicEntries(): percent is " + percent);
return percent;
}
/**
* Percentage of friends entries as compared to total.
*
* @return friends entries as %
*/
public float getFriendsEntries() {
float percent;
String sql = "SELECT count(*) FROM entry WHERE security='1';";
percent = (((float) sqlCount(sql) / (float) getEntries()) * 100);
if (log.isDebugEnabled())
log.debug("friendsEntries(): percent is " + percent);
return percent;
}
/**
* Percentage of private entries as compared to total.
*
* @return private entries as %
*/
public float getPrivateEntries() {
float percent;
String sql = "SELECT count(*) FROM entry WHERE security='0';";
percent = (((float) sqlCount(sql) / (float) getEntries()) * 100);
if (log.isDebugEnabled())
log.debug("privateEntries(): percent is " + percent);
return percent;
}
/**
* Determine the number of comments posted.
*
* @return The number of comments or -1 on error.
*/
public int getComments() {
try {
ObjectContext dataContext = DataContext.getThreadObjectContext();
SelectQuery query = new SelectQuery(com.justjournal.model.Comments.class);
List list = dataContext.performQuery(query);
return list.size();
} catch (CayenneRuntimeException ce) {
log.error(ce);
}
return -1;
}
/**
* Determine the number of journal styles posted.
*
* @return The number of styles or -1 on error.
*/
public int getStyles() {
try {
ObjectContext dataContext = DataContext.getThreadObjectContext();
SelectQuery query = new SelectQuery(com.justjournal.model.Style.class);
List list = dataContext.performQuery(query);
return list.size();
} catch (CayenneRuntimeException ce) {
log.error(ce);
}
return -1;
}
/**
* Determine the number of Tags used on the site.
*
* @return tag count or -1 on error.
*/
public int getTags() {
try {
ObjectContext dataContext = DataContext.getThreadObjectContext();
SelectQuery query = new SelectQuery(com.justjournal.model.Tags.class);
List list = dataContext.performQuery(query);
return list.size();
} catch (CayenneRuntimeException ce) {
log.error(ce);
}
return -1;
}
/**
* Perform a sql query returning a scalar int value typically form a count(*)
*
* @param sql query to perform
* @return int scalar from sql query
*/
private int sqlCount(String sql) {
int count = -1;
if (log.isDebugEnabled())
log.debug("sqlCount(): sql is " + sql);
try {
ResultSet rs = SQLHelper.executeResultSet(sql);
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
} catch (Exception e) {
log.error("sqlCount(): " + e.getMessage());
}
if (log.isDebugEnabled())
log.debug("sqlCount(): count is " + count);
return count;
}
}
|
package com.mxgraph.online;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.apphosting.api.DeadlineExceededException;
import com.mxgraph.online.Utils.UnsupportedContentException;
/**
* Servlet implementation ProxyServlet
*/
@SuppressWarnings("serial")
public class ProxyServlet extends HttpServlet
{
private static final Logger log = Logger
.getLogger(HttpServlet.class.getName());
/**
* Buffer size for content pass-through.
*/
private static int BUFFER_SIZE = 3 * 1024;
/**
* GAE deadline is 30 secs so timeout before that to avoid
* HardDeadlineExceeded errors.
*/
private static final int TIMEOUT = 29000;
/**
* A resuable empty byte array instance.
*/
private static byte[] emptyBytes = new byte[0];
/**
* @see HttpServlet#HttpServlet()
*/
public ProxyServlet()
{
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String urlParam = request.getParameter("url");
if (checkUrlParameter(urlParam))
{
// build the UML source from the compressed request parameter
String ref = request.getHeader("referer");
String ua = request.getHeader("User-Agent");
String auth = request.getHeader("Authorization");
String dom = getCorsDomain(ref, ua);
try(OutputStream out = response.getOutputStream())
{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
URL url = new URL(urlParam);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
response.setHeader("Cache-Control", "private, max-age=86400");
// Workaround for 451 response from Iconfinder CDN
connection.setRequestProperty("User-Agent", "draw.io");
//Forward auth header
if (auth != null)
{
connection.setRequestProperty("Authorization", auth);
}
if (dom != null && dom.length() > 0)
{
response.addHeader("Access-Control-Allow-Origin", dom);
}
// Status code pass-through and follow redirects
if (connection instanceof HttpURLConnection)
{
((HttpURLConnection) connection)
.setInstanceFollowRedirects(true);
int status = ((HttpURLConnection) connection)
.getResponseCode();
int counter = 0;
// Follows a maximum of 6 redirects
while (counter++ <= 6
&& (status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_MOVED_TEMP))
{
String redirectUrl = connection.getHeaderField("Location");
if (!checkUrlParameter(redirectUrl))
{
break;
}
url = new URL(redirectUrl);
connection = url.openConnection();
((HttpURLConnection) connection)
.setInstanceFollowRedirects(true);
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
// Workaround for 451 response from Iconfinder CDN
connection.setRequestProperty("User-Agent", "draw.io");
status = ((HttpURLConnection) connection)
.getResponseCode();
}
if (status >= 200 && status <= 299)
{
response.setStatus(status);
// Copies input stream to output stream
InputStream is = connection.getInputStream();
byte[] head = (contentAlwaysAllowed(urlParam)) ? emptyBytes
: Utils.checkStreamContent(is);
response.setContentType("application/octet-stream");
String base64 = request.getParameter("base64");
copyResponse(is, out, head,
base64 != null && base64.equals("1"));
}
else
{
response.setStatus(HttpURLConnection.HTTP_PRECON_FAILED);
}
}
else
{
response.setStatus(HttpURLConnection.HTTP_UNSUPPORTED_TYPE);
}
out.flush();
log.log(Level.FINEST, "processed proxy request: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
}
catch (DeadlineExceededException e)
{
response.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT);
}
catch (UnknownHostException | FileNotFoundException e)
{
// do not log 404 and DNS errors
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
catch (UnsupportedContentException e)
{
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
log.log(Level.SEVERE, "proxy request with invalid content: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
}
catch (Exception e)
{
response.setStatus(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
log.log(Level.FINE, "proxy request failed: url="
+ ((urlParam != null) ? urlParam : "[null]")
+ ", referer=" + ((ref != null) ? ref : "[null]")
+ ", user agent=" + ((ua != null) ? ua : "[null]"));
e.printStackTrace();
}
}
else
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
log.log(Level.SEVERE,
"proxy request with invalid URL parameter: url="
+ ((urlParam != null) ? urlParam : "[null]"));
}
}
/**
* Dynamically generated CORS header for known domains.
* @throws IOException
*/
protected void copyResponse(InputStream is, OutputStream out, byte[] head,
boolean base64) throws IOException
{
if (base64)
{
try (BufferedInputStream in = new BufferedInputStream(is,
BUFFER_SIZE))
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
os.write(head, 0, head.length);
for (int len = is.read(buffer); len != -1; len = is.read(buffer))
{
os.write(buffer, 0, len);
}
out.write(mxBase64.encodeToString(os.toByteArray(), false).getBytes());
}
}
else
{
out.write(head);
Utils.copy(is, out);
}
}
public boolean checkUrlParameter(String url)
{
if (url != null)
{
try
{
URL parsedUrl = new URL(url);
String protocol = parsedUrl.getProtocol();
String host = parsedUrl.getHost();
InetAddress address = InetAddress.getByName(host);
String hostAddress = address.getHostAddress();
host = host.toLowerCase();
return (protocol.equals("http") || protocol.equals("https"))
&& !address.isAnyLocalAddress()
&& !address.isLoopbackAddress()
&& !address.isLinkLocalAddress()
&& !host.endsWith(".internal") // Redundant
&& !host.endsWith(".local") // Redundant
&& !host.contains("localhost") // Redundant
&& !hostAddress.startsWith("0.") // 0.0.0.0/8
&& !hostAddress.startsWith("10.") // 10.0.0.0/8
&& !hostAddress.startsWith("127.") // 127.0.0.0/8
&& !hostAddress.startsWith("169.254.") // 169.254.0.0/16
&& !hostAddress.startsWith("172.16.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.17.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.18.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.19.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.20.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.21.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.22.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.23.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.24.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.25.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.26.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.27.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.28.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.29.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.30.") // 172.16.0.0/12
&& !hostAddress.startsWith("172.31.") // 172.16.0.0/12
&& !hostAddress.startsWith("192.0.0.") // 192.0.0.0/24
&& !hostAddress.startsWith("192.168.") // 192.168.0.0/16
&& !hostAddress.startsWith("198.18.") // 198.18.0.0/15
&& !hostAddress.startsWith("198.19.") // 198.18.0.0/15
&& !host.endsWith(".arpa"); // reverse domain (needed?)
}
catch (MalformedURLException e)
{
return false;
}
catch (UnknownHostException e)
{
return false;
}
}
else
{
return false;
}
}
/**
* Returns true if the content check should be omitted.
*/
public boolean contentAlwaysAllowed(String url)
{
return url.toLowerCase()
.startsWith("https://trello-attachments.s3.amazonaws.com/")
|| url.toLowerCase().startsWith("https://docs.google.com/");
}
/**
* Gets CORS header for request. Returning null means do not respond.
*/
protected String getCorsDomain(String referer, String userAgent)
{
String dom = null;
if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".draw.io/") + 8);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".diagrams.net/") + 13);
}
else if (referer != null && referer.toLowerCase()
.matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*"))
{
dom = referer.toLowerCase().substring(0,
referer.indexOf(".quipelements.com/") + 17);
}
// Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions)
// UA refers to old FF on macOS so low risk and fixes requests from existing servers
else if ((referer != null
&& referer.equals("draw.io Proxy Confluence Server"))
|| (userAgent != null && userAgent.equals(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0")))
{
dom = "";
}
return dom;
}
}
|
package com.pardot.rhombus;
import com.datastax.driver.core.*;
import com.datastax.driver.core.exceptions.AlreadyExistsException;
import com.datastax.driver.core.utils.UUIDs;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pardot.rhombus.cobject.*;
import com.pardot.rhombus.cobject.async.StatementIteratorConsumer;
import com.pardot.rhombus.util.JsonUtil;
import com.yammer.metrics.*;
import com.yammer.metrics.core.*;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.*;
public class ObjectMapper implements CObjectShardList {
private static Logger logger = LoggerFactory.getLogger(ObjectMapper.class);
private static final int reasonableStatementLimit = 20;
private boolean executeAsync = true;
private boolean logCql = false;
private boolean cacheBoundedQueries = true;
private CQLExecutor cqlExecutor;
private Session session;
private CKeyspaceDefinition keyspaceDefinition;
private CObjectCQLGenerator cqlGenerator;
private long statementTimeout = 5000;
public ObjectMapper(Session session, CKeyspaceDefinition keyspaceDefinition, Integer consistencyHorizon) {
this.cqlExecutor = new CQLExecutor(session, logCql);
this.session = session;
this.keyspaceDefinition = keyspaceDefinition;
this.cqlGenerator = new CObjectCQLGenerator(keyspaceDefinition.getDefinitions(), this, consistencyHorizon);
}
/**
* Build the tables contained in the keyspace definition.
* This method assumes that its keyspace exists and
* does not contain any tables.
*/
public void buildKeyspace(Boolean forceRebuild) {
//we are about to rework the the keyspaces, so lets clear the bounded query cache
cqlExecutor.clearStatementCache();
//First build the shard index
CQLStatement cql = CObjectCQLGenerator.makeCQLforShardIndexTableCreate();
try {
cqlExecutor.executeSync(cql);
} catch(Exception e) {
if(forceRebuild) {
CQLStatement dropCql = CObjectCQLGenerator.makeCQLforShardIndexTableDrop();
logger.debug("Attempting to drop table with cql {}", dropCql);
cqlExecutor.executeSync(dropCql);
cqlExecutor.executeSync(cql);
} else {
logger.debug("Not dropping shard index table");
}
}
//Next build the update index
cql = CObjectCQLGenerator.makeCQLforIndexUpdateTableCreate();
try{
cqlExecutor.executeSync(cql);
}
catch(Exception e) {
logger.debug("Unable to create update index table. It may already exist");
}
//Now build the tables for each object if the definition contains tables
if(keyspaceDefinition.getDefinitions() != null) {
for(CDefinition definition : keyspaceDefinition.getDefinitions().values()) {
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforCreate(definition.getName());
CQLStatementIterator dropStatementIterator = cqlGenerator.makeCQLforDrop(definition.getName());
while(statementIterator.hasNext()) {
cql = statementIterator.next();
CQLStatement dropCql = dropStatementIterator.next();
try {
cqlExecutor.executeSync(cql);
} catch (AlreadyExistsException e) {
if(forceRebuild) {
logger.debug("ForceRebuild is on, dropping table");
cqlExecutor.executeSync(dropCql);
cqlExecutor.executeSync(cql);
} else {
logger.warn("Table already exists and will not be updated");
}
}
}
}
}
}
public UUID getTimeUUIDAtEndOfConsistencyHorizion(){
return cqlGenerator.getTimeUUIDAtEndOfConsistencyHorizion();
}
public void executeStatements(CQLStatementIterator statementIterator) {
List<CQLStatementIterator> statementIterators = Lists.newArrayList();
statementIterators.add(statementIterator);
executeStatements(statementIterators);
}
public void executeStatements(List<CQLStatementIterator> statementIterators) {
boolean canExecuteAsync = true;
for(CQLStatementIterator statementIterator : statementIterators) {
if(!statementIterator.isBounded()) {
canExecuteAsync = false;
break;
}
}
if(canExecuteAsync && this.executeAsync) {
logger.debug("Executing statements async");
//If this is a bounded statement iterator, send it through the async path
long start = System.nanoTime();
List<StatementIteratorConsumer> consumers = Lists.newArrayList();
for(CQLStatementIterator statementIterator : statementIterators) {
StatementIteratorConsumer consumer = new StatementIteratorConsumer((BoundedCQLStatementIterator) statementIterator, cqlExecutor, statementTimeout);
consumer.start();
consumers.add(consumer);
}
for(StatementIteratorConsumer consumer : consumers) {
consumer.join();
}
logger.debug("Async execution took {}us", (System.nanoTime() - start) / 1000);
} else {
logger.debug("Executing statements sync");
long start = System.nanoTime();
for(CQLStatementIterator statementIterator : statementIterators) {
while(statementIterator.hasNext()) {
CQLStatement statement = statementIterator.next();
final com.yammer.metrics.core.Timer syncSingleExecTimer = com.yammer.metrics.Metrics.defaultRegistry().newTimer(ObjectMapper.class, "syncSingleExec");
final TimerContext syncSingleExecTimerContext = syncSingleExecTimer.time();
cqlExecutor.executeSync(statement);
syncSingleExecTimerContext.stop();
}
}
logger.debug("Sync execution took {} ms", (System.nanoTime() - start) / 1000000);
}
}
@Override
public List<Long> getShardIdList(CDefinition def, SortedMap<String, Object> indexValues, CObjectOrdering ordering, @Nullable UUID start, @Nullable UUID end) throws CQLGenerationException {
CQLStatement shardIdGet = CObjectCQLGenerator.makeCQLforGetShardIndexList(def, indexValues, ordering, start, end);
ResultSet resultSet = cqlExecutor.executeSync(shardIdGet);
List<Long> shardIdList = Lists.newArrayList();
for(Row row : resultSet) {
shardIdList.add(row.getLong("shardid"));
}
return shardIdList;
}
/**
* Insert a batch of mixed new object with values
* @param objects Objects to insert
* @return ID of most recently inserted object
* @throws CQLGenerationException
*/
public UUID insertBatchMixed(Map<String, List<Map<String, Object>>> objects) throws CQLGenerationException {
logger.debug("Insert batch mixed");
List<CQLStatementIterator> statementIterators = Lists.newArrayList();
UUID key = null;
for(String objectType : objects.keySet()) {
for(Map<String, Object> values : objects.get(objectType)) {
key = UUIDs.timeBased();
long timestamp = System.currentTimeMillis();
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp);
statementIterators.add(statementIterator);
}
}
executeStatements(statementIterators);
return key;
}
/**
* Insert a new object with values and key
* @param objectType Type of object to insert
* @param values Values to insert
* @param key Time UUID to use as key
* @return ID if newly inserted object
* @throws CQLGenerationException
*/
public UUID insert(String objectType, Map<String, Object> values, UUID key) throws CQLGenerationException {
logger.debug("Insert {}", objectType);
if(key == null) {
key = UUIDs.timeBased();
}
long timestamp = System.currentTimeMillis();
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp);
executeStatements(statementIterator);
return key;
}
/**
* Insert a new objectType with values
* @param objectType Type of object to insert
* @param values Values to insert
* @return UUID of inserted object
* @throws CQLGenerationException
*/
public UUID insert(String objectType, Map<String, Object> values) throws CQLGenerationException {
return insert(objectType, values, (UUID)null);
}
/**
* Used to insert an object with a UUID based on the provided timestamp
* Best used for testing, as time resolution collisions are not accounted for
* @param objectType Type of object to insert
* @param values Values to insert
* @param timestamp Timestamp to use to create the object UUID
* @return the UUID of the newly inserted object
*/
public UUID insert(String objectType, Map<String, Object> values, Long timestamp) throws CQLGenerationException {
UUID uuid = UUIDs.startOf(timestamp);
return insert(objectType, values, uuid);
}
/**
* Delete Object of type with id key
* @param objectType Type of object to delete
* @param key Key of object to delete
*/
public void delete(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
Map<String, Object> values = getByKey(objectType, key);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforDelete(objectType, key, values, null);
mapResults(statementIterator, def, 0L);
}
public void deleteObsoleteIndex(IndexUpdateRow row, CIndex index, Map<String,Object> indexValues){
CQLStatement cql = cqlGenerator.makeCQLforDeleteUUIDFromIndex(
keyspaceDefinition.getDefinitions().get(row.getObjectName()),
index,
row.getInstanceId(),
index.getIndexKeyAndValues(indexValues),
row.getTimeStampOfMostCurrentUpdate());
cqlExecutor.executeSync(cql);
}
public void deleteObsoleteUpdateIndexColumn(IndexUpdateRowKey rowKey, UUID id){
CQLStatement cql = cqlGenerator.makeCQLforDeleteObsoleteUpdateIndexColumn(rowKey, id);
cqlExecutor.executeSync(cql);
}
/**
* Update objectType with key using values
* @param objectType Type of object to update
* @param key Key of object to update
* @param values Values to update
* @param timestamp Timestamp to execute update at
* @param ttl Time to live for update
* @return new UUID of the object
* @throws CQLGenerationException
*/
public UUID update(String objectType, UUID key, Map<String, Object> values, Long timestamp, Integer ttl) throws CQLGenerationException {
//New Version
//(1) Get the old version
Map<String, Object> oldversion = getByKey(objectType, key);
//(2) Pass it all into the cql generator so it can create the right statements
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforUpdate(def,key,oldversion,values);
executeStatements(statementIterator);
return key;
}
/**
* Update objectType with key using values
* @param objectType Type of object to update
* @param key Key of object to update
* @param values Values to update
* @return new UUID of the object
* @throws CQLGenerationException
*/
public UUID update(String objectType, UUID key, Map<String, Object> values) throws CQLGenerationException {
return update(objectType, key, values, null, null);
}
/**
*
* @param objectType Type of object to get
* @param key Key of object to get
* @return Object of type with key or null if it does not exist
*/
public Map<String, Object> getByKey(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, key);
List<Map<String, Object>> results = mapResults(statementIterator, def, 1L);
if(results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* @param objectType Type of object to query
* @param criteria Criteria to query by
* @return List of objects that match the specified type and criteria
* @throws CQLGenerationException
*/
public List<Map<String, Object>> list(String objectType, Criteria criteria) throws CQLGenerationException {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, criteria);
return mapResults(statementIterator, def, criteria.getLimit());
}
protected SortedMap<String,Object> unpackIndexValuesFromJson(CDefinition def, String json) throws IOException, JsonMappingException {
org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper();
TreeMap<String,Object> jsonMap = om.readValue(json, TreeMap.class);
return JsonUtil.rhombusMapFromJsonMap(jsonMap,def);
}
public IndexUpdateRow getNextUpdateIndexRow(@Nullable IndexUpdateRowKey lastInstanceKey) throws IOException, JsonMappingException {
CQLStatement cqlForNext = (lastInstanceKey == null) ?
cqlGenerator.makeGetFirstEligibleIndexUpdate() : cqlGenerator.makeGetNextEligibleIndexUpdate(lastInstanceKey);
ResultSet resultSet = cqlExecutor.executeSync(cqlForNext);
if(resultSet.isExhausted()){
return null;
}
IndexUpdateRowKey nextInstanceKey = new IndexUpdateRowKey(resultSet.one());
CQLStatement cqlForRow = cqlGenerator.makeGetRowIndexUpdate(nextInstanceKey);
resultSet = cqlExecutor.executeSync(cqlForRow);
List<Row> results = resultSet.all();
if(results.size() == 0 ){
return null;
}
String objectName = results.get(0).getString("statictablename");
CDefinition def = keyspaceDefinition.getDefinitions().get(objectName);
List<SortedMap<String,Object>> indexValueList = Lists.newArrayList();
List<UUID> ids = Lists.newArrayList();
for(Row row : results){
indexValueList.add(unpackIndexValuesFromJson(def,row.getString("indexvalues")));
ids.add(row.getUUID("id"));
}
return new IndexUpdateRow(
objectName,
results.get(0).getUUID("instanceid"),
UUIDs.unixTimestamp(results.get(0).getUUID("id")),
indexValueList,
ids
);
}
/**
* Iterates through cql statements executing them in sequence and mapping the results until limit is reached
* @param statementIterator Statement iterator to execute
* @param definition definition to execute the statements against
* @return Ordered resultset concatenating results from statements in statement iterator.
*/
private List<Map<String, Object>> mapResults(CQLStatementIterator statementIterator, CDefinition definition, Long limit) {
List<Map<String, Object>> results = Lists.newArrayList();
int statementNumber = 0;
int resultNumber = 0;
while(statementIterator.hasNext(resultNumber) ) {
CQLStatement cql = statementIterator.next();
ResultSet resultSet = cqlExecutor.executeSync(cql);
for(Row row : resultSet) {
Map<String, Object> result = mapResult(row, definition);
results.add(result);
resultNumber++;
}
statementNumber++;
if((limit > 0 && resultNumber >= limit) || statementNumber > reasonableStatementLimit) {
logger.debug("Breaking from mapping results");
break;
}
}
return results;
}
/**
* @param row The row to map
* @param definition The definition to map the row on to
* @return Data contained in a row mapped to the object described in definition.
*/
private Map<String, Object> mapResult(Row row, CDefinition definition) {
Map<String, Object> result = Maps.newHashMap();
result.put("id", row.getUUID("id"));
for(CField field : definition.getFields().values()) {
result.put(field.getName(), getFieldValue(row, field));
}
return result;
}
private Object getFieldValue(Row row, CField field) {
Object fieldValue;
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
fieldValue = row.getString(field.getName());
break;
case BIGINT:
case COUNTER:
fieldValue = row.getLong(field.getName());
break;
case BLOB:
fieldValue = row.getBytes(field.getName());
break;
case BOOLEAN:
fieldValue = row.getBool(field.getName());
break;
case DECIMAL:
fieldValue = row.getDecimal(field.getName());
break;
case DOUBLE:
fieldValue = row.getDouble(field.getName());
break;
case FLOAT:
fieldValue = row.getFloat(field.getName());
break;
case INT:
fieldValue = row.getInt(field.getName());
break;
case TIMESTAMP:
fieldValue = row.getDate(field.getName());
break;
case UUID:
case TIMEUUID:
fieldValue = row.getUUID(field.getName());
break;
case VARINT:
fieldValue = row.getVarint(field.getName());
break;
default:
fieldValue = null;
}
return (fieldValue == null ? null : fieldValue);
}
public Map<String, Object> coerceRhombusValuesFromJsonMap(String objectType, Map<String, Object> values) {
return JsonUtil.rhombusMapFromJsonMap(values, keyspaceDefinition.getDefinitions().get(objectType));
}
public void setLogCql(boolean logCql) {
this.logCql = logCql;
this.cqlExecutor.setLogCql(logCql);
}
public boolean getExecuteAsync() {
return executeAsync;
}
public void setExecuteAsync(boolean executeAsync) {
logger.debug("{} setting executeAsync to {}", this.keyspaceDefinition.getName(), executeAsync);
this.executeAsync = executeAsync;
}
public void teardown() {
session.shutdown();
}
public boolean isCacheBoundedQueries() {
return cacheBoundedQueries;
}
public void setCacheBoundedQueries(boolean cacheBoundedQueries) {
this.cacheBoundedQueries = cacheBoundedQueries;
}
/**
* Set max execution time for insert statements run in parallel
* @param statementTimeout MS to wait before timing out multi insert
*/
public void setStatementTimeout(long statementTimeout) {
this.statementTimeout = statementTimeout;
}
public CQLExecutor getCqlExecutor(){
return cqlExecutor;
}
public CObjectCQLGenerator getCqlGenerator_ONLY_FOR_TESTING(){
return cqlGenerator;
}
public CKeyspaceDefinition getKeyspaceDefinition_ONLY_FOR_TESTING(){
return keyspaceDefinition;
}
protected CKeyspaceDefinition getKeyspaceDefinition() {
return keyspaceDefinition;
}
}
|
package com.pardot.rhombus;
import com.datastax.driver.core.*;
import com.datastax.driver.core.exceptions.AlreadyExistsException;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pardot.rhombus.cobject.*;
import com.pardot.rhombus.cobject.async.StatementIteratorConsumer;
import com.pardot.rhombus.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.UUID;
public class ObjectMapper implements CObjectShardList {
private static Logger logger = LoggerFactory.getLogger(ObjectMapper.class);
private static final int reasonableStatementLimit = 20;
private boolean executeAsync = true;
private boolean logCql = false;
private boolean cacheBoundedQueries = true;
private CQLExecutor cqlExecutor;
private Session session;
private CKeyspaceDefinition keyspaceDefinition;
private CObjectCQLGenerator cqlGenerator;
private long statementTimeout = 5000;
public ObjectMapper(Session session, CKeyspaceDefinition keyspaceDefinition) {
this.cqlExecutor = new CQLExecutor(session, logCql);
this.session = session;
this.keyspaceDefinition = keyspaceDefinition;
this.cqlGenerator = new CObjectCQLGenerator(keyspaceDefinition.getDefinitions(), this);
}
/**
* Build the tables contained in the keyspace definition.
* This method assumes that its keyspace exists and
* does not contain any tables.
*/
public void buildKeyspace(Boolean forceRebuild) {
//we are about to rework the the keyspaces, so lets clear the bounded query cache
cqlExecutor.clearStatementCache();
//First build the shard index
CQLStatement cql = CObjectCQLGenerator.makeCQLforShardIndexTableCreate();
try {
cqlExecutor.executeSync(cql);
} catch(Exception e) {
if(forceRebuild) {
CQLStatement dropCql = CObjectCQLGenerator.makeCQLforShardIndexTableDrop();
logger.debug("Attempting to drop table with cql {}", dropCql);
cqlExecutor.executeSync(dropCql);
cqlExecutor.executeSync(cql);
} else {
logger.debug("Not dropping shard index table");
}
}
//Next build the update index
cql = CObjectCQLGenerator.makeCQLforIndexUpdateTableCreate();
try{
cqlExecutor.executeSync(cql);
}
catch(Exception e) {
logger.debug("Unable to create update index table. It may already exist");
}
//Now build the tables for each object if the definition contains tables
if(keyspaceDefinition.getDefinitions() != null) {
for(CDefinition definition : keyspaceDefinition.getDefinitions().values()) {
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforCreate(definition.getName());
CQLStatementIterator dropStatementIterator = cqlGenerator.makeCQLforDrop(definition.getName());
while(statementIterator.hasNext()) {
cql = statementIterator.next();
CQLStatement dropCql = dropStatementIterator.next();
try {
cqlExecutor.executeSync(cql);
} catch (AlreadyExistsException e) {
if(forceRebuild) {
logger.debug("ForceRebuild is on, dropping table");
cqlExecutor.executeSync(dropCql);
cqlExecutor.executeSync(cql);
} else {
logger.warn("Table already exists and will not be updated");
}
}
}
}
}
}
public void executeStatements(CQLStatementIterator statementIterator) {
List<CQLStatementIterator> statementIterators = Lists.newArrayList();
statementIterators.add(statementIterator);
executeStatements(statementIterators);
}
public void executeStatements(List<CQLStatementIterator> statementIterators) {
boolean canExecuteAsync = true;
for(CQLStatementIterator statementIterator : statementIterators) {
if(!statementIterator.isBounded()) {
canExecuteAsync = false;
break;
}
}
if(canExecuteAsync && this.executeAsync) {
logger.debug("Executing statements async");
//If this is a bounded statement iterator, send it through the async path
long start = System.nanoTime();
List<StatementIteratorConsumer> consumers = Lists.newArrayList();
for(CQLStatementIterator statementIterator : statementIterators) {
StatementIteratorConsumer consumer = new StatementIteratorConsumer((BoundedCQLStatementIterator) statementIterator, cqlExecutor, statementTimeout);
consumer.start();
consumers.add(consumer);
}
for(StatementIteratorConsumer consumer : consumers) {
consumer.join();
}
logger.debug("Async execution took {} ms", (System.nanoTime() - start) / 1000000);
} else {
long start = System.nanoTime();
for(CQLStatementIterator statementIterator : statementIterators) {
while(statementIterator.hasNext()) {
CQLStatement statement = statementIterator.next();
cqlExecutor.executeSync(statement);
}
}
logger.debug("Sync execution took {} ms", (System.nanoTime() - start) / 1000000);
}
}
@Override
public List<Long> getShardIdList(CDefinition def, SortedMap<String, Object> indexValues, CObjectOrdering ordering, @Nullable UUID start, @Nullable UUID end) throws CQLGenerationException {
CQLStatement shardIdGet = CObjectCQLGenerator.makeCQLforGetShardIndexList(def, indexValues, ordering, start, end);
ResultSet resultSet = cqlExecutor.executeSync(shardIdGet);
List<Long> shardIdList = Lists.newArrayList();
for(Row row : resultSet) {
shardIdList.add(row.getLong("shardid"));
}
return shardIdList;
}
/**
* Insert a batch of mixed new object with values
* @param objects Objects to insert
* @return ID of most recently inserted object
* @throws CQLGenerationException
*/
public UUID insertBatchMixed(Map<String, List<Map<String, Object>>> objects) throws CQLGenerationException {
logger.debug("Insert batch mixed");
List<CQLStatementIterator> statementIterators = Lists.newArrayList();
UUID key = null;
for(String objectType : objects.keySet()) {
for(Map<String, Object> values : objects.get(objectType)) {
key = UUIDs.timeBased();
long timestamp = System.currentTimeMillis();
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp);
statementIterators.add(statementIterator);
}
}
executeStatements(statementIterators);
return key;
}
/**
* Insert a new object with values and key
* @param objectType Type of object to insert
* @param values Values to insert
* @param key Time UUID to use as key
* @return ID if newly inserted object
* @throws CQLGenerationException
*/
public UUID insert(String objectType, Map<String, Object> values, UUID key) throws CQLGenerationException {
logger.debug("Insert {}", objectType);
if(key == null) {
key = UUIDs.timeBased();
}
long timestamp = System.currentTimeMillis();
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp);
executeStatements(statementIterator);
return key;
}
/**
* Insert a new objectType with values
* @param objectType Type of object to insert
* @param values Values to insert
* @return UUID of inserted object
* @throws CQLGenerationException
*/
public UUID insert(String objectType, Map<String, Object> values) throws CQLGenerationException {
return insert(objectType, values, (UUID)null);
}
/**
* Used to insert an object with a UUID based on the provided timestamp
* Best used for testing, as time resolution collisions are not accounted for
* @param objectType Type of object to insert
* @param values Values to insert
* @param timestamp Timestamp to use to create the object UUID
* @return the UUID of the newly inserted object
*/
public UUID insert(String objectType, Map<String, Object> values, Long timestamp) throws CQLGenerationException {
UUID uuid = UUIDs.startOf(timestamp);
return insert(objectType, values, uuid);
}
/**
* Delete Object of type with id key
* @param objectType Type of object to delete
* @param key Key of object to delete
*/
public void delete(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
Map<String, Object> values = getByKey(objectType, key);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforDelete(objectType, key, values, null);
mapResults(statementIterator, def, 0L);
}
/**
* Update objectType with key using values
* @param objectType Type of object to update
* @param key Key of object to update
* @param values Values to update
* @param timestamp Timestamp to execute update at
* @param ttl Time to live for update
* @return new UUID of the object
* @throws CQLGenerationException
*/
public UUID update(String objectType, UUID key, Map<String, Object> values, Long timestamp, Integer ttl) throws CQLGenerationException {
//New Version
//(1) Get the old version
Map<String, Object> oldversion = getByKey(objectType, key);
//(2) Pass it all into the cql generator so it can create the right statements
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforUpdate(def,key,oldversion,values);
executeStatements(statementIterator);
return key;
}
/**
* Update objectType with key using values
* @param objectType Type of object to update
* @param key Key of object to update
* @param values Values to update
* @return new UUID of the object
* @throws CQLGenerationException
*/
public UUID update(String objectType, UUID key, Map<String, Object> values) throws CQLGenerationException {
return update(objectType, key, values, null, null);
}
/**
*
* @param objectType Type of object to get
* @param key Key of object to get
* @return Object of type with key or null if it does not exist
*/
public Map<String, Object> getByKey(String objectType, UUID key) {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, key);
List<Map<String, Object>> results = mapResults(statementIterator, def, 1L);
if(results.size() > 0) {
return results.get(0);
} else {
return null;
}
}
/**
* @param objectType Type of object to query
* @param criteria Criteria to query by
* @return List of objects that match the specified type and criteria
* @throws CQLGenerationException
*/
public List<Map<String, Object>> list(String objectType, Criteria criteria) throws CQLGenerationException {
CDefinition def = keyspaceDefinition.getDefinitions().get(objectType);
CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, criteria);
return mapResults(statementIterator, def, criteria.getLimit());
}
protected Map<String, Object> getNextUpdateIndexRow(@Nullable Long lastInstancetoken){
CQLStatement cqlForNext = (lastInstancetoken == null) ?
cqlGenerator.makeGetFirstEligibleIndexUpdate() : cqlGenerator.makeGetNextEligibleIndexUpdate(lastInstancetoken);
Map<String, Object> result = Maps.newHashMap();
ResultSet resultSet = cqlExecutor.executeSync(cqlForNext);
Long nextInstanceToken = resultSet.one().getLong(0);
CQLStatement cqlForRow = cqlGenerator.makeGetRowIndexUpdate(nextInstanceToken);
resultSet = cqlExecutor.executeSync(cqlForRow);
Row row = resultSet.one();
result.put("id", row.getUUID("id"));
result.put("statictablename", row.getString("statictablename"));
result.put("instanceid", row.getUUID("instanceid"));
result.put("indexvalues", row.getString("indexvalues"));
return result;
}
/**
* Iterates through cql statements executing them in sequence and mapping the results until limit is reached
* @param statementIterator Statement iterator to execute
* @param definition definition to execute the statements against
* @return Ordered resultset concatenating results from statements in statement iterator.
*/
private List<Map<String, Object>> mapResults(CQLStatementIterator statementIterator, CDefinition definition, Long limit) {
List<Map<String, Object>> results = Lists.newArrayList();
int statementNumber = 0;
int resultNumber = 0;
while(statementIterator.hasNext(resultNumber) ) {
CQLStatement cql = statementIterator.next();
ResultSet resultSet = cqlExecutor.executeSync(cql);
for(Row row : resultSet) {
Map<String, Object> result = mapResult(row, definition);
results.add(result);
resultNumber++;
}
statementNumber++;
if((limit > 0 && resultNumber >= limit) || statementNumber > reasonableStatementLimit) {
logger.debug("Breaking from mapping results");
break;
}
}
return results;
}
/**
* @param row The row to map
* @param definition The definition to map the row on to
* @return Data contained in a row mapped to the object described in definition.
*/
private Map<String, Object> mapResult(Row row, CDefinition definition) {
Map<String, Object> result = Maps.newHashMap();
result.put("id", row.getUUID("id"));
for(CField field : definition.getFields().values()) {
result.put(field.getName(), getFieldValue(row, field));
}
return result;
}
private Object getFieldValue(Row row, CField field) {
Object fieldValue;
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
fieldValue = row.getString(field.getName());
break;
case BIGINT:
case COUNTER:
fieldValue = row.getLong(field.getName());
break;
case BLOB:
fieldValue = row.getBytes(field.getName());
break;
case BOOLEAN:
fieldValue = row.getBool(field.getName());
break;
case DECIMAL:
fieldValue = row.getDecimal(field.getName());
break;
case DOUBLE:
fieldValue = row.getDouble(field.getName());
break;
case FLOAT:
fieldValue = row.getFloat(field.getName());
break;
case INT:
fieldValue = row.getInt(field.getName());
break;
case TIMESTAMP:
fieldValue = row.getDate(field.getName());
break;
case UUID:
case TIMEUUID:
fieldValue = row.getUUID(field.getName());
break;
case VARINT:
fieldValue = row.getVarint(field.getName());
break;
default:
fieldValue = null;
}
return (fieldValue == null ? null : fieldValue);
}
public Map<String, Object> coerceRhombusValuesFromJsonMap(String objectType, Map<String, Object> values) {
return JsonUtil.rhombusMapFromJsonMap(values, keyspaceDefinition.getDefinitions().get(objectType));
}
public void setLogCql(boolean logCql) {
this.logCql = logCql;
this.cqlExecutor.setLogCql(logCql);
}
public boolean isExecuteAsync() {
return executeAsync;
}
public void setExecuteAsync(boolean executeAsync) {
this.executeAsync = executeAsync;
}
public void teardown() {
session.shutdown();
}
public boolean isCacheBoundedQueries() {
return cacheBoundedQueries;
}
public void setCacheBoundedQueries(boolean cacheBoundedQueries) {
this.cacheBoundedQueries = cacheBoundedQueries;
}
/**
* Set max execution time for insert statements run in parallel
* @param statementTimeout MS to wait before timing out multi insert
*/
public void setStatementTimeout(long statementTimeout) {
this.statementTimeout = statementTimeout;
}
public CQLExecutor getCqlExecutor(){
return cqlExecutor;
}
}
|
package com.sksamuel.jqm4gwt;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* @author Stephen K Samuel samspade79@gmail.com 9 Jul 2011 12:57:43
*
* The {@link JQMContent} provides methods that facilitate interaction
* between GWT, JQM and the DOM.
*
*/
public class JQMContext {
private static Transition defaultTransition = Transition.POP;
public static native void disableHashListening() /*-{
$wnd.$.mobile.hashListeningEnabled = false;
}-*/;
/**
* Appends the given {@link JQMPage} to the DOM so that JQueryMobile is
* able to manipulate it and render it. This should only be done once per
* page, otherwise duplicate HTML would be added to the DOM and this would
* result in elements with overlapping IDs.
*
*/
public static void attachAndEnhance(JQMContainer container) {
RootPanel.get().add(container);
enhance(container);
container.setEnhanced(true);
}
/**
* Programatically change the displayed page to the given {@link JQMPage}
* instance. This uses the default transition which is Transition.POP
*/
public static void changePage(JQMContainer container) {
changePage(container, defaultTransition);
}
/**
* Change the displayed page to the given {@link JQMPage} instance using
* the supplied transition.
*/
public static void changePage(JQMContainer container, Transition transition) {
Mobile.changePage("#" + container.getId(), transition, false, true);
}
private static void enhance(JQMContainer c) {
render(c.getId());
}
public static Transition getDefaultTransition() {
return defaultTransition;
}
/**
* Return the pixel offset of an element from the left of the document.
* This can also be thought of as the y coordinate of the top of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getLeft(String id) /*-{
return $wnd.$("#" + id).offset().left;
}-*/;
/**
* Return the pixel offset of an element from the top of the document.
* This can also be thought of as the x coordinate of the left of the
* elements bounding box.
*
* @param id
* the id of the element to find the offset
*/
public native static int getTop(String id) /*-{
return $wnd.$("#" + id).offset().top;
}-*/;
public native static void initializePage() /*-{
$wnd.$.mobile.initializePage();
}-*/;
/**
* Ask JQuery Mobile to "render" the element with the given id.
*/
public static void render(String id) {
if (id == null || "".equals(id))
throw new IllegalArgumentException("render for empty id not possible");
renderImpl(id);
}
private static native void renderImpl(String id) /*-{
$wnd.$("#" + id).page();
}-*/;
public static void setDefaultTransition(Transition defaultTransition) {
JQMContext.defaultTransition = defaultTransition;
}
/**
* Scroll the page to the y-position of the given element. The element
* must be attached to the DOM (obviously!).
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Element e) {
if (e.getId() != null)
Mobile.silentScroll(getTop(e.getId()));
}
/**
* Scroll the page to the y-position of the given widget. The widget must
* be attached to the DOM (obviously!)
*
* This method will not fire jquery mobile scroll events.
*/
public static void silentScroll(Widget widget) {
silentScroll(widget.getElement());
}
}
|
package com.softartisans.timberwolf;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Driver class to grab emails and put them in HBase.
*/
final class App
{
@Option(required=true, name="--exchange-url",
usage="The URL of your Exchange Web Services endpoint.\nFor " +
"example: https://example.contoso.com/ews/exchange.asmx")
private String exchangeUrl;
@Option(required=true, name="--exchange-user",
usage="The username that will be used to authenticate with " +
"Exchange Web Services.")
private String exchangeUser;
@Option(required=true, name="--exchange-password",
usage="The password that will be used to authenticate with " +
"Exchange Web Services.")
private String exchangePassword;
@Option(required=true, name="--get-email-for",
usage="The user for whom to retrieve email.")
private String targetUser;
@Option(required=true, name="--hbase-quorum",
usage="The Zookeeper quorum used to connect to HBase.")
private String hbaseQuorum;
@Option(required=true, name="--hbase-port",
usage="The port used to connect to HBase.")
private String hbasePort;
@Option(required=true, name="--hbase-table",
usage="The HBase table name that email data will be imported " +
"into.")
private String hbaseTableName;
@Option(name="--hbase-column-family.",
usage="The column family for the imported email data. Default " +
"family is 'h'.")
private String hbaseColumnFamily = "h";
private App()
{
}
public static void main(final String[] args)
{
new App().run(args);
}
private void run(final String[] args)
{
CmdLineParser parser = new CmdLineParser(this);
try
{
parser.parseArgument(args);
}
catch(CmdLineException e)
{
System.err.println(e.getMessage());
System.err.println("java timberwolf [options...] arguments...");
parser.printUsage(System.err);
System.err.println();
return;
}
Logger log = LoggerFactory.getLogger(App.class);
BasicConfigurator.configure();
log.info("Timberwolf invoked with the following arguments:");
log.info("Exchange URL: {}", exchangeUrl);
log.info("Exchange User: {}", exchangeUser);
log.info("Exchange Password: {}", exchangePassword);
log.info("Target User: {}", targetUser);
log.info("HBase Quorum: {}", hbaseQuorum);
log.info("HBase Port: {}", hbasePort);
log.info("HBase Table Name: {}", hbaseTableName);
log.info("HBase Column Family: {}", hbaseColumnFamily);
}
}
|
package com.treelogic.proteus.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public abstract class Row {
protected int coilId;
protected int varName;
protected double value;
protected byte type;
protected double x;
public Row() {
this.type = this.getClass() == Row2D.class ? (byte) 0x01f : (byte) 0x00f;
}
public String toJson() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public int getCoilId() {
return coilId;
}
public void setCoilId(int coilId) {
this.coilId = coilId;
}
public int getVarName() {
return varName;
}
public void setVarName(int varName) {
this.varName = varName;
}
public double getValue() {
return value;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public void setValue(double value) {
this.value = value;
}
public byte getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + coilId;
result = prime * result + type;
long temp;
temp = Double.doubleToLongBits(value);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + varName;
temp = Double.doubleToLongBits(x);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Row other = (Row) obj;
if (coilId != other.coilId)
return false;
if (type != other.type)
return false;
if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value))
return false;
if (varName != other.varName)
return false;
if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
return false;
return true;
}
@Override
public String toString() {
return "Row [coilId=" + coilId + ", varName=" + varName + ", value=" + value + ", type=" + type + ", x=" + x
+ "]";
}
}
|
package com.wizzardo.jrt;
import com.wizzardo.tools.cache.Cache;
import com.wizzardo.tools.collections.CollectionTools;
import com.wizzardo.tools.io.FileTools;
import com.wizzardo.tools.misc.Consumer;
import com.wizzardo.tools.xml.Node;
import com.wizzardo.tools.xml.XmlParser;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RTorrentClient {
private String host;
private int port;
private ExecutorService executor = Executors.newSingleThreadExecutor();
private Cache<Long, Runnable> delayed = new Cache<Long, Runnable>(0) {
@Override
public void onRemoveItem(Long aLong, Runnable runnable) {
executor.submit(runnable);
}
};
public RTorrentClient(String host, int port) {
this.host = host;
this.port = port;
}
public int getFilesCount(TorrentInfo torrent) {
return getFilesCount(torrent.getHash());
}
public int getFilesCount(String hash) {
String response = new XmlParser().parse(executeRequest(new XmlRpc("d.get_size_files", new XmlRpc.Params().add(hash))))
// .get("params/param/value/i8").text();
.get(0).get(0).get(0).get(0).text();
return Integer.parseInt(response);
}
public String getFile(TorrentInfo torrent, int i) {
return getFile(torrent.getHash(), i);
}
public String getFile(String hash, int i) {
String file = new XmlParser().parse(executeRequest(new XmlRpc("f.get_path", new XmlRpc.Params().add(hash).add(i))))
// .get("params/param/value/string").text();
.get(0).get(0).get(0).get(0).text();
return file;
}
public void delayed(long ms, Consumer<RTorrentClient> consumer) {
delayed.put(System.nanoTime(), () -> consumer.consume(this), ms);
}
public void load(String torrent) {
List<TorrentInfo> before = getTorrents();
executeRequest(new XmlRpc("load", torrent));
delayed(2000, client -> {
List<TorrentInfo> after = getTorrents();
for (TorrentInfo info : before) {
after.removeIf(it -> it.getHash().equals(info.getHash()));
}
TorrentInfo ti = after.get(0);
System.out.println("start: " + ti.getHash());
client.start(ti);
if (torrent.startsWith("magnet")) {
delayed(5000, c -> {
System.out.println("start: " + ti.getHash());
c.start(ti);
});
}
});
}
public void stop(TorrentInfo torrent) {
stop(torrent.getHash());
}
public void stop(String hash) {
executeRequest(new XmlRpc("d.stop", hash));
}
public void start(TorrentInfo torrent) {
start(torrent.getHash());
}
public void start(String hash) {
executeRequest(new XmlRpc("d.start", hash));
}
public void pause(TorrentInfo torrent) {
pause(torrent.getHash());
}
public void pause(String hash) {
executeRequest(new XmlRpc("d.pause", hash));
}
public void resume(TorrentInfo torrent) {
resume(torrent.getHash());
}
public void resume(String hash) {
executeRequest(new XmlRpc("d.resume", hash));
}
public void remove(TorrentInfo torrent) {
remove(torrent.getHash());
}
public void remove(String hash) {
executeRequest(new XmlRpc("d.erase", hash));
}
public void removeWithData(TorrentInfo torrent) {
removeWithData(torrent.getHash());
}
public void removeWithData(String hash) {
String path;
if (getFilesCount(hash) == 1)
path = getFile(hash, 0);
else
path = getTorrentDirectory(hash);
executeRequest(new XmlRpc("d.erase", hash));
FileTools.deleteRecursive(new File(path));
}
public Collection<TorrentEntry> getEntries(TorrentInfo torrent) {
return getEntries(torrent.getHash());
}
public Collection<TorrentEntry> getEntries(String hash) {
XmlRpc.Params params = new XmlRpc.Params();
params.add(hash)
.add(0)
.add("f.get_path_components=")
.add("f.get_priority=")
.add("f.get_completed_chunks=")
.add("f.get_size_chunks=")
;
// for (int i = 0; i < l; i++) {
// params.add("f.get_path").add("D4264E9D08C1F6BD9BCFC1D4B47E149C577D1FFC").add(i);
String s = executeRequest(new XmlRpc("f.multicall", params));
Node xml = new XmlParser().parse(s);
Node files = xml.get(0).get(0).get(0).get(0).get(0);
TorrentEntry root = new TorrentEntry();
int id = 0;
for (Node child : files.children()) {
Node data = child.get(0).get(0);
Node path = data.get(0).get(0).get(0);
TorrentEntry entry = root;
for (int i = 0; i < path.size(); i++) {
String name = path.get(i).get(0).get(0).text();
entry = entry.getOrCreate(name);
}
entry.setId(id++);
entry.setPriority(FilePriority.byString(data.get(1).get(0).get(0).text()));
entry.setChunksCompleted(Integer.parseInt(data.get(2).get(0).get(0).text()));
entry.setChunksCount(Integer.parseInt(data.get(3).get(0).get(0).text()));
}
// System.out.println(files.toXML(true));
return root.getChildren().values();
}
public List<TorrentInfo> getTorrents() {
String response = executeRequest(new XmlRpc("d.multicall", "main",
"d.name=",
"d.hash=",
"d.size_bytes=",
"d.bytes_done=",
"d.get_down_rate=",
"d.get_up_rate=",
"d.get_complete=",
"d.is_open=",
"d.is_hash_checking=",
"d.get_state=",
"d.get_peers_complete=",
"d.get_peers_accounted=",
"d.get_up_total="
));
XmlParser parser = new XmlParser();
Node methodResponse = parser.parse(response);
// System.out.println("response: " + methodResponse.toXML(true));
// List<TorrentInfo> torrents = CollectionTools.collect(methodResponse.getAll("params/param/value/array/data/value/array/data"), data -> {
List<TorrentInfo> torrents = CollectionTools.collect(methodResponse.get(0).get(0).get(0).get(0).get(0).children(), data -> {
data = data.get(0).get(0);
TorrentInfo info = new TorrentInfo();
info.setName(data.get(0).get(0).text());
info.setHash(data.get(1).get(0).text());
info.setSize(Long.parseLong(data.get(2).get(0).text()));
info.setDownloaded(Long.parseLong(data.get(3).get(0).text()));
info.setDownloadSpeed(Long.parseLong(data.get(4).get(0).text()));
info.setUploadSpeed(Long.parseLong(data.get(5).get(0).text()));
info.setStatus(TorrentInfo.Status.valueOf("1".equals(data.get(6).get(0).text()), "1".equals(data.get(7).get(0).text()), "1".equals(data.get(8).get(0).text()), "1".equals(data.get(9).get(0).text())));
info.setSeeds(Long.parseLong(data.get(10).get(0).text()));
info.setPeers(Long.parseLong(data.get(11).get(0).text()));
info.setUploaded(Long.parseLong(data.get(12).get(0).text()));
return info;
});
XmlRpc.Params params = new XmlRpc.Params();
for (TorrentInfo info : torrents) {
params.add(new XmlRpc("t.multicall", info.getHash(), "d.get_hash=", "t.get_scrape_incomplete=", "t.get_scrape_complete="));
}
response = executeRequest(new XmlRpc("system.multicall", new XmlRpc.Params().add(params)));
Node multi = parser.parse(response);
CollectionTools.eachWithIndex(multi.get(0).get(0).get(0).get(0).get(0).children(), (i, node) -> {
int seeds = 0;
int peers = 0;
for (Node values : node.get(0).get(0).get(0).get(0).get(0).children()) {
peers += Integer.parseInt(values.get(0).get(0).get(0).text());
seeds += Integer.parseInt(values.get(0).get(0).get(1).text());
}
torrents.get(i).setTotalSeeds(seeds);
torrents.get(i).setTotalPeers(peers);
});
return torrents;
}
public void setFilePriority(TorrentInfo torrent, TorrentEntry entry, FilePriority priority) {
setFilePriority(torrent.getHash(), entry.getId(), priority);
}
public void setFilePriority(String hash, int file, FilePriority priority) {
XmlRpc.Params params = new XmlRpc.Params();
params.add(hash)
.add(file)
.add(priority.i)
;
String s = new RTorrentClient(host, port).executeRequest(new XmlRpc("f.set_priority", params));
// System.out.println(s);
s = new RTorrentClient(host, port).executeRequest(new XmlRpc("d.update_priorities", hash));
// System.out.println(s);
}
public String getDownloadDirectory() {
return new XmlParser().parse(executeRequest(new XmlRpc("get_directory"))).get(0).text();
}
public String getTorrentDirectory(TorrentInfo info) {
return getTorrentDirectory(info.getHash());
}
public String getTorrentDirectory(String hash) {
return new XmlParser().parse(executeRequest(new XmlRpc("d.get_directory", hash))).get(0).text();
}
private String executeRequest(XmlRpc request) {
String render = request.render();
// System.out.println("request: " + render);
String response = new ScgiClient.Request(host, port, render).get();
// System.out.println("response: " + response);
return response;
}
public static void main(String[] args) throws InterruptedException {
String host = args.length > 0 ? args[0] : "localhost";
int port = args.length > 1 ? Integer.parseInt(args[1]) : 5000;
RTorrentClient client = new RTorrentClient(host, port);
for (TorrentInfo info : client.getTorrents()) {
System.out.println(info);
if (info.getStatus() == TorrentInfo.Status.STOPPED)
client.start(info);
for (TorrentEntry entry : client.getEntries(info)) {
System.out.println((entry.isFolder() ? "D: " : "F: ") + entry.name);
}
System.out.println("getTorrentDirectory: " + client.getTorrentDirectory(info));
System.out.println("getDownloadDirectory: " + client.getDownloadDirectory());
}
// client.load("/tmp/test.torrent");
// client.remove("3E2C74D5C2A6DC62B1F6B8E655A56AB319FED56D");
// for (int i = 0; i < 1; i++) {
//// ScgiClient.XmlRpc.Params params = new ScgiClient.XmlRpc.Params();
//// List<ScgiClient.XmlRpc.Params> list = new ArrayList<>();
// long time = System.currentTimeMillis();
// List<TorrentInfo> torrents = new RTorrentClient(host, port).getTorrents();
// time = System.currentTimeMillis() - time;
// for (TorrentInfo info : torrents) {
// System.out.println(info);
//// new RTorrentClient(host, port).getEntries(info);
//// params.add(new ScgiClient.XmlRpc("t.multicall", info.getHash(), "d.get_hash=", "t.get_scrape_incomplete="));
// System.out.println("get torrents info: " + time + " ms");
// System.out.println("");
// Thread.sleep(1000);
// String request = new ScgiClient.XmlRpc(host, params).render();
// System.out.println(new ScgiClient.Request(host, port, request).get());
// if (args.length > 2) {
// String[] moreArgs = args.length > 3 ? Arrays.copyOfRange(args, 3, args.length) : new String[0];
// String request = new ScgiClient.XmlRpc(args[2], moreArgs).render();
// System.out.println(new ScgiClient.Request(host, port, request).get());
}
}
|
package com.xpn.xwiki.doc;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.content.parsers.LinkParser;
import com.xpn.xwiki.content.parsers.DocumentParser;
import com.xpn.xwiki.content.parsers.ParsingResultCollection;
import com.xpn.xwiki.content.Link;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.notify.XWikiNotificationRule;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.ListClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StaticListClass;
import com.xpn.xwiki.plugin.query.XWikiCriteria;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.validation.XWikiValidationInterface;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.web.EditForm;
import com.xpn.xwiki.web.ObjectAddForm;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.filter.CharacterFilter;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.suigeneris.jrcs.diff.Diff;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.Revision;
import org.suigeneris.jrcs.rcs.Version;
import org.suigeneris.jrcs.util.ToString;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class XWikiDocument
{
private static final Log log = LogFactory.getLog(XWikiDocument.class);
private String title;
private String parent;
private String web;
private String name;
private String content;
private String meta;
private String format;
private String creator;
private String author;
private String contentAuthor;
private String customClass;
private Date contentUpdateDate;
private Date updateDate;
private Date creationDate;
private Version version;
private long id = 0;
private boolean mostRecent = false;
private boolean isNew = true;
private String template;
private String language;
private String defaultLanguage;
private int translation;
private String database;
private BaseObject tags;
// Used to make sure the MetaData String is regenerated
private boolean isContentDirty = true;
// Used to make sure the MetaData String is regenerated
private boolean isMetaDataDirty = true;
public static final int HAS_ATTACHMENTS = 1;
public static final int HAS_OBJECTS = 2;
public static final int HAS_CLASS = 4;
private int elements = HAS_OBJECTS | HAS_ATTACHMENTS;
// Meta Data
private BaseClass xWikiClass;
private String xWikiClassXML;
private Map xWikiObjects = new HashMap();
private List attachmentList;
// Caching
private boolean fromCache = false;
private ArrayList objectsToRemove = new ArrayList();
// Template by default assign to a view
private String defaultTemplate;
private String validationScript;
private Object wikiNode;
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
private SoftReference archive;
private XWikiStoreInterface store;
public XWikiStoreInterface getStore(XWikiContext context)
{
return context.getWiki().getStore();
}
public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context)
{
return context.getWiki().getAttachmentStore();
}
public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context)
{
return context.getWiki().getVersioningStore();
}
public XWikiStoreInterface getStore()
{
return store;
}
public void setStore(XWikiStoreInterface store)
{
this.store = store;
}
public long getId()
{
if ((language == null) || language.trim().equals("")) {
id = getFullName().hashCode();
} else {
id = (getFullName() + ":" + language).hashCode();
}
//if (log.isDebugEnabled())
// log.debug("ID: " + getFullName() + " " + language + ": " + id);
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getSpace()
{
return web;
}
public void setSpace(String space)
{
this.web = space;
}
/**
* @return the name of the space of the document
* @deprecated use {@link #getSpace()} instead of this function
*/
public String getWeb()
{
return web;
}
/**
* @deprecated use {@link #setSpace(String)} instead of this function
*/
public void setWeb(String web)
{
this.web = web;
}
public String getVersion()
{
return getRCSVersion().toString();
}
public void setVersion(String version)
{
this.version = new Version(version);
}
public Version getRCSVersion()
{
if (version == null) {
version = new Version("1.1");
}
return version;
}
public void setRCSVersion(Version version)
{
this.version = version;
}
public XWikiDocument()
{
this("Main", "WebHome");
}
public XWikiDocument(String web, String name)
{
this.web = web;
int i1 = name.indexOf(".");
if (i1 == -1) {
this.name = name;
} else {
this.web = name.substring(0, i1);
this.name = name.substring(i1 + 1);
}
this.updateDate = new Date();
updateDate.setTime((updateDate.getTime() / 1000) * 1000);
this.contentUpdateDate = new Date();
contentUpdateDate.setTime((contentUpdateDate.getTime() / 1000) * 1000);
this.creationDate = new Date();
creationDate.setTime((creationDate.getTime() / 1000) * 1000);
this.parent = "";
this.content = "\n";
this.format = "";
this.author = "";
this.language = "";
this.defaultLanguage = "";
this.attachmentList = new ArrayList();
this.customClass = "";
}
public XWikiDocument getParentDoc()
{
return new XWikiDocument(web, getParent());
}
public String getParent()
{
return parent.trim();
}
public void setParent(String parent)
{
if (!parent.equals(this.parent)) {
setMetaDataDirty(true);
}
this.parent = parent;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
if (!content.equals(this.content)) {
setContentDirty(true);
setWikiNode(null);
}
this.content = content;
}
public String getRenderedContent(XWikiContext context) throws XWikiException
{
return context.getWiki().getRenderingEngine().renderDocument(this, context);
}
public String getRenderedContent(String text, XWikiContext context)
{
String result;
HashMap backup = new HashMap();
try {
backupContext(backup, context);
setAsContextDoc(context);
result = context.getWiki().getRenderingEngine().renderText(text, this, context);
} finally {
restoreContext(backup, context);
}
return result;
}
public String getEscapedContent(XWikiContext context) throws XWikiException
{
CharacterFilter filter = new CharacterFilter();
return filter.process(getTranslatedContent(context));
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getFullName()
{
StringBuffer buf = new StringBuffer();
buf.append(getSpace());
buf.append(".");
buf.append(getName());
return buf.toString();
}
public void setFullName(String name)
{
setFullName(name, null);
}
public String getTitle()
{
if (title == null) {
return "";
} else {
return title;
}
}
/**
* @param context the XWiki context used to get acces to the XWikiRenderingEngine object
* @return the document title. If a title has not been provided, look for a section title in
* the document's content and if not found return the page name. The returned title
* is also interpreted which means it's allowed to use Velocity, Groovy, etc syntax
* within a title.
*/
public String getDisplayTitle(XWikiContext context)
{
// 1) Check if the user has provided a title
String title = getTitle();
// 2) If not, then try to extract the title from the first document section title
if (title.length() == 0) {
title = extractTitle();
}
// 3) Last if a title has been found renders it as it can contain macros, velocity code,
// groovy, etc.
if (title.length() > 0) {
// This will not completely work for scriting code in title referencing variables
// defined elsewhere. In that case it'll only work if those variables have been
// parsed and put in the corresponding scripting context. This will not work for
// breadcrumbs for example.
title = context.getWiki().getRenderingEngine().interpretText(title, this, context);
} else {
// 4) No title has been found, return the page name as the title
title = getName();
}
return title;
}
/**
* @return the first level 1 or level 1.1 title text in the document's content or "" if none
* are found
* @todo this method has nothing to do in this class and should be moved elsewhere
*/
public String extractTitle()
{
try {
String content = getContent();
int i1 = 0;
int i2;
while (true) {
i2 = content.indexOf("\n", i1);
String title = "";
if (i2 != -1) {
title = content.substring(i1, i2).trim();
} else {
title = content.substring(i1).trim();
}
if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) {
return title.substring(title.indexOf(" ")).trim();
}
if (i2 == -1) {
break;
}
i1 = i2 + 1;
}
} catch (Exception e) {
}
return "";
}
public void setTitle(String title)
{
if (title == null) {
title = "";
}
if (!title.equals(this.title)) {
setContentDirty(true);
}
this.title = title;
}
public String getFormat()
{
if (format == null) {
return "";
} else {
return format;
}
}
public void setFormat(String format)
{
this.format = format;
if (!format.equals(this.format)) {
setMetaDataDirty(true);
}
}
public String getAuthor()
{
if (author == null) {
return "";
} else {
return author.trim();
}
}
public String getContentAuthor()
{
if (contentAuthor == null) {
return "";
} else {
return contentAuthor.trim();
}
}
public void setAuthor(String author)
{
if (!getAuthor().equals(this.author)) {
setMetaDataDirty(true);
}
this.author = author;
}
public void setContentAuthor(String contentAuthor)
{
if (!getContentAuthor().equals(this.contentAuthor)) {
setMetaDataDirty(true);
}
this.contentAuthor = contentAuthor;
}
public String getCreator()
{
if (creator == null) {
return "";
} else {
return creator.trim();
}
}
public void setCreator(String creator)
{
if (!getCreator().equals(this.creator)) {
setMetaDataDirty(true);
}
this.creator = creator;
}
public Date getDate()
{
if (updateDate == null) {
return new Date();
} else {
return updateDate;
}
}
public void setDate(Date date)
{
if ((date != null) && (!date.equals(this.updateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.updateDate = date;
}
public Date getCreationDate()
{
if (creationDate == null) {
return new Date();
} else {
return creationDate;
}
}
public void setCreationDate(Date date)
{
if ((date != null) && (!creationDate.equals(this.creationDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.creationDate = date;
}
public Date getContentUpdateDate()
{
if (contentUpdateDate == null) {
return new Date();
} else {
return contentUpdateDate;
}
}
public void setContentUpdateDate(Date date)
{
if ((date != null) && (!date.equals(this.contentUpdateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.contentUpdateDate = date;
}
public String getMeta()
{
return meta;
}
public void setMeta(String meta)
{
if (meta == null) {
if (this.meta != null) {
setMetaDataDirty(true);
}
} else if (!meta.equals(this.meta)) {
setMetaDataDirty(true);
}
this.meta = meta;
}
public void appendMeta(String meta)
{
StringBuffer buf = new StringBuffer(this.meta);
buf.append(meta);
buf.append("\n");
this.meta = buf.toString();
setMetaDataDirty(true);
}
public boolean isContentDirty()
{
return isContentDirty;
}
public void incrementVersion()
{
if (version == null) {
version = new Version("1.1");
} else {
version = version.next();
}
}
public void setContentDirty(boolean contentDirty)
{
isContentDirty = contentDirty;
}
public boolean isMetaDataDirty()
{
return isMetaDataDirty;
}
public void setMetaDataDirty(boolean metaDataDirty)
{
isMetaDataDirty = metaDataDirty;
}
public String getAttachmentURL(String filename, XWikiContext context)
{
return getAttachmentURL(filename, "download", context);
}
public String getAttachmentURL(String filename, String action, XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(),
action, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalAttachmentURL(String filename, String action, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context);
return url.toString();
}
public String getAttachmentURL(String filename, String action, String querystring,
XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(),
action, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(),
getName(), revision, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, String querystring,
XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(),
getName(), revision, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, boolean redirect, XWikiContext context)
{
URL url = context.getURLFactory()
.createURL(getSpace(), getName(), action, null, null, getDatabase(), context);
if (redirect) {
if (url == null) {
return null;
} else {
return url.toString();
}
} else {
return context.getURLFactory().getURL(url, context);
}
}
public String getURL(String action, XWikiContext context)
{
return getURL(action, false, context);
}
public String getURL(String action, String querystring, XWikiContext context)
{
URL url = context.getURLFactory().createURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalURL(String action, XWikiContext context)
{
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
null, null, getDatabase(), context);
return url.toString();
}
public String getExternalURL(String action, String querystring, XWikiContext context)
{
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return url.toString();
}
public String getParentURL(XWikiContext context) throws XWikiException
{
XWikiDocument doc = new XWikiDocument();
doc.setFullName(getParent(), context);
URL url = context.getURLFactory()
.createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException
{
loadArchive(context);
return getDocumentArchive();
}
/**
* return a wrapped version of an XWikiDocument. Prefer this function instead of new
* Document(XWikiDocument, XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context)
{
if (!((customClassName == null) || (customClassName.equals("")))) {
try {
Class[] classes = new Class[]{XWikiDocument.class, XWikiContext.class};
Object[] args = new Object[]{this, context};
return (com.xpn.xwiki.api.Document) Class.forName(customClassName)
.getConstructor(classes).newInstance(args);
} catch (InstantiationException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (NoSuchMethodException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
public com.xpn.xwiki.api.Document newDocument(XWikiContext context)
{
String customClass = getCustomClass();
return newDocument(customClass, context);
}
public void loadArchive(XWikiContext context) throws XWikiException
{
if (archive == null) {
XWikiDocumentArchive arch =
getVersioningStore(context).getXWikiDocumentArchive(this, context);
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
archive = new SoftReference(arch);
}
}
public XWikiDocumentArchive getDocumentArchive()
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (archive == null) {
return null;
} else {
return (XWikiDocumentArchive) archive.get();
}
}
public void setDocumentArchive(XWikiDocumentArchive arch)
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (arch != null) {
this.archive = new SoftReference(arch);
}
}
public void setDocumentArchive(String sarch) throws XWikiException
{
XWikiDocumentArchive xda = new XWikiDocumentArchive(getId());
xda.setArchive(sarch);
setDocumentArchive(xda);
}
public Version[] getRevisions(XWikiContext context) throws XWikiException
{
return getVersioningStore(context).getXWikiDocVersions(this, context);
}
public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException
{
try {
Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context);
int length = nb;
// 0 means all revisions
if (nb == 0) {
length = revisions.length;
}
if (revisions.length < length) {
length = revisions.length;
}
String[] recentrevs = new String[length];
for (int i = 1; i <= length; i++) {
recentrevs[i - 1
] = revisions[revisions.length - i].toString();
}
return recentrevs;
} catch (Exception e) {
return new String[0];
}
}
public boolean isMostRecent()
{
return mostRecent;
}
public void setMostRecent(boolean mostRecent)
{
this.mostRecent = mostRecent;
}
public BaseClass getxWikiClass()
{
if (xWikiClass == null) {
xWikiClass = new BaseClass();
xWikiClass.setName(getFullName());
}
return xWikiClass;
}
public void setxWikiClass(BaseClass xWikiClass)
{
this.xWikiClass = xWikiClass;
}
public Map getxWikiObjects()
{
return xWikiObjects;
}
public void setxWikiObjects(Map xWikiObjects)
{
this.xWikiObjects = xWikiObjects;
}
public BaseObject getxWikiObject()
{
return getObject(getFullName());
}
public List getxWikiClasses(XWikiContext context)
{
List list = new ArrayList();
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = null;
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
bclass = obj.getxWikiClass(context);
if (bclass != null) {
break;
}
}
}
if (bclass != null) {
list.add(bclass);
}
}
return list;
}
public int createNewObject(String classname, XWikiContext context) throws XWikiException
{
BaseObject object = BaseClass.newCustomClassInstance(classname, context);
object.setName(getFullName());
object.setClassName(classname);
Vector objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
objects.add(object);
int nb = objects.size() - 1;
object.setNumber(nb);
setContentDirty(true);
return nb;
}
public int getObjectNumbers(String classname)
{
try {
return ((Vector) getxWikiObjects().get(classname)).size();
} catch (Exception e) {
return 0;
}
}
public Vector getObjects(String classname)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return (Vector) getxWikiObjects().get(classname);
}
public void setObjects(String classname, Vector objects)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
getxWikiObjects().put(classname, objects);
}
public BaseObject getObject(String classname)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
Vector objects = (Vector) getxWikiObjects().get(classname);
if (objects == null) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
return obj;
}
}
return null;
}
public BaseObject getObject(String classname, int nb)
{
try {
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return (BaseObject) ((Vector) getxWikiObjects().get(classname)).get(nb);
} catch (Exception e) {
return null;
}
}
public BaseObject getObject(String classname, String key, String value)
{
return getObject(classname, key, value, false);
}
public BaseObject getObject(String classname, String key, String value, boolean failover)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
try {
if (value == null) {
if (failover) {
return getObject(classname);
} else {
return null;
}
}
Vector objects = (Vector) getxWikiObjects().get(classname);
if ((objects == null) || (objects.size() == 0)) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
if (value.equals(obj.getStringValue(key))) {
return obj;
}
}
}
if (failover) {
return getObject(classname);
} else {
return null;
}
} catch (Exception e) {
if (failover) {
return getObject(classname);
}
e.printStackTrace();
return null;
}
}
public void addObject(String classname, BaseObject object)
{
Vector vobj = getObjects(classname);
if (vobj == null) {
setObject(classname, 0, object);
} else {
setObject(classname, vobj.size(), object);
}
setContentDirty(true);
}
public void setObject(String classname, int nb, BaseObject object)
{
Vector objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
if (nb >= objects.size()) {
objects.setSize(nb + 1);
}
objects.set(nb, object);
object.setNumber(nb);
setContentDirty(true);
}
/**
* @return true if the document is a new one (ie it has never been saved) or false otherwise
*/
public boolean isNew()
{
return isNew;
}
public void setNew(boolean aNew)
{
isNew = aNew;
}
public void mergexWikiClass(XWikiDocument templatedoc)
{
BaseClass bclass = getxWikiClass();
BaseClass tbclass = templatedoc.getxWikiClass();
if (tbclass != null) {
if (bclass == null) {
setxWikiClass((BaseClass) tbclass.clone());
} else {
getxWikiClass().merge((BaseClass) tbclass.clone());
}
}
setContentDirty(true);
}
public void mergexWikiObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector objects = (Vector) getxWikiObjects().get(name);
if (objects != null) {
Vector tobjects = (Vector) templatedoc.getxWikiObjects().get(name);
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj = (BaseObject) ((BaseObject) tobjects.get(i)).clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
} else {
Vector tobjects = templatedoc.getObjects(name);
objects = new Vector();
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
}
getxWikiObjects().put(name, objects);
}
}
setContentDirty(true);
}
public void clonexWikiObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector tobjects = templatedoc.getObjects(name);
Vector objects = new Vector();
objects.setSize(tobjects.size());
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.set(i, bobj);
}
}
getxWikiObjects().put(name, objects);
}
}
public String getTemplate()
{
if (template == null) {
return "";
} else {
return template;
}
}
public void setTemplate(String template)
{
this.template = template;
setMetaDataDirty(true);
}
public String displayPrettyName(String fieldname, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before,
XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayPrettyName(fieldname, showMandatory, before, object, context);
} catch (Exception e) {
return "";
}
}
public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj,
XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before,
BaseObject obj, XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String dprettyName = "";
if ((showMandatory) && (pclass.getValidationRegExp() != null) &&
(!pclass.getValidationRegExp().equals("")))
{
dprettyName = context.getWiki().addMandatory(context);
}
if (before) {
return dprettyName + pclass.getPrettyName();
} else {
return pclass.getPrettyName() + dprettyName;
}
}
catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayTooltip(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String tooltip = pclass.getTooltip();
if ((tooltip != null) && (!tooltip.trim().equals(""))) {
String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) +
"\" class=\"tooltip_image\" align=\"middle\" />";
return context.getWiki().addTooltip(img, tooltip, context);
} else {
return "";
}
}
catch (Exception e) {
return "";
}
}
public String display(String fieldname, String type, BaseObject obj, XWikiContext context)
{
return display(fieldname, type, "", obj, context);
}
public String display(String fieldname, String type, String pref, BaseObject obj,
XWikiContext context)
{
HashMap backup = new HashMap();
try {
backupContext(backup, context);
setAsContextDoc(context);
type = type.toLowerCase();
StringBuffer result = new StringBuffer();
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String prefix =
pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_";
if (pclass.isCustomDisplayed(context)) {
pclass.displayCustom(result, fieldname, prefix, type, obj, context);
} else if (type.equals("view")) {
pclass.displayView(result, fieldname, prefix, obj, context);
} else if (type.equals("rendered")) {
String fcontent = pclass.displayView(fieldname, prefix, obj, context);
result.append(getRenderedContent(fcontent, context));
} else if (type.equals("edit")) {
context.addDisplayedField(fieldname);
result.append("{pre}");
pclass.displayEdit(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("hidden")) {
result.append("{pre}");
pclass.displayHidden(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("search")) {
result.append("{pre}");
prefix = obj.getxWikiClass(context).getName() + "_";
pclass.displaySearch(result, fieldname, prefix,
(XWikiCriteria) context.get("query"), context);
result.append("{/pre}");
} else {
pclass.displayView(result, fieldname, prefix, obj, context);
}
return result.toString();
}
catch (Exception ex) {
log.warn("Exception showing field " + fieldname, ex);
return "";
}
finally {
restoreContext(backup, context);
}
}
public String display(String fieldname, BaseObject obj, XWikiContext context)
{
String type = null;
try {
type = (String) context.get("display");
}
catch (Exception e) {
}
if (type == null) {
type = "view";
}
return display(fieldname, type, obj, context);
}
public String display(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return display(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String display(String fieldname, String mode, XWikiContext context)
{
return display(fieldname, mode, "", context);
}
public String display(String fieldname, String mode, String prefix, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
if (object == null) {
return "";
} else {
return display(fieldname, mode, object, context);
}
} catch (Exception e) {
return "";
}
}
public String displayForm(String className, String header, String format, XWikiContext context)
{
return displayForm(className, header, format, true, context);
}
public String displayForm(String className, String header, String format, boolean linebreak,
XWikiContext context)
{
Vector objects = getObjects(className);
if (format.endsWith("\\n")) {
linebreak = true;
}
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
VelocityContext vcontext = new VelocityContext();
vcontext.put("formatter", new VelocityFormatter(vcontext));
for (Iterator it = fields.iterator(); it.hasNext();) {
PropertyClass pclass = (PropertyClass) it.next();
vcontext.put(pclass.getName(), pclass.getPrettyName());
}
result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(),
vcontext, context));
if (linebreak) {
result.append("\n");
}
// display each line
for (int i = 0; i < objects.size(); i++) {
vcontext.put("id", new Integer(i + 1));
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
String name = (String) it.next();
vcontext.put(name, display(name, object, context));
}
result.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(),
vcontext, context));
if (linebreak) {
result.append("\n");
}
}
}
return result.toString();
}
public String displayForm(String className, XWikiContext context)
{
Vector objects = getObjects(className);
if (objects == null) {
return "";
}
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
result.append("{table}\n");
boolean first = true;
for (Iterator it = fields.iterator(); it.hasNext();) {
if (first == true) {
first = false;
} else {
result.append("|");
}
PropertyClass pclass = (PropertyClass) it.next();
result.append(pclass.getPrettyName());
}
result.append("\n");
for (int i = 0; i < objects.size(); i++) {
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
first = true;
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
if (first == true) {
first = false;
} else {
result.append("|");
}
String data = display((String) it.next(), object, context);
data = data.trim();
data = data.replaceAll("\n", " ");
if (data.length() == 0) {
result.append(" ");
} else {
result.append(data);
}
}
result.append("\n");
}
}
result.append("{table}\n");
return result.toString();
}
public boolean isFromCache()
{
return fromCache;
}
public void setFromCache(boolean fromCache)
{
this.fromCache = fromCache;
}
public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String defaultLanguage = eform.getDefaultLanguage();
if (defaultLanguage != null) {
setDefaultLanguage(defaultLanguage);
}
String defaultTemplate = eform.getDefaultTemplate();
if (defaultTemplate != null) {
setDefaultTemplate(defaultTemplate);
}
String creator = eform.getCreator();
if ((creator != null) && (!creator.equals(getCreator()))) {
if ((getCreator().equals(context.getUser()))
|| (context.getWiki().getRightService().hasAdminRights(context)))
{
setCreator(creator);
}
}
String parent = eform.getParent();
if (parent != null) {
setParent(parent);
}
String tags = eform.getTags();
if (tags != null) {
setTags(tags, context);
}
}
/**
* add tags to the document.
*/
public void setTags(String tags, XWikiContext context) throws XWikiException
{
loadTags(context);
StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context)
.getField(XWikiConstant.TAG_CLASS_PROP_TAGS);
tagProp.fromString(tags);
this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags));
setMetaDataDirty(true);
}
public String getTags(XWikiContext context)
{
ListProperty prop = (ListProperty) getTagProperty(context);
if (prop != null) {
return prop.getTextValue();
}
return null;
}
public List getTagsList(XWikiContext context)
{
List tagList = null;
BaseProperty prop = getTagProperty(context);
if (prop != null) {
tagList = (List) prop.getValue();
}
return tagList;
}
private BaseProperty getTagProperty(XWikiContext context)
{
loadTags(context);
return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS));
}
private void loadTags(XWikiContext context)
{
if (this.tags == null) {
this.tags = getObject(XWikiConstant.TAG_CLASS, true, context);
}
}
public List getTagsPossibleValues(XWikiContext context)
{
loadTags(context);
String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context)
.getField(XWikiConstant.TAG_CLASS_PROP_TAGS)).getValues();
return ListClass.getListFromString(possibleValues);
//((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString();
}
public void readTranslationMetaFromForm(EditForm eform, XWikiContext context)
throws XWikiException
{
String content = eform.getContent();
if ((content != null) && (!content.equals(""))) {
// Cleanup in case we use HTMLAREA
// content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", content);
content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content);
setContent(content);
}
String title = eform.getTitle();
if (title != null) {
setTitle(title);
}
}
public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
Iterator itobj = getxWikiObjects().keySet().iterator();
while (itobj.hasNext()) {
String name = (String) itobj.next();
Vector bobjects = getObjects(name);
Vector newobjects = new Vector();
newobjects.setSize(bobjects.size());
for (int i = 0; i < bobjects.size(); i++) {
BaseObject oldobject = getObject(name, i);
if (oldobject != null) {
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass
.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
newobjects.set(newobject.getNumber(), newobject);
}
}
getxWikiObjects().put(name, newobjects);
}
setContentDirty(true);
}
public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
readDocMetaFromForm(eform, context);
readTranslationMetaFromForm(eform, context);
readObjectsFromForm(eform, context);
}
/*
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException {
// Get the class from the template
String template = eform.getTemplate();
if ((template!=null)&&(!template.equals(""))) {
if (template.indexOf('.')==-1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = { template, getFullName() };
throw new XWikiException( XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplate(template);
mergexWikiObjects(templatedoc);
}
}
}
*/
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException
{
String template = eform.getTemplate();
readFromTemplate(template, context);
}
public void readFromTemplate(String template, XWikiContext context) throws XWikiException
{
if ((template != null) && (!template.equals(""))) {
String content = getContent();
if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) {
Object[] args = {getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
"Cannot add a template to document {0} because it already has content", null,
args);
} else {
if (template.indexOf('.') == -1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = {template, getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null,
args);
} else {
setTemplate(template);
setContent(templatedoc.getContent());
if ((getParent() == null) || (getParent().equals(""))) {
String tparent = templatedoc.getParent();
if (tparent != null) {
setParent(tparent);
}
}
if (isNew()) {
// We might have received the object from the cache
// and the templace objects might have been copied already
// we need to remove them
setxWikiObjects(new HashMap());
}
// Merge the external objects
// Currently the choice is not to merge the base class and object because it is not
// the prefered way of using external classes and objects.
mergexWikiObjects(templatedoc);
}
}
}
setContentDirty(true);
}
public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc,
int event, XWikiContext context)
{
// Do nothing for the moment..
// A usefull thing here would be to look at any instances of a Notification Object
// with email addresses and send an email to warn that the document has been modified..
}
/**
* Use the document passsed as parameter as the new identity for the current document.
*
* @param document the document containing the new identity
* @throws XWikiException in case of error
*/
private void clone(XWikiDocument document) throws XWikiException
{
setDatabase(document.getDatabase());
setRCSVersion(document.getRCSVersion());
setDocumentArchive(document.getDocumentArchive());
setAuthor(document.getAuthor());
setContentAuthor(document.getContentAuthor());
setContent(document.getContent());
setContentDirty(document.isContentDirty());
setCreationDate(document.getCreationDate());
setDate(document.getDate());
setCustomClass(document.getCustomClass());
setContentUpdateDate(document.getContentUpdateDate());
setTitle(document.getTitle());
setFormat(document.getFormat());
setFromCache(document.isFromCache());
setElements(document.getElements());
setId(document.getId());
setMeta(document.getMeta());
setMetaDataDirty(document.isMetaDataDirty());
setMostRecent(document.isMostRecent());
setName(document.getName());
setNew(document.isNew());
setStore(document.getStore());
setTemplate(document.getTemplate());
setSpace(document.getSpace());
setParent(document.getParent());
setCreator(document.getCreator());
setDefaultLanguage(document.getDefaultLanguage());
setDefaultTemplate(document.getDefaultTemplate());
setValidationScript(document.getValidationScript());
setLanguage(document.getLanguage());
setTranslation(document.getTranslation());
setxWikiClass((BaseClass) document.getxWikiClass().clone());
setxWikiClassXML(document.getxWikiClassXML());
clonexWikiObjects(document);
copyAttachments(document);
elements = document.elements;
}
public Object clone()
{
XWikiDocument doc = null;
try {
doc = (XWikiDocument) getClass().newInstance();
doc.setDatabase(getDatabase());
doc.setRCSVersion(getRCSVersion());
doc.setDocumentArchive(getDocumentArchive());
doc.setAuthor(getAuthor());
doc.setContentAuthor(getContentAuthor());
doc.setContent(getContent());
doc.setContentDirty(isContentDirty());
doc.setCreationDate(getCreationDate());
doc.setDate(getDate());
doc.setCustomClass(getCustomClass());
doc.setContentUpdateDate(getContentUpdateDate());
doc.setTitle(getTitle());
doc.setFormat(getFormat());
doc.setFromCache(isFromCache());
doc.setElements(getElements());
doc.setId(getId());
doc.setMeta(getMeta());
doc.setMetaDataDirty(isMetaDataDirty());
doc.setMostRecent(isMostRecent());
doc.setName(getName());
doc.setNew(isNew());
doc.setStore(getStore());
doc.setTemplate(getTemplate());
doc.setSpace(getSpace());
doc.setParent(getParent());
doc.setCreator(getCreator());
doc.setDefaultLanguage(getDefaultLanguage());
doc.setDefaultTemplate(getDefaultTemplate());
doc.setValidationScript(getValidationScript());
doc.setLanguage(getLanguage());
doc.setTranslation(getTranslation());
doc.setxWikiClass((BaseClass) getxWikiClass().clone());
doc.setxWikiClassXML(getxWikiClassXML());
doc.clonexWikiObjects(this);
doc.copyAttachments(this);
doc.elements = elements;
} catch (Exception e) {
// This should not happen
}
return doc;
}
public void copyAttachments(XWikiDocument xWikiSourceDocument)
{
Iterator attit = xWikiSourceDocument.getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
XWikiAttachment newattachment = (XWikiAttachment) attachment.clone();
newattachment.setDoc(this);
if (newattachment.getAttachment_archive() != null) {
newattachment.getAttachment_archive().setAttachment(newattachment);
}
if (newattachment.getAttachment_content() != null) {
newattachment.getAttachment_content().setContentDirty(true);
}
getAttachmentList().add(newattachment);
}
setContentDirty(true);
}
public void loadAttachments(XWikiContext context) throws XWikiException
{
Iterator attit = getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
attachment.loadContent(context);
attachment.loadArchive(context);
}
}
public boolean equals(Object object)
{
XWikiDocument doc = (XWikiDocument) object;
if (!getName().equals(doc.getName())) {
return false;
}
if (!getSpace().equals(doc.getSpace())) {
return false;
}
if (!getAuthor().equals(doc.getAuthor())) {
return false;
}
if (!getContentAuthor().equals(doc.getContentAuthor())) {
return false;
}
if (!getParent().equals(doc.getParent())) {
return false;
}
if (!getCreator().equals(doc.getCreator())) {
return false;
}
if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) {
return false;
}
if (!getLanguage().equals(doc.getLanguage())) {
return false;
}
if (getTranslation() != doc.getTranslation()) {
return false;
}
if (getDate().getTime() != doc.getDate().getTime()) {
return false;
}
if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) {
return false;
}
if (getCreationDate().getTime() != doc.getCreationDate().getTime()) {
return false;
}
if (!getFormat().equals(doc.getFormat())) {
return false;
}
if (!getTitle().equals(doc.getTitle())) {
return false;
}
if (!getContent().equals(doc.getContent())) {
return false;
}
if (!getVersion().equals(doc.getVersion())) {
return false;
}
if (!getTemplate().equals(doc.getTemplate())) {
return false;
}
if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) {
return false;
}
if (!getValidationScript().equals(doc.getValidationScript())) {
return false;
}
if (!getxWikiClass().equals(doc.getxWikiClass())) {
return false;
}
Set list1 = getxWikiObjects().keySet();
Set list2 = doc.getxWikiObjects().keySet();
if (!list1.equals(list2)) {
return false;
}
for (Iterator it = list1.iterator(); it.hasNext();) {
String name = (String) it.next();
Vector v1 = getObjects(name);
Vector v2 = doc.getObjects(name);
if (v1.size() != v2.size()) {
return false;
}
for (int i = 0; i < v1.size(); i++) {
if ((v1.get(i) == null) && (v2.get(i) != null)) {
return false;
}
if (!v1.get(i).equals(v2.get(i))) {
return false;
}
}
}
return true;
}
public String toXML(Document doc, XWikiContext context)
{
OutputFormat outputFormat = new OutputFormat("", true);
if ((context == null) || (context.getWiki() == null)) {
outputFormat.setEncoding("UTF-8");
} else {
outputFormat.setEncoding(context.getWiki().getEncoding());
}
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String getXMLContent(XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(context);
Document doc = tdoc.toXMLDocument(true, true, false, false, context);
return toXML(doc, context);
}
public String toXML(XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(context);
return toXML(doc, context);
}
public String toFullXML(XWikiContext context) throws XWikiException
{
return toXML(true, false, true, true, context);
}
public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context)
throws IOException
{
try {
String zipname = getSpace() + "/" + getName();
String language = getLanguage();
if ((language != null) && (!language.equals(""))) {
zipname += "." + language;
}
ZipEntry zipentry = new ZipEntry(zipname);
zos.putNextEntry(zipentry);
zos.write(toXML(true, false, true, withVersions, context).getBytes());
zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException
{
addToZip(zos, true, context);
}
public String toXML(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(bWithObjects, bWithRendering,
bWithAttachmentContent, bWithVersions, context);
return toXML(doc, context);
}
public Document toXMLDocument(XWikiContext context) throws XWikiException
{
return toXMLDocument(true, false, false, false, context);
}
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException
{
Document doc = new DOMDocument();
Element docel = new DOMElement("xwikidoc");
doc.setRootElement(docel);
Element el = new DOMElement("web");
el.addText(getSpace());
docel.add(el);
el = new DOMElement("name");
el.addText(getName());
docel.add(el);
el = new DOMElement("language");
el.addText(getLanguage());
docel.add(el);
el = new DOMElement("defaultLanguage");
el.addText(getDefaultLanguage());
docel.add(el);
el = new DOMElement("translation");
el.addText("" + getTranslation());
docel.add(el);
el = new DOMElement("parent");
el.addText(getParent());
docel.add(el);
el = new DOMElement("creator");
el.addText(getCreator());
docel.add(el);
el = new DOMElement("author");
el.addText(getAuthor());
docel.add(el);
el = new DOMElement("customClass");
el.addText(getCustomClass());
docel.add(el);
el = new DOMElement("contentAuthor");
el.addText(getContentAuthor());
docel.add(el);
long d = getCreationDate().getTime();
el = new DOMElement("creationDate");
el.addText("" + d);
docel.add(el);
d = getDate().getTime();
el = new DOMElement("date");
el.addText("" + d);
docel.add(el);
d = getContentUpdateDate().getTime();
el = new DOMElement("contentUpdateDate");
el.addText("" + d);
docel.add(el);
el = new DOMElement("version");
el.addText(getVersion());
docel.add(el);
el = new DOMElement("title");
el.addText(getTitle());
docel.add(el);
el = new DOMElement("template");
el.addText(getTemplate());
docel.add(el);
el = new DOMElement("defaultTemplate");
el.addText(getDefaultTemplate());
docel.add(el);
el = new DOMElement("validationScript");
el.addText(getValidationScript());
docel.add(el);
List alist = getAttachmentList();
for (int ai = 0; ai < alist.size(); ai++) {
XWikiAttachment attach = (XWikiAttachment) alist.get(ai);
docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context));
}
if (bWithObjects) {
// Add Class
BaseClass bclass = getxWikiClass();
if (bclass.getFieldList().size() > 0) {
docel.add(bclass.toXML(null));
}
// Add Objects
Iterator it = getxWikiObjects().values().iterator();
while (it.hasNext()) {
Vector objects = (Vector) it.next();
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
BaseClass objclass = null;
if (obj.getName().equals(obj.getClassName())) {
objclass = bclass;
} else {
objclass = obj.getxWikiClass(context);
}
docel.add(obj.toXML(objclass));
}
}
}
}
// Add Content
el = new DOMElement("content");
//Filter filter = new CharacterFilter();
//String newcontent = filter.process(getContent());
//String newcontent = encodedXMLStringAsUTF8(getContent());
String newcontent = content;
el.addText(newcontent);
docel.add(el);
if (bWithRendering) {
el = new DOMElement("renderedcontent");
try {
el.addText(getRenderedContent(context));
} catch (XWikiException e) {
el.addText("Exception with rendering content: " + e.getFullMessage());
}
docel.add(el);
}
if (bWithVersions) {
el = new DOMElement("versions");
try {
el.addText(getDocumentArchive(context).getArchive());
} catch (XWikiException e) {
return null;
}
docel.add(el);
}
return doc;
}
protected String encodedXMLStringAsUTF8(String xmlString)
{
if (xmlString == null) {
return "";
}
int length = xmlString.length();
char character;
StringBuffer result = new StringBuffer();
for (int i = 0; i < length; i++) {
character = xmlString.charAt(i);
switch (character) {
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\n':
result.append("\n");
break;
case '\r':
result.append("\r");
break;
case '\t':
result.append("\t");
break;
default:
if (character < 0x20) {
} else if (character > 0x7F) {
result.append("&
result.append(Integer.toHexString(character).toUpperCase());
result.append(";");
} else {
result.append(character);
}
break;
}
}
return result.toString();
}
protected String getElement(Element docel, String name)
{
Element el = docel.element(name);
if (el == null) {
return "";
} else {
return el.getText();
}
}
public void fromXML(String xml) throws XWikiException
{
fromXML(xml, false);
}
public void fromXML(InputStream is) throws XWikiException
{
fromXML(is, false);
}
public void fromXML(String xml, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(xml);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC,
XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(InputStream in, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC,
XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(Document domdoc, boolean withArchive) throws XWikiException
{
Element docel = domdoc.getRootElement();
setName(getElement(docel, "name"));
setSpace(getElement(docel, "web"));
setParent(getElement(docel, "parent"));
setCreator(getElement(docel, "creator"));
setAuthor(getElement(docel, "author"));
setCustomClass(getElement(docel, "customClass"));
setContentAuthor(getElement(docel, "contentAuthor"));
setVersion(getElement(docel, "version"));
setContent(getElement(docel, "content"));
setLanguage(getElement(docel, "language"));
setDefaultLanguage(getElement(docel, "defaultLanguage"));
setTitle(getElement(docel, "title"));
setDefaultTemplate(getElement(docel, "defaultTemplate"));
setValidationScript(getElement(docel, "validationScript"));
String strans = getElement(docel, "translation");
if ((strans == null) || strans.equals("")) {
setTranslation(0);
} else {
setTranslation(Integer.parseInt(strans));
}
String archive = getElement(docel, "versions");
if (withArchive && archive != null && archive.length() > 0) {
setDocumentArchive(archive);
}
String sdate = getElement(docel, "date");
if (!sdate.equals("")) {
Date date = new Date(Long.parseLong(sdate));
setDate(date);
}
String scdate = getElement(docel, "creationDate");
if (!scdate.equals("")) {
Date cdate = new Date(Long.parseLong(scdate));
setCreationDate(cdate);
}
List atels = docel.elements("attachment");
for (int i = 0; i < atels.size(); i++) {
Element atel = (Element) atels.get(i);
XWikiAttachment attach = new XWikiAttachment();
attach.setDoc(this);
attach.fromXML(atel);
getAttachmentList().add(attach);
}
Element cel = docel.element("class");
BaseClass bclass = new BaseClass();
if (cel != null) {
bclass.fromXML(cel);
setxWikiClass(bclass);
}
List objels = docel.elements("object");
for (int i = 0; i < objels.size(); i++) {
Element objel = (Element) objels.get(i);
BaseObject bobject = new BaseObject();
bobject.fromXML(objel);
addObject(bobject.getClassName(), bobject);
}
// We have been reading from XML so the document does not need a new version when saved
setMetaDataDirty(false);
setContentDirty(false);
}
public void setAttachmentList(List list)
{
attachmentList = list;
}
public List getAttachmentList()
{
return attachmentList;
}
public void saveAllAttachments(XWikiContext context) throws XWikiException
{
for (int i = 0; i < attachmentList.size(); i++) {
saveAttachmentContent((XWikiAttachment) attachmentList.get(i), context);
}
}
public void saveAttachmentsContent(List attachments, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore()
.saveAttachmentsContent(attachments, this, true, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
saveAttachmentContent(attachment, true, true, context);
}
protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate,
boolean bTransaction, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore()
.saveAttachmentContent(attachment, bParentUpdate, context, bTransaction);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true);
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void deleteAttachment(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
try {
context.getWiki().getAttachmentStore()
.deleteXWikiAttachment(attachment, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public List getBacklinks(XWikiContext context) throws XWikiException
{
return getStore(context).loadBacklinks(getFullName(), context, true);
}
public List getLinks(XWikiContext context) throws XWikiException
{
return getStore(context).loadLinks(getId(), context, true);
}
public void renameProperties(String className, Map fieldsToRename)
{
Vector objects = getObjects(className);
if (objects == null) {
return;
}
for (int j = 0; j < objects.size(); j++) {
BaseObject bobject = (BaseObject) objects.get(j);
if (bobject == null) {
continue;
}
for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) {
String origname = (String) renameit.next();
String newname = (String) fieldsToRename.get(origname);
BaseProperty origprop = (BaseProperty) bobject.safeget(origname);
if (origprop != null) {
BaseProperty prop = (BaseProperty) origprop.clone();
bobject.removeField(origname);
prop.setName(newname);
bobject.addField(newname, prop);
}
}
}
setContentDirty(true);
}
public void addObjectsToRemove(BaseObject object)
{
getObjectsToRemove().add(object);
setContentDirty(true);
}
public ArrayList getObjectsToRemove()
{
return objectsToRemove;
}
public void setObjectsToRemove(ArrayList objectsToRemove)
{
this.objectsToRemove = objectsToRemove;
setContentDirty(true);
}
public List getIncludedPages(XWikiContext context)
{
try {
String pattern =
"#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)";
List list = context.getUtil().getUniqueMatches(getContent(), pattern, 2);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
if (name.indexOf(".") == -1) {
list.set(i, getSpace() + "." + name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return list;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public List getIncludedMacros(XWikiContext context)
{
return context.getWiki().getIncludedMacros(getSpace(), getContent(), context);
}
public List getLinkedPages(XWikiContext context)
{
try {
String pattern = "\\[(.*?)\\]";
List newlist = new ArrayList();
List list = context.getUtil().getUniqueMatches(getContent(), pattern, 1);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
int i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 1);
}
i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 4);
}
i1 = name.indexOf("
if (i1 != -1) {
name = name.substring(0, i1);
}
i1 = name.indexOf("?");
if (i1 != -1) {
name = name.substring(0, i1);
}
// Let's get rid of anything that's not a real link
if (name.trim().equals("") || (name.indexOf("$") != -1) ||
(name.indexOf(":
|| (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1)
|| (name.indexOf("..") != -1) || (name.indexOf(":") != -1) ||
(name.indexOf("=") != -1))
{
continue;
}
// generate the link
String newname = StringUtils.replace(Util.noaccents(name), " ", "");
// If it is a local link let's add the space
if (newname.indexOf(".") == -1) {
newname = getSpace() + "." + name;
}
if (context.getWiki().exists(newname, context)) {
name = newname;
} else {
// If it is a local link let's add the space
if (name.indexOf(".") == -1) {
name = getSpace() + "." + name;
}
}
// Let's finally ignore the autolinks
if (!name.equals(getFullName())) {
newlist.add(name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return newlist;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context) throws XWikiException
{
String result = pclass.displayView(pclass.getName(), prefix, object, context);
return getRenderedContent(result, context);
}
public String displayView(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayView(pclass.getName(), prefix, object, context);
}
public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayEdit(pclass.getName(), prefix, object, context);
}
public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayHidden(pclass.getName(), prefix, object, context);
}
public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displaySearch(pclass.getName(), prefix, criteria, context);
}
public XWikiAttachment getAttachment(String filename)
{
List list = getAttachmentList();
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().equals(filename)) {
return attach;
}
}
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().startsWith(filename + ".")) {
return attach;
}
}
return null;
}
public BaseObject getFirstObject(String fieldname)
{
// Keeping this function with context null for compatibilit reasons
// It should not be used, since it would miss properties which are only defined in the class
// and not present in the object because the object was not updated
return getFirstObject(fieldname, null);
}
public BaseObject getFirstObject(String fieldname, XWikiContext context)
{
Collection objectscoll = getxWikiObjects().values();
if (objectscoll == null) {
return null;
}
for (Iterator itobjs = objectscoll.iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject obj = (BaseObject) itobjs2.next();
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
if (bclass != null) {
Set set = bclass.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
Set set = obj.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
}
}
return null;
}
public int getIntValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getIntValue(fieldName);
}
public long getLongValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getLongValue(fieldName);
}
public String getStringValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return "";
}
String result = obj.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public int getIntValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getIntValue(fieldName);
}
}
public long getLongValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getLongValue(fieldName);
}
}
public String getStringValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return "";
}
String result = object.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public void setStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringValue(fieldName, value);
setContentDirty(true);
}
public List getListValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return new ArrayList();
}
return obj.getListValue(fieldName);
}
public List getListValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return new ArrayList();
}
return object.getListValue(fieldName);
}
public void setListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setListValue(fieldName, value);
setContentDirty(true);
}
public void setLargeStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setLargeStringValue(fieldName, value);
setContentDirty(true);
}
public void setIntValue(String className, String fieldName, int value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setIntValue(fieldName, value);
setContentDirty(true);
}
public String getDatabase()
{
return database;
}
public void setDatabase(String database)
{
this.database = database;
}
public void setFullName(String fullname, XWikiContext context)
{
if (fullname == null) {
return;
}
int i0 = fullname.lastIndexOf(":");
int i1 = fullname.lastIndexOf(".");
if (i0 != -1) {
database = fullname.substring(0, i0);
web = fullname.substring(i0 + 1, i1);
name = fullname.substring(i1 + 1);
} else {
if (i1 == -1) {
try {
web = context.getDoc().getSpace();
} catch (Exception e) {
web = "XWiki";
}
name = fullname;
} else {
web = fullname.substring(0, i1);
name = fullname.substring(i1 + 1);
}
}
if (name.equals("")) {
name = "WebHome";
}
setContentDirty(true);
}
public String getLanguage()
{
if (language == null) {
return "";
} else {
return language.trim();
}
}
public void setLanguage(String language)
{
this.language = language;
}
public String getDefaultLanguage()
{
if (defaultLanguage == null) {
return "";
} else {
return defaultLanguage.trim();
}
}
public void setDefaultLanguage(String defaultLanguage)
{
this.defaultLanguage = defaultLanguage;
setMetaDataDirty(true);
}
public int getTranslation()
{
return translation;
}
public void setTranslation(int translation)
{
this.translation = translation;
setMetaDataDirty(true);
}
public String getTranslatedContent(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedContent(language, context);
}
public String getTranslatedContent(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(language, context);
String rev = (String) context.get("rev");
if ((rev == null) || (rev.length() == 0)) {
return tdoc.getContent();
}
XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context);
return cdoc.getContent();
}
public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedDocument(language, context);
}
public XWikiDocument getTranslatedDocument(String language, XWikiContext context)
throws XWikiException
{
XWikiDocument tdoc = this;
if (!((language == null) || (language.equals("")) || language.equals(defaultLanguage))) {
tdoc = new XWikiDocument(getSpace(), getName());
tdoc.setLanguage(language);
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
tdoc = getStore(context).loadXWikiDoc(tdoc, context);
if (tdoc.isNew()) {
tdoc = this;
}
} catch (Exception e) {
tdoc = this;
} finally {
context.setDatabase(database);
}
}
return tdoc;
}
public String getRealLanguage(XWikiContext context) throws XWikiException
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public String getRealLanguage()
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public List getTranslationList(XWikiContext context) throws XWikiException
{
return getStore().getTranslationList(this, context);
}
public List getXMLDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.toXML(context)),
ToString.stringToArray(newdoc.toXML(context))));
}
public List getContentDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.getContent()),
ToString.stringToArray(newdoc.getContent())));
}
public List getContentDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getContentDiff(origdoc, newdoc, context);
}
public List getContentDiff(String rev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getContentDiff(this, revdoc, context);
}
public List getLastChanges(XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
Version version = getRCSVersion();
String prev = "1." + (version.last() - 1);
XWikiDocument prevdoc = context.getWiki().getDocument(this, prev, context);
return getDeltas(Diff.diff(ToString.stringToArray(getContent()),
ToString.stringToArray(prevdoc.getContent())));
}
public List getRenderedContentDiff(XWikiDocument origdoc, XWikiDocument newdoc,
XWikiContext context) throws XWikiException, DifferentiationFailedException
{
String content1, content2;
content1 = context.getWiki().getRenderingEngine()
.renderText(origdoc.getContent(), origdoc, context);
content2 =
context.getWiki().getRenderingEngine().renderText(newdoc.getContent(), newdoc, context);
return getDeltas(Diff.diff(ToString.stringToArray(content1),
ToString.stringToArray(content2)));
}
public List getRenderedContentDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getRenderedContentDiff(origdoc, newdoc, context);
}
public List getRenderedContentDiff(String rev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getRenderedContentDiff(this, revdoc, context);
}
protected List getDeltas(Revision rev)
{
ArrayList list = new ArrayList();
for (int i = 0; i < rev.size(); i++) {
list.add(rev.getDelta(i));
}
return list;
}
public List getMetaDataDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getMetaDataDiff(origdoc, newdoc, context);
}
public List getMetaDataDiff(String rev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getMetaDataDiff(this, revdoc, context);
}
public List getMetaDataDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
List list = new ArrayList();
if ((origdoc == null) || (newdoc == null)) {
return list;
}
if (!origdoc.getParent().equals(newdoc.getParent())) {
list.add(new MetaDataDiff("parent", origdoc.getParent(), newdoc.getParent()));
}
if (!origdoc.getAuthor().equals(newdoc.getAuthor())) {
list.add(new MetaDataDiff("author", origdoc.getAuthor(), newdoc.getAuthor()));
}
if (!origdoc.getSpace().equals(newdoc.getSpace())) {
list.add(new MetaDataDiff("web", origdoc.getSpace(), newdoc.getSpace()));
}
if (!origdoc.getName().equals(newdoc.getName())) {
list.add(new MetaDataDiff("name", origdoc.getName(), newdoc.getName()));
}
if (!origdoc.getLanguage().equals(newdoc.getLanguage())) {
list.add(new MetaDataDiff("language", origdoc.getLanguage(), newdoc.getLanguage()));
}
if (!origdoc.getDefaultLanguage().equals(newdoc.getDefaultLanguage())) {
list.add(new MetaDataDiff("defaultLanguage", origdoc.getDefaultLanguage(),
newdoc.getDefaultLanguage()));
}
return list;
}
public List getObjectDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getObjectDiff(origdoc, newdoc, context);
}
public List getObjectDiff(String rev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getObjectDiff(this, revdoc, context);
}
public List getObjectDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
ArrayList difflist = new ArrayList();
for (Iterator itobjs = origdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject origobj = (BaseObject) itobjs2.next();
BaseObject newobj = newdoc.getObject(origobj.getClassName(), origobj.getNumber());
List dlist;
if (newobj == null) {
dlist = origobj.getDiff(new BaseObject(), context);
} else {
dlist = origobj.getDiff(newobj, context);
}
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
for (Iterator itobjs = newdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject newobj = (BaseObject) itobjs2.next();
BaseObject origobj = origdoc.getObject(newobj.getClassName(), newobj.getNumber());
if (origobj == null) {
origobj = new BaseObject();
origobj.setClassName(newobj.getClassName());
origobj.setNumber(newobj.getNumber());
List dlist = origobj.getDiff(newobj, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
return difflist;
}
public List getClassDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
ArrayList difflist = new ArrayList();
BaseClass origclass = origdoc.getxWikiClass();
BaseClass newclass = newdoc.getxWikiClass();
if ((newclass == null) && (origclass == null)) {
return difflist;
}
List dlist = origclass.getDiff(newclass, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
return difflist;
}
/**
* Rename the current document and all the backlinks leading to it. See
* {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details.
*
* @param newDocumentName the new document name. If the space is not specified then defaults
* to the current space.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, XWikiContext context)
throws XWikiException
{
rename(newDocumentName, getBacklinks(context), context);
}
/**
* Rename the current document and all the links pointing to it in the list of passed backlink
* documents. The renaming algorithm takes into account the fact that there are several ways to
* write a link to a given page and all those forms need to be renamed. For example the
* following links all point to the same page:
* <ul>
* <li>[Page]</li>
* <li>[Page?param=1]</li>
* <li>[currentwiki:Page]</li>
* <li>[CurrentSpace.Page]</li>
* </ul>
* <p>Note: links without a space are renamed with the space added.</p>
*
* @param newDocumentName the new document name. If the space is not specified then defaults
* to the current space.
* @param backlinkDocumentNames the list of documents to parse and for which links will be
* modified to point to the new renamed document.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, List backlinkDocumentNames,
XWikiContext context) throws XWikiException
{
// TODO: Do all this in a single DB transaction as otherwise the state will be unknown if
// something fails in the middle...
// Set the context to point to the document being renamed. This is required so that
// the Link.getNormalizedName() method which uses context.getDoc().getSpace() gets the
// space from the document and not the space from the document where the renamed is called
// from. If we don't do this and if the rename is being done from a document in a different
// space the we won't be able to recognize links which have no space defined and which
// point to the document being renamed...
XWikiDocument originalCurrentDocument = context.getDoc();
context.setDoc(this);
// Parse the new document in order to get a Link object so that we can easily get the
// space and page name.
Link newLink = new LinkParser().parse(newDocumentName);
// If the new document name doesn't contain the space name, use the current space name.
if (newLink.getSpace() == null) {
newLink.setSpace(getSpace());
}
// Step 1: Copy the document under a new name
context.getWiki().copyDocument(getFullName(), newDocumentName, context);
// Step 2: For each backlink to rename, parse the backlink document and replace the links
// with the new name.
// Note: we ignore invalid links here. Invalid links should be shown to the user so
// that they fix them but the rename feature ignores them.
DocumentParser documentParser = new DocumentParser();
for (Iterator it = backlinkDocumentNames.iterator(); it.hasNext();) {
String backlinkDocumentName = (String) it.next();
XWikiDocument backlinkDocument =
context.getWiki().getDocument(backlinkDocumentName, context);
// Note: Here we cannot do a simple search/replace as there are several ways to point
// to the same document. For example [Page], [Page?param=1], [currentwiki:Page],
// [CurrentSpace.Page] all point to the same document. Thus we have to parse the links
// to recognize them and only then do a replace.
ParsingResultCollection result =
documentParser.parseLinks(backlinkDocument.getContent());
// For each link in a backlink document check if it corresponds to the current document
// name. If so, rename it with the new name.
for (Iterator links = result.getValidElements().iterator(); links.hasNext();) {
Link link = (Link) links.next();
String linkText = link.toString();
if (getFullName().equals(link.getNormalizedName(context))) {
// We've found a link to rename! Rename it!
// TODO: Also handle the case where we're renaming to an external link.
link.setSpace(newLink.getSpace());
link.setPage(newLink.getPage());
// We need to add the link delimiters ("[" and "]") for doing the search and
// replace as otherwise we might rename text with the same content as a link.
String newContent = StringUtils.replaceOnce(backlinkDocument.getContent(),
"[" + linkText + "]", "[" + link.toString() + "]");
backlinkDocument.setContent(newContent);
}
}
context.getWiki().saveDocument(backlinkDocument, context);
}
// Step 3: Delete the old document
context.getWiki().deleteDocument(this, context);
// Step 4: The current document needs to point to the renamed document as otherwise it's
// pointing to an invalid XWikiDocument object as it's been deleted...
clone(context.getWiki().getDocument(newDocumentName, context));
// Restore the current document in the context
context.setDoc(originalCurrentDocument);
}
public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException
{
String oldname = getFullName();
loadAttachments(context);
loadArchive(context);
/* if (oldname.equals(docname))
return this; */
XWikiDocument newdoc = (XWikiDocument) clone();
newdoc.setFullName(newDocumentName, context);
newdoc.setContentDirty(true);
newdoc.getxWikiClass().setName(newDocumentName);
Vector objects = newdoc.getObjects(oldname);
if (objects != null) {
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject object = (BaseObject) it.next();
object.setName(newDocumentName);
}
}
return newdoc;
}
public XWikiLock getLock(XWikiContext context) throws XWikiException
{
XWikiLock theLock = getStore(context).loadLock(getId(), context, true);
if (theLock != null) {
int timeout =
context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context);
if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) {
getStore(context).deleteLock(theLock, context, true);
theLock = null;
}
}
return theLock;
}
public void setLock(String userName, XWikiContext context) throws XWikiException
{
XWikiLock lock = new XWikiLock(getId(), userName);
getStore(context).saveLock(lock, context, true);
}
public void removeLock(XWikiContext context) throws XWikiException
{
XWikiLock lock = getStore(context).loadLock(getId(), context, true);
if (lock != null) {
getStore(context).deleteLock(lock, context, true);
}
}
public void insertText(String text, String marker, XWikiContext context) throws XWikiException
{
setContent(StringUtils.replaceOnce(getContent(), marker, text + marker));
context.getWiki().saveDocument(this, context);
}
public Object getWikiNode()
{
return wikiNode;
}
public void setWikiNode(Object wikiNode)
{
this.wikiNode = wikiNode;
}
public String getxWikiClassXML()
{
return xWikiClassXML;
}
public void setxWikiClassXML(String xWikiClassXML)
{
this.xWikiClassXML = xWikiClassXML;
}
public int getElements()
{
return elements;
}
public void setElements(int elements)
{
this.elements = elements;
}
public void setElement(int element, boolean toggle)
{
if (toggle) {
elements = elements | element;
} else {
elements = elements & (~element);
}
}
public boolean hasElement(int element)
{
return ((elements & element) == element);
}
public String getDefaultEditURL(XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
if (getContent().indexOf("includeForm(") != -1) {
return getEditURL("inline", "", context);
} else {
String editor = xwiki.getEditorPreference(context);
return getEditURL("edit", editor, context);
}
}
public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String language = "";
XWikiDocument tdoc = (XWikiDocument) context.get("tdoc");
String realLang = tdoc.getRealLanguage(context);
if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) {
language = realLang;
}
return getEditURL(action, mode, language, context);
}
public String getEditURL(String action, String mode, String language, XWikiContext context)
{
StringBuffer editparams = new StringBuffer();
if (!mode.equals("")) {
editparams.append("xpage=");
editparams.append(mode);
}
if (!language.equals("")) {
if (!mode.equals("")) {
editparams.append("&");
}
editparams.append("language=");
editparams.append(language);
}
return getURL(action, editparams.toString(), context);
}
public String getDefaultTemplate()
{
if (defaultTemplate == null) {
return "";
} else {
return defaultTemplate;
}
}
public void setDefaultTemplate(String defaultTemplate)
{
this.defaultTemplate = defaultTemplate;
setMetaDataDirty(true);
}
public Vector getComments()
{
return getComments(true);
}
public Vector getComments(boolean asc)
{
if (asc) {
return getObjects("XWiki.XWikiComments");
} else {
Vector list = getObjects("XWiki.XWikiComments");
if (list == null) {
return list;
}
Vector newlist = new Vector();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public boolean isCurrentUserCreator(XWikiContext context)
{
return isCreator(context.getUser());
}
public boolean isCreator(String username)
{
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return username.equals(getCreator());
}
public boolean isCurrentUserPage(XWikiContext context)
{
String username = context.getUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public boolean isCurrentLocalUserPage(XWikiContext context)
{
String username = context.getLocalUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public void resetArchive(XWikiContext context) throws XWikiException
{
getVersioningStore(context).resetRCSArchive(this, true, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException
{
// Read info in object
ObjectAddForm form = new ObjectAddForm();
form.setRequest((HttpServletRequest) context.getRequest());
form.readRequest();
String className = form.getClassName();
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, "", 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, prefix, 0, context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(addObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, int num, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, "", num, context);
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, int num,
XWikiContext context) throws XWikiException
{
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(
Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, "", context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, prefix, 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, int num,
XWikiContext context) throws XWikiException
{
int nb;
BaseObject oldobject = getObject(className, num);
if (oldobject == null) {
nb = createNewObject(className, context);
oldobject = getObject(className, nb);
} else {
nb = oldobject.getNumber();
}
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(
Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public List updateObjectsFromRequest(String className, XWikiContext context)
throws XWikiException
{
return updateObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List updateObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(updateObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
public boolean isAdvancedContent()
{
String[] matches = {"<%", "#set", "#include", "#if", "public class",
"/* Advanced content */", "## Advanced content", "/* Programmatic content */",
"## Programmatic content"};
String content2 = content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
String htmlregexp =
"</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>";
try {
Util util = new Util();
List list = util.getUniqueMatches(content2, htmlregexp, 1);
if (list.size() > 0) {
return true;
}
} catch (MalformedPatternException e) {
}
return false;
}
public boolean isProgrammaticContent()
{
String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document",
"$xwiki.getXWiki()", "$context.getContext()",
"$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */",
"## Programmatic content",
"$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup",
"$xwiki.sendMessage",
"$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString",
"$doc.toXML()", "$doc.toXMLDocument()",
};
String content2 = content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
return false;
}
public boolean removeObject(BaseObject bobj)
{
Vector objects = getObjects(bobj.getClassName());
if (objects == null) {
return false;
}
if (objects.elementAt(bobj.getNumber()) == null) {
return false;
}
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
return true;
}
/**
* Remove all the object of the class in parameter
*
* @param className the class name of the objects to be removed
*/
public boolean removeObjects(String className)
{
Vector objects = getObjects(className);
if (objects == null) {
return false;
}
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject bobj = (BaseObject) it.next();
if (bobj != null) {
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
}
}
return true;
}
// This method to split section according to title .
public List getSplitSectionsAccordingToTitle() throws XWikiException
{
// pattern to match the title
Pattern pattern =
Pattern.compile("^[\\p{Space}]*(1(\\.1)*)[\\p{Space}]+(.*?)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(getContent());
List splitSections = new ArrayList();
int sectionNumber = 0;
String contentTemp = getContent();
int beforeIndex = 0;
while (matcher.find()) { // find title to split
String sectionLevel = matcher.group(1);
if (sectionLevel.equals("1") || sectionLevel.equals("1.1")) {
// only set editting for the title that is 1 or 1.1
sectionNumber++;
String sectionTitle = matcher.group(3);
int sectionIndex = contentTemp.indexOf(matcher.group(0), beforeIndex);
beforeIndex = sectionIndex + matcher.group(0).length();
// initialize a documentSection object
DocumentSection docSection =
new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle);
// add the document section to list
splitSections.add(docSection);
}
}
return splitSections;
}
// This function to return a Document section with parameter is sectionNumber
public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException
{
// return a document section according to section number
return (DocumentSection) getSplitSectionsAccordingToTitle().get(sectionNumber - 1);
}
// This method to return the content of a section
public String getContentOfSection(int sectionNumber) throws XWikiException
{
List splitSections = getSplitSectionsAccordingToTitle();
int indexEnd = 0;
// get current section
DocumentSection section = getDocumentSection(sectionNumber);
int indexStart = section.getSectionIndex();
String sectionLevel = section.getSectionLevel();
for (int i = sectionNumber; i < splitSections.size(); i++) {
// get next section
DocumentSection nextSection = getDocumentSection(i + 1);
String nextLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextLevel)) {
// if section level is next section level
indexEnd = nextSection.getSectionIndex();
break;
}
if (sectionLevel.length() > nextLevel.length()) {
// section level length is greater than next section level length (1.1 and 1)
indexEnd = nextSection.getSectionIndex();
break;
}
}
String sectionContent = null;
if (indexStart < 0) {
indexStart = 0;
}
if (indexEnd == 0) {
sectionContent = getContent().substring(indexStart);
} else {
sectionContent = getContent().substring(indexStart, indexEnd); // get section content
}
return sectionContent;
}
// This function to update a section content in document
public String updateDocumentSection(int sectionNumber, String newSectionContent)
throws XWikiException
{
StringBuffer newContent = new StringBuffer();
// get document section that will be edited
DocumentSection docSection = getDocumentSection(sectionNumber);
int numberOfSection = getSplitSectionsAccordingToTitle().size();
int indexSection = docSection.getSectionIndex();
if (numberOfSection == 1) {
// there is only a sections in document
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else if (sectionNumber == numberOfSection) {
// edit lastest section that doesn't contain subtitle
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else {
String sectionLevel = docSection.getSectionLevel();
int nextSectionIndex = 0;
// get index of next section
for (int i = sectionNumber; i < numberOfSection; i++) {
DocumentSection nextSection = getDocumentSection(i + 1); // get next section
String nextSectionLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextSectionLevel)) {
nextSectionIndex = nextSection.getSectionIndex();
break;
} else if (sectionLevel.length() > nextSectionLevel.length()) {
nextSectionIndex = nextSection.getSectionIndex();
break;
}
}
if (nextSectionIndex == 0) {// edit the last section
newContent = newContent.append(getContent().substring(0, indexSection))
.append(newSectionContent);
return newContent.toString();
} else {
String contentAfter = getContent().substring(nextSectionIndex);
String contentBegin = getContent().substring(0, indexSection);
newContent =
newContent.append(contentBegin).append(newSectionContent).append(contentAfter);
}
return newContent.toString();
}
}
/**
* Computes a document hash, taking into account all document data: content, objects,
* attachments, metadata... TODO: cache the hash value, update only on modification.
*/
public String getVersionHashCode(XWikiContext context)
{
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
log.error("Cannot create MD5 object", ex);
return this.hashCode() + "";
}
try {
String valueBeforeMD5 = toXML(true, false, true, false, context);
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
return sb.toString();
} catch (Exception ex) {
log.error("Exception while computing document hash", ex);
}
return this.hashCode() + "";
}
public static String getInternalPropertyName(String propname, XWikiContext context)
{
XWikiMessageTool msg = ((XWikiMessageTool) context.get("msg"));
String cpropname = StringUtils.capitalize(propname);
return (msg == null) ? cpropname : msg.get(cpropname);
}
public String getInternalProperty(String propname)
{
String methodName = "get" + StringUtils.capitalize(propname);
try {
Method method = getClass().getDeclaredMethod(methodName, null);
return (String) method.invoke(this, null);
} catch (Exception e) {
return null;
}
}
public String getCustomClass()
{
if (customClass == null) {
return "";
}
return customClass;
}
public void setCustomClass(String customClass)
{
this.customClass = customClass;
setMetaDataDirty(true);
}
public void setValidationScript(String validationScript)
{
this.validationScript = validationScript;
setMetaDataDirty(true);
}
public String getValidationScript()
{
if (validationScript == null) {
return "";
} else {
return validationScript;
}
}
public BaseObject newObject(String classname, XWikiContext context) throws XWikiException
{
int nb = createNewObject(classname, context);
return getObject(classname, nb);
}
public BaseObject getObject(String classname, boolean create, XWikiContext context)
{
try {
BaseObject obj = getObject(classname);
if ((obj == null) && create) {
return newObject(classname, context);
}
if (obj == null) {
return null;
} else {
return obj;
}
} catch (Exception e) {
return null;
}
}
public boolean validate(XWikiContext context) throws XWikiException
{
return validate(null, context);
}
public boolean validate(String[] classNames, XWikiContext context) throws XWikiException
{
boolean isValid = true;
if ((classNames == null) || (classNames.length == 0)) {
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = context.getWiki().getClass(classname, context);
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
isValid &= bclass.validateObject(obj, context);
}
}
}
} else {
for (int i = 0; i < classNames.length; i++) {
Vector objects = getObjects(classNames[i]);
if (objects != null) {
for (int j = 0; j < objects.size(); j++) {
BaseObject obj = (BaseObject) objects.get(j);
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
isValid &= bclass.validateObject(obj, context);
}
}
}
}
}
String validationScript = "";
XWikiRequest req = context.getRequest();
if (req != null) {
validationScript = req.get("xvalidation");
}
if ((validationScript == null) || (validationScript.trim().equals(""))) {
validationScript = getValidationScript();
}
if ((validationScript != null) && (!validationScript.trim().equals(""))) {
isValid &= executeValidationScript(context, validationScript);
}
return isValid;
}
private boolean executeValidationScript(XWikiContext context, String validationScript)
throws XWikiException
{
try {
XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki()
.parseGroovyFromPage(validationScript, context);
return validObject.validateDocument(this, context);
} catch (Throwable e) {
XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context);
return false;
}
}
public static void backupContext(HashMap backup, XWikiContext context)
{
backup.put("doc", context.getDoc());
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
if (vcontext != null) {
backup.put("vdoc", vcontext.get("doc"));
backup.put("vcdoc", vcontext.get("cdoc"));
backup.put("vtdoc", vcontext.get("tdoc"));
}
Map gcontext = (Map) context.get("gcontext");
if (gcontext != null) {
backup.put("gdoc", gcontext.get("doc"));
backup.put("gcdoc", gcontext.get("cdoc"));
backup.put("gtdoc", gcontext.get("tdoc"));
}
}
public static void restoreContext(HashMap backup, XWikiContext context)
{
context.setDoc((XWikiDocument) backup.get("doc"));
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
if (backup.get("vdoc") != null) {
vcontext.put("doc", backup.get("vdoc"));
}
if (backup.get("vcdoc") != null) {
vcontext.put("cdoc", backup.get("vcdoc"));
}
if (backup.get("vtdoc") != null) {
vcontext.put("tdoc", backup.get("vtdoc"));
}
}
if (gcontext != null) {
if (backup.get("gdoc") != null) {
gcontext.put("doc", backup.get("gdoc"));
}
if (backup.get("gcdoc") != null) {
gcontext.put("cdoc", backup.get("gcdoc"));
}
if (backup.get("gtdoc") != null) {
gcontext.put("tdoc", backup.get("gtdoc"));
}
}
}
public void setAsContextDoc(XWikiContext context)
{
try {
context.setDoc(this);
com.xpn.xwiki.api.Document apidoc = this.newDocument(context);
com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument();
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
vcontext.put("doc", apidoc);
vcontext.put("tdoc", tdoc);
}
if (gcontext != null) {
gcontext.put("doc", apidoc);
gcontext.put("tdoc", tdoc);
}
} catch (XWikiException ex) {
log.warn("Unhandled exception setting context", ex);
}
}
}
|
package com.xpn.xwiki.doc;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.validation.XWikiValidationInterface;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.notify.XWikiNotificationRule;
import com.xpn.xwiki.objects.*;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StaticListClass;
import com.xpn.xwiki.objects.classes.ListClass;
import com.xpn.xwiki.plugin.query.XWikiCriteria;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.web.EditForm;
import com.xpn.xwiki.web.ObjectAddForm;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.filter.CharacterFilter;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.suigeneris.jrcs.diff.Diff;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.Revision;
import org.suigeneris.jrcs.rcs.Version;
import org.suigeneris.jrcs.util.ToString;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.Class;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class XWikiDocument {
private static final Log log = LogFactory.getLog(XWikiDocument.class);
private String title;
private String parent;
private String web;
private String name;
private String content;
private String meta;
private String format;
private String creator;
private String author;
private String contentAuthor;
private String customClass;
private Date contentUpdateDate;
private Date updateDate;
private Date creationDate;
private Version version;
private long id = 0;
private boolean mostRecent = false;
private boolean isNew = true;
private String template;
private String language;
private String defaultLanguage;
private int translation;
private String database;
private BaseObject tags;
// Used to make sure the MetaData String is regenerated
private boolean isContentDirty = true;
// Used to make sure the MetaData String is regenerated
private boolean isMetaDataDirty = true;
public static final int HAS_ATTACHMENTS = 1;
public static final int HAS_OBJECTS = 2;
public static final int HAS_CLASS = 4;
private int elements = HAS_OBJECTS | HAS_ATTACHMENTS;
// Meta Data
private BaseClass xWikiClass;
private String xWikiClassXML;
private Map xWikiObjects = new HashMap();
private List attachmentList;
// Caching
private boolean fromCache = false;
private ArrayList objectsToRemove = new ArrayList();
// Template by default assign to a view
private String defaultTemplate;
private String validationScript;
private Object wikiNode;
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
private SoftReference archive;
private XWikiStoreInterface store;
public XWikiStoreInterface getStore(XWikiContext context) {
return context.getWiki().getStore();
}
public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) {
return context.getWiki().getAttachmentStore();
}
public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) {
return context.getWiki().getVersioningStore();
}
public XWikiStoreInterface getStore() {
return store;
}
public void setStore(XWikiStoreInterface store) {
this.store = store;
}
public long getId() {
if ((language == null) || language.trim().equals(""))
id = getFullName().hashCode();
else
id = (getFullName() + ":" + language).hashCode();
//if (log.isDebugEnabled())
// log.debug("ID: " + getFullName() + " " + language + ": " + id);
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSpace() {
return web;
}
public void setSpace(String space) {
this.web = space;
}
/**
*
*
* @deprecated use {@link #getSpace()} instead of this function
* @return the name of the space of the document
*/
public String getWeb() {
return web;
}
/**
* @deprecated use {@link #setSpace(String)} instead of this function
* @param web
*/
public void setWeb(String web) {
this.web = web;
}
public String getVersion() {
return getRCSVersion().toString();
}
public void setVersion(String version) {
this.version = new Version(version);
}
public Version getRCSVersion() {
if (version == null) {
version = new Version("1.1");
}
return version;
}
public void setRCSVersion(Version version) {
this.version = version;
}
public XWikiDocument() {
this("Main", "WebHome");
}
public XWikiDocument(String web, String name) {
this.web = web;
int i1 = name.indexOf(".");
if (i1 == -1) {
this.name = name;
} else {
this.web = name.substring(0, i1);
this.name = name.substring(i1 + 1);
}
this.updateDate = new Date();
updateDate.setTime((updateDate.getTime()/1000) * 1000);
this.contentUpdateDate = new Date();
contentUpdateDate.setTime((contentUpdateDate.getTime()/1000) * 1000);
this.creationDate = new Date();
creationDate.setTime((creationDate.getTime()/1000) * 1000);
this.parent = "";
this.content = "\n";
this.format = "";
this.author = "";
this.language = "";
this.defaultLanguage = "";
this.attachmentList = new ArrayList();
this.customClass = "";
}
public XWikiDocument getParentDoc() {
return new XWikiDocument(web, getParent());
}
public String getParent() {
return parent.trim();
}
public void setParent(String parent) {
if (!parent.equals(this.parent)) {
setMetaDataDirty(true);
}
this.parent = parent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
if (!content.equals(this.content)) {
setContentDirty(true);
setWikiNode(null);
}
this.content = content;
}
public String getRenderedContent(XWikiContext context) throws XWikiException {
return context.getWiki().getRenderingEngine().renderDocument(this, context);
}
public String getRenderedContent(String text, XWikiContext context) {
/*
// TODO: verify the impact of this code
String result;
HashMap backup = new HashMap();
backupContext(backup, context);
setAsContextDoc(context);
result = context.getWiki().getRenderingEngine().renderText(text, this, context);
restoreContext(backup, context);
*/
String result = context.getWiki().getRenderingEngine().renderText(text, this, context);
return result;
}
public String getEscapedContent(XWikiContext context) throws XWikiException {
CharacterFilter filter = new CharacterFilter();
return filter.process(getTranslatedContent(context));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFullName() {
StringBuffer buf = new StringBuffer();
buf.append(getSpace());
buf.append(".");
buf.append(getName());
return buf.toString();
}
public void setFullName(String name) {
setFullName(name, null);
}
public String getTitle() {
if (title == null)
return "";
else
return title;
}
public String getDisplayTitle() {
String title = getTitle();
if (title.equals("")) {
title = extractTitle();
}
if (title.equals(""))
return getName();
else
return title;
}
public String extractTitle() {
try {
String content = getContent();
int i1 = 0;
int i2;
while (true) {
i2 = content.indexOf("\n", i1);
String title = "";
if (i2 != -1)
title = content.substring(i1, i2).trim();
else
title = content.substring(i1).trim();
if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+")))
return title.substring(title.indexOf(" ")).trim();
if (i2 == -1)
break;
i1 = i2 + 1;
}
} catch (Exception e) {
}
return "";
}
public void setTitle(String title) {
if (title == null)
title = "";
if (!title.equals(this.title)) {
setContentDirty(true);
}
this.title = title;
}
public String getFormat() {
if (format == null)
return "";
else
return format;
}
public void setFormat(String format) {
this.format = format;
if (!format.equals(this.format)) {
setMetaDataDirty(true);
}
}
public String getAuthor() {
if (author == null)
return "";
else
return author.trim();
}
public String getContentAuthor() {
if (contentAuthor == null)
return "";
else
return contentAuthor.trim();
}
public void setAuthor(String author) {
if (!getAuthor().equals(this.author)) {
setMetaDataDirty(true);
}
this.author = author;
}
public void setContentAuthor(String contentAuthor) {
if (!getContentAuthor().equals(this.contentAuthor)) {
setMetaDataDirty(true);
}
this.contentAuthor = contentAuthor;
}
public String getCreator() {
if (creator == null)
return "";
else
return creator.trim();
}
public void setCreator(String creator) {
if (!getCreator().equals(this.creator)) {
setMetaDataDirty(true);
}
this.creator = creator;
}
public Date getDate() {
if (updateDate == null)
return new Date();
else
return updateDate;
}
public void setDate(Date date) {
if ((date != null) && (!date.equals(this.updateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date!=null)
date.setTime((date.getTime()/1000) * 1000);
this.updateDate = date;
}
public Date getCreationDate() {
if (creationDate == null)
return new Date();
else
return creationDate;
}
public void setCreationDate(Date date) {
if ((date != null) && (!creationDate.equals(this.creationDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date!=null)
date.setTime((date.getTime()/1000) * 1000);
this.creationDate = date;
}
public Date getContentUpdateDate() {
if (contentUpdateDate == null)
return new Date();
else
return contentUpdateDate;
}
public void setContentUpdateDate(Date date) {
if ((date != null) && (!date.equals(this.contentUpdateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date!=null)
date.setTime((date.getTime()/1000) * 1000);
this.contentUpdateDate = date;
}
public String getMeta() {
return meta;
}
public void setMeta(String meta) {
if (meta == null) {
if (this.meta != null)
setMetaDataDirty(true);
} else if (!meta.equals(this.meta)) {
setMetaDataDirty(true);
}
this.meta = meta;
}
public void appendMeta(String meta) {
StringBuffer buf = new StringBuffer(this.meta);
buf.append(meta);
buf.append("\n");
this.meta = buf.toString();
setMetaDataDirty(true);
}
public boolean isContentDirty() {
return isContentDirty;
}
public void incrementVersion() {
if (version == null)
version = new Version("1.1");
else {
version = version.next();
}
}
public void setContentDirty(boolean contentDirty) {
isContentDirty = contentDirty;
}
public boolean isMetaDataDirty() {
return isMetaDataDirty;
}
public void setMetaDataDirty(boolean metaDataDirty) {
isMetaDataDirty = metaDataDirty;
}
public String getAttachmentURL(String filename, XWikiContext context) {
return getAttachmentURL(filename, "download", context);
}
public String getAttachmentURL(String filename, String action, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, boolean redirect, XWikiContext context) {
URL url = context.getURLFactory().createURL(getSpace(), getName(), action, null, null, getDatabase(), context);
if (redirect) {
if (url == null)
return null;
else
return url.toString();
} else
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, XWikiContext context) {
return getURL(action, false, context);
}
public String getURL(String action, String querystring, XWikiContext context) {
URL url = context.getURLFactory().createURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalURL(String action, XWikiContext context) {
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
null, null, getDatabase(), context);
return url.toString();
}
public String getExternalURL(String action, String querystring, XWikiContext context) {
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return url.toString();
}
public String getParentURL(XWikiContext context) throws XWikiException {
XWikiDocument doc = new XWikiDocument();
doc.setFullName(getParent(), context);
URL url = context.getURLFactory().createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException {
loadArchive(context);
return getDocumentArchive();
}
/**
* return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, XWikiContext)
*
* @param context
* @return
*/
public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) {
if (!((customClassName == null) || (customClassName.equals(""))))
try {
Class[] classes = new Class[] { XWikiDocument.class, XWikiContext.class };
Object[] args = new Object[] { this, context };
return (com.xpn.xwiki.api.Document) Class.forName(customClassName).getConstructor(classes).newInstance(args);
} catch (InstantiationException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (NoSuchMethodException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
}
return new com.xpn.xwiki.api.Document(this, context);
}
public com.xpn.xwiki.api.Document newDocument(XWikiContext context) {
String customClass = getCustomClass();
return newDocument(customClass, context);
}
public void loadArchive(XWikiContext context) throws XWikiException {
if (archive==null) {
XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context);
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
archive = new SoftReference(arch);
}
}
public XWikiDocumentArchive getDocumentArchive() {
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (archive==null)
return null;
else
return (XWikiDocumentArchive) archive.get();
}
public void setDocumentArchive(XWikiDocumentArchive arch) {
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (arch!=null)
this.archive = new SoftReference(arch);
}
public void setDocumentArchive(String sarch) throws XWikiException {
XWikiDocumentArchive xda = new XWikiDocumentArchive(getId());
xda.setArchive(sarch);
setDocumentArchive(xda);
}
public Version[] getRevisions(XWikiContext context) throws XWikiException {
return getVersioningStore(context).getXWikiDocVersions(this, context);
}
public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException {
try {
Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context);
int length = nb;
// 0 means all revisions
if (nb == 0)
length = revisions.length;
if (revisions.length < length)
length = revisions.length;
String[] recentrevs = new String[length];
for (int i = 1; i <= length; i++)
recentrevs[i - 1
] = revisions[revisions.length - i].toString();
return recentrevs;
} catch (Exception e) {
return new String[0];
}
}
public boolean isMostRecent() {
return mostRecent;
}
public void setMostRecent(boolean mostRecent) {
this.mostRecent = mostRecent;
}
public BaseClass getxWikiClass() {
if (xWikiClass == null) {
xWikiClass = new BaseClass();
xWikiClass.setName(getFullName());
}
return xWikiClass;
}
public void setxWikiClass(BaseClass xWikiClass) {
this.xWikiClass = xWikiClass;
}
public Map getxWikiObjects() {
return xWikiObjects;
}
public void setxWikiObjects(Map xWikiObjects) {
this.xWikiObjects = xWikiObjects;
}
public BaseObject getxWikiObject() {
return getObject(getFullName());
}
public List getxWikiClasses(XWikiContext context) {
List list = new ArrayList();
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = null;
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
bclass = obj.getxWikiClass(context);
if (bclass != null)
break;
}
}
if (bclass != null)
list.add(bclass);
}
return list;
}
public int createNewObject(String classname, XWikiContext context) throws XWikiException {
BaseObject object = BaseClass.newCustomClassInstance(classname, context);
object.setName(getFullName());
object.setClassName(classname);
Vector objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
objects.add(object);
int nb = objects.size() - 1;
object.setNumber(nb);
setContentDirty(true);
return nb;
}
public int getObjectNumbers(String classname) {
try {
return ((Vector) getxWikiObjects().get(classname)).size();
} catch (Exception e) {
return 0;
}
}
public Vector getObjects(String classname) {
if (classname.indexOf(".")==-1)
classname = "XWiki." + classname;
return (Vector) getxWikiObjects().get(classname);
}
public void setObjects(String classname, Vector objects) {
if (classname.indexOf(".")==-1)
classname = "XWiki." + classname;
getxWikiObjects().put(classname, objects);
}
public BaseObject getObject(String classname) {
if (classname.indexOf(".")==-1)
classname = "XWiki." + classname;
Vector objects = (Vector) getxWikiObjects().get(classname);
if (objects == null)
return null;
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null)
return obj;
}
return null;
}
public BaseObject getObject(String classname, int nb) {
try {
if (classname.indexOf(".")==-1)
classname = "XWiki." + classname;
return (BaseObject) ((Vector) getxWikiObjects().get(classname)).get(nb);
} catch (Exception e) {
return null;
}
}
public BaseObject getObject(String classname, String key, String value) {
return getObject(classname, key, value, false);
}
public BaseObject getObject(String classname, String key, String value, boolean failover) {
if (classname.indexOf(".")==-1)
classname = "XWiki." + classname;
try {
if (value == null) {
if (failover)
return getObject(classname);
else
return null;
}
Vector objects = (Vector) getxWikiObjects().get(classname);
if ((objects == null) || (objects.size() == 0))
return null;
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
if (value.equals(obj.getStringValue(key)))
return obj;
}
}
if (failover)
return getObject(classname);
else
return null;
} catch (Exception e) {
if (failover)
return getObject(classname);
e.printStackTrace();
return null;
}
}
public void addObject(String classname, BaseObject object) {
Vector vobj = getObjects(classname);
if (vobj == null)
setObject(classname, 0, object);
else
setObject(classname, vobj.size(), object);
setContentDirty(true);
}
public void setObject(String classname, int nb, BaseObject object) {
Vector objects = null;
objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
if (nb >= objects.size()) {
objects.setSize(nb + 1);
}
objects.set(nb, object);
object.setNumber(nb);
setContentDirty(true);
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean aNew) {
isNew = aNew;
}
public void mergexWikiClass(XWikiDocument templatedoc) {
BaseClass bclass = getxWikiClass();
BaseClass tbclass = templatedoc.getxWikiClass();
if (tbclass != null) {
if (bclass == null) {
setxWikiClass((BaseClass) tbclass.clone());
} else {
getxWikiClass().merge((BaseClass) tbclass.clone());
}
}
setContentDirty(true);
}
public void mergexWikiObjects(XWikiDocument templatedoc) {
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector objects = (Vector) getxWikiObjects().get(name);
if (objects != null) {
Vector tobjects = (Vector) templatedoc.getxWikiObjects().get(name);
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj = (BaseObject) ((BaseObject) tobjects.get(i)).clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
} else {
Vector tobjects = templatedoc.getObjects(name);
objects = new Vector();
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
}
getxWikiObjects().put(name, objects);
}
}
setContentDirty(true);
}
public void clonexWikiObjects(XWikiDocument templatedoc) {
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector tobjects = templatedoc.getObjects(name);
Vector objects = new Vector();
objects.setSize(tobjects.size());
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.set(i, bobj);
}
}
getxWikiObjects().put(name, objects);
}
}
public String getTemplate() {
if (template==null)
return "";
else
return template;
}
public void setTemplate(String template) {
this.template = template;
setMetaDataDirty(true);
}
public String displayPrettyName(String fieldname, XWikiContext context) {
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) {
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) {
try {
BaseObject object = getxWikiObject();
if (object == null)
object = getFirstObject(fieldname, context);
return displayPrettyName(fieldname, showMandatory, before, object, context);
} catch (Exception e) {
return "";
}
}
public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) {
return displayPrettyName(fieldname, false, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) {
return displayPrettyName(fieldname, showMandatory, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) {
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String dprettyName = "";
if ((showMandatory)&&(pclass.getValidationRegExp()!=null)&&(!pclass.getValidationRegExp().equals(""))) {
dprettyName = context.getWiki().addMandatory(context);
}
if (before)
return dprettyName + pclass.getPrettyName();
else
return pclass.getPrettyName() + dprettyName;
}
catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, XWikiContext context) {
try {
BaseObject object = getxWikiObject();
if (object == null)
object = getFirstObject(fieldname, context);
return displayTooltip(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) {
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String tooltip = pclass.getTooltip();
if ((tooltip!=null)&&(!tooltip.trim().equals(""))) {
String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />";
return context.getWiki().addTooltip(img, tooltip, context);
} else
return "";
}
catch (Exception e) {
return "";
}
}
public String display(String fieldname, String type, BaseObject obj, XWikiContext context) {
return display(fieldname, type, "", obj, context);
}
public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) {
try {
HashMap backup = new HashMap();
backupContext(backup, context);
setAsContextDoc(context);
type = type.toLowerCase();
StringBuffer result = new StringBuffer();
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_";
if (pclass.isCustomDisplayed(context)){
pclass.displayCustom(result, fieldname, prefix, type, obj, context);
}
else if (type.equals("view")) {
pclass.displayView(result, fieldname, prefix, obj, context);
} else if (type.equals("rendered")) {
String fcontent = pclass.displayView(fieldname, prefix, obj, context);
result.append(getRenderedContent(fcontent, context));
} else if (type.equals("edit")) {
context.addDisplayedField(fieldname);
result.append("{pre}");
pclass.displayEdit(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("hidden")) {
result.append("{pre}");
pclass.displayHidden(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("search")) {
result.append("{pre}");
prefix = obj.getxWikiClass(context).getName() + "_";
pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context);
result.append("{/pre}");
} else {
pclass.displayView(result, fieldname, prefix, obj, context);
}
restoreContext(backup, context);
return result.toString();
}
catch (Exception ex) {
log.warn("Exception showing field " + fieldname, ex);
return "";
}
}
public String display(String fieldname, BaseObject obj, XWikiContext context) {
String type = null;
try {
type = (String) context.get("display");
}
catch (Exception e) {
}
if (type == null)
type = "view";
return display(fieldname, type, obj, context);
}
public String display(String fieldname, XWikiContext context) {
try {
BaseObject object = getxWikiObject();
if (object == null)
object = getFirstObject(fieldname, context);
return display(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String display(String fieldname, String mode, XWikiContext context) {
return display(fieldname, mode, "", context);
}
public String display(String fieldname, String mode, String prefix, XWikiContext context) {
try {
BaseObject object = getxWikiObject();
if (object == null)
object = getFirstObject(fieldname, context);
if (object == null)
return "";
else
return display(fieldname, mode, object, context);
} catch (Exception e) {
return "";
}
}
public String displayForm(String className, String header, String format, XWikiContext context) {
return displayForm(className, header, format, true, context);
}
public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) {
Vector objects = getObjects(className);
if (format.endsWith("\\n"))
linebreak = true;
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null)
return "";
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0)
return "";
StringBuffer result = new StringBuffer();
VelocityContext vcontext = new VelocityContext();
vcontext.put("formatter", new VelocityFormatter(vcontext));
for (Iterator it = fields.iterator(); it.hasNext();) {
PropertyClass pclass = (PropertyClass) it.next();
vcontext.put(pclass.getName(), pclass.getPrettyName());
}
result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context));
if (linebreak)
result.append("\n");
// display each line
for (int i = 0; i < objects.size(); i++) {
vcontext.put("id", new Integer(i + 1));
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
String name = (String) it.next();
vcontext.put(name, display(name, object, context));
}
result.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(), vcontext, context));
if (linebreak)
result.append("\n");
}
}
return result.toString();
}
public String displayForm(String className, XWikiContext context) {
Vector objects = getObjects(className);
if (objects == null)
return "";
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null)
return "";
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0)
return "";
StringBuffer result = new StringBuffer();
result.append("{table}\n");
boolean first = true;
for (Iterator it = fields.iterator(); it.hasNext();) {
if (first == true)
first = false;
else
result.append("|");
PropertyClass pclass = (PropertyClass) it.next();
result.append(pclass.getPrettyName());
}
result.append("\n");
for (int i = 0; i < objects.size(); i++) {
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
first = true;
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
if (first == true)
first = false;
else
result.append("|");
String data = display((String) it.next(), object, context);
if (data.trim().equals(""))
result.append(" ");
else
result.append(data);
}
result.append("\n");
}
}
result.append("{table}\n");
return result.toString();
}
public boolean isFromCache() {
return fromCache;
}
public void setFromCache(boolean fromCache) {
this.fromCache = fromCache;
}
public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException {
String defaultLanguage = eform.getDefaultLanguage();
if (defaultLanguage != null)
setDefaultLanguage(defaultLanguage);
String defaultTemplate = eform.getDefaultTemplate();
if (defaultTemplate != null)
setDefaultTemplate(defaultTemplate);
String creator = eform.getCreator();
if ((creator != null) && (!creator.equals(getCreator()))) {
if ((getCreator().equals(context.getUser()))
|| (context.getWiki().getRightService().hasAdminRights(context)))
setCreator(creator);
}
String parent = eform.getParent();
if (parent != null)
setParent(parent);
String tags = eform.getTags();
if (tags != null)
setTags(tags, context);
}
/**
* add tags to the document.
* @param tags
*/
public void setTags(String tags, XWikiContext context) throws XWikiException {
loadTags(context);
StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS);
tagProp.fromString(tags);
this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags));
setMetaDataDirty(true);
}
public String getTags(XWikiContext context){
ListProperty prop = (ListProperty) getTagProperty(context);
if (prop != null)
return prop.getTextValue();
return null;
}
public List getTagsList(XWikiContext context){
List tagList = null;
BaseProperty prop = getTagProperty(context);
if (prop != null)
tagList = (List) prop.getValue();
return tagList;
}
private BaseProperty getTagProperty(XWikiContext context){
loadTags(context);
return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS));
}
private void loadTags(XWikiContext context){
if (this.tags == null){
this.tags = getObject(XWikiConstant.TAG_CLASS, true, context);
}
}
public List getTagsPossibleValues(XWikiContext context){
loadTags(context);
String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)).getValues();
return ListClass.getListFromString(possibleValues);
//((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString();
}
public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException {
String content = eform.getContent();
if ((content != null) && (!content.equals(""))) {
// Cleanup in case we use HTMLAREA
// content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", content);
content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content);
setContent(content);
}
String title = eform.getTitle();
if (title != null)
setTitle(title);
}
public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException {
Iterator itobj = getxWikiObjects().keySet().iterator();
while (itobj.hasNext()) {
String name = (String) itobj.next();
Vector bobjects = getObjects(name);
Vector newobjects = new Vector();
newobjects.setSize(bobjects.size());
for (int i = 0; i < bobjects.size(); i++) {
BaseObject oldobject = getObject(name, i);
if (oldobject != null) {
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
newobjects.set(newobject.getNumber(), newobject);
}
}
getxWikiObjects().put(name, newobjects);
}
setContentDirty(true);
}
public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException {
readDocMetaFromForm(eform, context);
readTranslationMetaFromForm(eform, context);
readObjectsFromForm(eform, context);
}
/*
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException {
// Get the class from the template
String template = eform.getTemplate();
if ((template!=null)&&(!template.equals(""))) {
if (template.indexOf('.')==-1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = { template, getFullName() };
throw new XWikiException( XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplate(template);
mergexWikiObjects(templatedoc);
}
}
}
*/
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException {
String template = eform.getTemplate();
readFromTemplate(template, context);
}
public void readFromTemplate(String template, XWikiContext context) throws XWikiException {
if ((template != null) && (!template.equals(""))) {
String content = getContent();
if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) {
Object[] args = {getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
"Cannot add a template to document {0} because it already has content", null, args);
} else {
if (template.indexOf('.') == -1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = {template, getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplate(template);
setContent(templatedoc.getContent());
if ((getParent() == null) || (getParent().equals(""))) {
String tparent = templatedoc.getParent();
if (tparent != null)
setParent(tparent);
}
if (isNew()) {
// We might have received the object from the cache
// and the templace objects might have been copied already
// we need to remove them
setxWikiObjects(new HashMap());
}
// Merge the external objects
// Currently the choice is not to merge the base class and object because it is not
// the prefered way of using external classes and objects.
mergexWikiObjects(templatedoc);
}
}
}
setContentDirty(true);
}
public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) {
// Do nothing for the moment..
// A usefull thing here would be to look at any instances of a Notification Object
// with email addresses and send an email to warn that the document has been modified..
}
public Object clone() {
XWikiDocument doc = null;
try {
doc = (XWikiDocument) getClass().newInstance();
doc.setDatabase(getDatabase());
doc.setRCSVersion(getRCSVersion());
doc.setDocumentArchive(getDocumentArchive());
doc.setAuthor(getAuthor());
doc.setContentAuthor(getContentAuthor());
doc.setContent(getContent());
doc.setContentDirty(isContentDirty());
doc.setCreationDate(getCreationDate());
doc.setDate(getDate());
doc.setCustomClass(getCustomClass());
doc.setContentUpdateDate(getContentUpdateDate());
doc.setTitle(getTitle());
doc.setFormat(getFormat());
doc.setFromCache(isFromCache());
doc.setElements(getElements());
doc.setId(getId());
doc.setMeta(getMeta());
doc.setMetaDataDirty(isMetaDataDirty());
doc.setMostRecent(isMostRecent());
doc.setName(getName());
doc.setNew(isNew());
doc.setStore(getStore());
doc.setTemplate(getTemplate());
doc.setSpace(getSpace());
doc.setParent(getParent());
doc.setCreator(getCreator());
doc.setDefaultLanguage(getDefaultLanguage());
doc.setDefaultTemplate(getDefaultTemplate());
doc.setValidationScript(getValidationScript());
doc.setLanguage(getLanguage());
doc.setTranslation(getTranslation());
doc.setxWikiClass((BaseClass) getxWikiClass().clone());
doc.setxWikiClassXML(getxWikiClassXML());
doc.clonexWikiObjects(this);
doc.copyAttachments(this);
doc.elements = elements;
} catch (Exception e) {
// This should not happen
}
return doc;
}
public void copyAttachments(XWikiDocument xWikiSourceDocument) {
Iterator attit = xWikiSourceDocument.getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
XWikiAttachment newattachment = (XWikiAttachment) attachment.clone();
newattachment.setDoc(this);
if (newattachment.getAttachment_archive()!=null)
newattachment.getAttachment_archive().setAttachment(newattachment);
if (newattachment.getAttachment_content()!=null)
newattachment.getAttachment_content().setContentDirty(true);
getAttachmentList().add(newattachment);
}
setContentDirty(true);
}
public void loadAttachments(XWikiContext context) throws XWikiException {
Iterator attit = getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
attachment.loadContent(context);
attachment.loadArchive(context);
}
}
public boolean equals(Object object) {
XWikiDocument doc = (XWikiDocument) object;
if (!getName().equals(doc.getName()))
return false;
if (!getSpace().equals(doc.getSpace()))
return false;
if (!getAuthor().equals(doc.getAuthor()))
return false;
if (!getContentAuthor().equals(doc.getContentAuthor()))
return false;
if (!getParent().equals(doc.getParent()))
return false;
if (!getCreator().equals(doc.getCreator()))
return false;
if (!getDefaultLanguage().equals(doc.getDefaultLanguage()))
return false;
if (!getLanguage().equals(doc.getLanguage()))
return false;
if (getTranslation() != doc.getTranslation())
return false;
if (getDate().getTime() != doc.getDate().getTime())
return false;
if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime())
return false;
if (getCreationDate().getTime() != doc.getCreationDate().getTime())
return false;
if (!getFormat().equals(doc.getFormat()))
return false;
if (!getTitle().equals(doc.getTitle()))
return false;
if (!getContent().equals(doc.getContent()))
return false;
if (!getVersion().equals(doc.getVersion()))
return false;
if (!getTemplate().equals(doc.getTemplate()))
return false;
if (!getDefaultTemplate().equals(doc.getDefaultTemplate()))
return false;
if (!getValidationScript().equals(doc.getValidationScript()))
return false;
if (!getxWikiClass().equals(doc.getxWikiClass()))
return false;
Set list1 = getxWikiObjects().keySet();
Set list2 = doc.getxWikiObjects().keySet();
if (!list1.equals(list2))
return false;
for (Iterator it = list1.iterator(); it.hasNext();) {
String name = (String) it.next();
Vector v1 = getObjects(name);
Vector v2 = doc.getObjects(name);
if (v1.size() != v2.size())
return false;
for (int i = 0; i < v1.size(); i++) {
if ((v1.get(i) == null) && (v2.get(i) != null))
return false;
if (!v1.get(i).equals(v2.get(i)))
return false;
}
}
return true;
}
public String toXML(Document doc, XWikiContext context) {
OutputFormat outputFormat = new OutputFormat("", true);
if ((context == null) || (context.getWiki() == null))
outputFormat.setEncoding("UTF-8");
else
outputFormat.setEncoding(context.getWiki().getEncoding());
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String getXMLContent(XWikiContext context) throws XWikiException {
XWikiDocument tdoc = getTranslatedDocument(context);
Document doc = tdoc.toXMLDocument(true, true, false, false, context);
return toXML(doc, context);
}
public String toXML(XWikiContext context) throws XWikiException {
Document doc = toXMLDocument(context);
return toXML(doc, context);
}
public String toFullXML(XWikiContext context) throws XWikiException {
return toXML(true, false, true, true, context);
}
public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException {
try {
String zipname = getSpace() + "/" + getName();
String language = getLanguage();
if ((language != null) && (!language.equals("")))
zipname += "." + language;
ZipEntry zipentry = new ZipEntry(zipname);
zos.putNextEntry(zipentry);
zos.write(toXML(true, false, true, withVersions, context).getBytes());
zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException {
addToZip(zos, true, context);
}
public String toXML(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException {
Document doc = toXMLDocument(bWithObjects, bWithRendering,
bWithAttachmentContent, bWithVersions, context);
return toXML(doc, context);
}
public Document toXMLDocument(XWikiContext context) throws XWikiException {
return toXMLDocument(true, false, false, false, context);
}
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException {
Document doc = new DOMDocument();
Element docel = new DOMElement("xwikidoc");
doc.setRootElement(docel);
Element el = new DOMElement("web");
el.addText(getSpace());
docel.add(el);
el = new DOMElement("name");
el.addText(getName());
docel.add(el);
el = new DOMElement("language");
el.addText(getLanguage());
docel.add(el);
el = new DOMElement("defaultLanguage");
el.addText(getDefaultLanguage());
docel.add(el);
el = new DOMElement("translation");
el.addText("" + getTranslation());
docel.add(el);
el = new DOMElement("parent");
el.addText(getParent());
docel.add(el);
el = new DOMElement("creator");
el.addText(getCreator());
docel.add(el);
el = new DOMElement("author");
el.addText(getAuthor());
docel.add(el);
el = new DOMElement("customClass");
el.addText(getCustomClass());
docel.add(el);
el = new DOMElement("contentAuthor");
el.addText(getContentAuthor());
docel.add(el);
long d = getCreationDate().getTime();
el = new DOMElement("creationDate");
el.addText("" + d);
docel.add(el);
d = getDate().getTime();
el = new DOMElement("date");
el.addText("" + d);
docel.add(el);
d = getContentUpdateDate().getTime();
el = new DOMElement("contentUpdateDate");
el.addText("" + d);
docel.add(el);
el = new DOMElement("version");
el.addText(getVersion());
docel.add(el);
el = new DOMElement("title");
el.addText(getTitle());
docel.add(el);
el = new DOMElement("template");
el.addText(getTemplate());
docel.add(el);
el = new DOMElement("defaultTemplate");
el.addText(getDefaultTemplate());
docel.add(el);
el = new DOMElement("validationScript");
el.addText(getValidationScript());
docel.add(el);
List alist = getAttachmentList();
for (int ai = 0; ai < alist.size(); ai++) {
XWikiAttachment attach = (XWikiAttachment) alist.get(ai);
docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context));
}
if (bWithObjects) {
// Add Class
BaseClass bclass = getxWikiClass();
if (bclass.getFieldList().size() > 0) {
docel.add(bclass.toXML(null));
}
// Add Objects
Iterator it = getxWikiObjects().values().iterator();
while (it.hasNext()) {
Vector objects = (Vector) it.next();
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
BaseClass objclass = null;
if (obj.getName().equals(obj.getClassName()))
objclass = bclass;
else
objclass = obj.getxWikiClass(context);
docel.add(obj.toXML(objclass));
}
}
}
}
// Add Content
el = new DOMElement("content");
//Filter filter = new CharacterFilter();
//String newcontent = filter.process(getContent());
//String newcontent = encodedXMLStringAsUTF8(getContent());
String newcontent = content;
el.addText(newcontent);
docel.add(el);
if (bWithRendering) {
el = new DOMElement("renderedcontent");
try {
el.addText(getRenderedContent(context));
} catch (XWikiException e) {
el.addText("Exception with rendering content: " + e.getFullMessage());
}
docel.add(el);
}
if (bWithVersions) {
el = new DOMElement("versions");
try {
el.addText(getDocumentArchive(context).getArchive());
} catch (XWikiException e) {
return null;
}
docel.add(el);
}
return doc;
}
protected String encodedXMLStringAsUTF8(String xmlString) {
if (xmlString == null) {
return "";
}
int length = xmlString.length();
char character;
StringBuffer result = new StringBuffer();
for (int i = 0; i < length; i++) {
character = xmlString.charAt(i);
switch (character) {
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\n':
result.append("\n");
break;
case '\r':
result.append("\r");
break;
case '\t':
result.append("\t");
break;
default:
if (character < 0x20) {
} else if (character > 0x7F) {
result.append("&
result.append(Integer.toHexString(character).toUpperCase());
result.append(";");
} else {
result.append(character);
}
break;
}
}
return result.toString();
}
protected String getElement(Element docel, String name) {
Element el = docel.element(name);
if (el == null)
return "";
else
return el.getText();
}
public void fromXML(String xml) throws XWikiException {
fromXML(xml, false);
}
public void fromXML(String xml, boolean withArchive) throws XWikiException {
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(xml);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null);
}
Element docel = domdoc.getRootElement();
setName(getElement(docel, "name"));
setSpace(getElement(docel, "web"));
setParent(getElement(docel, "parent"));
setCreator(getElement(docel, "creator"));
setAuthor(getElement(docel, "author"));
setCustomClass(getElement(docel, "customClass"));
setContentAuthor(getElement(docel, "contentAuthor"));
setVersion(getElement(docel, "version"));
setContent(getElement(docel, "content"));
setLanguage(getElement(docel, "language"));
setDefaultLanguage(getElement(docel, "defaultLanguage"));
setTitle(getElement(docel,"title"));
setDefaultTemplate(getElement(docel,"defaultTemplate"));
setValidationScript(getElement(docel,"validationScript"));
String strans = getElement(docel, "translation");
if ((strans == null) || strans.equals(""))
setTranslation(0);
else
setTranslation(Integer.parseInt(strans));
String archive = getElement(docel, "versions");
if (withArchive && archive != null && archive.length() > 0) {
setDocumentArchive(archive);
}
String sdate = getElement(docel, "date");
if (!sdate.equals("")) {
Date date = new Date(Long.parseLong(sdate));
setDate(date);
}
String scdate = getElement(docel, "creationDate");
if (!scdate.equals("")) {
Date cdate = new Date(Long.parseLong(scdate));
setCreationDate(cdate);
}
List atels = docel.elements("attachment");
for (int i = 0; i < atels.size(); i++) {
Element atel = (Element) atels.get(i);
XWikiAttachment attach = new XWikiAttachment();
attach.setDoc(this);
attach.fromXML(atel);
getAttachmentList().add(attach);
}
Element cel = docel.element("class");
BaseClass bclass = new BaseClass();
if (cel != null) {
bclass.fromXML(cel);
setxWikiClass(bclass);
}
List objels = docel.elements("object");
for (int i = 0; i < objels.size(); i++) {
Element objel = (Element) objels.get(i);
BaseObject bobject = new BaseObject();
bobject.fromXML(objel);
addObject(bobject.getClassName(), bobject);
}
// We have been reading from XML so the document does not need a new version when saved
setMetaDataDirty(false);
setContentDirty(false);
}
public void setAttachmentList(List list) {
attachmentList = list;
}
public List getAttachmentList() {
return attachmentList;
}
public void saveAllAttachments(XWikiContext context) throws XWikiException {
for (int i = 0; i < attachmentList.size(); i++) {
saveAttachmentContent((XWikiAttachment) attachmentList.get(i), context);
}
}
public void saveAttachmentsContent(List attachments, XWikiContext context) throws XWikiException {
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null)
context.setDatabase(getDatabase());
context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true);
}catch(java.lang.OutOfMemoryError e){
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null)
context.setDatabase(database);
}
}
public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException {
saveAttachmentContent(attachment, true, true, context);
}
protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException {
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null)
context.setDatabase(getDatabase());
context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction);
}catch(java.lang.OutOfMemoryError e){
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null)
context.setDatabase(database);
}
}
public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException {
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null)
context.setDatabase(getDatabase());
context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true);
} finally {
if (database != null)
context.setDatabase(database);
}
}
public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException {
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null)
context.setDatabase(getDatabase());
try{
context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true);
}catch(java.lang.OutOfMemoryError e){
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
} finally {
if (database != null)
context.setDatabase(database);
}
}
public List getBacklinks(XWikiContext context) throws XWikiException {
return getStore(context).loadBacklinks(getFullName(), context, true);
}
public List getLinks(XWikiContext context) throws XWikiException {
return getStore(context).loadLinks(getId(), context, true);
}
public void renameProperties(String className, Map fieldsToRename) {
Vector objects = getObjects(className);
if (objects == null)
return;
for (int j = 0; j < objects.size(); j++) {
BaseObject bobject = (BaseObject) objects.get(j);
if (bobject == null)
continue;
for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) {
String origname = (String) renameit.next();
String newname = (String) fieldsToRename.get(origname);
BaseProperty origprop = (BaseProperty) bobject.safeget(origname);
if (origprop != null) {
BaseProperty prop = (BaseProperty) origprop.clone();
bobject.removeField(origname);
prop.setName(newname);
bobject.addField(newname, prop);
}
}
}
setContentDirty(true);
}
public void addObjectsToRemove(BaseObject object) {
getObjectsToRemove().add(object);
setContentDirty(true);
}
public ArrayList getObjectsToRemove() {
return objectsToRemove;
}
public void setObjectsToRemove(ArrayList objectsToRemove) {
this.objectsToRemove = objectsToRemove;
setContentDirty(true);
}
public List getIncludedPages(XWikiContext context) {
try {
String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)";
List list = context.getUtil().getMatches(getContent(), pattern, 2);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
if (name.indexOf(".") == -1) {
list.set(i, getSpace() + "." + name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return list;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public List getIncludedMacros(XWikiContext context) {
return context.getWiki().getIncludedMacros(getSpace(), getContent(), context);
}
public List getLinkedPages(XWikiContext context) {
try {
String pattern = "\\[(.*?)\\]";
List newlist = new ArrayList();
List list = context.getUtil().getMatches(getContent(), pattern, 1);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
int i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 1);
}
i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 4);
}
i1 = name.indexOf("
if (i1 != -1) {
name = name.substring(0, i1);
}
i1 = name.indexOf("?");
if (i1 != -1) {
name = name.substring(0, i1);
}
// Let's get rid of anything that's not a real link
if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(":
|| (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1)
|| (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1))
continue;
// generate the link
String newname = StringUtils.replace(Util.noaccents(name), " ", "");
// If it is a local link let's add the space
if (newname.indexOf(".") == -1) {
newname = getSpace() + "." + name;
}
if (context.getWiki().exists(newname, context)) {
name = newname;
} else {
// If it is a local link let's add the space
if (name.indexOf(".") == -1) {
name = getSpace() + "." + name;
}
}
// Let's finally ignore the autolinks
if (!name.equals(getFullName()))
newlist.add(name);
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return newlist;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException {
String result = pclass.displayView(pclass.getName(), prefix, object, context);
return getRenderedContent(result, context);
}
public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) {
return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context);
}
public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) {
return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context);
}
public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) {
return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context);
}
public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) {
return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context);
}
public XWikiAttachment getAttachment(String filename) {
List list = getAttachmentList();
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().equals(filename)) {
return attach;
}
}
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().startsWith(filename + ".")) {
return attach;
}
}
return null;
}
public BaseObject getFirstObject(String fieldname) {
// Keeping this function with context null for compatibilit reasons
// It should not be used, since it would miss properties which are only defined in the class
// and not present in the object because the object was not updated
return getFirstObject(fieldname, null);
}
public BaseObject getFirstObject(String fieldname, XWikiContext context) {
Collection objectscoll = getxWikiObjects().values();
if (objectscoll == null)
return null;
for (Iterator itobjs = objectscoll.iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject obj = (BaseObject) itobjs2.next();
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
if (bclass!=null) {
Set set = bclass.getPropertyList();
if ((set != null) && set.contains(fieldname))
return obj;
}
Set set = obj.getPropertyList();
if ((set != null) && set.contains(fieldname))
return obj;
}
}
}
return null;
}
public int getIntValue(String className, String fieldName) {
BaseObject obj = getObject(className, 0);
if (obj == null)
return 0;
return obj.getIntValue(fieldName);
}
public long getLongValue(String className, String fieldName) {
BaseObject obj = getObject(className, 0);
if (obj == null)
return 0;
return obj.getLongValue(fieldName);
}
public String getStringValue(String className, String fieldName) {
BaseObject obj = getObject(className);
if (obj == null)
return "";
String result = obj.getStringValue(fieldName);
if (result.equals(" "))
return "";
else
return result;
}
public int getIntValue(String fieldName) {
BaseObject object = getFirstObject(fieldName, null);
if (object == null)
return 0;
else
return object.getIntValue(fieldName);
}
public long getLongValue(String fieldName) {
BaseObject object = getFirstObject(fieldName, null);
if (object == null)
return 0;
else
return object.getLongValue(fieldName);
}
public String getStringValue(String fieldName) {
BaseObject object = getFirstObject(fieldName, null);
if (object == null)
return "";
String result = object.getStringValue(fieldName);
if (result.equals(" "))
return "";
else
return result;
}
public void setStringValue(String className, String fieldName, String value) {
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringValue(fieldName, value);
setContentDirty(true);
}
public List getListValue(String className, String fieldName) {
BaseObject obj = getObject(className);
if (obj == null)
return new ArrayList();
return obj.getListValue(fieldName);
}
public List getListValue(String fieldName) {
BaseObject object = getFirstObject(fieldName, null);
if (object == null)
return new ArrayList();
return object.getListValue(fieldName);
}
public void setListValue(String className, String fieldName, List value) {
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setListValue(fieldName, value);
setContentDirty(true);
}
public void setLargeStringValue(String className, String fieldName, String value) {
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setLargeStringValue(fieldName, value);
setContentDirty(true);
}
public void setIntValue(String className, String fieldName, int value) {
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setIntValue(fieldName, value);
setContentDirty(true);
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public void setFullName(String fullname, XWikiContext context) {
if (fullname == null)
return;
int i0 = fullname.lastIndexOf(":");
int i1 = fullname.lastIndexOf(".");
if (i0 != -1) {
database = fullname.substring(0, i0);
web = fullname.substring(i0 + 1, i1);
name = fullname.substring(i1 + 1);
} else {
if (i1 == -1) {
try {
web = context.getDoc().getSpace();
} catch (Exception e) {
web = "XWiki";
}
name = fullname;
} else {
web = fullname.substring(0, i1);
name = fullname.substring(i1 + 1);
}
}
if (name.equals(""))
name = "WebHome";
setContentDirty(true);
}
public String getLanguage() {
if (language == null)
return "";
else
return language.trim();
}
public void setLanguage(String language) {
this.language = language;
}
public String getDefaultLanguage() {
if (defaultLanguage == null)
return "";
else
return defaultLanguage.trim();
}
public void setDefaultLanguage(String defaultLanguage) {
this.defaultLanguage = defaultLanguage;
setMetaDataDirty(true);
}
public int getTranslation() {
return translation;
}
public void setTranslation(int translation) {
this.translation = translation;
setMetaDataDirty(true);
}
public String getTranslatedContent(XWikiContext context) throws XWikiException {
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedContent(language, context);
}
public String getTranslatedContent(String language, XWikiContext context) throws XWikiException {
XWikiDocument tdoc = getTranslatedDocument(language, context);
String rev = (String) context.get("rev");
if ((rev == null) || (rev.length() == 0))
return tdoc.getContent();
XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context);
return cdoc.getContent();
}
public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException {
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedDocument(language, context);
}
public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException {
XWikiDocument tdoc = this;
if (!((language == null) || (language.equals("")) || language.equals(defaultLanguage))) {
tdoc = new XWikiDocument(getSpace(), getName());
tdoc.setLanguage(language);
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null)
context.setDatabase(getDatabase());
tdoc = getStore(context).loadXWikiDoc(tdoc, context);
if (tdoc.isNew())
tdoc = this;
} catch (Exception e) {
tdoc = this;
} finally {
context.setDatabase(database);
}
}
return tdoc;
}
public String getRealLanguage(XWikiContext context) throws XWikiException {
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default")))
return getDefaultLanguage();
else
return lang;
}
public String getRealLanguage() {
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default")))
return getDefaultLanguage();
else
return lang;
}
public List getTranslationList(XWikiContext context) throws XWikiException {
return getStore().getTranslationList(this, context);
}
public List getXMLDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException, DifferentiationFailedException {
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.toXML(context)), ToString.stringToArray(newdoc.toXML(context))));
}
public List getContentDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException, DifferentiationFailedException {
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.getContent()), ToString.stringToArray(newdoc.getContent())));
}
public List getContentDiff(String origrev, String newrev, XWikiContext context) throws XWikiException, DifferentiationFailedException {
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getContentDiff(origdoc, newdoc, context);
}
public List getContentDiff(String rev, XWikiContext context) throws XWikiException, DifferentiationFailedException {
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getContentDiff(this, revdoc, context);
}
public List getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException {
Version version = getRCSVersion();
String prev = "1." + (version.last() - 1);
XWikiDocument prevdoc = context.getWiki().getDocument(this, prev, context);
return getDeltas(Diff.diff(ToString.stringToArray(getContent()),
ToString.stringToArray(prevdoc.getContent())));
}
public List getRenderedContentDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException, DifferentiationFailedException {
String content1, content2;
content1 = context.getWiki().getRenderingEngine().renderText(origdoc.getContent(), origdoc, context);
content2 = context.getWiki().getRenderingEngine().renderText(newdoc.getContent(), newdoc, context);
return getDeltas(Diff.diff(ToString.stringToArray(content1),
ToString.stringToArray(content2)));
}
public List getRenderedContentDiff(String origrev, String newrev, XWikiContext context) throws XWikiException, DifferentiationFailedException {
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getRenderedContentDiff(origdoc, newdoc, context);
}
public List getRenderedContentDiff(String rev, XWikiContext context) throws XWikiException, DifferentiationFailedException {
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getRenderedContentDiff(this, revdoc, context);
}
protected List getDeltas(Revision rev) {
ArrayList list = new ArrayList();
for (int i = 0; i < rev.size(); i++) {
list.add(rev.getDelta(i));
}
return list;
}
public List getMetaDataDiff(String origrev, String newrev, XWikiContext context) throws XWikiException {
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getMetaDataDiff(origdoc, newdoc, context);
}
public List getMetaDataDiff(String rev, XWikiContext context) throws XWikiException {
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getMetaDataDiff(this, revdoc, context);
}
public List getMetaDataDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException {
List list = new ArrayList();
if ((origdoc == null) || (newdoc == null))
return list;
if (!origdoc.getParent().equals(newdoc.getParent()))
list.add(new MetaDataDiff("parent", origdoc.getParent(), newdoc.getParent()));
if (!origdoc.getAuthor().equals(newdoc.getAuthor()))
list.add(new MetaDataDiff("author", origdoc.getAuthor(), newdoc.getAuthor()));
if (!origdoc.getSpace().equals(newdoc.getSpace()))
list.add(new MetaDataDiff("web", origdoc.getSpace(), newdoc.getSpace()));
if (!origdoc.getName().equals(newdoc.getName()))
list.add(new MetaDataDiff("name", origdoc.getName(), newdoc.getName()));
if (!origdoc.getLanguage().equals(newdoc.getLanguage()))
list.add(new MetaDataDiff("language", origdoc.getLanguage(), newdoc.getLanguage()));
if (!origdoc.getDefaultLanguage().equals(newdoc.getDefaultLanguage()))
list.add(new MetaDataDiff("defaultLanguage", origdoc.getDefaultLanguage(), newdoc.getDefaultLanguage()));
return list;
}
public List getObjectDiff(String origrev, String newrev, XWikiContext context) throws XWikiException {
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getObjectDiff(origdoc, newdoc, context);
}
public List getObjectDiff(String rev, XWikiContext context) throws XWikiException {
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getObjectDiff(this, revdoc, context);
}
public List getObjectDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException {
ArrayList difflist = new ArrayList();
for (Iterator itobjs = origdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject origobj = (BaseObject) itobjs2.next();
BaseObject newobj = newdoc.getObject(origobj.getClassName(), origobj.getNumber());
List dlist;
if (newobj == null)
dlist = origobj.getDiff(new BaseObject(), context);
else
dlist = origobj.getDiff(newobj, context);
if (dlist.size() > 0)
difflist.add(dlist);
}
}
for (Iterator itobjs = newdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject newobj = (BaseObject) itobjs2.next();
BaseObject origobj = origdoc.getObject(newobj.getClassName(), newobj.getNumber());
if (origobj == null) {
origobj = new BaseObject();
origobj.setClassName(newobj.getClassName());
origobj.setNumber(newobj.getNumber());
List dlist = origobj.getDiff(newobj, context);
if (dlist.size() > 0)
difflist.add(dlist);
}
}
}
return difflist;
}
public List getClassDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context) throws XWikiException {
ArrayList difflist = new ArrayList();
BaseClass origclass = origdoc.getxWikiClass();
BaseClass newclass = newdoc.getxWikiClass();
if ((newclass == null) && (origclass == null))
return difflist;
List dlist = origclass.getDiff(newclass, context);
if (dlist.size() > 0)
difflist.add(dlist);
return difflist;
}
/**
* @deprecated {@link #copyDocument(String docname, XWikiContext context)}
* Only do a copy and not a renaming
* @param docname
* @param context
* @return
* @throws XWikiException
*/
public XWikiDocument renameDocument(String docname, XWikiContext context) throws XWikiException {
return copyDocument(docname, context);
}
public XWikiDocument copyDocument(String docname, XWikiContext context) throws XWikiException {
String oldname = getFullName();
loadAttachments(context);
loadArchive(context);
/* if (oldname.equals(docname))
return this; */
XWikiDocument newdoc = (XWikiDocument) clone();
newdoc.setFullName(docname, context);
newdoc.setContentDirty(true);
newdoc.getxWikiClass().setName(docname);
Vector objects = newdoc.getObjects(oldname);
if (objects != null) {
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject object = (BaseObject) it.next();
object.setName(docname);
}
}
return newdoc;
}
public XWikiLock getLock(XWikiContext context) throws XWikiException {
XWikiLock theLock = getStore(context).loadLock(getId(), context, true);
if (theLock != null) {
int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context);
if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) {
getStore(context).deleteLock(theLock, context, true);
theLock = null;
}
}
return theLock;
}
public void setLock(String userName, XWikiContext context) throws XWikiException {
XWikiLock lock = new XWikiLock(getId(), userName);
getStore(context).saveLock(lock, context, true);
}
public void removeLock(XWikiContext context) throws XWikiException {
XWikiLock lock = getStore(context).loadLock(getId(), context, true);
if (lock != null) {
getStore(context).deleteLock(lock, context, true);
}
}
public void insertText(String text, String marker, XWikiContext context) throws XWikiException {
setContent(StringUtils.replaceOnce(getContent(), marker, text + marker));
context.getWiki().saveDocument(this, context);
}
public Object getWikiNode() {
return wikiNode;
}
public void setWikiNode(Object wikiNode) {
this.wikiNode = wikiNode;
}
public String getxWikiClassXML() {
return xWikiClassXML;
}
public void setxWikiClassXML(String xWikiClassXML) {
this.xWikiClassXML = xWikiClassXML;
}
public int getElements() {
return elements;
}
public void setElements(int elements) {
this.elements = elements;
}
public void setElement(int element, boolean toggle) {
if (toggle)
elements = elements | element;
else
elements = elements & (~element);
}
public boolean hasElement(int element) {
return ((elements & element) == element);
}
public String getDefaultEditURL(XWikiContext context) throws XWikiException {
com.xpn.xwiki.XWiki xwiki = context.getWiki();
if (getContent().indexOf("includeForm(") != -1) {
return getEditURL("inline", "", context);
} else {
String editor = xwiki.getEditorPreference(context);
return getEditURL("edit", editor, context);
}
}
public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException {
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String language = "";
XWikiDocument tdoc = (XWikiDocument) context.get("tdoc");
String realLang = tdoc.getRealLanguage(context);
if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) {
language = realLang;
}
return getEditURL(action, mode, language, context);
}
public String getEditURL(String action, String mode, String language, XWikiContext context) {
StringBuffer editparams = new StringBuffer();
if (!mode.equals("")) {
editparams.append("xpage=");
editparams.append(mode);
}
if (!language.equals("")) {
if (!mode.equals(""))
editparams.append("&");
editparams.append("language=");
editparams.append(language);
}
return getURL(action, editparams.toString(), context);
}
public String getDefaultTemplate() {
if (defaultTemplate==null)
return "";
else
return defaultTemplate;
}
public void setDefaultTemplate(String defaultTemplate) {
this.defaultTemplate = defaultTemplate;
setMetaDataDirty(true);
}
public Vector getComments() {
return getComments(true);
}
public Vector getComments(boolean asc) {
if (asc)
return getObjects("XWiki.XWikiComments");
else {
Vector list = getObjects("XWiki.XWikiComments");
if (list == null)
return list;
Vector newlist = new Vector();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public boolean isCurrentUserCreator(XWikiContext context) {
return isCreator(context.getUser());
}
public boolean isCreator(String username) {
if (username.equals("XWiki.XWikiGuest"))
return false;
return username.equals(getCreator());
}
public boolean isCurrentUserPage(XWikiContext context) {
String username = context.getUser();
if (username.equals("XWiki.XWikiGuest"))
return false;
return context.getUser().equals(getFullName());
}
public boolean isCurrentLocalUserPage(XWikiContext context) {
String username = context.getLocalUser();
if (username.equals("XWiki.XWikiGuest"))
return false;
return context.getUser().equals(getFullName());
}
public void resetArchive(XWikiContext context) throws XWikiException {
getVersioningStore(context).resetRCSArchive(this, true, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException {
// Read info in object
ObjectAddForm form = new ObjectAddForm();
form.setRequest((HttpServletRequest) context.getRequest());
form.readRequest();
String className = form.getClassName();
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException {
return addObjectFromRequest(className, "", 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException {
return addObjectFromRequest(className, prefix, 0, context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, XWikiContext context) throws XWikiException {
return addObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException {
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))){
objectsNumberDone.add(new Integer(num));
objects.add(addObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException {
return addObjectFromRequest(className, "", num, context);
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException {
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException {
return updateObjectFromRequest(className, "", context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException {
return updateObjectFromRequest(className, prefix, 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException {
int nb;
BaseObject oldobject = getObject(className, num);
if (oldobject==null) {
nb = createNewObject(className, context);
oldobject = getObject(className, nb);
} else
nb = oldobject.getNumber();
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public List updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException {
return updateObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException {
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))){
objectsNumberDone.add(new Integer(num));
objects.add(updateObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
public boolean isAdvancedContent() {
String[] matches = { "<%" , "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content" };
String content2 = content.toLowerCase();
for (int i=0;i<matches.length;i++) {
if (content2.indexOf(matches[i].toLowerCase())!=-1)
return true;
}
String htmlregexp = "</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>";
try {
Util util = new Util();
List list = util.getMatches(content2, htmlregexp, 1);
if (list.size()>0)
return true;
} catch (MalformedPatternException e) {
}
return false;
}
public boolean isProgrammaticContent() {
String[] matches = { "<%" , "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()",
"$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content",
"$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage",
"$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",
};
String content2 = content.toLowerCase();
for (int i=0;i<matches.length;i++) {
if (content2.indexOf(matches[i].toLowerCase())!=-1)
return true;
}
return false;
}
public boolean removeObject(BaseObject bobj) {
Vector objects = getObjects(bobj.getClassName());
if (objects==null)
return false;
if (objects.elementAt(bobj.getNumber())==null)
return false;
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
return true;
}
/**
* Remove all the object of the class in parameter
* @param className the class name of the objects to be removed
* @return
*/
public boolean removeObjects(String className) {
Vector objects = getObjects(className);
if (objects==null)
return false;
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject bobj = (BaseObject) it.next();
if (bobj != null) {
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
}
}
return true;
}
// This method to split section according to title .
public List getSplitSectionsAccordingToTitle() throws XWikiException {
// pattern to match the title
Pattern pattern = Pattern.compile("^[\\p{Space}]*(1(\\.1)*)[\\p{Space}]+(.*?)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(getContent());
List splitSections = new ArrayList();
int sectionNumber = 0;
String contentTemp = getContent();
int beforeIndex = 0;
while (matcher.find()){ // find title to split
String sectionLevel = matcher.group(1);
if (sectionLevel.equals("1") || sectionLevel.equals("1.1")) {
// only set editting for the title that is 1 or 1.1
sectionNumber++ ;
String sectionTitle = matcher.group(3);
int sectionIndex = contentTemp.indexOf(matcher.group(0), beforeIndex);
beforeIndex = sectionIndex + matcher.group(0).length();
// initialize a documentSection object
DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle);
// add the document section to list
splitSections.add(docSection);
}
}
return splitSections;
}
// This function to return a Document section with parameter is sectionNumber
public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException {
// return a document section according to section number
return (DocumentSection)getSplitSectionsAccordingToTitle().get(sectionNumber - 1);
}
// This method to return the content of a section
public String getContentOfSection(int sectionNumber) throws XWikiException {
List splitSections = getSplitSectionsAccordingToTitle();
int indexEnd = 0 ;
// get current section
DocumentSection section = getDocumentSection(sectionNumber);
int indexStart = section.getSectionIndex();
String sectionLevel = section.getSectionLevel();
for(int i = sectionNumber; i < splitSections.size(); i++){
// get next section
DocumentSection nextSection = getDocumentSection(i + 1);
String nextLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextLevel)) {
// if section level is next section level
indexEnd = nextSection.getSectionIndex();
break ;
}
if (sectionLevel.length() > nextLevel.length()) {
// section level length is greater than next section level length (1.1 and 1)
indexEnd = nextSection.getSectionIndex();
break ;
}
}
String sectionContent = null;
if (indexStart < 0) indexStart = 0;
if (indexEnd == 0) sectionContent = getContent().substring(indexStart);
else sectionContent = getContent().substring(indexStart,indexEnd); // get section content
return sectionContent;
}
// This function to update a section content in document
public String updateDocumentSection(int sectionNumber , String newSectionContent) throws XWikiException {
StringBuffer newContent = new StringBuffer();
// get document section that will be edited
DocumentSection docSection = getDocumentSection(sectionNumber);
int numberOfSection = getSplitSectionsAccordingToTitle().size();
int indexSection = docSection.getSectionIndex();
if (numberOfSection == 1) {
// there is only a sections in document
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else if (sectionNumber == numberOfSection) {
// edit lastest section that doesn't contain subtitle
String contentBegin = getContent().substring(0,indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else {
String sectionLevel = docSection.getSectionLevel();
int nextSectionIndex = 0;
// get index of next section
for (int i=sectionNumber; i < numberOfSection; i++) {
DocumentSection nextSection = getDocumentSection(i + 1); // get next section
String nextSectionLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextSectionLevel)) {
nextSectionIndex = nextSection.getSectionIndex();
break;
} else if (sectionLevel.length() > nextSectionLevel.length()) {
nextSectionIndex = nextSection.getSectionIndex();
break;
}
}
if (nextSectionIndex == 0) {// edit the last section
newContent = newContent.append(getContent().substring(0,indexSection)).append(newSectionContent);
return newContent.toString();
} else {
String contentAfter = getContent().substring(nextSectionIndex);
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter);
}
return newContent.toString();
}
}
/**
* Computes a document hash, taking into account all document data:
* content, objects, attachments, metadata...
* TODO: cache the hash value, update only on modification.
*/
public String getVersionHashCode(XWikiContext context){
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
log.error("Cannot create MD5 object", ex);
return this.hashCode() + "";
}
try {
String valueBeforeMD5 = toXML(true, false, true, false, context);
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
} catch (Exception ex) {
log.error("Exception while computing document hash", ex);
}
return this.hashCode() + "";
}
public static String getInternalPropertyName(String propname, XWikiContext context) {
XWikiMessageTool msg = ((XWikiMessageTool)context.get("msg"));
String cpropname = StringUtils.capitalize(propname);
return (msg==null) ? cpropname : msg.get(cpropname);
}
public String getInternalProperty(String propname) {
String methodName = "get" + StringUtils.capitalize(propname);
try {
Method method = getClass().getDeclaredMethod(methodName, null);
return (String) method.invoke(this, null);
} catch (Exception e) {
return null;
}
}
public String getCustomClass() {
if (customClass == null)
return "";
return customClass;
}
public void setCustomClass(String customClass) {
this.customClass = customClass;
setMetaDataDirty(true);
}
public void setValidationScript(String validationScript) {
this.validationScript = validationScript;
setMetaDataDirty(true);
}
public String getValidationScript() {
if (validationScript==null)
return "";
else
return validationScript;
}
public BaseObject newObject(String classname, XWikiContext context) throws XWikiException {
int nb = createNewObject(classname, context);
return getObject(classname, nb);
}
public BaseObject getObject(String classname, boolean create, XWikiContext context) {
try {
BaseObject obj = getObject(classname);
if ((obj == null) && create) {
return newObject(classname, context);
}
if (obj == null)
return null;
else
return obj;
} catch (Exception e) {
return null;
}
}
public boolean validate(XWikiContext context) throws XWikiException {
return validate(null, context);
}
public boolean validate(String[] classNames, XWikiContext context) throws XWikiException {
boolean isValid = true;
if ((classNames==null)||(classNames.length==0)) {
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = context.getWiki().getClass(classname, context);
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
isValid &= bclass.validateObject(obj, context);
}
}
}
} else {
for (int i=0;i<classNames.length;i++) {
Vector objects = getObjects(classNames[i]);
if (objects!=null) {
for (int j = 0; j < objects.size(); j++) {
BaseObject obj = (BaseObject) objects.get(j);
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
isValid &= bclass.validateObject(obj, context);
}
}
}
}
}
String validationScript = "";
XWikiRequest req = context.getRequest();
if (req!=null) {
validationScript = req.get("xvalidation");
}
if ((validationScript==null)||(validationScript.trim().equals(""))) {
validationScript = getValidationScript();
}
if ((validationScript!=null)&&(!validationScript.trim().equals(""))) {
isValid &= executeValidationScript(context, validationScript);
}
return isValid;
}
private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException {
try {
XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context);
return validObject.validateDocument(this, context);
} catch (Throwable e) {
XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context);
return false;
}
}
public static void backupContext(HashMap backup, XWikiContext context) {
backup.put("doc", context.getDoc());
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
if (vcontext != null) {
backup.put("vdoc", vcontext.get("doc"));
backup.put("vcdoc", vcontext.get("cdoc"));
backup.put("vtdoc", vcontext.get("tdoc"));
}
Map gcontext = (Map) context.get("gcontext");
if (gcontext != null) {
backup.put("gdoc", gcontext.get("doc"));
backup.put("gcdoc", gcontext.get("cdoc"));
backup.put("gtdoc", gcontext.get("tdoc"));
}
}
public static void restoreContext(HashMap backup, XWikiContext context) {
context.setDoc((XWikiDocument)backup.get("doc"));
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
if (backup.get("vdoc") != null) {
vcontext.put("doc", backup.get("vdoc"));
}
if (backup.get("vcdoc") != null) {
vcontext.put("cdoc", backup.get("vcdoc"));
}
if (backup.get("vtdoc") != null) {
vcontext.put("tdoc", backup.get("vtdoc"));
}
}
if (gcontext != null) {
if (backup.get("gdoc") != null) {
gcontext.put("doc", backup.get("gdoc"));
}
if (backup.get("gcdoc") != null) {
gcontext.put("cdoc", backup.get("gcdoc"));
}
if (backup.get("gtdoc") != null) {
gcontext.put("tdoc", backup.get("gtdoc"));
}
}
}
public void setAsContextDoc(XWikiContext context) {
try {
context.setDoc(this);
com.xpn.xwiki.api.Document apidoc = this.newDocument(context);
com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument();
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
vcontext.put("doc", apidoc);
vcontext.put("tdoc", tdoc);
}
if (gcontext != null) {
gcontext.put("doc", apidoc);
gcontext.put("tdoc", tdoc);
}
} catch (XWikiException ex) {
log.warn("Unhandled exception setting context", ex);
}
}
}
|
package core.primitives;
public class DoublePrimitive implements PrimitiveConstants {
double d1 = 100;
double d2 = BYTE;
double d3 = SHORT;
double d4 = INT;
double d5 = LONG;
double d6 = FLOAT;
double d7 = DOUBLE;
double d9 = CHAR;
// COMPILE ERROR: incompatible types: boolean cannot be converted to double
// double d8 = BOOLEAN;
}
|
package data.structure.tree;
public class NodeBinTree<E extends Comparable<E>> {
protected E element;
protected NodeBinTree<E> father;
protected NodeBinTree<E> leftChild;
protected NodeBinTree<E> rightChild;
protected NodeBinTree<E> demote;
// Getters and Setters
public E getElement() {
return this.element;
}
public void setElement(E element) {
this.element = element;
}
public NodeBinTree<E> getFather() {
return this.father;
}
public void setFather(NodeBinTree<E> father) {
this.father = father;
}
public NodeBinTree<E> getLeftChild() {
return this.leftChild;
}
public void setLeftChild(NodeBinTree<E> lChild) {
this.leftChild = lChild;
}
public NodeBinTree<E> getRightChild() {
return this.rightChild;
}
public void setRightChild(NodeBinTree<E> rChild) {
this.rightChild = rChild;
}
/**
* Public Constructor
*
* @return NodeBinTree<E>
*/
public NodeBinTree(E element) {
this.element = element;
this.father = null;
this.leftChild = null;
this.rightChild = null;
this.demote = null;
}
/**
* Public Constructor
*
* @return NodeBinTree<E>
*/
public NodeBinTree(E element, NodeBinTree<E> father) {
this.element = element;
this.father = father;
this.leftChild = null;
this.rightChild = null;
this.demote = null;
}
/**
* Public Constructor
*
* @return NodeBinTree<E>
*/
public NodeBinTree(E element, NodeBinTree<E> father,
NodeBinTree<E> lChild) {
this.element = element;
this.father = father;
this.leftChild = lChild;
this.rightChild = null;
this.demote = null;
}
/**
* Public Constructor
*
* @return NodeBinTree<E>
*/
public NodeBinTree(E element, NodeBinTree<E> father,
NodeBinTree<E> lChild, NodeBinTree<E> rChild) {
this.element = element;
this.father = father;
this.leftChild = lChild;
this.rightChild = rChild;
this.demote = null;
}
/**
* Swap the node content with its father.
*
* @return void
*/
public void swapFather() {
E temp = this.element;
this.element = this.father.getElement();
this.father.setElement(temp);
}
/**
* Swap the node content with its left child.
*
* @return void
*/
public void swapLeftChild() {
E temp = this.element;
this.element = this.leftChild.getElement();
this.leftChild.setElement(temp);
}
/**
* Swap the node content with its right child.
*
* @return void
*/
public void swapRightChild() {
E temp = this.element;
this.element = this.rightChild.getElement();
this.rightChild.setElement(temp);
}
/**
* Informs if this node is the root of the tree.
*
* @return boolean
*/
public boolean isRoot() {
return null == this.father;
}
/**
* Informs if this node is one leaf of the tree.
*
* @return boolean
*/
public boolean isLeaf() {
return null == this.leftChild &&
null == this.rightChild;
}
/**
* Returns the number of children this node has.
*
* @return int
*/
public int howManyChildren() {
int result = 0;
if (null != leftChild) result++;
if (null != rightChild) result++;
return result;
}
/**
* Informs the number of descendents.
*
* @return int
*/
public int familySize() {
int temp = 1;
if (null != leftChild) temp += leftChild.familySize();
if (null != rightChild) temp += rightChild.familySize();
return temp;
}
/**
* Informs the max depth.
*
* @return int
*/
public int maxDepth() {
int leftDepth = (null != leftChild) ? leftChild.maxDepth(): 0;
int rightDepth = (null != rightChild) ? rightChild.maxDepth(): 0;
return 1 + ((leftDepth > rightDepth) ? leftDepth : rightDepth);
}
/**
* Returns the sibling if it exists.
*
* @return NodeBinTree<E>
*/
public NodeBinTree<E> sibling() {
if (null == father) return null;
return (this != father.leftChild) ? father.leftChild : father.rightChild;
}
/**
* Returns the node with minor content at right of this.
*
* @return NodeBinTree<E>
*/
public NodeBinTree<E> minorOnTheRight() {
if (null == rightChild) return null;
NodeBinTree<E> next = rightChild;
while (null != next.leftChild) next = next.leftChild;
return next;
}
/**
* Returns the node with largest content on the left of this.
*
* @return NodeBinTree<E>
*/
public NodeBinTree<E> largestOnTheLeft() {
if (null == leftChild) return null;
NodeBinTree<E> next = leftChild;
while (null != next.rightChild) next = next.rightChild;
return next;
}
/**
* Returns the node position in an array based representation.
*
* @return int
*/
public int position() {
if (this.isRoot()) return 1;
int temp = 2 * father.position();
return (amILeftChild()) ? temp : temp + 1;
}
/**
* Informs if this node is a left child.
*
* @return boolean
*/
protected boolean amILeftChild() {
return father.leftChild == this;
}
/**
* Swaps the content of two nodes.
*/
public void swap(NodeBinTree<E> other) {
E temp = other.element;
other.element = element;
element = temp;
}
/**
* Become this node a root node.
*/
public void promote() {
if (null != this.demote) return;
this.demote = this.father;
this.father = null;
}
/**
* Brings this node back to condition before it became a root node.
*/
public void demote() {
if (null == this.demote) return;
this.father = this.demote;
this.demote = null;
}
@Override
public String toString() {
return element.toString();
}
}
|
package de.prob2.ui.menu;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import de.codecentric.centerdevice.MenuToolkit;
import de.prob.scripting.Api;
import de.prob.scripting.ModelTranslationError;
import de.prob.statespace.AnimationSelector;
import de.prob.statespace.StateSpace;
import de.prob.statespace.Trace;
import de.prob2.ui.MainController;
import de.prob2.ui.animations.AnimationsView;
import de.prob2.ui.consoles.b.BConsoleStage;
import de.prob2.ui.consoles.groovy.GroovyConsoleStage;
import de.prob2.ui.formula.FormulaInputStage;
import de.prob2.ui.history.HistoryView;
import de.prob2.ui.internal.UIState;
import de.prob2.ui.modelchecking.ModelcheckingController;
import de.prob2.ui.operations.OperationsView;
import de.prob2.ui.preferences.PreferencesStage;
import de.prob2.ui.prob2fx.CurrentStage;
import de.prob2.ui.prob2fx.CurrentTrace;
import de.prob2.ui.stats.StatsView;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TitledPane;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCombination;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public final class MenuController extends MenuBar {
// FIXME all checkboxes selected when reloading detached
private enum ApplyDetachedEnum {
JSON, USER
}
private final class DetachViewStageController {
@FXML private Stage detached;
@FXML private Button apply;
@FXML private CheckBox detachOperations;
@FXML private CheckBox detachHistory;
@FXML private CheckBox detachModelcheck;
@FXML private CheckBox detachStats;
@FXML private CheckBox detachAnimations;
private final Preferences windowPrefs;
private final Set<Stage> wrapperStages;
private DetachViewStageController() {
windowPrefs = Preferences.userNodeForPackage(MenuController.DetachViewStageController.class);
wrapperStages = new HashSet<>();
}
@FXML
public void initialize() {
detached.initModality(Modality.APPLICATION_MODAL);
detached.getIcons().add(new Image("prob_128.gif"));
currentStage.register(detached, this.getClass().getName());
}
@FXML
private void apply() {
apply(ApplyDetachedEnum.USER);
}
private void apply(ApplyDetachedEnum detachedBy) {
Parent root = loadPreset("main.fxml");
assert root != null;
SplitPane pane = (SplitPane) root.getChildrenUnmodifiable().get(1);
Accordion accordion = (Accordion) pane.getItems().get(0);
removeTP(accordion, pane, detachedBy);
uiState.setGuiState("detached");
this.detached.close();
}
private void removeTP(Accordion accordion, SplitPane pane, ApplyDetachedEnum detachedBy) {
final HashSet<Stage> wrapperStagesCopy = new HashSet<>(wrapperStages);
wrapperStages.clear();
for (final Stage stage : wrapperStagesCopy) {
stage.setScene(null);
stage.hide();
}
for (final Iterator<TitledPane> it = accordion.getPanes().iterator(); it.hasNext();) {
final TitledPane tp = it.next();
if (removable(tp, detachedBy)) {
it.remove();
transferToNewWindow((Parent)tp.getContent(), tp.getText());
}
}
if (accordion.getPanes().isEmpty()) {
pane.getItems().remove(accordion);
pane.setDividerPositions(0);
pane.lookupAll(".split-pane-divider").forEach(div -> div.setMouseTransparent(true));
}
}
private boolean removable(TitledPane tp, ApplyDetachedEnum detachedBy) {
return (removablePane(tp, detachOperations, detachedBy) && tp.getContent() instanceof OperationsView) ||
(removablePane(tp, detachHistory, detachedBy) && tp.getContent() instanceof HistoryView) ||
(removablePane(tp, detachModelcheck, detachedBy) && tp.getContent() instanceof ModelcheckingController) ||
(removablePane(tp, detachStats, detachedBy) && tp.getContent() instanceof StatsView) ||
(removablePane(tp, detachAnimations, detachedBy) && tp.getContent() instanceof AnimationsView);
}
private boolean removablePane(TitledPane tp, CheckBox detached, ApplyDetachedEnum detachedBy) {
boolean condition = detached.isSelected();
if(detachedBy == ApplyDetachedEnum.JSON) {
condition = uiState.getSavedStageBoxes().containsKey(tp.getText());
if(condition) {
detached.setSelected(true);
}
}
return condition;
}
private void transferToNewWindow(Parent node, String title) {
Stage stage = new Stage();
wrapperStages.add(stage);
stage.setTitle(title);
currentStage.register(stage, null);
stage.getIcons().add(new Image("prob_128.gif"));
stage.setOnHidden(e -> {
windowPrefs.putDouble(node.getClass()+"X",stage.getX());
windowPrefs.putDouble(node.getClass()+"Y",stage.getY());
windowPrefs.putDouble(node.getClass()+"Width",stage.getWidth());
windowPrefs.putDouble(node.getClass()+"Height",stage.getHeight());
if (node instanceof OperationsView) {
detachOperations.setSelected(false);
} else if (node instanceof HistoryView) {
detachHistory.setSelected(false);
} else if (node instanceof ModelcheckingController) {
detachModelcheck.setSelected(false);
} else if (node instanceof StatsView) {
detachStats.setSelected(false);
} else if (node instanceof AnimationsView) {
detachAnimations.setSelected(false);
}
dvController.apply();
});
stage.setWidth(windowPrefs.getDouble(node.getClass()+"Width",200));
stage.setHeight(windowPrefs.getDouble(node.getClass()+"Height",100));
stage.setX(windowPrefs.getDouble(node.getClass()+"X", Screen.getPrimary().getVisualBounds().getWidth()-stage.getWidth()/2));
stage.setY(windowPrefs.getDouble(node.getClass()+"Y", Screen.getPrimary().getVisualBounds().getHeight()-stage.getHeight()/2));
Scene scene = new Scene(node);
scene.getStylesheets().add("prob.css");
stage.setScene(scene);
stage.show();
}
}
private static final URL FXML_ROOT;
static {
try {
FXML_ROOT = new URL(MenuController.class.getResource("menu.fxml"), "..");
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
private final Injector injector;
private final Api api;
private final AnimationSelector animationSelector;
private final CurrentStage currentStage;
private final CurrentTrace currentTrace;
private final RecentFiles recentFiles;
private final UIState uiState;
private final DetachViewStageController dvController;
private final Object openLock;
private Window window;
@FXML private Menu recentFilesMenu;
@FXML private MenuItem recentFilesPlaceholder;
@FXML private MenuItem clearRecentFiles;
@FXML private Menu windowMenu;
@FXML private MenuItem preferencesItem;
@FXML private MenuItem enterFormulaForVisualization;
@FXML private MenuItem aboutItem;
@Inject
private MenuController(
final FXMLLoader loader,
final Injector injector,
final Api api,
final AnimationSelector animationSelector,
final CurrentStage currentStage,
final CurrentTrace currentTrace,
final RecentFiles recentFiles,
final UIState uiState
) {
this.injector = injector;
this.api = api;
this.animationSelector = animationSelector;
this.currentStage = currentStage;
this.currentTrace = currentTrace;
this.recentFiles = recentFiles;
this.uiState = uiState;
this.openLock = new Object();
loader.setLocation(getClass().getResource("menu.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException e) {
logger.error("loading fxml failed", e);
}
if (System.getProperty("os.name", "").toLowerCase().contains("mac")) {
// Mac-specific menu stuff
this.setUseSystemMenuBar(true);
final MenuToolkit tk = MenuToolkit.toolkit();
// Remove About menu item from Help
aboutItem.getParentMenu().getItems().remove(aboutItem);
aboutItem.setText("About ProB 2");
// Remove Preferences menu item from Edit
preferencesItem.getParentMenu().getItems().remove(preferencesItem);
preferencesItem.setAccelerator(KeyCombination.valueOf("Shortcut+,"));
// Create Mac-style application menu
final Menu applicationMenu = tk.createDefaultApplicationMenu("ProB 2");
this.getMenus().add(0, applicationMenu);
tk.setApplicationMenu(applicationMenu);
applicationMenu.getItems().setAll(aboutItem, new SeparatorMenuItem(), preferencesItem,
new SeparatorMenuItem(), tk.createHideMenuItem("ProB 2"), tk.createHideOthersMenuItem(),
tk.createUnhideAllMenuItem(), new SeparatorMenuItem(), tk.createQuitMenuItem("ProB 2"));
// Add Mac-style items to Window menu
windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(),
tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem(),
new SeparatorMenuItem());
tk.autoAddWindowMenuItems(windowMenu);
// Make this the global menu bar
tk.setGlobalMenuBar(this);
}
final FXMLLoader stageLoader = injector.getInstance(FXMLLoader.class);
stageLoader.setLocation(getClass().getResource("detachedPerspectivesChoice.fxml"));
this.dvController = new DetachViewStageController();
stageLoader.setController(this.dvController);
try {
stageLoader.load();
} catch (IOException e) {
logger.error("loading fxml failed", e);
}
}
@FXML
public void initialize() {
this.sceneProperty().addListener((observable, from, to) -> {
if (to != null) {
to.windowProperty().addListener((observable1, from1, to1) -> this.window = to1);
}
});
final ListChangeListener<String> recentFilesListener = change -> {
final ObservableList<MenuItem> recentItems = this.recentFilesMenu.getItems();
final List<MenuItem> newItems = getRecentFileItems();
// If there are no recent files, show a placeholder and disable clearing
this.clearRecentFiles.setDisable(newItems.isEmpty());
if (newItems.isEmpty()) {
newItems.add(this.recentFilesPlaceholder);
}
// Add a shortcut for reopening the most recent file
newItems.get(0).setAccelerator(KeyCombination.valueOf("Shift+Shortcut+'O'"));
// Keep the last two items (the separator and the "clear recent files" item)
newItems.addAll(recentItems.subList(recentItems.size()-2, recentItems.size()));
// Replace the old recents with the new ones
this.recentFilesMenu.getItems().setAll(newItems);
};
this.recentFiles.addListener(recentFilesListener);
// Fire the listener once to populate the recent files menu
recentFilesListener.onChanged(null);
this.enterFormulaForVisualization.disableProperty().bind(currentTrace.currentStateProperty().initializedProperty().not());
}
@FXML
private void handleClearRecentFiles() {
this.recentFiles.clear();
}
@FXML
private void handleLoadDefault() {
uiState.clearDetachedStages();
loadPreset("main.fxml");
}
@FXML
private void handleLoadSeparated() {
uiState.clearDetachedStages();
loadPreset("separatedHistory.fxml");
}
@FXML
private void handleLoadSeparated2() {
uiState.clearDetachedStages();
loadPreset("separatedHistoryAndStatistics.fxml");
}
@FXML
private void handleLoadStacked() {
uiState.clearDetachedStages();
loadPreset("stackedLists.fxml");
}
@FXML
public void handleLoadDetached() {
this.dvController.detached.showAndWait();
}
public void applyDetached() {
this.dvController.apply(ApplyDetachedEnum.JSON);
}
@FXML
private void handleLoadPerspective() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open File");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("FXML Files", "*.fxml"));
File selectedFile = fileChooser.showOpenDialog(window);
if (selectedFile != null) {
try {
FXMLLoader loader = injector.getInstance(FXMLLoader.class);
loader.setLocation(selectedFile.toURI().toURL());
uiState.setGuiState(selectedFile.toString());
Parent root = loader.load();
window.getScene().setRoot(root);
} catch (IOException e) {
logger.error("loading fxml failed", e);
Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e);
alert.getDialogPane().getStylesheets().add("prob.css");
alert.showAndWait();
}
}
}
private void openAsync(String path) {
new Thread(() -> this.open(path), "File Opener Thread").start();
}
private void open(String path) {
// NOTE: This method may be called from outside the JavaFX main thread, for example from openAsync.
// This means that all JavaFX calls must be wrapped in Platform.runLater.
// Prevent multiple threads from loading a file at the same time
synchronized (this.openLock) {
final StateSpace newSpace;
try {
newSpace = this.api.b_load(path);
} catch (IOException | ModelTranslationError e) {
logger.error("loading file failed", e);
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e);
alert.getDialogPane().getStylesheets().add("prob.css");
alert.show();
});
return;
}
this.animationSelector.addNewAnimation(new Trace(newSpace));
Platform.runLater(() -> {
injector.getInstance(ModelcheckingController.class).resetView();
// Remove the path first to avoid listing the same file twice.
this.recentFiles.remove(path);
this.recentFiles.add(0, path);
});
}
}
@FXML
private void handleOpen(ActionEvent event) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open File");
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Classical B Files", "*.mch", "*.ref", "*.imp"));
final File selectedFile = fileChooser.showOpenDialog(this.window);
if (selectedFile == null) {
return;
}
this.openAsync(selectedFile.getAbsolutePath());
}
@FXML
private void handleClose(final ActionEvent event) {
final Stage stage = this.currentStage.get();
if (stage != null) {
stage.close();
}
}
@FXML
private void handlePreferences() {
final Stage preferencesStage = injector.getInstance(PreferencesStage.class);
preferencesStage.show();
preferencesStage.toFront();
}
@FXML
private void handleFormulaInput() {
final Stage formulaInputStage = injector.getInstance(FormulaInputStage.class);
formulaInputStage.showAndWait();
formulaInputStage.toFront();
}
@FXML
private void handleGroovyConsole() {
final Stage groovyConsoleStage = injector.getInstance(GroovyConsoleStage.class);
groovyConsoleStage.show();
groovyConsoleStage.toFront();
}
@FXML
private void handleBConsole() {
final Stage bConsoleStage = injector.getInstance(BConsoleStage.class);
bConsoleStage.show();
bConsoleStage.toFront();
}
public Parent loadPreset(String location) {
FXMLLoader loader = injector.getInstance(FXMLLoader.class);
this.uiState.setGuiState(location);
try {
loader.setLocation(new URL(FXML_ROOT, location));
} catch (MalformedURLException e) {
logger.error("Malformed location", e);
Alert alert = new Alert(Alert.AlertType.ERROR, "Malformed location:\n" + e);
alert.getDialogPane().getStylesheets().add("prob.css");
alert.showAndWait();
return null;
}
loader.setRoot(injector.getInstance(MainController.class));
injector.getInstance(MainController.class).refresh(uiState);
Parent root;
try {
root = loader.load();
} catch (IOException e) {
logger.error("loading fxml failed", e);
Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e);
alert.getDialogPane().getStylesheets().add("prob.css");
alert.showAndWait();
return null;
}
window.getScene().setRoot(root);
if (System.getProperty("os.name", "").toLowerCase().contains("mac")) {
final MenuToolkit tk = MenuToolkit.toolkit();
tk.setGlobalMenuBar(this);
tk.setApplicationMenu(this.getMenus().get(0));
}
return root;
}
@FXML
private void handleReportBug() {
final Stage reportBugStage = injector.getInstance(ReportBugStage.class);
reportBugStage.show();
reportBugStage.toFront();
}
private List<MenuItem> getRecentFileItems(){
final List<MenuItem> newItems = new ArrayList<>();
for (String s : this.recentFiles) {
final MenuItem item = new MenuItem(new File(s).getName());
item.setOnAction(event -> this.openAsync(s));
newItems.add(item);
}
return newItems;
}
}
|
package de.tblsoft.solr.http;
import com.google.common.base.Strings;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HTTPHelper {
private static Logger LOG = LoggerFactory.getLogger(HTTPHelper.class);
public static String delete(String url) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpPost = new HttpDelete(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append(EntityUtils.toString(response.getEntity()));
httpclient.close();
return responseBuilder.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String put(String url, String postString, String contentType) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut httpPost = new HttpPut(url);
if (postString != null) {
StringEntity entity = new StringEntity(postString, "UTF-8");
httpPost.setEntity(entity);
}
if(!Strings.isNullOrEmpty(contentType)) {
httpPost.setHeader("Content-Type",contentType);
}
CloseableHttpResponse response = httpclient.execute(httpPost);
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append(EntityUtils.toString(response.getEntity()));
if(response.getStatusLine().getStatusCode() != 200) {
LOG.info(responseBuilder.toString());
}
httpclient.close();
return responseBuilder.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String post(String url, String postString) {
return post(url, postString, null);
}
public static String post(String url, String postString, String contentType) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(postString, "UTF-8");
httpPost.setEntity(entity);
if(!Strings.isNullOrEmpty(contentType)) {
httpPost.setHeader("Content-Type",contentType);
}
CloseableHttpResponse response = httpclient.execute(httpPost);
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append(EntityUtils.toString(response.getEntity()));
httpclient.close();
if(response.getStatusLine().getStatusCode() >= 300) {
throw new RuntimeException("Problem: " + response.getStatusLine().getStatusCode() + " payload: " + responseBuilder.toString());
}
return responseBuilder.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void webHook(String url, String... parameters) {
if(Strings.isNullOrEmpty(url)) {
return;
}
Map<String, String> parametersMap = new HashMap<>();
for (int i = 0; i < parameters.length; i=i+2) {
parametersMap.put(parameters[i], parameters[i+1]);
}
StrSubstitutor strSubstitutor = new StrSubstitutor(parametersMap);
String webhook = strSubstitutor.replace(url);
// TODO this should be async
get(webhook);
}
public static String get(String url) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpPost = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
StringBuilder responseBuilder = new StringBuilder();
responseBuilder.append(EntityUtils.toString(response.getEntity()));
httpclient.close();
return responseBuilder.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static InputStream getInputStream(String url) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpPost = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
return response.getEntity().getContent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static InputStream getAsInputStream(String url) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpPost = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
return response.getEntity().getContent();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Store the body of the url in the specified fileName.
*
* @param url The url where the content is fetched.
* @param fileName The fileName where the content is stored.
*/
public static void get2File(String url, File fileName) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpPost = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
InputStream is = response.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(fileName);
org.apache.commons.io.IOUtils.copy(is, fos);
httpclient.close();
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static int getStatusCode(String url) {
try {
CloseableHttpClient httpclient = HttpClients.custom().disableRedirectHandling().build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpGet);
httpclient.close();
return response.getStatusLine().getStatusCode();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getRedirectLocation(String url) {
try {
CloseableHttpClient httpclient = HttpClients.custom().disableRedirectHandling().build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpGet);
httpclient.close();
Header location = response.getFirstHeader("Location");
if(location == null) {
return url;
}
return location.getValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getCookieValueFromHeader(String cookieName, HttpResponse response) {
Header[] headers = response.getHeaders("Set-Cookie");
if(headers == null) {
return null;
}
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
for(HttpCookie cookie : cookies) {
if(cookie.getName().equals(cookieName)) {
return cookie.getValue();
}
}
}
return null;
}
public static String removeQueryParameter(String url) {
if(Strings.isNullOrEmpty(url)) {
return url;
}
int index = url.indexOf("?");
if(index > 0) {
return url.substring(0, index);
}
return url;
}
}
|
package de.website.Bean;
import java.io.File;
import java.io.InputStream;
import java.sql.*;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.xml.transform.Result;
import de.website.database.Nutzer;
import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.model.UploadedFile;
@ManagedBean(name = "uploadImage")
@SessionScoped
public class ImageUploadBean {
final static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(DbQuery.class);
private UploadedFile file;
private FileUpload image;
Nutzer nutzer = Nutzer.getInstance();
DbQuery dbCon = nutzer.getDbCon();
Exchange ex = Exchange.getInstance();
public void upload() {
System.out.println(image.getAllowTypes());
if (this.file != null) {
try {
int iid = ex.getPid();
if(iid == 0){
FacesMessage msg = new FacesMessage("Bitte wählen Sie ein Projekt aus!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}else {
System.out.println(file.getFileName());
InputStream fin = file.getInputstream();
Nutzer nutzer = Nutzer.getInstance();
DbQuery dbCon = nutzer.getDbCon();
Connection con = ex.getConnection();
//TODO: check If Image already exists
PreparedStatement pre = con.prepareStatement("insert into Bilder (iid, Bilder) values(?,?)");
pre.setInt(1, ex.getPid());
pre.setBinaryStream(2, fin, file.getSize());
pre.executeUpdate();
pre.close();
FacesMessage msg = new FacesMessage("Das Bild ", file.getFileName() + " wurde erfolgreich gespeichert.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
} catch (Exception e) {
logger.error("Fehler Datenbank-Bilder-Upload: " + e);
}
}
else{
FacesMessage msg = new FacesMessage("Bitte wählen Sie ein Bild aus!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public FileUpload getImage() {
return image;
}
public void setImage(FileUpload image) {
this.image = image;
}
}
|
package graphql.validation;
import graphql.Internal;
import graphql.language.Argument;
import graphql.language.Directive;
import graphql.language.Document;
import graphql.language.Field;
import graphql.language.FragmentDefinition;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.Node;
import graphql.language.OperationDefinition;
import graphql.language.SelectionSet;
import graphql.language.TypeName;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Internal
public class RulesVisitor implements DocumentVisitor {
private final List<AbstractRule> rules = new ArrayList<>();
private ValidationContext validationContext;
private boolean subVisitor;
private List<AbstractRule> rulesVisitingFragmentSpreads = new ArrayList<>();
private Map<Node, List<AbstractRule>> rulesToSkipByUntilNode = new IdentityHashMap<>();
private Set<AbstractRule> rulesToSkip = new LinkedHashSet<>();
public RulesVisitor(ValidationContext validationContext, List<AbstractRule> rules) {
this(validationContext, rules, false);
}
public RulesVisitor(ValidationContext validationContext, List<AbstractRule> rules, boolean subVisitor) {
this.validationContext = validationContext;
this.subVisitor = subVisitor;
this.rules.addAll(rules);
this.subVisitor = subVisitor;
findRulesVisitingFragmentSpreads();
}
private void findRulesVisitingFragmentSpreads() {
for (AbstractRule rule : rules) {
if (rule.isVisitFragmentSpreads()) {
rulesVisitingFragmentSpreads.add(rule);
}
}
}
@Override
public void enter(Node node, List<Node> ancestors) {
validationContext.getTraversalContext().enter(node, ancestors);
Set<AbstractRule> tmpRulesSet = new LinkedHashSet<>(this.rules);
tmpRulesSet.removeAll(rulesToSkip);
List<AbstractRule> rulesToConsider = new ArrayList<>(tmpRulesSet);
if (node instanceof Argument) {
checkArgument((Argument) node, rulesToConsider);
} else if (node instanceof TypeName) {
checkTypeName((TypeName) node, rulesToConsider);
} else if (node instanceof VariableDefinition) {
checkVariableDefinition((VariableDefinition) node, rulesToConsider);
} else if (node instanceof Field) {
checkField((Field) node, rulesToConsider);
} else if (node instanceof InlineFragment) {
checkInlineFragment((InlineFragment) node, rulesToConsider);
} else if (node instanceof Directive) {
checkDirective((Directive) node, ancestors, rulesToConsider);
} else if (node instanceof FragmentSpread) {
checkFragmentSpread((FragmentSpread) node, rulesToConsider, ancestors);
} else if (node instanceof FragmentDefinition) {
checkFragmentDefinition((FragmentDefinition) node, rulesToConsider);
} else if (node instanceof OperationDefinition) {
checkOperationDefinition((OperationDefinition) node, rulesToConsider);
} else if (node instanceof VariableReference) {
checkVariable((VariableReference) node, rulesToConsider);
} else if (node instanceof SelectionSet) {
checkSelectionSet((SelectionSet) node, rulesToConsider);
}
}
private void checkArgument(Argument node, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkArgument(node);
}
}
private void checkTypeName(TypeName node, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkTypeName(node);
}
}
private void checkVariableDefinition(VariableDefinition variableDefinition, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkVariableDefinition(variableDefinition);
}
}
private void checkField(Field field, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkField(field);
}
}
private void checkInlineFragment(InlineFragment inlineFragment, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkInlineFragment(inlineFragment);
}
}
private void checkDirective(Directive directive, List<Node> ancestors, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkDirective(directive, ancestors);
}
}
private void checkFragmentSpread(FragmentSpread fragmentSpread, List<AbstractRule> rules, List<Node> ancestors) {
for (AbstractRule rule : rules) {
rule.checkFragmentSpread(fragmentSpread);
}
List<AbstractRule> rulesVisitingFragmentSpreads = getRulesVisitingFragmentSpreads(rules);
if (rulesVisitingFragmentSpreads.size() > 0) {
FragmentDefinition fragment = validationContext.getFragment(fragmentSpread.getName());
if (fragment != null && !ancestors.contains(fragment)) {
new LanguageTraversal(ancestors).traverse(fragment, new RulesVisitor(validationContext, rulesVisitingFragmentSpreads, true));
}
}
}
private List<AbstractRule> getRulesVisitingFragmentSpreads(List<AbstractRule> rules) {
List<AbstractRule> result = new ArrayList<>();
for (AbstractRule rule : rules) {
if (rule.isVisitFragmentSpreads()) result.add(rule);
}
return result;
}
private void checkFragmentDefinition(FragmentDefinition fragmentDefinition, List<AbstractRule> rules) {
if (!subVisitor) {
rulesToSkipByUntilNode.put(fragmentDefinition, new ArrayList<>(rulesVisitingFragmentSpreads));
rulesToSkip.addAll(rulesVisitingFragmentSpreads);
}
for (AbstractRule rule : rules) {
if (!subVisitor && (rule.isVisitFragmentSpreads())) continue;
rule.checkFragmentDefinition(fragmentDefinition);
}
}
private void checkOperationDefinition(OperationDefinition operationDefinition, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkOperationDefinition(operationDefinition);
}
}
private void checkSelectionSet(SelectionSet selectionSet, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkSelectionSet(selectionSet);
}
}
private void checkVariable(VariableReference variableReference, List<AbstractRule> rules) {
for (AbstractRule rule : rules) {
rule.checkVariable(variableReference);
}
}
@Override
public void leave(Node node, List<Node> ancestors) {
validationContext.getTraversalContext().leave(node, ancestors);
if (node instanceof Document) {
documentFinished((Document) node);
} else if (node instanceof OperationDefinition) {
leaveOperationDefinition((OperationDefinition) node);
} else if (node instanceof SelectionSet) {
leaveSelectionSet((SelectionSet) node);
}
if (rulesToSkipByUntilNode.containsKey(node)) {
rulesToSkip.removeAll(rulesToSkipByUntilNode.get(node));
rulesToSkipByUntilNode.remove(node);
}
}
private void leaveSelectionSet(SelectionSet selectionSet) {
for (AbstractRule rule : rules) {
rule.leaveSelectionSet(selectionSet);
}
}
private void leaveOperationDefinition(OperationDefinition operationDefinition) {
for (AbstractRule rule : rules) {
rule.leaveOperationDefinition(operationDefinition);
}
}
private void documentFinished(Document document) {
for (AbstractRule rule : rules) {
rule.documentFinished(document);
}
}
}
|
package hudson.plugins.scm.koji;
import hudson.AbortException;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Job;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.scm.koji.client.KojiBuildDownloader;
import hudson.plugins.scm.koji.client.KojiListBuilds;
import hudson.plugins.scm.koji.model.Build;
import hudson.plugins.scm.koji.model.KojiBuildDownloadResult;
import hudson.plugins.scm.koji.model.KojiScmConfig;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static hudson.plugins.scm.koji.Constants.PROCESSED_BUILDS_HISTORY;
import java.io.Serializable;
import java.net.InetAddress;
public class KojiSCM extends SCM implements LoggerHelp, Serializable {
@Extension
public static final KojiScmDescriptor DESCRIPTOR = new KojiScmDescriptor();
private static final Logger LOG = LoggerFactory.getLogger(KojiSCM.class);
private static final boolean verbose = true;
private String kojiTopUrl;
private String kojiDownloadUrl;
private String packageName;
private String arch;
private String tag;
private String excludeNvr;
private String downloadDir;
private boolean cleanDownloadDir;
private boolean dirPerNvr;
private int maxPreviousBuilds;
private transient TaskListener currentListener;
private boolean canLog() {
return (verbose && currentListener != null && currentListener.getLogger() != null);
}
private String host() {
try {
String h = InetAddress.getLocalHost().getHostName();
if (h == null) {
return "null";
} else {
return h;
}
} catch (Exception ex) {
return ex.toString();
}
}
void print(String s) {
try {
currentListener.getLogger().println(s);
} catch (Exception ex) {
LOG.error("During printing of log to TaskListener", ex);
}
}
@Override
public void log(String s) {
LOG.info(s);
if (canLog()) {
print("[KojiSCM][" + host() + "] " + s);
}
}
@Override
public void log(String s, Object o) {
LOG.info(s, o);
if (canLog()) {
print("[KojiSCM][" + host() + "] " + s + ": " + o.toString());
}
}
@Override
public void log(String s, Object... o) {
LOG.info(s, o);
if (canLog()) {
print("[KojiSCM][" + host() + "] " + s);
for (Object object : o) {
print("[KojiSCM] " + object.toString());
}
}
}
@DataBoundConstructor
public KojiSCM(String kojiTopUrl, String kojiDownloadUrl, String packageName, String arch, String tag, String excludeNvr, String downloadDir, boolean cleanDownloadDir, boolean dirPerNvr, int maxPreviousBuilds) {
this.kojiTopUrl = kojiTopUrl;
this.kojiDownloadUrl = kojiDownloadUrl;
this.packageName = packageName;
this.arch = arch;
this.tag = tag;
this.excludeNvr = excludeNvr;
this.downloadDir = downloadDir;
this.cleanDownloadDir = cleanDownloadDir;
this.dirPerNvr = dirPerNvr;
this.maxPreviousBuilds = maxPreviousBuilds;
}
@Override
public ChangeLogParser createChangeLogParser() {
return new KojiChangeLogParser();
}
@Override
public SCMDescriptor<?> getDescriptor() {
return DESCRIPTOR;
}
@Override
public void checkout(Run<?, ?> run, Launcher launcher, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
currentListener = listener;
log("Checking out remote revision");
if (baseline != null && !(baseline instanceof KojiRevisionState)) {
throw new RuntimeException("Expected instance of KojiRevisionState, got: " + baseline);
}
// TODO add some flag to allow checkout on local or remote machine
KojiBuildDownloader downloadWorker = new KojiBuildDownloader(createConfig(),
createNotProcessedNvrPredicate(run.getParent()));
downloadWorker.setListener(listener);
KojiBuildDownloadResult downloadResult = workspace.act(downloadWorker);
if (downloadResult == null) {
log("Checkout finished without any results");
listener.getLogger().println("No updates.");
throw new AbortException("Checkout was invoked but no remote changes found");
}
Build build = downloadResult.getBuild();
log("Checkout downloaded build: {}", build);
String displayName = build.getVersion() + "-" + build.getRelease();
log("Updating the build name to: {}", displayName);
run.setDisplayName(displayName);
log("Saving the nvr of checked out build to history: {} >> {}", build.getNvr(), PROCESSED_BUILDS_HISTORY);
Files.write(
new File(run.getParent().getRootDir(), PROCESSED_BUILDS_HISTORY).toPath(),
Arrays.asList(build.getNvr()),
StandardCharsets.UTF_8,
StandardOpenOption.APPEND, StandardOpenOption.CREATE);
// if there is a changelog file - write it:
if (changelogFile != null) {
log("Saving the build info to changelog file: {}", changelogFile.getAbsolutePath());
new BuildsSerializer().write(build, changelogFile);
}
run.addAction(new KojiEnvVarsAction(build.getNvr(), downloadResult.getRpmsDirectory(),
downloadResult.getRpmFiles().stream().sequential().collect(Collectors.joining(File.pathSeparator))));
}
@Override
public PollingResult compareRemoteRevisionWith(Job<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException {
currentListener = listener;
log("Comparing remote revision with: {}", baseline);
if (!(baseline instanceof KojiRevisionState)) {
throw new RuntimeException("Expected instance of KojiRevisionState, got: " + baseline);
}
KojiListBuilds worker = new KojiListBuilds(createConfig(),
createNotProcessedNvrPredicate(project));
Build build;
if (!DESCRIPTOR.getKojiSCMConfig()) {
// when requiresWorkspaceForPolling is set to false (based on descriptor), worksapce may be null.
// but not always. So If it os not null, the path to it is passed on.
// however, its usage may be invalid. See KojiListBuilds.invole comemnt about BUILD_XML
File wFile = null;
if (workspace != null) {
wFile = new File(workspace.toURI().getPath());
}
build = worker.invoke(wFile, null);
} else {
build = workspace.act(worker);
}
if (build != null) {
log("Got new remote build: {}", build);
return new PollingResult(baseline, new KojiRevisionState(build), PollingResult.Change.INCOMPARABLE);
}
// if we are still here - no remote changes:
log("No remote changes");
return new PollingResult(baseline, null, PollingResult.Change.NONE);
}
@Override
@SuppressWarnings("UseSpecificCatch")
public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
currentListener = listener;
log("Calculating revision for project '{}' from build: {}", run.getParent().getName(), run.getNumber());
KojiRevisionFromBuild worker = new KojiRevisionFromBuild();
FilePath buildWorkspace = new FilePath(run.getRootDir());
Build build = buildWorkspace.act(worker);
if (build != null) {
log("Got revision from build {}: {}", run.getNumber(), build.getNvr());
return new KojiRevisionState(build);
}
log("No build info found");
return new KojiRevisionState(null);
}
@Override
public boolean supportsPolling() {
return true;
}
@Override
public boolean requiresWorkspaceForPolling() {
// this is merchandize - if it is true, then the jobs can not run in parallel (se "Execute concurrent builds if necessary" in project settings)
// when it is false, projects can run inparalel, but pooling operation do not have workspace
return DESCRIPTOR.getKojiSCMConfig();
}
private Predicate<String> createNotProcessedNvrPredicate(Job<?, ?> job) throws IOException {
File processedNvrFile = new File(job.getRootDir(), PROCESSED_BUILDS_HISTORY);
return NotProcessedNvrPredicate.createNotProcessedNvrPredicateFromFile(processedNvrFile);
}
private KojiScmConfig createConfig() {
return new KojiScmConfig(kojiTopUrl, kojiDownloadUrl, packageName, arch, tag, excludeNvr, downloadDir,
cleanDownloadDir, dirPerNvr, maxPreviousBuilds);
}
public String getKojiTopUrl() {
return kojiTopUrl;
}
@DataBoundSetter
public void setKojiTopUrl(String kojiTopUrl) {
this.kojiTopUrl = kojiTopUrl;
}
public String getKojiDownloadUrl() {
return kojiDownloadUrl;
}
@DataBoundSetter
public void setKojiDownloadUrl(String kojiDownloadUrl) {
this.kojiDownloadUrl = kojiDownloadUrl;
}
public String getPackageName() {
return packageName;
}
@DataBoundSetter
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getArch() {
return arch;
}
@DataBoundSetter
public void setArch(String arch) {
this.arch = arch;
}
public String getTag() {
return tag;
}
@DataBoundSetter
public void setTag(String tag) {
this.tag = tag;
}
public String getExcludeNvr() {
return excludeNvr;
}
@DataBoundSetter
public void setExcludeNvr(String excludeNvr) {
this.excludeNvr = excludeNvr;
}
public String getDownloadDir() {
return downloadDir;
}
@DataBoundSetter
public void setDownloadDir(String downloadDir) {
this.downloadDir = downloadDir;
}
public boolean isCleanDownloadDir() {
return cleanDownloadDir;
}
@DataBoundSetter
public void setCleanDownloadDir(boolean cleanDownloadDir) {
this.cleanDownloadDir = cleanDownloadDir;
}
public boolean isDirPerNvr() {
return dirPerNvr;
}
@DataBoundSetter
public void setDirPerNvr(boolean dirPerNvr) {
this.dirPerNvr = dirPerNvr;
}
public int getMaxPreviousBuilds() {
return maxPreviousBuilds;
}
@DataBoundSetter
public void setMaxPreviousBuilds(int maxPreviousBuilds) {
this.maxPreviousBuilds = maxPreviousBuilds;
}
}
|
package info.faceland.bolt;
import info.faceland.hilt.HiltItemStack;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.DoubleChest;
import org.bukkit.block.Hopper;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
public class BoltListener implements Listener {
private final BoltPlugin plugin;
public BoltListener(BoltPlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.getBlockPlaced().getState() instanceof Hopper) {
if (event.getBlockPlaced().getRelative(BlockFace.UP).getState() instanceof Chest) {
if (!BoltAPI.isChestOwner(
((Chest) event.getBlockPlaced().getRelative(BlockFace.UP).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW + "You cannot place hoppers under chests you do not own.");
}
} else if (event.getBlockPlaced().getRelative(BlockFace.UP).getState() instanceof DoubleChest) {
if (!BoltAPI.isChestOwner(
((DoubleChest) event.getBlockPlaced().getRelative(BlockFace.UP).getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.YELLOW + "You cannot place hoppers under chests you do not own.");
}
}
} else if (event.getBlockPlaced().getState() instanceof Chest) {
Chest chest = (Chest) event.getBlockPlaced().getState();
ItemStack old = chest.getInventory().getItem(chest.getInventory().getSize() / 2 - 1);
if (old != null && old.getType() == Material.PAPER) {
HiltItemStack his = new HiltItemStack(old);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
}
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "<Click to Toggle>");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
lore.add(ChatColor.GRAY + "Type /add <playername> while looking");
lore.add(ChatColor.GRAY + "at this chest to allow people to use it.");
hiltItemStack.setLore(lore);
chest.getInventory().setItem(chest.getInventory().getSize() - 1, hiltItemStack);
} else if (event.getBlockPlaced().getState() instanceof InventoryHolder &&
event.getBlockPlaced().getState() instanceof DoubleChest) {
DoubleChest chest = (DoubleChest) event.getBlockPlaced().getState();
ItemStack old = chest.getInventory().getItem(chest.getInventory().getSize() / 2 - 1);
if (old != null && old.getType() == Material.PAPER) {
HiltItemStack his = new HiltItemStack(old);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
chest.getInventory().setItem(chest.getInventory().getSize() / 2 - 1, null);
}
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "< Click to Toggle >");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
List<String> allowedUsers = BoltAPI.getAllowedUsers(chest.getInventory());
if (allowedUsers.size() > 0) {
for (String s : allowedUsers) {
lore.add(ChatColor.WHITE + s);
}
} else {
lore.add(ChatColor.GRAY + "Type /add <playername> while looking at");
lore.add(ChatColor.GRAY + "this chest to allow people to use it.");
}
hiltItemStack.setLore(lore);
chest.getInventory().setItem(chest.getInventory().getSize() - 1, hiltItemStack);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreakEvent(BlockBreakEvent event) {
if (!(event.getBlock().getState() instanceof InventoryHolder)) {
return;
}
if (!BoltAPI.isChestOwner(((InventoryHolder) event.getBlock().getState()).getInventory(),
event.getPlayer().getName())) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You cannot break this chest.");
return;
}
InventoryHolder holder = (InventoryHolder) event.getBlock().getState();
ItemStack itemStack = holder.getInventory().getItem(holder.getInventory().getSize() - 1);
if (itemStack == null) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (!his.getName().startsWith(ChatColor.GOLD + "Chest Status:")) {
return;
}
if (holder.getInventory() instanceof DoubleChestInventory) {
if (holder.getInventory().getItem(holder.getInventory().getSize() / 2 - 1) != null) {
event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(),
holder.getInventory().getItem(
holder.getInventory().getSize() / 2 - 1));
}
HiltItemStack hiltItemStack = new HiltItemStack(Material.PAPER);
hiltItemStack.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
List<String> lore = new ArrayList<>();
lore.add(ChatColor.WHITE + "<Click to Toggle>");
lore.add(ChatColor.GOLD + "Owner: " + ChatColor.WHITE + event.getPlayer().getName());
List<String> allowedUsers = BoltAPI.getAllowedUsers(holder.getInventory());
if (allowedUsers.size() > 0) {
for (String s : allowedUsers) {
lore.add(ChatColor.WHITE + s);
}
} else {
lore.add(ChatColor.GRAY + "Type /add <playername> while looking at");
lore.add(ChatColor.GRAY + "this chest to allow people to use it.");
}
hiltItemStack.setLore(lore);
holder.getInventory().setItem(holder.getInventory().getSize() / 2 - 1, hiltItemStack);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryOpen(InventoryOpenEvent event) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
if (event.getInventory().getHolder() instanceof Chest) {
if (BoltAPI.isChestLocked(event.getInventory(), (Player) event.getPlayer())) {
event.setCancelled(true);
((Player) event.getPlayer()).sendMessage(ChatColor.YELLOW + "This chest is locked.");
}
} else if (event.getInventory().getHolder() instanceof DoubleChest) {
if (BoltAPI.isChestLocked(event.getInventory(), (Player) event.getPlayer())) {
event.setCancelled(true);
((Player) event.getPlayer()).sendMessage(ChatColor.YELLOW + "This chest is locked.");
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) {
return;
}
if (event.getInventory().getHolder() instanceof Chest) {
ItemStack itemStack = event.getCurrentItem();
if (itemStack == null || itemStack.getType() != Material.PAPER) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (BoltAPI.isChestOwner(event.getInventory(), event.getWhoClicked().getName())) {
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked");
event.setCurrentItem(his);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
event.setCurrentItem(his);
}
}
} else if (event.getInventory().getHolder() instanceof DoubleChest) {
ItemStack itemStack = event.getCurrentItem();
if (itemStack == null || itemStack.getType() != Material.PAPER) {
return;
}
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (BoltAPI.isChestOwner(event.getInventory(), event.getWhoClicked().getName())) {
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked");
event.setCurrentItem(his);
} else if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
his.setName(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked");
event.setCurrentItem(his);
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
ItemStack itemStack = event.getEntity().getItemStack();
HiltItemStack his = new HiltItemStack(itemStack);
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.RED + "Locked")) {
event.setCancelled(true);
}
if (his.getName().equals(ChatColor.GOLD + "Chest Status: " + ChatColor.GREEN + "Unlocked")) {
event.setCancelled(true);
}
}
}
|
package info.faceland.mint;
import com.tealcube.minecraft.bukkit.TextUtils;
import com.tealcube.minecraft.bukkit.bullion.GoldDropEvent;
import com.tealcube.minecraft.bukkit.facecore.ui.ActionBarMessage;
import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils;
import com.tealcube.minecraft.bukkit.hilt.HiltItemStack;
import com.tealcube.minecraft.bukkit.shade.apache.commons.lang3.math.NumberUtils;
import com.tealcube.minecraft.bukkit.shade.google.common.base.CharMatcher;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.nunnerycode.mint.MintPlugin;
import java.text.DecimalFormat;
import java.util.*;
public class MintListener implements Listener {
private static final DecimalFormat DF = new DecimalFormat("
private final MintPlugin plugin;
private final Set<UUID> dead;
public MintListener(MintPlugin mintPlugin) {
this.plugin = mintPlugin;
this.dead = new HashSet<>();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onMintEvent(MintEvent mintEvent) {
if (mintEvent.getUuid().equals("")) {
return;
}
UUID uuid;
try {
uuid = UUID.fromString(mintEvent.getUuid());
} catch (IllegalArgumentException e) {
uuid = Bukkit.getPlayer(mintEvent.getUuid()).getUniqueId();
}
Player player = Bukkit.getPlayer(uuid);
if (player == null) {
return;
}
PlayerInventory pi = player.getInventory();
HiltItemStack wallet = null;
ItemStack[] contents = pi.getContents();
for (ItemStack is : contents) {
if (is == null || is.getType() == Material.AIR) {
continue;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
wallet = his;
}
}
if (wallet == null) {
wallet = new HiltItemStack(Material.PAPER);
}
pi.removeItem(wallet);
player.updateInventory();
double b = plugin.getEconomy().getBalance(player);
wallet.setName(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")));
wallet.setLore(TextUtils.args(
TextUtils.color(plugin.getSettings().getStringList("config.wallet.lore")),
new String[][]{{"%amount%", DF.format(b)},
{"%currency%", b == 1.00D ? plugin.getEconomy().currencyNameSingular()
: plugin.getEconomy().currencyNamePlural()}}));
if (pi.getItem(17) != null && pi.getItem(17).getType() != Material.AIR) {
ItemStack old = new HiltItemStack(pi.getItem(17));
pi.setItem(17, wallet);
pi.addItem(old);
} else {
pi.setItem(17, wallet);
}
player.updateInventory();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDeathEvent(final EntityDeathEvent event) {
if (event instanceof PlayerDeathEvent || dead.contains(event.getEntity().getUniqueId())) {
return;
}
dead.add(event.getEntity().getUniqueId());
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
dead.remove(event.getEntity().getUniqueId());
}
}, 20L * 5);
EntityType entityType = event.getEntityType();
double reward = plugin.getSettings().getDouble("rewards." + entityType.name(), 0D);
Location worldSpawn = event.getEntity().getWorld().getSpawnLocation();
Location entityLoc = event.getEntity().getLocation();
double distanceSquared = Math.pow(worldSpawn.getX() - entityLoc.getX(), 2) + Math.pow(worldSpawn.getZ() -
entityLoc.getZ(),
2);
reward += reward * (distanceSquared / Math.pow(10D, 2D))
* plugin.getSettings().getDouble("config.per-ten-blocks-mult", 0.0);
if (reward == 0D) {
return;
}
GoldDropEvent gde = new GoldDropEvent(event.getEntity().getKiller(), event.getEntity(), reward);
Bukkit.getPluginManager().callEvent(gde);
HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET);
his.setName(ChatColor.GOLD + "REWARD!");
his.setLore(Arrays.asList(DF.format(gde.getAmount())));
event.getDrops().add(his);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemPickupEvent(PlayerPickupItemEvent event) {
if (event.isCancelled()) {
return;
}
if (event.getItem() == null || event.getItem().getItemStack() == null) {
return;
}
Item item = event.getItem();
HiltItemStack hiltItemStack = new HiltItemStack(item.getItemStack());
int stacksize = hiltItemStack.getAmount();
if (hiltItemStack.getType() != Material.GOLD_NUGGET) {
return;
}
if (!hiltItemStack.getName().equals(ChatColor.GOLD + "REWARD!")) {
return;
}
String name = item.getCustomName();
if (name == null) {
return;
}
event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.CHICKEN_EGG_POP, 0.8F, 2);
String stripped = ChatColor.stripColor(name);
String replaced = CharMatcher.JAVA_LETTER.removeFrom(stripped).trim();
double amount = stacksize * NumberUtils.toDouble(replaced);
plugin.getEconomy().depositPlayer(event.getPlayer(), amount);
event.getItem().remove();
event.setCancelled(true);
String message = "<dark green>Wallet: <white>" + plugin.getEconomy().format(plugin.getEconomy().getBalance(
event.getPlayer())).replace(" ", ChatColor.GREEN + " ");
ActionBarMessage.send(event.getPlayer(), message);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerDeathEvent(final PlayerDeathEvent event) {
if (dead.contains(event.getEntity().getUniqueId())) {
return;
}
dead.add(event.getEntity().getUniqueId());
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
dead.remove(event.getEntity().getUniqueId());
}
}, 20L * 5);
double amount = plugin.getEconomy().getBalance(event.getEntity());
HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET);
his.setName(ChatColor.GOLD + "REWARD!");
his.setLore(Arrays.asList(DF.format(amount) + ""));
event.getEntity().getWorld().dropItemNaturally(event.getEntity().getLocation(), his);
plugin.getEconomy().withdrawPlayer(event.getEntity().getUniqueId().toString(), amount);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerDropItemEvent(PlayerDropItemEvent event) {
Item item = event.getItemDrop();
ItemStack is = item.getItemStack();
HiltItemStack his = new HiltItemStack(is);
if (!his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) {
return;
}
if (his.getLore().size() < 1) {
return;
}
plugin.getEconomy().setBalance(event.getPlayer().getUniqueId().toString(), 0.00);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawnEvent(ItemSpawnEvent event) {
Material i = event.getEntity().getItemStack().getType();
switch (i) {
case PAPER:
HiltItemStack walletStack = new HiltItemStack(event.getEntity().getItemStack());
if (walletStack.getName()
.equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) {
if (walletStack.getLore().isEmpty()) {
return;
}
String s = walletStack.getLore().get(0);
String stripped = ChatColor.stripColor(s);
String replaced = CharMatcher.JAVA_LETTER.removeFrom(stripped);
double amount = NumberUtils.toDouble(replaced);
HiltItemStack nugget = new HiltItemStack(Material.GOLD_NUGGET);
nugget.setName(ChatColor.GOLD + "REWARD!");
event.getEntity().setItemStack(nugget);
event.getEntity().setCustomName(ChatColor.YELLOW + plugin.getEconomy().format(amount));
event.getEntity().setCustomNameVisible(true);
}
break;
case GOLD_NUGGET:
HiltItemStack nuggetStack = new HiltItemStack(event.getEntity().getItemStack());
if (!nuggetStack.getName().equals(ChatColor.GOLD + "REWARD!") || nuggetStack.getLore().isEmpty()) {
return;
}
String s = nuggetStack.getLore().get(0);
String stripped = ChatColor.stripColor(s);
double amount = NumberUtils.toDouble(stripped);
if (amount <= 0.00D) {
event.setCancelled(true);
return;
}
HiltItemStack nugget = new HiltItemStack(Material.GOLD_NUGGET);
nugget.setName(ChatColor.GOLD + "REWARD!");
event.getEntity().setItemStack(nugget);
event.getEntity().setCustomName(ChatColor.YELLOW + plugin.getEconomy().format(amount));
event.getEntity().setCustomNameVisible(true);
break;
default:
break;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCraftItem(CraftItemEvent event) {
for (ItemStack is : event.getInventory().getMatrix()) {
if (is == null || is.getType() != Material.PAPER) {
continue;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) {
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onInventoryClickEvent(InventoryClickEvent event) {
ItemStack is = event.getCurrentItem();
if (is == null || is.getType() == Material.AIR) {
return;
}
HiltItemStack his = new HiltItemStack(is);
if (his.getLore().size() < 1) {
return;
}
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
event.setCancelled(true);
}
}
@EventHandler
public void onInventoryClose(InventoryCloseEvent event) {
if (!event.getInventory().getName()
.equals(TextUtils.color(plugin.getSettings().getString("language.pawn-shop-name")))) {
return;
}
double value = 0D;
int amountSold = 0;
for (ItemStack itemStack : event.getInventory().getContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
HiltItemStack hiltItemStack = new HiltItemStack(itemStack);
if (hiltItemStack.getName()
.equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) {
continue;
}
List<String> lore = hiltItemStack.getLore();
double amount = plugin.getSettings().getDouble("prices.materials." + hiltItemStack.getType().name(), 0D);
if (!lore.isEmpty()) {
amount += plugin.getSettings().getDouble("prices.options.lore.base-price", 3D);
amount += plugin.getSettings().getDouble("prices.options.lore" + ".per-line", 1D) * lore.size();
}
String strippedName = ChatColor.stripColor(hiltItemStack.getName());
if (plugin.getSettings().isSet("prices.names." + strippedName)) {
value += plugin.getSettings().getDouble("prices.names." + strippedName, 0D) * hiltItemStack.getAmount();
} else {
value += amount * hiltItemStack.getAmount();
}
}
for (HumanEntity entity : event.getViewers()) {
if (!(entity instanceof Player)) {
continue;
}
if (value > 0) {
plugin.getEconomy().depositPlayer((Player) entity, value);
MessageUtils.sendMessage(entity, plugin.getSettings().getString("language.pawn-success"),
new String[][]{{"%amount%", "" + amountSold},
{"%currency%", plugin.getEconomy().format(value)}});
}
}
}
@EventHandler
public void onInventoryPickupItem(InventoryPickupItemEvent event) {
HiltItemStack his = new HiltItemStack(event.getItem().getItemStack());
if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", ""))) ||
his.getName().equals(
ChatColor.GOLD + "REWARD!")) {
event.setCancelled(true);
}
}
}
|
package kalang.compiler;
import java.io.*;
import java.nio.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import kalang.antlr.KalangLexer;
import kalang.antlr.KalangParser;
import kalang.ast.ClassNode;
import kalang.util.AstBuilderFactory;
import kalang.util.TokenStreamFactory;
import org.antlr.v4.runtime.CommonTokenStream;
import static kalang.compiler.CompilePhase.*;
import kalang.util.LexerFactory;
import org.antlr.v4.runtime.TokenStream;
/**
*
* @author Kason Yang <i@kasonyang.com>
*/
public class CompilationUnit {
private KalangLexer lexer;
private KalangParser parser;
private AstBuilder astBuilder;
private SemanticAnalyzer semanticAnalyzer;
private CodeGenerator codeGenerator;
@Nonnull
private ClassNode ast;
private AstLoader astLoader;
private CommonTokenStream tokens;
private int compilingPhase;
private CompileErrorHandler errorHandler;
public CompilationUnit(@Nonnull KalangSource source,@Nonnull AstLoader astLoader) {
this.astLoader = astLoader;
init(source);
}
private void init(KalangSource source){
lexer = createLexer(source.getText());
tokens = createTokenStream(lexer);
parser = createParser(tokens);
astBuilder = createAstBuilder(source, tokens);
astBuilder.importPackage("java.lang");
astBuilder.importPackage("java.util");
ast = astBuilder.getAst();
semanticAnalyzer = new SemanticAnalyzer(source,astLoader);
}
protected CommonTokenStream createTokenStream(KalangLexer lexer){
return TokenStreamFactory.createTokenStream(lexer);
}
protected AstBuilder createAstBuilder(KalangSource source , CommonTokenStream tokens){
return AstBuilderFactory.createAstBuilder(source, tokens);
}
protected void doCompilePhase(int phase){
if(phase==PHASE_INITIALIZE){
}else if(phase==PHASE_PARSING){
parseMeta(errorHandler);
}else if(phase == PHASE_BUILDAST){
parseBody(errorHandler);
}else if(phase==PHASE_SEMANTIC){
semanticAnalysis(errorHandler);
}else if(phase == PHASE_CLASSGEN){
if(codeGenerator==null){
throw new IllegalStateException("CodeGenerator is missing");
}
codeGenerator.generate(ast);
}
}
public void compile(int targetPhase){
while(compilingPhase<targetPhase){
compilingPhase++;
doCompilePhase(compilingPhase);
}
}
protected void parseMeta(CompileErrorHandler semanticErrorHandler){
parse(semanticErrorHandler, AstBuilder.PARSING_PHASE_META);
}
public void parseBody(CompileErrorHandler semanticErrorHandler){
parse(semanticErrorHandler, AstBuilder.PARSING_PHASE_ALL);
}
protected void parse(CompileErrorHandler semanticErrorHandler, int targetParsingPhase) {
astBuilder.setErrorHandler(semanticErrorHandler);
astBuilder.compile(targetParsingPhase,astLoader);
}
protected void semanticAnalysis(CompileErrorHandler handler) {
semanticAnalyzer.setAstSemanticErrorHandler(handler);
semanticAnalyzer.check(ast);
}
@Nonnull
public ClassNode getAst() {
return ast;
}
@Nonnull
public AstBuilder getAstBuilder() {
return astBuilder;
}
@Nonnull
public SemanticAnalyzer getSemanticAnalyzer() {
return semanticAnalyzer;
}
@Nonnull
public AstLoader getAstLoader() {
return astLoader;
}
@Nonnull
public CommonTokenStream getTokenStream() {
return tokens;
}
public CompileErrorHandler getErrorHandler() {
return errorHandler;
}
public void setErrorHandler(CompileErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
public CodeGenerator getCodeGenerator() {
return codeGenerator;
}
public void setCodeGenerator(CodeGenerator codeGenerator) {
this.codeGenerator = codeGenerator;
}
protected KalangLexer createLexer(String source) {
return LexerFactory.createLexer(source);
}
protected KalangParser createParser(TokenStream tokenStream) {
return new KalangParser(tokenStream);
}
public KalangLexer getLexer() {
return lexer;
}
public KalangParser getParser() {
return parser;
}
public CommonTokenStream getTokens() {
return tokens;
}
}
|
package me.doubledutch.pikadb;
import java.util.*;
import org.json.*;
public class ObjectSet{
private Map<String,Map<Integer,Variant>> columnValueMap=new HashMap<String,Map<Integer,Variant>>();
private Set<Integer> oidSet=new LinkedHashSet<Integer>();
private Set<LargeHash> oidHashSet=new LinkedHashSet<LargeHash>();
// TODO: Check performance implications of using linked hash set
private boolean open;
private int matchCounter;
public ObjectSet(boolean open){
this.open=open;
}
public boolean anyObjectsInBloomFilter(LargeHash bloomfilter){
// TODO: look into maintaining a separate set of hashed oid's
for(LargeHash hoid:oidHashSet){
// LargeHash hoid=MurmurHash3.getSelectiveBits(oid);
// if((hoid & bloomfilter) == hoid){
if(bloomfilter.containsHash(hoid)){
return true;
}
}
return false;
}
public boolean isOpen(){
return open;
}
public int getCount(){
return oidSet.size();
}
public int getMatchCount(){
return matchCounter;
}
public void resetMatchCounter(){
matchCounter=0;
}
public boolean contains(Integer oid){
if(open){
return true;
}
if(oidSet.contains(oid)){
matchCounter++;
return true;
}
return false;
}
public void addOID(Integer oid){
// JSONObject obj=new JSONObject();
// objectMap.put(oid,obj)
// if(!oidSet.contains(oid)){
oidSet.add(oid);
oidHashSet.add(MurmurHash3.getSelectiveBits(oid));
// objectList.add(obj);
}
public JSONObject getObject(Integer oid)throws JSONException{
if(!oidSet.contains(oid)){
return null;
}
JSONObject obj=new JSONObject();
for(String key:columnValueMap.keySet()){
Map<Integer,Variant> map=columnValueMap.get(key);
if(map.containsKey(oid)){
Variant v=map.get(oid);
obj.put(key,v.getObjectValue());
}
}
return obj;
// return objectMap.get(oid);
}
public void addVariantList(String columnName,List<Variant> list){
if(!columnValueMap.containsKey(columnName)){
columnValueMap.put(columnName,new HashMap<Integer,Variant>());
}
Map<Integer,Variant> map=columnValueMap.get(columnName);
for(Variant v:list){
Integer oid=v.getOID();
if(!oidSet.contains(oid)){
if(!open){
continue;
}else{
addOID(oid);
map.put(oid,v);
}
}else{
map.put(oid,v);
}
}
}
public void addVariant(String columnName,Variant v){
Integer oid=v.getOID();
if(!oidSet.contains(oid)){
if(!open){
return;
}
addOID(oid);
}
if(!columnValueMap.containsKey(columnName)){
columnValueMap.put(columnName,new HashMap<Integer,Variant>());
}
columnValueMap.get(columnName).put(oid,v);
/*if(!objectMap.containsKey(oid)){
if(!open){
return;
}
addOID(oid);
}
JSONObject obj=objectMap.get(oid);
obj.put(columnName,v.getObjectValue());*/
}
public Collection<Variant> getVariants(String columnName){
if(columnValueMap.containsKey(columnName)){
return columnValueMap.get(columnName).values();
}
return new LinkedList<Variant>();
}
public List<JSONObject> getObjectList()throws JSONException{
// System.out.println("Crafting objects");
List<JSONObject> objectList=new ArrayList<JSONObject>();
for(Integer oid:oidSet){
// System.out.println("Making one");
objectList.add(getObject(oid));
}
return objectList;
}
}
|
package mil.dds.anet.database;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;
import org.joda.time.DateTime;
import org.skife.jdbi.v2.DefaultMapper;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import com.google.common.base.Joiner;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.AuthorizationGroup;
import mil.dds.anet.beans.Organization;
import mil.dds.anet.beans.Organization.OrganizationType;
import mil.dds.anet.beans.Person;
import mil.dds.anet.beans.Task;
import mil.dds.anet.beans.Position;
import mil.dds.anet.beans.Report;
import mil.dds.anet.beans.Report.ReportState;
import mil.dds.anet.beans.ReportPerson;
import mil.dds.anet.beans.ReportSensitiveInformation;
import mil.dds.anet.beans.RollupGraph;
import mil.dds.anet.beans.Tag;
import mil.dds.anet.beans.lists.AbstractAnetBeanList.ReportList;
import mil.dds.anet.beans.search.OrganizationSearchQuery;
import mil.dds.anet.beans.search.ReportSearchQuery;
import mil.dds.anet.database.AdminDao.AdminSettingKeys;
import mil.dds.anet.database.mappers.AuthorizationGroupMapper;
import mil.dds.anet.database.mappers.TaskMapper;
import mil.dds.anet.database.mappers.ReportMapper;
import mil.dds.anet.database.mappers.ReportPersonMapper;
import mil.dds.anet.database.mappers.TagMapper;
import mil.dds.anet.search.sqlite.SqliteReportSearcher;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.Utils;
public class ReportDao implements IAnetDao<Report> {
private static final String[] fields = { "uuid", "state", "createdAt", "updatedAt", "engagementDate",
"locationUuid", "approvalStepUuid", "intent", "exsum", "atmosphere", "cancelledReason",
"advisorOrganizationUuid", "principalOrganizationUuid", "releasedAt",
"atmosphereDetails", "text", "keyOutcomes",
"nextSteps", "authorUuid"};
private static final String tableName = "reports";
public static final String REPORT_FIELDS = DaoUtils.buildFieldAliases(tableName, fields);
private final Handle dbHandle;
private final String weekFormat;
public ReportDao(Handle db) {
this.dbHandle = db;
this.weekFormat = getWeekFormat(DaoUtils.getDbType(db));
}
private String getWeekFormat(DaoUtils.DbType dbType) {
switch (dbType) {
case MSSQL:
return "DATEPART(week, %s)";
case SQLITE:
return "strftime('%%%%W', substr(%s, 1, 10))";
case POSTGRESQL:
return "EXTRACT(WEEK FROM %s)";
default:
throw new RuntimeException("No week format found for " + dbType);
}
}
public ReportList getAll(int pageNum, int pageSize) {
// Return the reports without sensitive information
return getAll(pageNum, pageSize, null);
}
public ReportList getAll(int pageNum, int pageSize, Person user) {
String sql = DaoUtils.buildPagedGetAllSql(DaoUtils.getDbType(dbHandle),
"Reports", "reports join people on reports.\"authorUuid\" = people.uuid", REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS,
"reports.\"createdAt\"");
Query<Report> query = dbHandle.createQuery(sql)
.bind("limit", pageSize)
.bind("offset", pageSize * pageNum)
.map(new ReportMapper());
return ReportList.fromQuery(user, query, pageNum, pageSize);
}
public Report insert(Report r) {
// Create a report without sensitive information
return insert(r, null);
}
public Report insert(Report r, Person user) {
return dbHandle.inTransaction(new TransactionCallback<Report>() {
@Override
public Report inTransaction(Handle conn, TransactionStatus status) throws Exception {
DaoUtils.setInsertFields(r);
//MSSQL requires explicit CAST when a datetime2 might be NULL.
StringBuilder sql = new StringBuilder("/* insertReport */ INSERT INTO reports "
+ "(uuid, state, \"createdAt\", \"updatedAt\", \"locationUuid\", intent, exsum, "
+ "text, \"keyOutcomes\", \"nextSteps\", \"authorUuid\", "
+ "\"engagementDate\", \"releasedAt\", atmosphere, \"cancelledReason\", "
+ "\"atmosphereDetails\", \"advisorOrganizationUuid\", "
+ "\"principalOrganizationUuid\") VALUES "
+ "(:uuid, :state, :createdAt, :updatedAt, :locationUuid, :intent, "
+ ":exsum, :reportText, :keyOutcomes, "
+ ":nextSteps, :authorUuid, ");
if (DaoUtils.isMsSql(dbHandle)) {
sql.append("CAST(:engagementDate AS datetime2), CAST(:releasedAt AS datetime2), ");
} else {
sql.append(":engagementDate, :releasedAt, ");
}
sql.append(":atmosphere, :cancelledReason, :atmosphereDetails, :advisorOrgUuid, :principalOrgUuid)");
dbHandle.createStatement(sql.toString())
.bindFromProperties(r)
.bind("state", DaoUtils.getEnumId(r.getState()))
.bind("atmosphere", DaoUtils.getEnumId(r.getAtmosphere()))
.bind("cancelledReason", DaoUtils.getEnumId(r.getCancelledReason()))
.bind("locationUuid", DaoUtils.getUuid(r.getLocation()))
.bind("authorUuid", DaoUtils.getUuid(r.getAuthor()))
.bind("advisorOrgUuid", DaoUtils.getUuid(r.getAdvisorOrg()))
.bind("principalOrgUuid", DaoUtils.getUuid(r.getPrincipalOrg()))
.execute();
// Write sensitive information (if allowed)
final ReportSensitiveInformation rsi = AnetObjectEngine.getInstance().getReportSensitiveInformationDao().insert(r.getReportSensitiveInformation(), user, r);
r.setReportSensitiveInformation(rsi);
final ReportBatch rb = dbHandle.attach(ReportBatch.class);
if (r.getAttendees() != null) {
//Setify based on attendeeUuid to prevent violations of unique key constraint.
Map<String,ReportPerson> attendeeMap = new HashMap<>();
r.getAttendees().stream().forEach(rp -> attendeeMap.put(rp.getUuid(), rp));
rb.insertReportAttendees(r.getUuid(), new ArrayList<ReportPerson>(attendeeMap.values()));
}
if (r.getAuthorizationGroups() != null) {
rb.insertReportAuthorizationGroups(r.getUuid(), r.getAuthorizationGroups());
}
if (r.getTasks() != null) {
rb.insertReportTasks(r.getUuid(), r.getTasks());
}
if (r.getTags() != null) {
rb.insertReportTags(r.getUuid(), r.getTags());
}
return r;
}
});
}
public interface ReportBatch {
@SqlBatch("INSERT INTO \"reportPeople\" (\"reportUuid\", \"personUuid\", \"isPrimary\") VALUES (:reportUuid, :uuid, :primary)")
void insertReportAttendees(@Bind("reportUuid") String reportUuid,
@BindBean List<ReportPerson> reportPeople);
@SqlBatch("INSERT INTO \"reportAuthorizationGroups\" (\"reportUuid\", \"authorizationGroupUuid\") VALUES (:reportUuid, :uuid)")
void insertReportAuthorizationGroups(@Bind("reportUuid") String reportUuid,
@BindBean List<AuthorizationGroup> authorizationGroups);
@SqlBatch("INSERT INTO \"reportTasks\" (\"reportUuid\", \"taskUuid\") VALUES (:reportUuid, :uuid)")
void insertReportTasks(@Bind("reportUuid") String reportUuid,
@BindBean List<Task> tasks);
@SqlBatch("INSERT INTO \"reportTags\" (\"reportUuid\", \"tagUuid\") VALUES (:reportUuid, :uuid)")
void insertReportTags(@Bind("reportUuid") String reportUuid,
@BindBean List<Tag> tags);
}
@Deprecated
public Report getById(int id) {
// Return the report without sensitive information
return getById(id, null);
}
@Deprecated
public Report getById(int id, Person user) {
Query<Report> query = dbHandle.createQuery("/* getReportById */ SELECT " + REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS
+ "FROM reports, people "
+ "WHERE reports.id = :id "
+ "AND reports.\"authorUuid\" = people.uuid")
.bind("id", id)
.map(new ReportMapper());
List<Report> results = query.list();
if (results.size() == 0) { return null; }
Report r = results.get(0);
r.setUser(user);
return r;
}
public Report getByUuid(String uuid) {
// Return the report without sensitive information
return getByUuid(uuid, null);
}
public Report getByUuid(String uuid, Person user) {
final Report result = dbHandle.createQuery("/* getReportByUuid */ SELECT " + REPORT_FIELDS + ", " + PersonDao.PERSON_FIELDS
+ "FROM reports, people "
+ "WHERE reports.uuid = :uuid "
+ "AND reports.\"authorUuid\" = people.uuid")
.bind("uuid", uuid)
.map(new ReportMapper())
.first();
if (result == null) { return null; }
result.setUser(user);
return result;
}
/** This should always be wrapped in a transaction! But actually it's never used at all. */
public int update(Report r) {
// Update the report without sensitive information
return update(r, null);
}
/** NOTE: this should always be wrapped in a transaction! (If JDBI were able to handle nested calls to inTransaction, we would have
* one inside this method, but it isn't.)
* @param r the report to update, in its updated state
* @param user the user attempting the update, for authorization purposes
* @return the number of rows updated by the final update call (should be 1 in all cases).
*/
public int update(Report r, Person user) {
// Write sensitive information (if allowed)
AnetObjectEngine.getInstance().getReportSensitiveInformationDao().insertOrUpdate(r.getReportSensitiveInformation(), user, r);
DaoUtils.setUpdateFields(r);
StringBuilder sql = new StringBuilder("/* updateReport */ UPDATE reports SET "
+ "state = :state, \"updatedAt\" = :updatedAt, \"locationUuid\" = :locationUuid, "
+ "intent = :intent, exsum = :exsum, text = :reportText, "
+ "\"keyOutcomes\" = :keyOutcomes, \"nextSteps\" = :nextSteps, "
+ "\"approvalStepUuid\" = :approvalStepUuid, ");
if (DaoUtils.isMsSql(dbHandle)) {
sql.append("\"engagementDate\" = CAST(:engagementDate AS datetime2), \"releasedAt\" = CAST(:releasedAt AS datetime2), ");
} else {
sql.append("\"engagementDate\" = :engagementDate, \"releasedAt\" = :releasedAt, ");
}
sql.append("atmosphere = :atmosphere, \"atmosphereDetails\" = :atmosphereDetails, "
+ "\"cancelledReason\" = :cancelledReason, "
+ "\"principalOrganizationUuid\" = :principalOrgUuid, \"advisorOrganizationUuid\" = :advisorOrgUuid "
+ "WHERE uuid = :uuid");
return dbHandle.createStatement(sql.toString())
.bindFromProperties(r)
.bind("state", DaoUtils.getEnumId(r.getState()))
.bind("locationUuid", DaoUtils.getUuid(r.getLocation()))
.bind("authorUuid", DaoUtils.getUuid(r.getAuthor()))
.bind("approvalStepUuid", DaoUtils.getUuid(r.getApprovalStep()))
.bind("atmosphere", DaoUtils.getEnumId(r.getAtmosphere()))
.bind("cancelledReason", DaoUtils.getEnumId(r.getCancelledReason()))
.bind("advisorOrgUuid", DaoUtils.getUuid(r.getAdvisorOrg()))
.bind("principalOrgUuid", DaoUtils.getUuid(r.getPrincipalOrg()))
.execute();
}
public void updateToDraftState(Report r) {
dbHandle.execute("/* UpdateFutureEngagement */ UPDATE reports SET state = ? "
+ "WHERE uuid = ?", DaoUtils.getEnumId(ReportState.DRAFT), r.getUuid());
}
public int addAttendeeToReport(ReportPerson rp, Report r) {
return dbHandle.createStatement("/* addReportAttendee */ INSERT INTO \"reportPeople\" "
+ "(\"personUuid\", \"reportUuid\", \"isPrimary\") VALUES (:personUuid, :reportUuid, :isPrimary)")
.bind("personUuid", rp.getUuid())
.bind("reportUuid", r.getUuid())
.bind("isPrimary", rp.isPrimary())
.execute();
}
public int removeAttendeeFromReport(Person p, Report r) {
return dbHandle.createStatement("/* deleteReportAttendee */ DELETE FROM \"reportPeople\" "
+ "WHERE \"reportUuid\" = :reportUuid AND \"personUuid\" = :personUuid")
.bind("reportUuid", r.getUuid())
.bind("personUuid", p.getUuid())
.execute();
}
public int updateAttendeeOnReport(ReportPerson rp, Report r) {
return dbHandle.createStatement("/* updateAttendeeOnReport*/ UPDATE \"reportPeople\" "
+ "SET \"isPrimary\" = :isPrimary WHERE \"reportUuid\" = :reportUuid AND \"personUuid\" = :personUuid")
.bind("reportUuid", r.getUuid())
.bind("personUuid", rp.getUuid())
.bind("isPrimary", rp.isPrimary())
.execute();
}
public int addAuthorizationGroupToReport(AuthorizationGroup a, Report r) {
return dbHandle.createStatement("/* addAuthorizationGroupToReport */ INSERT INTO \"reportAuthorizationGroups\" (\"authorizationGroupUuid\", \"reportUuid\") "
+ "VALUES (:authorizationGroupUuid, :reportUuid)")
.bind("reportUuid", r.getUuid())
.bind("authorizationGroupUuid", a.getUuid())
.execute();
}
public int removeAuthorizationGroupFromReport(AuthorizationGroup a, Report r) {
return dbHandle.createStatement("/* removeAuthorizationGroupFromReport*/ DELETE FROM \"reportAuthorizationGroups\" "
+ "WHERE \"reportUuid\" = :reportUuid AND \"authorizationGroupUuid\" = :authorizationGroupUuid")
.bind("reportUuid", r.getUuid())
.bind("authorizationGroupUuid", a.getUuid())
.execute();
}
public int addTaskToReport(Task p, Report r) {
return dbHandle.createStatement("/* addTaskToReport */ INSERT INTO \"reportTasks\" (\"taskUuid\", \"reportUuid\") "
+ "VALUES (:taskUuid, :reportUuid)")
.bind("reportUuid", r.getUuid())
.bind("taskUuid", p.getUuid())
.execute();
}
public int removeTaskFromReport(Task p, Report r) {
return dbHandle.createStatement("/* removeTaskFromReport*/ DELETE FROM \"reportTasks\" "
+ "WHERE \"reportUuid\" = :reportUuid AND \"taskUuid\" = :taskUuid")
.bind("reportUuid", r.getUuid())
.bind("taskUuid", p.getUuid())
.execute();
}
public int addTagToReport(Tag t, Report r) {
return dbHandle.createStatement("/* addTagToReport */ INSERT INTO \"reportTags\" (\"reportUuid\", \"tagUuid\") "
+ "VALUES (:reportUuid, :tagUuid)")
.bind("reportUuid", r.getUuid())
.bind("tagUuid", t.getUuid())
.execute();
}
public int removeTagFromReport(Tag t, Report r) {
return dbHandle.createStatement("/* removeTagFromReport */ DELETE FROM \"reportTags\" "
+ "WHERE \"reportUuid\" = :reportUuid AND \"tagUuid\" = :tagUuid")
.bind("reportUuid", r.getUuid())
.bind("tagUuid", t.getUuid())
.execute();
}
public List<ReportPerson> getAttendeesForReport(String reportUuid) {
return dbHandle.createQuery("/* getAttendeesForReport */ SELECT " + PersonDao.PERSON_FIELDS
+ ", \"reportPeople\".\"isPrimary\" FROM \"reportPeople\" "
+ "LEFT JOIN people ON \"reportPeople\".\"personUuid\" = people.uuid "
+ "WHERE \"reportPeople\".\"reportUuid\" = :reportUuid")
.bind("reportUuid", reportUuid)
.map(new ReportPersonMapper())
.list();
}
public List<AuthorizationGroup> getAuthorizationGroupsForReport(String reportUuid) {
return dbHandle.createQuery("/* getAuthorizationGroupsForReport */ SELECT * FROM \"authorizationGroups\", \"reportAuthorizationGroups\" "
+ "WHERE \"reportAuthorizationGroups\".\"reportUuid\" = :reportUuid "
+ "AND \"reportAuthorizationGroups\".\"authorizationGroupUuid\" = \"authorizationGroups\".uuid")
.bind("reportUuid", reportUuid)
.map(new AuthorizationGroupMapper())
.list();
}
public List<Task> getTasksForReport(Report report) {
return dbHandle.createQuery("/* getTasksForReport */ SELECT * FROM tasks, \"reportTasks\" "
+ "WHERE \"reportTasks\".\"reportUuid\" = :reportUuid "
+ "AND \"reportTasks\".\"taskUuid\" = tasks.uuid")
.bind("reportUuid", report.getUuid())
.map(new TaskMapper())
.list();
}
public List<Tag> getTagsForReport(String reportUuid) {
return dbHandle.createQuery("/* getTagsForReport */ SELECT * FROM \"reportTags\" "
+ "INNER JOIN tags ON \"reportTags\".\"tagUuid\" = tags.uuid "
+ "WHERE \"reportTags\".\"reportUuid\" = :reportUuid "
+ "ORDER BY tags.name")
.bind("reportUuid", reportUuid)
.map(new TagMapper())
.list();
}
//Does an unauthenticated search. This will never return any DRAFT or REJECTED reports
public ReportList search(ReportSearchQuery query) {
return search(query, null);
}
public ReportList search(ReportSearchQuery query, Person user) {
return AnetObjectEngine.getInstance().getSearcher().getReportSearcher()
.runSearch(query, dbHandle, user);
}
/*
* Deletes a given report from the database.
* Ensures consistency by removing all references to a report before deleting a report.
*/
public void deleteReport(final Report report) {
dbHandle.inTransaction(new TransactionCallback<Void>() {
public Void inTransaction(Handle conn, TransactionStatus status) throws Exception {
// Delete tags
dbHandle.execute("/* deleteReport.tags */ DELETE FROM \"reportTags\" where \"reportUuid\" = ?", report.getUuid());
//Delete tasks
dbHandle.execute("/* deleteReport.tasks */ DELETE FROM \"reportTasks\" where \"reportUuid\" = ?", report.getUuid());
//Delete attendees
dbHandle.execute("/* deleteReport.attendees */ DELETE FROM \"reportPeople\" where \"reportUuid\" = ?", report.getUuid());
//Delete comments
dbHandle.execute("/* deleteReport.comments */ DELETE FROM comments where \"reportUuid\" = ?", report.getUuid());
//Delete \"approvalActions\"
dbHandle.execute("/* deleteReport.actions */ DELETE FROM \"approvalActions\" where \"reportUuid\" = ?", report.getUuid());
//Delete relation to authorization groups
dbHandle.execute("/* deleteReport.\"authorizationGroups\" */ DELETE FROM \"reportAuthorizationGroups\" where \"reportUuid\" = ?", report.getUuid());
//Delete report
dbHandle.execute("/* deleteReport.report */ DELETE FROM reports where uuid = ?", report.getUuid());
return null;
}
});
}
private DateTime getRollupEngagmentStart(DateTime start) {
String maxReportAgeStr = AnetObjectEngine.getInstance().getAdminSetting(AdminSettingKeys.DAILY_ROLLUP_MAX_REPORT_AGE_DAYS);
if (maxReportAgeStr == null) {
throw new WebApplicationException("Missing Admin Setting for " + AdminSettingKeys.DAILY_ROLLUP_MAX_REPORT_AGE_DAYS);
}
Integer maxReportAge = Integer.parseInt(maxReportAgeStr);
return start.minusDays(maxReportAge);
}
/* Generates the Rollup Graph for a particular Organization Type, starting at the root of the org hierarchy */
public List<RollupGraph> getDailyRollupGraph(DateTime start, DateTime end, OrganizationType orgType, Map<String, Organization> nonReportingOrgs) {
final List<Map<String, Object>> results = rollupQuery(start, end, orgType, null, false);
final Map<String,Organization> orgMap = AnetObjectEngine.getInstance().buildTopLevelOrgHash(orgType);
return generateRollupGraphFromResults(results, orgMap, nonReportingOrgs);
}
/* Generates a Rollup graph for a particular organization. Starting with a given parent Organization */
public List<RollupGraph> getDailyRollupGraph(DateTime start, DateTime end, String parentOrgUuid, OrganizationType orgType, Map<String, Organization> nonReportingOrgs) {
List<Organization> orgList = null;
final Map<String, Organization> orgMap;
if (!parentOrgUuid.equals(Organization.DUMMY_ORG_UUID)) {
//doing this as two separate queries because I do need all the information about the organizations
OrganizationSearchQuery query = new OrganizationSearchQuery();
query.setParentOrgUuid(parentOrgUuid);
query.setParentOrgRecursively(true);
query.setPageSize(Integer.MAX_VALUE);
orgList = AnetObjectEngine.getInstance().getOrganizationDao().search(query).getList();
Optional<Organization> parentOrg = orgList.stream().filter(o -> o.getUuid().equals(parentOrgUuid)).findFirst();
if (parentOrg.isPresent() == false) {
throw new WebApplicationException("No such organization with uuid " + parentOrgUuid, Status.NOT_FOUND);
}
orgMap = Utils.buildParentOrgMapping(orgList, parentOrgUuid);
} else {
orgMap = new HashMap<String, Organization>(); //guaranteed to match no orgs!
}
final List<Map<String,Object>> results = rollupQuery(start, end, orgType, orgList, parentOrgUuid.equals(Organization.DUMMY_ORG_UUID));
return generateRollupGraphFromResults(results, orgMap, nonReportingOrgs);
}
/* Generates Advisor Report Insights for Organizations */
public List<Map<String,Object>> getAdvisorReportInsights(DateTime start, DateTime end, String orgUuid) {
final Map<String,Object> sqlArgs = new HashMap<String,Object>();
StringBuilder sql = new StringBuilder();
sql.append("/* AdvisorReportInsightsQuery */ ");
sql.append("SELECT ");
sql.append("CASE WHEN a.\"organizationUuid\" IS NULL THEN b.\"organizationUuid\" ELSE a.\"organizationUuid\" END AS \"organizationUuid\",");
sql.append("CASE WHEN a.\"organizationShortName\" IS NULL THEN b.\"organizationShortName\" ELSE a.\"organizationShortName\" END AS \"organizationShortName\",");
sql.append("%1$s");
sql.append("%2$s");
sql.append("CASE WHEN a.week IS NULL THEN b.week ELSE a.week END AS week,");
sql.append("CASE WHEN a.\"nrReportsSubmitted\" IS NULL THEN 0 ELSE a.\"nrReportsSubmitted\" END AS \"nrReportsSubmitted\",");
sql.append("CASE WHEN b.\"nrEngagementsAttended\" IS NULL THEN 0 ELSE b.\"nrEngagementsAttended\" END AS \"nrEngagementsAttended\"");
sql.append(" FROM (");
sql.append("SELECT ");
sql.append("organizations.uuid AS \"organizationUuid\",");
sql.append("organizations.\"shortName\" AS \"organizationShortName\",");
sql.append("%3$s");
sql.append("%4$s");
sql.append(" " + String.format(weekFormat, "reports.\"createdAt\"") + " AS week,");
sql.append("COUNT(reports.\"authorUuid\") AS \"nrReportsSubmitted\"");
sql.append(" FROM ");
sql.append("positions,");
sql.append("reports,");
sql.append("%5$s");
sql.append("organizations");
sql.append(" WHERE positions.\"currentPersonUuid\" = reports.\"authorUuid\"");
sql.append(" %6$s");
sql.append(" AND reports.\"advisorOrganizationUuid\" = organizations.uuid");
sql.append(" AND positions.type = :positionAdvisor");
sql.append(" AND reports.state IN ( :reportReleased, :reportPending, :reportDraft )");
sql.append(" AND reports.\"createdAt\" BETWEEN :startDate and :endDate");
sql.append(" %11$s");
sql.append(" GROUP BY ");
sql.append("organizations.uuid,");
sql.append("organizations.\"shortName\",");
sql.append("%7$s");
sql.append("%8$s");
sql.append(" " + String.format(weekFormat, "reports.\"createdAt\""));
sql.append(") a");
sql.append(" FULL OUTER JOIN (");
sql.append("SELECT ");
sql.append("organizations.uuid AS \"organizationUuid\",");
sql.append("organizations.\"shortName\" AS \"organizationShortName\",");
sql.append("%3$s");
sql.append("%4$s");
sql.append(" " + String.format(weekFormat, "reports.\"engagementDate\"") + " AS week,");
sql.append("COUNT(\"reportPeople\".\"personUuid\") AS \"nrEngagementsAttended\"");
sql.append(" FROM ");
sql.append("positions,");
sql.append("%5$s");
sql.append("reports,");
sql.append("\"reportPeople\",");
sql.append("organizations");
sql.append(" WHERE positions.\"currentPersonUuid\" = \"reportPeople\".personUuid");
sql.append(" %6$s");
sql.append(" AND \"reportPeople\".\"reportUuid\" = reports.uuid");
sql.append(" AND reports.\"advisorOrganizationUuid\" = organizations.uuid");
sql.append(" AND positions.type = :positionAdvisor");
sql.append(" AND reports.state IN ( :reportReleased, :reportPending, :reportDraft )");
sql.append(" AND reports.\"engagementDate\" BETWEEN :startDate and :endDate");
sql.append(" %11$s");
sql.append(" GROUP BY ");
sql.append("organizations.uuid,");
sql.append("organizations.\"shortName\",");
sql.append("%7$s");
sql.append("%8$s");
sql.append(" " + String.format(weekFormat, "reports.\"engagementDate\""));
sql.append(") b");
sql.append(" ON ");
sql.append(" a.\"organizationUuid\" = b.\"organizationUuid\"");
sql.append(" %9$s");
sql.append(" AND a.week = b.week");
sql.append(" ORDER BY ");
sql.append("\"organizationShortName\",");
sql.append("%10$s");
sql.append("week;");
final Object[] fmtArgs;
if (!Organization.DUMMY_ORG_UUID.equals(orgUuid)) {
fmtArgs = new String[] {
"CASE WHEN a.\"personUuid\" IS NULL THEN b.\"personUuid\" ELSE a.\"personUuid\" END AS \"personUuid\",",
"CASE WHEN a.name IS NULL THEN b.name ELSE a.name END AS name,",
"people.uuid AS \"personUuid\",",
"people.name AS name,",
"people,",
"AND positions.\"currentPersonUuid\" = people.uuid",
"people.uuid,",
"people.name,",
"AND a.\"personUuid\" = b.\"personUuid\"",
"name,",
"AND organizations.uuid = :organizationUuid"};
sqlArgs.put("organizationUuid", orgUuid);
} else {
fmtArgs = new String[] {
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""};
}
sqlArgs.put("startDate", start);
sqlArgs.put("endDate", end);
sqlArgs.put("positionAdvisor", Position.PositionType.ADVISOR.ordinal());
sqlArgs.put("reportDraft", ReportState.DRAFT.ordinal());
sqlArgs.put("reportPending", ReportState.PENDING_APPROVAL.ordinal());
sqlArgs.put("reportReleased", ReportState.RELEASED.ordinal());
return dbHandle.createQuery(String.format(sql.toString(), fmtArgs))
.bindFromMap(sqlArgs)
.map(new DefaultMapper(false))
.list();
}
/** Helper method that builds and executes the daily rollup query
* Handles both MsSql and Sqlite
* Searching for just all reports and for reports in certain organizations.
* @param orgType: the type of organization to be looking for
* @param orgs: the list of orgs for whose reports to find, null means all
* @param missingOrgReports: true if we want to look for reports specifically with NULL org uuid's.
*/
private List<Map<String,Object>> rollupQuery(DateTime start,
DateTime end,
OrganizationType orgType,
List<Organization> orgs,
boolean missingOrgReports) {
String orgColumn = String.format("\"%s\"", orgType == OrganizationType.ADVISOR_ORG ? "advisorOrganizationUuid" : "principalOrganizationUuid");
Map<String,Object> sqlArgs = new HashMap<String,Object>();
StringBuilder sql = new StringBuilder();
sql.append("/* RollupQuery */ SELECT " + orgColumn + " as \"orgUuid\", state, count(*) AS count ");
sql.append("FROM reports WHERE ");
// NOTE: more date-comparison work here that might be worth abstracting, but might not
if (DaoUtils.getDbType(dbHandle) != DaoUtils.DbType.SQLITE) {
sql.append("\"releasedAt\" >= :startDate and \"releasedAt\" < :endDate "
+ "AND \"engagementDate\" > :engagementDateStart ");
sqlArgs.put("startDate", start);
sqlArgs.put("endDate", end.plusMillis(1));
sqlArgs.put("engagementDateStart", getRollupEngagmentStart(start));
} else {
sql.append("\"releasedAt\" >= DateTime(:startDate) AND \"releasedAt\" <= DateTime(:endDate) "
+ "AND \"engagementDate\" > DateTime(:engagementDateStart) ");
sqlArgs.put("startDate", SqliteReportSearcher.sqlitePattern.print(start));
sqlArgs.put("endDate", SqliteReportSearcher.sqlitePattern.print(end));
sqlArgs.put("engagementDateStart", SqliteReportSearcher.sqlitePattern.print(getRollupEngagmentStart(start)));
}
if (orgs != null) {
List<String> sqlBind = new LinkedList<String>();
int orgNum = 0;
for (Organization o : orgs) {
sqlArgs.put("orgUuid" + orgNum, o.getUuid());
sqlBind.add(":orgUuid" + orgNum);
orgNum++;
}
String orgInSql = Joiner.on(',').join(sqlBind);
sql.append("AND " + orgColumn + " IN (" + orgInSql + ") ");
} else if (missingOrgReports) {
sql.append(" AND " + orgColumn + " IS NULL ");
}
sql.append("GROUP BY " + orgColumn + ", state");
return dbHandle.createQuery(sql.toString())
.bindFromMap(sqlArgs)
.map(new DefaultMapper(false))
.list();
}
/* Given the results from the database on the number of reports grouped by organization
* And the map of each organization to the organization that their reports roll up to
* this method returns the final rollup graph information.
*/
private List<RollupGraph> generateRollupGraphFromResults(List<Map<String, Object>> dbResults, Map<String, Organization> orgMap, Map<String, Organization> nonReportingOrgs) {
final Map<String, Map<ReportState,Integer>> rollup = new HashMap<>();
for (Map<String,Object> result : dbResults) {
final String orgUuid = (String) result.get("orgUuid");
if (nonReportingOrgs.containsKey(orgUuid)) {
// Skip non-reporting organizations
continue;
}
final Integer count = ((Number) result.get("count")).intValue();
final ReportState state = ReportState.values()[(Integer) result.get("state")];
final String parentOrgUuid = DaoUtils.getUuid(orgMap.get(orgUuid));
Map<ReportState,Integer> orgBar = rollup.get(parentOrgUuid);
if (orgBar == null) {
orgBar = new HashMap<ReportState,Integer>();
rollup.put(parentOrgUuid, orgBar);
}
orgBar.put(state, Utils.orIfNull(orgBar.get(state), 0) + count);
}
// Add all (top-level) organizations without any reports
for (final Map.Entry<String, Organization> entry : orgMap.entrySet()) {
final String orgUuid = entry.getKey();
if (nonReportingOrgs.containsKey(orgUuid)) {
// Skip non-reporting organizations
continue;
}
final String parentOrgUuid = DaoUtils.getUuid(orgMap.get(orgUuid));
if (!rollup.keySet().contains(parentOrgUuid)) {
final Map<ReportState, Integer> orgBar = new HashMap<ReportState, Integer>();
orgBar.put(ReportState.RELEASED, 0);
orgBar.put(ReportState.CANCELLED, 0);
rollup.put(parentOrgUuid, orgBar);
}
}
final List<RollupGraph> result = new LinkedList<RollupGraph>();
for (Map.Entry<String, Map<ReportState,Integer>> entry : rollup.entrySet()) {
Map<ReportState,Integer> values = entry.getValue();
RollupGraph bar = new RollupGraph();
bar.setOrg(orgMap.get(entry.getKey()));
bar.setReleased(Utils.orIfNull(values.get(ReportState.RELEASED), 0));
bar.setCancelled(Utils.orIfNull(values.get(ReportState.CANCELLED), 0));
result.add(bar);
}
return result;
}
}
|
package net.malisis.core.util;
import net.malisis.core.block.BoundingBoxType;
import net.malisis.core.block.MalisisBlock;
import net.malisis.core.util.chunkcollision.IChunkCollidable;
import net.minecraft.block.Block;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
/**
* @author Ordinastie
*
*/
public class AABBUtils
{
public static enum Axis
{
X, Y, Z
};
private static int[] cos = { 1, 0, -1, 0 };
private static int[] sin = { 0, 1, 0, -1 };
public static AxisAlignedBB empty()
{
return empty(new BlockPos(0, 0, 0));
}
public static AxisAlignedBB empty(BlockPos pos)
{
return new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX(), pos.getY(), pos.getZ());
}
public static AxisAlignedBB identity()
{
return identity(new BlockPos(0, 0, 0));
}
public static AxisAlignedBB identity(BlockPos pos)
{
return new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1);
}
public static AxisAlignedBB[] identities()
{
return identities(new BlockPos(0, 0, 0));
}
public static AxisAlignedBB[] identities(BlockPos pos)
{
return new AxisAlignedBB[] { identity(pos) };
}
public static AxisAlignedBB copy(AxisAlignedBB aabb)
{
return new AxisAlignedBB(aabb.minX, aabb.minY, aabb.minZ, aabb.maxX, aabb.maxY, aabb.maxZ);
}
/**
* Rotate the {@link AxisAlignedBB} based on the specified direction.<br>
* Assumes {@link ForgeDirection#NORTH} to be the default non rotated direction.<br>
*
*
* @param aabb the aabb
* @param dir the dir
* @return the axis aligned bb
*/
public static AxisAlignedBB rotate(AxisAlignedBB aabb, EnumFacing dir)
{
return rotate(aabb, EnumFacingUtils.getRotationCount(dir));
}
public static AxisAlignedBB[] rotate(AxisAlignedBB[] aabbs, EnumFacing dir)
{
return rotate(aabbs, EnumFacingUtils.getRotationCount(dir));
}
public static AxisAlignedBB[] rotate(AxisAlignedBB[] aabbs, int angle)
{
for (int i = 0; i < aabbs.length; i++)
aabbs[i] = rotate(aabbs[i], angle);
return aabbs;
}
public static AxisAlignedBB rotate(AxisAlignedBB aabb, int angle)
{
return rotate(aabb, angle, Axis.Y);
}
public static AxisAlignedBB rotate(AxisAlignedBB aabb, int angle, Axis axis)
{
if (aabb == null)
return null;
int a = -angle & 3;
int s = sin[a];
int c = cos[a];
aabb = aabb.offset(-0.5F, -0.5F, -0.5F);
double minX = aabb.minX;
double minY = aabb.minY;
double minZ = aabb.minZ;
double maxX = aabb.maxX;
double maxY = aabb.maxY;
double maxZ = aabb.maxZ;
if (axis == Axis.X)
{
minY = (aabb.minY * c) - (aabb.minZ * s);
maxY = (aabb.maxY * c) - (aabb.maxZ * s);
minZ = (aabb.minY * s) + (aabb.minZ * c);
maxZ = (aabb.maxY * s) + (aabb.maxZ * c);
}
if (axis == Axis.Y)
{
minX = (aabb.minX * c) - (aabb.minZ * s);
maxX = (aabb.maxX * c) - (aabb.maxZ * s);
minZ = (aabb.minX * s) + (aabb.minZ * c);
maxZ = (aabb.maxX * s) + (aabb.maxZ * c);
}
if (axis == Axis.Z)
{
minX = (aabb.minX * c) - (aabb.minY * s);
maxX = (aabb.maxX * c) - (aabb.maxY * s);
minY = (aabb.minX * s) + (aabb.minY * c);
maxY = (aabb.maxX * s) + (aabb.maxY * c);
}
aabb = new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ);
aabb = aabb.offset(0.5F, 0.5F, 0.5F);
return aabb;
}
public static AxisAlignedBB readFromNBT(NBTTagCompound tag)
{
return new AxisAlignedBB(tag.getDouble("minX"), tag.getDouble("minY"), tag.getDouble("minZ"), tag.getDouble("maxX"),
tag.getDouble("maxY"), tag.getDouble("maxZ"));
}
public static void writeToNBT(NBTTagCompound tag, AxisAlignedBB aabb)
{
if (aabb == null)
return;
tag.setDouble("minX", aabb.minX);
tag.setDouble("minY", aabb.minY);
tag.setDouble("minZ", aabb.minZ);
tag.setDouble("maxX", aabb.maxX);
tag.setDouble("maxY", aabb.maxY);
tag.setDouble("maxZ", aabb.maxZ);
}
/**
* Gets a {@link AxisAlignedBB} that englobes the passed {@code AxisAlignedBB}.
*
* @param aabbs the aabbs
* @return the axis aligned bb
*/
public static AxisAlignedBB combine(AxisAlignedBB[] aabbs)
{
if (aabbs == null || aabbs.length == 0)
return null;
AxisAlignedBB ret = null;
for (AxisAlignedBB aabb : aabbs)
{
if (ret == null)
ret = aabb;
else if (aabb != null)
ret.union(aabb);
}
return ret;
}
/**
* Offsets the passed {@link AxisAlignedBB}s by the specified coordinates.
*
* @param x the x
* @param y the y
* @param z the z
* @param aabbs the aabbs
*/
public static AxisAlignedBB[] offset(double x, double y, double z, AxisAlignedBB... aabbs)
{
return offset(new BlockPos(x, y, z), aabbs);
}
public static AxisAlignedBB offset(BlockPos pos, AxisAlignedBB aabb)
{
return aabb.offset(pos.getX(), pos.getY(), pos.getZ());
}
public static AxisAlignedBB[] offset(BlockPos pos, AxisAlignedBB... aabbs)
{
if (aabbs == null)
return null;
for (int i = 0; i < aabbs.length; i++)
if (aabbs[i] != null)
aabbs[i] = aabbs[i].offset(pos.getX(), pos.getY(), pos.getZ());
return aabbs;
}
public static boolean isColliding(AxisAlignedBB aabb, AxisAlignedBB[] aabbs)
{
return isColliding(new AxisAlignedBB[] { aabb }, aabbs);
}
public static boolean isColliding(AxisAlignedBB[] aabbs, AxisAlignedBB aabb)
{
return isColliding(aabbs, new AxisAlignedBB[] { aabb });
}
/**
* Checks if a group of {@link AxisAlignedBB} is colliding with another one.
*
* @param aabbs1 the aabbs1
* @param aabbs2 the aabbs2
* @return true, if is colliding
*/
public static boolean isColliding(AxisAlignedBB[] aabbs1, AxisAlignedBB[] aabbs2)
{
for (AxisAlignedBB aabb1 : aabbs1)
{
if (aabb1 != null)
{
for (AxisAlignedBB aabb2 : aabbs2)
if (aabb2 != null && aabb1.intersectsWith(aabb2))
return true;
}
}
return false;
}
/**
* Gets the collision bounding boxes.
*
* @param world the world
* @param block the block
* @param x the x
* @param y the y
* @param z the z
* @return the collision bounding boxes
*/
public static AxisAlignedBB[] getCollisionBoundingBoxes(World world, Block block, BlockPos pos)
{
return getCollisionBoundingBoxes(world, new MBlockState(pos, block), false);
}
/**
* Gets the collision bounding boxes for the block.
*
* @param world the world
* @param block the block
* @param x the x
* @param y the y
* @param z the z
* @param offset if true, the boxes are offset by the coordinate
* @return the collision bounding boxes
*/
public static AxisAlignedBB[] getCollisionBoundingBoxes(World world, Block block, BlockPos pos, boolean offset)
{
return getCollisionBoundingBoxes(world, new MBlockState(pos, block), offset);
}
/**
* Gets the collision bounding boxes.
*
* @param world the world
* @param state the state
* @return the collision bounding boxes
*/
public static AxisAlignedBB[] getCollisionBoundingBoxes(World world, MBlockState state)
{
return getCollisionBoundingBoxes(world, state, false);
}
/**
* Gets the collision bounding boxes for the state.
*
* @param world the world
* @param state the state
* @return the collision bounding boxes
*/
public static AxisAlignedBB[] getCollisionBoundingBoxes(World world, MBlockState state, boolean offset)
{
AxisAlignedBB[] aabbs = new AxisAlignedBB[0];
if (state.getBlock() instanceof IChunkCollidable)
aabbs = ((IChunkCollidable) state.getBlock()).getBoundingBox(world, state.getPos(), BoundingBoxType.CHUNKCOLLISION);
else if (state.getBlock() instanceof MalisisBlock)
aabbs = ((MalisisBlock) state.getBlock()).getBoundingBox(world, state.getPos(), BoundingBoxType.CHUNKCOLLISION);
else
{
AxisAlignedBB aabb = state.getBlock().getCollisionBoundingBox(world, state.getPos(), state.getBlockState());
if (aabb != null)
aabbs = new AxisAlignedBB[] { aabb.offset(-state.getX(), -state.getY(), -state.getZ()) };
}
if (offset)
AABBUtils.offset(state.getX(), state.getY(), state.getZ(), aabbs);
return aabbs;
}
}
|
package nl.wiegman.home.klimaat;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Klimaat {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false, unique = true)
private Date datumtijd;
@Column(precision = 4, scale = 2)
private BigDecimal temperatuur;
@Column(precision = 4, scale = 1)
private BigDecimal luchtvochtigheid;
@JsonIgnore
@ManyToOne(optional = false)
private KlimaatSensor klimaatSensor;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public BigDecimal getTemperatuur() {
return temperatuur;
}
public void setTemperatuur(BigDecimal temperatuur) {
this.temperatuur = temperatuur;
}
public BigDecimal getLuchtvochtigheid() {
return luchtvochtigheid;
}
public void setLuchtvochtigheid(BigDecimal luchtvochtigheid) {
this.luchtvochtigheid = luchtvochtigheid;
}
public Date getDatumtijd() {
return datumtijd;
}
public void setDatumtijd(Date datumtijd) {
this.datumtijd = datumtijd;
}
public KlimaatSensor getKlimaatSensor() {
return klimaatSensor;
}
public void setKlimaatSensor(KlimaatSensor klimaatSensor) {
this.klimaatSensor = klimaatSensor;
}
}
|
package org.apache.maven.wrapper;
/**
* @author <a href="mailto:konstantin.sobolev@gmail.com">Konstantin Sobolev</a>
*/
public class Logger {
private static final boolean VERBOSE = "true".equalsIgnoreCase(System.getenv(MavenWrapperMain.MVNW_VERBOSE));
public static void info(String msg) {
if (VERBOSE) {
System.out.println(msg);
}
}
public static void warn(String msg) {
System.out.println(msg);
}
}
|
package org.concord.energy3d.model;
import java.awt.geom.Path2D;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.scene.Scene.TextureMode;
import org.concord.energy3d.scene.SceneManager;
import org.concord.energy3d.shapes.AngleAnnotation;
import org.concord.energy3d.shapes.SizeAnnotation;
import org.concord.energy3d.util.MeshLib;
import org.concord.energy3d.util.PolygonWithHoles;
import org.concord.energy3d.util.SelectUtil;
import org.concord.energy3d.util.Util;
import org.concord.energy3d.util.WallVisitor;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.geometry.primitives.Point;
import org.poly2tri.transform.coordinate.AnyToXYTransform;
import org.poly2tri.transform.coordinate.XYToAnyTransform;
import org.poly2tri.triangulation.point.TPoint;
import org.poly2tri.triangulation.point.ardor3d.ArdorVector3Point;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.CollisionTreeManager;
import com.ardor3d.intersection.PickResults;
import com.ardor3d.intersection.PickingUtil;
import com.ardor3d.intersection.PrimitivePickResults;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Ray3;
import com.ardor3d.math.Vector2;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.scenegraph.hint.PickingHint;
import com.ardor3d.ui.text.BMText.Align;
import com.ardor3d.util.geom.BufferUtils;
public class Wall extends HousePart {
private static final long serialVersionUID = 1L;
private static final double DEFAULT_WALL_HEIGHT = 30.0; // the recommended default wall height is 6m
private static double userDefaultWallHeight = DEFAULT_WALL_HEIGHT;
private static int currentVisitStamp = 1;
private static boolean extendToRoofEnabled = true;
private transient Mesh backMesh;
private transient Mesh surroundMesh;
private transient Mesh invisibleMesh;
private transient Mesh windowsSurroundMesh;
private transient Mesh outlineMesh;
private transient Roof roof;
private transient int visitStamp;
private transient Vector3 normal;
private transient AnyToXYTransform toXY;
private transient XYToAnyTransform fromXY;
private transient List<List<Vector3>> wallAndWindowsPoints;
private double wallThickness;
private transient Snap[] neighbors;
private transient Vector3 thicknessNormal;
private boolean isShortWall;
public static void resetDefaultWallHeight() {
userDefaultWallHeight = DEFAULT_WALL_HEIGHT;
}
public static void clearVisits() {
currentVisitStamp = ++currentVisitStamp % 1000;
}
public Wall() {
super(2, 4, userDefaultWallHeight);
}
@Override
protected boolean mustHaveContainer() {
return false;
}
@Override
protected void init() {
super.init();
wallThickness = 0.5;
neighbors = new Snap[2];
if (thicknessNormal != null)
thicknessNormal.normalizeLocal().multiplyLocal(wallThickness);
mesh = new Mesh("Wall");
mesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(1));
// mesh.getSceneHints().setPickingHint(PickingHint.Pickable, false);
mesh.setRenderState(offsetState);
mesh.setModelBound(new BoundingBox());
root.attachChild(mesh);
backMesh = new Mesh("Wall (Back)");
backMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(1));
backMesh.setDefaultColor(ColorRGBA.LIGHT_GRAY);
backMesh.getSceneHints().setPickingHint(PickingHint.Pickable, false);
backMesh.setRenderState(offsetState);
backMesh.setModelBound(new BoundingBox());
root.attachChild(backMesh);
surroundMesh = new Mesh("Wall (Surround)");
surroundMesh.getMeshData().setIndexMode(IndexMode.Quads);
surroundMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(12));
surroundMesh.getMeshData().setNormalBuffer(BufferUtils.createVector3Buffer(12));
surroundMesh.setDefaultColor(ColorRGBA.GRAY);
surroundMesh.setRenderState(offsetState);
surroundMesh.setModelBound(new BoundingBox());
root.attachChild(surroundMesh);
invisibleMesh = new Mesh("Wall (Invisible)");
invisibleMesh.getMeshData().setIndexMode(IndexMode.Quads);
invisibleMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(4));
invisibleMesh.getSceneHints().setCullHint(CullHint.Always);
invisibleMesh.setRenderState(offsetState);
invisibleMesh.setModelBound(new BoundingBox());
root.attachChild(invisibleMesh);
windowsSurroundMesh = new Mesh("Wall (Windows Surround)");
windowsSurroundMesh.getMeshData().setIndexMode(IndexMode.Quads);
windowsSurroundMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(1000));
windowsSurroundMesh.getMeshData().setNormalBuffer(BufferUtils.createVector3Buffer(1000));
windowsSurroundMesh.setDefaultColor(ColorRGBA.GRAY);
windowsSurroundMesh.getSceneHints().setPickingHint(PickingHint.Pickable, false);
windowsSurroundMesh.setRenderState(offsetState);
/* lets not use bounds for this mesh because when there are no windows its bounds is set to center 0,0,0 which shifts the overall bounds toward zero */
windowsSurroundMesh.setModelBound(null);
root.attachChild(windowsSurroundMesh);
outlineMesh = new Line("Wall (Outline)");
outlineMesh.getMeshData().setVertexBuffer(BufferUtils.createVector3Buffer(8));
outlineMesh.setDefaultColor(ColorRGBA.BLACK);
outlineMesh.setModelBound(null);
Util.disablePickShadowLight(outlineMesh);
root.attachChild(outlineMesh);
updateTextureAndColor();
final UserData userData = new UserData(this);
mesh.setUserData(userData);
backMesh.setUserData(userData);
surroundMesh.setUserData(userData);
invisibleMesh.setUserData(userData);
}
@Override
public void setPreviewPoint(final int x, final int y) {
Snap.clearAnnotationDrawn();
if (editPointIndex == -1 || editPointIndex == 0 || editPointIndex == 2) {
final HousePart previousContainer = container;
PickedHousePart picked = pickContainer(x, y, new Class<?>[] { Foundation.class });
if (container != previousContainer && previousContainer != null && (isFirstPointInserted() || container == null)) {
container = previousContainer;
picked = null;
}
if (container == null)
return;
Vector3 p = null;
if (picked != null)
p = picked.getPoint();
else
p = findClosestPointOnFoundation(x, y);
if (p == null)
return;
if (container != null)
p.setZ(container.height);
final int index = (editPointIndex == -1) ? points.size() - 2 : editPointIndex;
boolean snappedToWall = snapToWall(p, index);
if (!snappedToWall) {
snapToGrid(p, getAbsPoint(index), getGridSize(), false);
snappedToWall = snapToWall(p, index); // see if it can be snapped after grid move
}
if (!snappedToWall)
snapToFoundation(p);
if (index == 2) // make sure z of 2nd base point is same as 2st (needed for platform picking side)
p.setZ(points.get(0).getZ());
final Vector3 p_rel = toRelative(p);
points.get(index).set(p_rel);
points.get(index + 1).set(p_rel).setZ(p.getZ() + height);
} else if (editPointIndex == 1 || editPointIndex == 3) {
final int lower = (editPointIndex == 1) ? 0 : 2;
final Vector3 base = getAbsPoint(lower);
final Vector3 closestPoint = Util.closestPoint(base, Vector3.UNIT_Z, x, y);
snapToGrid(closestPoint, getAbsPoint(editPointIndex), getGridSize());
height = Math.max(getGridSize(), closestPoint.getZ() - base.getZ());
userDefaultWallHeight = height;
final double z = height + base.getZ();
points.get(1).setZ(z);
points.get(3).setZ(z);
}
Scene.getInstance().connectWalls();
drawThisAndNeighbors(false);
setEditPointsVisible(true);
if (container != null)
((Foundation) container).scanChildrenHeight();
}
public Vector3 findClosestPointOnFoundation(final int x, final int y) {
final PickedHousePart floorPick = SelectUtil.pickPart(x, y, (HousePart) null);
if (floorPick != null) {
Vector3 p = floorPick.getPoint();
ReadOnlyVector3 closesPoint = container.points.get(0);
for (int i = 1; i < 4; i++)
if (closesPoint.distance(p) > container.points.get(i).distance(p))
closesPoint = container.points.get(i);
ReadOnlyVector3 secondClosesPoint = closesPoint == container.points.get(0) ? container.points.get(1) : container.points.get(0);
for (int i = 0; i < 4; i++)
if (secondClosesPoint.distance(p) > container.points.get(i).distance(p) && container.points.get(i) != closesPoint)
secondClosesPoint = container.points.get(i);
final Vector3 dir = closesPoint.subtract(secondClosesPoint, null).normalizeLocal();
p = Util.closestPoint(closesPoint, dir, p, Vector3.NEG_UNIT_Z);
snapToGrid(p, getAbsPoint(editPointIndex == -1 ? points.size() - 2 : editPointIndex), getGridSize());
p = Util.closestPoint(closesPoint, dir, p, Vector3.NEG_UNIT_Z);
p.setX(MathUtils.clamp(p.getX(), Math.min(container.points.get(0).getX(), container.points.get(2).getX()), Math.max(container.points.get(0).getX(), container.points.get(2).getX())));
p.setY(MathUtils.clamp(p.getY(), Math.min(container.points.get(0).getY(), container.points.get(1).getY()), Math.max(container.points.get(0).getY(), container.points.get(1).getY())));
p.getZ();
return p;
} else
return null;
}
private void drawThisAndNeighbors(final boolean extendToRoofEnabled) {
thicknessNormal = null;
isShortWall = true;
Wall.extendToRoofEnabled = extendToRoofEnabled;
if (isDrawable())
computeInsideDirectionOfAttachedWalls(true);
draw();
drawChildren();
Wall.extendToRoofEnabled = true;
}
@Override
public void complete() {
drawThisAndNeighbors(true); // needed in order to extend wall to roof
super.complete();
}
protected boolean snapToWall(final Vector3 p, final int index) {
ReadOnlyVector3 closestPoint = null;
double closestDistance = Double.MAX_VALUE;
for (final HousePart housePart : container.getChildren()) {
if (housePart instanceof Wall && housePart != this) {
final Wall wall = (Wall) housePart;
for (int i = 0; i < wall.points.size(); i += 2) {
final ReadOnlyVector3 p2 = wall.getAbsPoint(i);
final double distance = p.distance(p2);
if (distance < closestDistance) {
closestPoint = p2;
closestDistance = distance;
}
}
}
}
final double snapDistance = isSnapToObjects() ? getGridSize() : SNAP_DISTANCE;
final boolean snap;
if (isFirstPointInserted() && p.subtract(getAbsPoint(index == 0 ? 2 : 0), null).length() < getGridSize() * 2)
snap = false;
else if (closestDistance < snapDistance)
snap = true;
else if (neighbors[index / 2] != null && closestDistance < snapDistance + getGridSize())
snap = true;
else
snap = false;
if (snap) {
p.set(closestPoint);
return true;
} else
return false;
}
private boolean snapToFoundation(final Vector3 current) {
if (container == null)
return false;
ReadOnlyVector3 snapPoint = null;
double snapDistance = Double.MAX_VALUE;
final int[] indices = new int[] { 0, 2, 3, 1, 0 };
for (int i = 0; i < indices.length - 1; i++) {
final Vector3 p1 = container.getAbsPoint(indices[i]);
final Vector3 p2 = container.getAbsPoint(indices[i + 1]);
final Vector2 p2D = Util.projectPointOnLine(new Vector2(current.getX(), current.getY()), new Vector2(p1.getX(), p1.getY()), new Vector2(p2.getX(), p2.getY()), true);
final Vector3 p = new Vector3(p2D.getX(), p2D.getY(), current.getZ());
final double d = p.distance(current);
if (d < snapDistance) {
snapDistance = d;
snapPoint = p;
}
}
if (snapDistance < getGridSize() / 2) {
current.set(snapPoint.getX(), snapPoint.getY(), current.getZ());
return true;
} else
return false;
}
@Override
public boolean isDrawable() {
return super.isDrawable() && !isAtSamePlaceAsAnotherPart(this);
}
private boolean isAtSamePlaceAsAnotherPart(final HousePart selectedHousePart) {
if (selectedHousePart instanceof Wall) {
final Vector3 p0 = selectedHousePart.getAbsPoint(0);
final Vector3 p2 = selectedHousePart.getAbsPoint(2);
for (final HousePart part : selectedHousePart.getContainer().getChildren())
if (part != selectedHousePart && part instanceof Wall && part.isDrawCompleted()) {
final Vector3 q0 = part.getAbsPoint(0);
final Vector3 q2 = part.getAbsPoint(2);
if ((p0.equals(q0) && p2.equals(q2)) || (p2.equals(q0) && p0.equals(q2)))
return true;
}
}
return false;
}
@Override
protected void drawMesh() {
mesh.getSceneHints().setCullHint(isDrawable() ? CullHint.Inherit : CullHint.Always);
backMesh.getSceneHints().setCullHint(isDrawable() && !isFrozen() ? CullHint.Inherit : CullHint.Always);
surroundMesh.getSceneHints().setCullHint(isDrawable() && !isFrozen() ? CullHint.Inherit : CullHint.Always);
windowsSurroundMesh.getSceneHints().setCullHint(isDrawable() && !isFrozen() ? CullHint.Inherit : CullHint.Always);
outlineMesh.getSceneHints().setCullHint(isDrawable() ? CullHint.Inherit : CullHint.Always);
if (!isDrawable())
return;
computeNormalAndXYTransform();
wallAndWindowsPoints = computeWallAndWindowPolygon(false);
extendToRoof(wallAndWindowsPoints.get(0));
if (Scene.getInstance().isDrawThickness() && isShortWall) {
final Vector3 dir = getAbsPoint(2).subtract(getAbsPoint(0), null).normalizeLocal();
if (neighbors[0] != null && neighbors[0].getNeighborOf(this).isFirstPointInserted()) {
if (isPerpendicularToNeighbor(0))
reduceBackMeshWidth(wallAndWindowsPoints.get(0), dir, 0);
}
if (neighbors[1] != null && neighbors[1].getNeighborOf(this).isFirstPointInserted()) {
dir.normalizeLocal().negateLocal();
if (isPerpendicularToNeighbor(1))
reduceBackMeshWidth(wallAndWindowsPoints.get(0), dir, 1);
}
}
drawOutline(wallAndWindowsPoints);
drawPolygon(wallAndWindowsPoints, mesh, true, true, true);
drawPolygon(wallAndWindowsPoints, invisibleMesh, false, false, false);
CollisionTreeManager.INSTANCE.updateCollisionTree(mesh);
CollisionTreeManager.INSTANCE.updateCollisionTree(invisibleMesh);
if (!isFrozen()) {
drawBackMesh(computeWallAndWindowPolygon(true));
drawSurroundMesh(thicknessNormal);
drawWindowsSurroundMesh(thicknessNormal);
}
drawHeatFlux();
root.updateWorldBound(true);
}
private void drawPolygon(final List<List<Vector3>> wallAndWindowsPoints, final Mesh mesh, final boolean drawHoles, final boolean normal, final boolean texture) {
final List<PolygonPoint> polygonPoints = new ArrayList<PolygonPoint>(wallAndWindowsPoints.get(0).size());
for (final Vector3 p : wallAndWindowsPoints.get(0)) {
final PolygonPoint tp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(tp);
polygonPoints.add(tp);
}
final PolygonWithHoles polygon = new PolygonWithHoles(polygonPoints);
if (drawHoles) {
for (int i = 1; i < wallAndWindowsPoints.size(); i++) {
final List<PolygonPoint> holePoints = new ArrayList<PolygonPoint>(wallAndWindowsPoints.get(i).size());
for (final Vector3 p : wallAndWindowsPoints.get(i)) {
final PolygonPoint tp = new PolygonPoint(p.getX(), p.getY(), p.getZ());
toXY.transform(tp);
holePoints.add(tp);
}
polygon.addHole(new Polygon(holePoints));
}
}
if (texture) {
final double scale = Scene.getInstance().getTextureMode() == TextureMode.Simple ? 1.0 : 8.0;
final boolean fullTexture = Scene.getInstance().getTextureMode() == TextureMode.Full;
final ReadOnlyVector3 p0 = getAbsPoint(0);
final ReadOnlyVector3 p01 = getAbsPoint(1).subtractLocal(p0).normalizeLocal().multiplyLocal(scale * (fullTexture ? 1.5 : 1.0));
final ReadOnlyVector3 p02 = getAbsPoint(2).subtractLocal(p0).normalizeLocal().multiplyLocal(scale * (fullTexture ? 2.0 : 1.0));
final TPoint o = new TPoint(p0.getX(), p0.getY(), p0.getZ());
final TPoint u = new TPoint(p01.getX(), p01.getY(), p01.getZ());
final TPoint v = new TPoint(p02.getX(), p02.getY(), p02.getZ());
toXY.transform(o);
toXY.transform(u);
MeshLib.fillMeshWithPolygon(mesh, polygon, fromXY, normal, o, u, v);
} else
MeshLib.fillMeshWithPolygon(mesh, polygon, fromXY, normal, null, null, null);
}
private void drawOutline(final List<List<Vector3>> wallAndWindowsPoints) {
final List<Vector3> wallPolygonPoints = wallAndWindowsPoints.get(0);
FloatBuffer outlineVertexBuffer = outlineMesh.getMeshData().getVertexBuffer();
final int requiredSize = 2 * (wallPolygonPoints.size() + (wallAndWindowsPoints.size() - 1) * 4);
if (outlineVertexBuffer.capacity() / 3 < requiredSize) {
outlineVertexBuffer = BufferUtils.createVector3Buffer(requiredSize);
outlineMesh.getMeshData().setVertexBuffer(outlineVertexBuffer);
} else {
outlineVertexBuffer.rewind();
outlineVertexBuffer.limit(outlineVertexBuffer.capacity());
}
outlineVertexBuffer.rewind();
ReadOnlyVector3 prev = wallPolygonPoints.get(wallPolygonPoints.size() - 1);
for (final ReadOnlyVector3 point : wallPolygonPoints) {
outlineVertexBuffer.put(prev.getXf()).put(prev.getYf()).put(prev.getZf());
prev = point;
outlineVertexBuffer.put(point.getXf()).put(point.getYf()).put(point.getZf());
}
for (int i = 1; i < wallAndWindowsPoints.size(); i++) {
final List<Vector3> windowHolePoints = wallAndWindowsPoints.get(i);
prev = windowHolePoints.get(3);
for (int j = 0; j < 4; j++) {
final ReadOnlyVector3 point = windowHolePoints.get(j);
outlineVertexBuffer.put(prev.getXf()).put(prev.getYf()).put(prev.getZf());
prev = point;
outlineVertexBuffer.put(point.getXf()).put(point.getYf()).put(point.getZf());
}
}
outlineVertexBuffer.limit(outlineVertexBuffer.position());
outlineMesh.getMeshData().updateVertexCount();
outlineMesh.updateModelBound();
outlineMesh.setTranslation(getFaceDirection().multiply(0.001, null));
}
public List<List<Vector3>> computeWallAndWindowPolygon(final boolean backMesh) {
final List<List<Vector3>> polygonPoints = new ArrayList<List<Vector3>>();
final ReadOnlyVector3 trans = backMesh ? getThicknessNormal() : Vector3.ZERO;
// Start the polygon with (1) then 0, 2, 3, [roof points] so that roof
// points are appended to the end of vertex list
final ArrayList<Vector3> wallPoints = new ArrayList<Vector3>(4);
addPolygonPoint(wallPoints, this, 1, trans);
addPolygonPoint(wallPoints, this, 0, trans);
addPolygonPoint(wallPoints, this, 2, trans);
addPolygonPoint(wallPoints, this, 3, trans);
polygonPoints.add(wallPoints);
// Add window holes
for (final HousePart child : children) {
if (child instanceof Window && includeWindow(child))
polygonPoints.add(computeWindowHole(child, trans));
}
return polygonPoints;
}
private List<Vector3> computeWindowHole(final HousePart window, final ReadOnlyVector3 trans) {
final List<Vector3> windowPoints = new ArrayList<Vector3>(4);
addPolygonPoint(windowPoints, window, 1, trans);
addPolygonPoint(windowPoints, window, 0, trans);
addPolygonPoint(windowPoints, window, 2, trans);
addPolygonPoint(windowPoints, window, 3, trans);
return windowPoints;
}
private void addPolygonPoint(final List<Vector3> points, final HousePart housePart, final int index, final ReadOnlyVector3 trans) {
points.add(housePart.getAbsPoint(index).addLocal(trans));
}
private void extendToRoof(final List<Vector3> polygon) {
if (!extendToRoofEnabled)
return;
final int[] upper = { 0, 3 };
for (final int i : upper) {
final Vector3 tp = polygon.get(i);
final double z = findRoofIntersection(tp);
tp.set(tp.getX(), tp.getY(), z);
}
Vector3 tp = polygon.get(0);
final ReadOnlyVector3 o = tp;
tp = polygon.get(3);
final Vector3 dir = tp.subtract(o, null);
dir.setZ(0);
final double length = dir.length();
dir.normalizeLocal();
if (roof != null && !isFrozen()) {
Vector3 direction = null;
ReadOnlyVector3 previousStretchPoint = polygon.get(3);
final double step = 0.1;
for (double d = length - step; d > step; d -= step) {
final Vector3 p = dir.multiply(d, null).addLocal(o);
final double findRoofIntersection = findRoofIntersection(p);
final ReadOnlyVector3 currentStretchPoint = new Vector3(p.getX(), p.getY(), findRoofIntersection);
final Vector3 currentDirection = currentStretchPoint.subtract(previousStretchPoint, null).normalizeLocal();
if (direction == null) {
direction = currentDirection;
} else if (direction.dot(currentDirection) < 1.0 - MathUtils.ZERO_TOLERANCE) {
direction = null;
p.setZ(findRoofIntersection);
polygon.add(p);
}
previousStretchPoint = currentStretchPoint;
}
}
}
public double findRoofIntersection(final ReadOnlyVector3 p) {
return findRoofIntersection(p, Vector3.UNIT_Z, -0.02).getZ();
}
public ReadOnlyVector3 findRoofIntersection(final ReadOnlyVector3 p, final ReadOnlyVector3 direction, final double offset) {
if (roof == null)
return p;
final PickResults pickResults = new PrimitivePickResults();
PickingUtil.findPick(roof.getRoofPartsRoot(), new Ray3(new Vector3(p.getX(), p.getY(), direction.equals(Vector3.UNIT_Z) ? 0 : p.getZ()), direction), pickResults, false);
if (pickResults.getNumber() > 0) {
return pickResults.getPickData(0).getIntersectionRecord().getIntersectionPoint(0).add(direction.multiply(Scene.getInstance().getOverhangLength() > 0.05 ? offset : 0, null), null);
} else
return p;
}
public boolean isPerpendicularToNeighbor(final int neighbor) {
final Vector3 dir = getAbsPoint(2).subtract(getAbsPoint(0), null).normalizeLocal();
final int i = neighbors[neighbor].getSnapPointIndexOfNeighborOf(this);
final Vector3 otherDir = getAbsPoint(i == 0 ? 2 : 0).subtract(getAbsPoint(i), null).normalizeLocal();
return Math.abs(dir.dot(otherDir)) < 0.1;
}
public boolean includeWindow(final HousePart window) {
return window.getPoints().size() >= 4 && window.getAbsPoint(2).subtract(window.getAbsPoint(0), null).length() >= 0.1;
}
private void drawBackMesh(final List<List<Vector3>> polygon) {
final Vector3 dir = getAbsPoint(2).subtract(getAbsPoint(0), null).normalizeLocal();
if (neighbors[0] != null && neighbors[0].getNeighborOf(this).isFirstPointInserted() && !(Scene.getInstance().isDrawThickness() && isShortWall && isPerpendicularToNeighbor(0))) {
reduceBackMeshWidth(polygon.get(0), dir, 0);
}
if (neighbors[1] != null && neighbors[1].getNeighborOf(this).isFirstPointInserted() && !(Scene.getInstance().isDrawThickness() && isShortWall && isPerpendicularToNeighbor(1))) {
dir.normalizeLocal().negateLocal();
reduceBackMeshWidth(polygon.get(0), dir, 1);
}
enforceGablePointsRangeAndRemoveDuplicatedGablePoints(polygon.get(0));
extendToRoof(polygon.get(0));
/* lower the z of back wall to ensure it doesn't stick up through the roof */
if (roof != null)
for (final Vector3 p : polygon.get(0))
p.setZ(p.getZ() - 0.3);
drawPolygon(polygon, backMesh, true, true, false);
}
private void enforceGablePointsRangeAndRemoveDuplicatedGablePoints(final List<Vector3> polygonPoints) {
final Vector2 min = new Vector2(Math.min(polygonPoints.get(1).getX(), polygonPoints.get(2).getX()), Math.min(polygonPoints.get(1).getY(), polygonPoints.get(2).getY()));
final Vector2 max = new Vector2(Math.max(polygonPoints.get(1).getX(), polygonPoints.get(2).getX()), Math.max(polygonPoints.get(1).getY(), polygonPoints.get(2).getY()));
for (int i = 4; i < polygonPoints.size(); i++) {
final Vector3 tp = polygonPoints.get(i);
tp.set(Math.max(tp.getX(), min.getX()), Math.max(tp.getY(), min.getY()), tp.getZ());
tp.set(Math.min(tp.getX(), max.getX()), Math.min(tp.getY(), max.getY()), tp.getZ());
for (int j = 0; j < i; j++) {
final Vector3 tpj = polygonPoints.get(j);
if (Util.isEqual(tpj.getX(), tp.getX()) && Util.isEqual(tpj.getY(), tp.getY())) {
polygonPoints.remove(i);
i
break;
}
}
}
}
private void reduceBackMeshWidth(final List<Vector3> polygon, final ReadOnlyVector3 wallDir, final int neighbor) {
final Snap snap = neighbors[neighbor];
final int neighborPointIndex = snap.getSnapPointIndexOfNeighborOf(this);
final Wall otherWall = snap.getNeighborOf(this);
final Vector3 otherWallDir = otherWall.getAbsPoint(neighborPointIndex == 0 ? 2 : 0).subtract(otherWall.getAbsPoint(neighborPointIndex), null).normalizeLocal();
final double angle = Math.max(0.1, otherWallDir.smallestAngleBetween(wallDir));
final double angle360;
if (wallDir.dot(otherWall.getThicknessNormal().normalize(null)) < 0)
angle360 = Math.PI + angle;
else
angle360 = angle;
final boolean reverse = angle360 >= Math.PI;
final double length = wallThickness * Math.tan((Math.PI - angle) / 2) * (reverse ? -1 : 1);
final Vector3 v = wallDir.normalize(null).multiplyLocal(length);
final Vector3 p1 = polygon.get(neighbor == 0 ? 1 : 2);
final Vector3 p2 = polygon.get(neighbor == 0 ? 0 : 3);
// now reduce the actual wall points
p1.set(p1.getX() + v.getX(), p1.getY() + v.getY(), p1.getZ());
p2.set(p2.getX() + v.getX(), p2.getY() + v.getY(), p2.getZ());
}
public Vector3 getThicknessNormal() {
if (thicknessNormal != null)
return thicknessNormal;
computeNormalAndXYTransform();
final Vector3 n = normal.clone();
final Snap neighbor;
final int whichNeighbor;
if (editPointIndex == 0 || editPointIndex == 1) {
/*
* if edit point has snapped to a new wall then use the angle with new wall to determine inside direction of this wall otherwise use the angle with the other wall attached to none moving corner of the this wall
*/
if (neighbors[0] == null)
whichNeighbor = 1;
else
whichNeighbor = 0;
} else {
if (neighbors[1] == null)
whichNeighbor = 0;
else
whichNeighbor = 1;
}
neighbor = neighbors[whichNeighbor];
if (neighbor != null && neighbor.getNeighborOf(this).getPoints().size() >= 4) {
final HousePart other = neighbor.getNeighborOf(this);
final int otherPointIndex = neighbor.getSnapPointIndexOfNeighborOf(this);
final Vector3 otherWallDir = other.getAbsPoint(otherPointIndex == 0 ? 2 : 0).subtract(other.getAbsPoint(otherPointIndex), null).normalizeLocal();
if (n.dot(otherWallDir) < 0)
n.negateLocal();
} else {
final ReadOnlyVector3 camera = SceneManager.getInstance().getCamera().getDirection();
if (camera.dot(n) < 0)
n.negateLocal();
}
n.multiplyLocal(wallThickness);
thicknessNormal = n;
return thicknessNormal;
}
private void computeNormalAndXYTransform() {
final Vector3 p02 = getAbsPoint(2).subtract(getAbsPoint(0), null).normalizeLocal();
final Vector3 p01 = getAbsPoint(1).subtract(getAbsPoint(0), null).normalizeLocal();
normal = p02.crossLocal(p01).normalizeLocal();
toXY = new AnyToXYTransform(normal.getX(), normal.getY(), normal.getZ());
fromXY = new XYToAnyTransform(normal.getX(), normal.getY(), normal.getZ());
}
private void drawSurroundMesh(final ReadOnlyVector3 thickness) {
final boolean drawThicknessAndIsLongWall = Scene.getInstance().isDrawThickness() && !isShortWall;
final boolean noNeighbor0 = neighbors[0] == null || (drawThicknessAndIsLongWall && isPerpendicularToNeighbor(0));
final boolean noNeighbor1 = neighbors[1] == null || (drawThicknessAndIsLongWall && isPerpendicularToNeighbor(1));
final boolean visible = roof == null || noNeighbor0 || noNeighbor1;
surroundMesh.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
if (!visible) {
if (surroundMesh.getModelBound() != null)
surroundMesh.setModelBound(null);
} else {
if (surroundMesh.getModelBound() == null)
surroundMesh.setModelBound(new BoundingBox());
}
if (!visible)
return;
final FloatBuffer vertexBuffer = surroundMesh.getMeshData().getVertexBuffer();
final FloatBuffer normalBuffer = surroundMesh.getMeshData().getNormalBuffer();
vertexBuffer.rewind();
normalBuffer.rewind();
vertexBuffer.limit(vertexBuffer.capacity());
normalBuffer.limit(normalBuffer.capacity());
final Vector3 sideNormal = thickness.cross(0, 0, 1, null).normalizeLocal();
if (noNeighbor0)
addSurroundQuad(0, 1, sideNormal.negate(null), thickness, vertexBuffer, normalBuffer);
if (noNeighbor1)
addSurroundQuad(3, 2, sideNormal, thickness, vertexBuffer, normalBuffer);
if (roof == null)
addSurroundQuad(1, 3, Vector3.UNIT_Z, thickness, vertexBuffer, normalBuffer);
vertexBuffer.limit(vertexBuffer.position());
normalBuffer.limit(normalBuffer.position());
surroundMesh.getMeshData().updateVertexCount();
surroundMesh.updateModelBound();
CollisionTreeManager.INSTANCE.updateCollisionTree(surroundMesh);
}
protected void addSurroundQuad(final int i1, final int i2, final ReadOnlyVector3 n, final ReadOnlyVector3 thickness, final FloatBuffer vertexBuffer, final FloatBuffer normalBuffer) {
final ReadOnlyVector3 p1 = getAbsPoint(i1);
final ReadOnlyVector3 p2 = p1.add(thickness, null);
final ReadOnlyVector3 p3 = getAbsPoint(i2);
final ReadOnlyVector3 p4 = p3.add(thickness, null);
vertexBuffer.put(p1.getXf()).put(p1.getYf()).put(p1.getZf());
vertexBuffer.put(p3.getXf()).put(p3.getYf()).put(p3.getZf());
vertexBuffer.put(p4.getXf()).put(p4.getYf()).put(p4.getZf());
vertexBuffer.put(p2.getXf()).put(p2.getYf()).put(p2.getZf());
for (int i = 0; i < 4; i++)
normalBuffer.put(n.getXf()).put(n.getYf()).put(n.getZf());
}
private void drawWindowsSurroundMesh(final Vector3 thickness) {
final FloatBuffer vertexBuffer = windowsSurroundMesh.getMeshData().getVertexBuffer();
final FloatBuffer normalBuffer = windowsSurroundMesh.getMeshData().getNormalBuffer();
vertexBuffer.rewind();
normalBuffer.rewind();
vertexBuffer.limit(vertexBuffer.capacity());
normalBuffer.limit(vertexBuffer.capacity());
final int[] order1 = new int[] { 0, 1, 3, 2, 0 };
final int[] order2 = new int[] { 2, 3, 1, 0, 2 };
final Vector3 sideNormal = thickness.cross(0, 0, 1, null).normalizeLocal();
final Vector3 n = new Vector3();
final Vector3 p = new Vector3();
final Vector3 wallDirection = getAbsPoint(2).subtract(getAbsPoint(0), null);
for (final HousePart child : children) {
if (child instanceof Window && includeWindow(child)) {
int[] order = order1;
final Vector3 windowDirection = child.getAbsPoint(2).subtract(child.getAbsPoint(0), null);
if (windowDirection.dot(wallDirection) < 0)
order = order2;
for (int index = 0; index < order.length - 1; index++) {
int i = order[index];
p.set(child.getAbsPoint(i));
vertexBuffer.put(p.getXf()).put(p.getYf()).put(p.getZf());
p.set(child.getAbsPoint(i)).addLocal(thickness);
vertexBuffer.put(p.getXf()).put(p.getYf()).put(p.getZf());
i = order[index + 1];
p.set(child.getAbsPoint(i)).addLocal(thickness);
vertexBuffer.put(p.getXf()).put(p.getYf()).put(p.getZf());
p.set(child.getAbsPoint(i));
vertexBuffer.put(p.getXf()).put(p.getYf()).put(p.getZf());
if (index == 1 || index == 3) {
int z = 1;
if (index == 1)
z = -z;
final boolean reversedThickness = getAbsPoint(1).subtract(getAbsPoint(0), null).normalizeLocal().crossLocal(wallDirection.normalize(null)).dot(thicknessNormal.normalize(null)) >= 0;
if (!reversedThickness)
z = -z;
for (int j = 0; j < 4; j++)
normalBuffer.put(0).put(0).put(z);
} else if (index == 0 || index == 2) {
n.set(sideNormal);
if (index == 2)
n.negateLocal();
for (int j = 0; j < 4; j++)
normalBuffer.put(n.getXf()).put(n.getYf()).put(n.getZf());
}
}
}
}
final int pos = vertexBuffer.position();
vertexBuffer.limit(pos != 0 ? pos : 1);
windowsSurroundMesh.getMeshData().updateVertexCount();
windowsSurroundMesh.updateModelBound();
}
public Snap getOtherSnap(final Snap snap) {
if (snap == null && neighbors[1] != null)
return neighbors[1];
for (final Snap s : neighbors)
if (s != null && !s.equals(snap))
return s;
return null;
}
private void setNeighbor(final int pointIndex, final Snap newSnap, final boolean updateNeighbors) {
final int i = pointIndex < 2 ? 0 : 1;
final Snap oldSnap = neighbors[i];
neighbors[i] = newSnap;
// if (newSnap == null && !updateNeighbors) { // see if it is attached to another wall
// connectedWalls();
// return;
if (!updateNeighbors || oldSnap == newSnap || (oldSnap != null && oldSnap.equals(newSnap)))
return;
if (oldSnap != null) {
final Wall neighbor = oldSnap.getNeighborOf(this);
neighbor.setNeighbor(oldSnap.getSnapPointIndexOfNeighborOf(this), null, false);
neighbor.draw();
}
if (newSnap != null) {
final Wall neighbor = newSnap.getNeighborOf(this);
neighbor.setNeighbor(newSnap.getSnapPointIndexOfNeighborOf(this), newSnap, false);
}
}
@Override
protected void setHeight(final double newHeight, final boolean finalize) {
super.setHeight(newHeight, finalize);
points.get(1).setZ(newHeight + container.height);
if (isFirstPointInserted())
points.get(3).setZ(newHeight + container.height);
}
@Override
public void flatten(final double flattenTime) {
final ReadOnlyVector3 n = getFaceDirection();
double angle = n.smallestAngleBetween(Vector3.NEG_UNIT_Y);
if (n.dot(Vector3.UNIT_X) < 0)
angle = -angle;
root.setRotation((new Matrix3().fromAngles(0, 0, -flattenTime * angle)));
super.flatten(flattenTime);
for (final HousePart part : children)
if (!part.isPrintable()) {
part.getRoot().setTransform(root.getTransform());
part.getRoot().updateGeometricState(0);
}
}
@Override
public ReadOnlyVector3 getFaceDirection() {
if (thicknessNormal == null)
thicknessNormal = getThicknessNormal();
return thicknessNormal.negate(null).normalizeLocal();
}
@Override
public void drawAnnotations() {
if (points.size() < 4)
return;
final ReadOnlyVector3 faceDirection = getFaceDirection();
int annotCounter = 0;
int angleAnnotCounter = 0;
if (wallAndWindowsPoints != null) {
final List<Vector3> wallPolygonPoints = wallAndWindowsPoints.get(0);
final Vector3 actualNormal = wallPolygonPoints.get(0).subtract(wallPolygonPoints.get(1), null).normalizeLocal().crossLocal(wallPolygonPoints.get(2).subtract(wallPolygonPoints.get(1), null).normalizeLocal()).negateLocal();
final boolean reverse = actualNormal.dot(getFaceDirection()) < 0;
final double lowestWallZ = Math.min(wallPolygonPoints.get(0).getZ(), wallPolygonPoints.get(3).getZ());
double low = lowestWallZ;
double hi = Math.max(wallPolygonPoints.get(0).getZ(), wallPolygonPoints.get(3).getZ());
for (int i = 4; i < wallPolygonPoints.size(); i++) {
if (wallPolygonPoints.get(i).getZ() < low)
low = wallPolygonPoints.get(i).getZ();
if (wallPolygonPoints.get(i).getZ() > hi)
hi = wallPolygonPoints.get(i).getZ();
}
final float lineWidth = original == null ? 1f : 2f;
final boolean isRectangular = hi - low < 0.1;
;
if (isRectangular) {
final ReadOnlyVector3 p1 = wallPolygonPoints.get(0).multiply(new Vector3(1, 1, 0), null).addLocal(0, 0, lowestWallZ);
final ReadOnlyVector3 p2 = wallPolygonPoints.get(1);
final ReadOnlyVector3 p3 = wallPolygonPoints.get(2);
final ReadOnlyVector3 p4 = wallPolygonPoints.get(3).multiply(new Vector3(1, 1, 0), null).addLocal(0, 0, lowestWallZ);
final boolean front = false;
fetchSizeAnnot(annotCounter++).setRange(p1, p2, getCenter(), faceDirection, front, front ? Align.South : Align.Center, true, reverse, Scene.isDrawAnnotationsInside());
fetchSizeAnnot(annotCounter++).setRange(p2, p3, getCenter(), faceDirection, original == null, original == null ? Align.South : Align.Center, true, reverse, Scene.isDrawAnnotationsInside());
fetchSizeAnnot(annotCounter++).setRange(p3, p4, getCenter(), faceDirection, front, front ? Align.South : Align.Center, true, reverse, Scene.isDrawAnnotationsInside());
fetchSizeAnnot(annotCounter++).setRange(p4, p1, getCenter(), faceDirection, front, front ? Align.South : Align.Center, true, reverse, Scene.isDrawAnnotationsInside());
for (int i = 0; i < annotCounter; i++)
fetchSizeAnnot(i).setLineWidth(lineWidth);
fetchAngleAnnot(angleAnnotCounter++).setRange(p2, p1, p3, getFaceDirection());
fetchAngleAnnot(angleAnnotCounter++).setRange(p3, p2, p4, getFaceDirection());
fetchAngleAnnot(angleAnnotCounter++).setRange(p4, p3, p1, getFaceDirection());
fetchAngleAnnot(angleAnnotCounter++).setRange(p1, p4, p2, getFaceDirection());
for (int i = 0; i < annotCounter; i++)
fetchAngleAnnot(i).setLineWidth(lineWidth);
} else
for (int i = 0; i < wallPolygonPoints.size(); i++) {
final boolean front = i == 1 && original == null;
final ReadOnlyVector3 p1 = wallPolygonPoints.get(i);
final ReadOnlyVector3 p2 = wallPolygonPoints.get((i + 1) % wallPolygonPoints.size());
final ReadOnlyVector3 p3 = wallPolygonPoints.get((i + 2) % wallPolygonPoints.size());
final double minLength = 4.0;
if (p1.distance(p2) > minLength) {
final ReadOnlyVector3 min = new Vector3(Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())), Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())), 0);
final ReadOnlyVector3 max = new Vector3(Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())), Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())), 0);
final ReadOnlyVector3 center = min.add(max, null).divideLocal(2.0).addLocal(0, 0, getCenter().getZ());
final SizeAnnotation sizeAnnot = fetchSizeAnnot(annotCounter++);
sizeAnnot.setRange(p1, p2, center, faceDirection, front, front ? Align.South : Align.Center, true, reverse, Scene.isDrawAnnotationsInside());
sizeAnnot.setLineWidth(lineWidth);
}
if (p1.distance(p2) > minLength && p2.distance(p3) > minLength) {
final AngleAnnotation angleAnnot = fetchAngleAnnot(angleAnnotCounter++);
angleAnnot.setRange(p2, p1, p3, getFaceDirection());
angleAnnot.setLineWidth(lineWidth);
}
}
}
}
public void visitNeighbors(final WallVisitor visitor) {
Wall currentWall = this;
Snap snap = null;
Wall.clearVisits();
while (currentWall != null && !currentWall.isVisited()) {
currentWall.visit();
snap = currentWall.getOtherSnap(snap);
if (snap == null)
break;
currentWall = snap.getNeighborOf(currentWall);
}
visitNeighborsForward(currentWall, null, visitor);
}
public void visitNeighborsForward(Wall currentWall, Snap snap, final WallVisitor visitor) {
class VisitInfo {
Wall wall;
Snap prev, next;
VisitInfo(final Wall wall, final Snap prev, final Snap next) {
this.wall = wall;
this.prev = prev;
this.next = next;
}
}
final ArrayList<VisitInfo> visits = new ArrayList<VisitInfo>();
Wall.clearVisits();
while (currentWall != null && !currentWall.isVisited()) {
final Snap prevSnap = snap;
snap = currentWall.getOtherSnap(snap);
visits.add(new VisitInfo(currentWall, prevSnap, snap));
currentWall.visit();
if (snap == null)
break;
currentWall = snap.getNeighborOf(currentWall);
}
for (final VisitInfo visit : visits)
visitor.visit(visit.wall, visit.prev, visit.next);
}
public void computeInsideDirectionOfAttachedWalls(final boolean drawNeighborWalls) {
if (this.thicknessNormal != null)
return;
final ArrayList<Wall> walls;
if (drawNeighborWalls)
walls = new ArrayList<Wall>();
else
walls = null;
final double[] side = new double[] { 0.0 };
Wall.clearVisits();
visitNeighbors(new WallVisitor() {
@Override
public void visit(final Wall wall, final Snap prev, final Snap next) {
if (next != null) {
final int indexP2 = next.getSnapPointIndexOf(wall);
final ReadOnlyVector3 p1 = wall.getAbsPoint(indexP2 == 0 ? 2 : 0);
final ReadOnlyVector3 p2 = wall.getAbsPoint(indexP2);
final ReadOnlyVector3 p3 = next.getNeighborOf(wall).getAbsPoint(next.getSnapPointIndexOfNeighborOf(wall) == 0 ? 2 : 0);
final ReadOnlyVector3 p1_p2 = p2.subtract(p1, null).normalizeLocal();
final ReadOnlyVector3 p2_p3 = p3.subtract(p2, null).normalizeLocal();
side[0] += Util.angleBetween(p1_p2, p2_p3, Vector3.UNIT_Z);
}
if (drawNeighborWalls && wall != Wall.this && !walls.contains(wall))
walls.add(wall);
}
});
Wall.clearVisits();
visitNeighbors(new WallVisitor() {
@Override
public void visit(final Wall wall, final Snap prev, final Snap next) {
if (next != null) {
final int indexP2 = next.getSnapPointIndexOf(wall);
final Vector3 p1 = wall.getAbsPoint(indexP2 == 0 ? 2 : 0);
final Vector3 p2 = wall.getAbsPoint(indexP2);
final Vector3 p1_p2 = p2.subtract(p1, null);
wall.thicknessNormal = p1_p2.cross(Vector3.UNIT_Z, null).normalizeLocal().multiplyLocal(wallThickness);
if (side[0] > 0)
wall.thicknessNormal.negateLocal();
} else if (prev != null) {
final int indexP2 = prev.getSnapPointIndexOf(wall);
final Vector3 p2 = wall.getAbsPoint(indexP2);
final Vector3 p3 = wall.getAbsPoint(indexP2 == 0 ? 2 : 0);
final Vector3 p2_p3 = p3.subtract(p2, null);
wall.thicknessNormal = p2_p3.cross(Vector3.UNIT_Z, null).normalizeLocal().multiplyLocal(wallThickness);
if (side[0] > 0)
wall.thicknessNormal.negateLocal();
}
}
});
if (drawNeighborWalls)
for (final HousePart wall : walls) {
wall.draw();
wall.drawChildren();
}
}
@Override
protected String getTextureFileName() {
return Scene.getInstance().getTextureMode() == TextureMode.Simple ? "wall.png" : "wall_brick.png";
}
public boolean isVisited() {
return visitStamp == currentVisitStamp;
}
public void visit() {
visitStamp = currentVisitStamp;
}
public void setRoof(final Roof roof) {
this.roof = roof;
}
@Override
public void setOriginal(final HousePart original) {
final Wall originalWall = (Wall) original;
this.thicknessNormal = originalWall.getThicknessNormal();
root.detachChild(invisibleMesh);
root.detachChild(backMesh);
root.detachChild(surroundMesh);
root.detachChild(windowsSurroundMesh);
root.detachChild(outlineMesh);
backMesh = originalWall.backMesh.makeCopy(true);
surroundMesh = originalWall.surroundMesh.makeCopy(true);
windowsSurroundMesh = originalWall.windowsSurroundMesh.makeCopy(true);
outlineMesh = originalWall.outlineMesh.makeCopy(true);
((Line) outlineMesh).setLineWidth(printOutlineThickness);
root.attachChild(backMesh);
root.attachChild(surroundMesh);
root.attachChild(windowsSurroundMesh);
root.attachChild(outlineMesh);
final Mesh orgInvisibleMesh = originalWall.invisibleMesh;
invisibleMesh = orgInvisibleMesh.makeCopy(true);
invisibleMesh.setUserData(new UserData(this, ((UserData) orgInvisibleMesh.getUserData()).getIndex(), false));
root.attachChild(invisibleMesh);
wallAndWindowsPoints = originalWall.wallAndWindowsPoints;
super.setOriginal(original);
}
public Roof getRoof() {
return roof;
}
@Override
public void drawGrids(final double gridSize) {
final ReadOnlyVector3 p0 = getAbsPoint(0);
final ReadOnlyVector3 p2 = getAbsPoint(2);
final ReadOnlyVector3 width = p2.subtract(p0, null);
final ArrayList<ReadOnlyVector3> points = new ArrayList<ReadOnlyVector3>();
final int cols = (int) (width.length() / gridSize);
double gableHeight = height;
ReadOnlyVector3 gablePeakBase = p0;
for (int col = 1; col < cols; col++) {
final ReadOnlyVector3 lineP1 = width.normalize(null).multiplyLocal(col * gridSize).addLocal(p0);
points.add(lineP1);
final ReadOnlyVector3 lineP2 = findRoofIntersection(new Vector3(lineP1.getX(), lineP1.getY(), height), Vector3.UNIT_Z, 0);
points.add(lineP2);
if (lineP2.getZ() > gableHeight) {
gableHeight = lineP2.getZ();
gablePeakBase = lineP1;
}
}
final ReadOnlyVector3 height = getAbsPoint(1).subtractLocal(p0).normalizeLocal().multiplyLocal(gableHeight);
final int rows = (int) (gableHeight / gridSize);
for (int row = 1; row < rows; row++) {
final ReadOnlyVector3 pMiddle = height.normalize(null).multiplyLocal(row * gridSize).addLocal(gablePeakBase);
ReadOnlyVector3 lineP1 = new Vector3(p0.getX(), p0.getY(), pMiddle.getZ());
ReadOnlyVector3 lineP2 = new Vector3(p2.getX(), p2.getY(), pMiddle.getZ());
if (pMiddle.getZ() > this.height) {
ReadOnlyVector3 tmp;
tmp = findRoofIntersection(pMiddle, width.normalize(null), 0);
if (tmp != pMiddle)
lineP1 = tmp;
tmp = findRoofIntersection(pMiddle, width.normalize(null).negateLocal(), 0);
if (tmp != pMiddle)
lineP2 = tmp;
}
points.add(lineP1);
points.add(lineP2);
}
if (points.size() < 2)
return;
final FloatBuffer buf = BufferUtils.createVector3Buffer(points.size());
for (final ReadOnlyVector3 p : points)
buf.put(p.getXf()).put(p.getYf()).put(p.getZf());
gridsMesh.getMeshData().setVertexBuffer(buf);
}
@Override
public void reset() {
super.reset();
if (root == null)
init();
thicknessNormal = null;
neighbors[0] = neighbors[1] = null;
}
public void setBackMeshesVisible(final boolean visible) {
backMesh.setVisible(visible);
surroundMesh.setVisible(visible);
windowsSurroundMesh.setVisible(visible);
}
@Override
public void updateTextureAndColor() {
updateTextureAndColor(mesh, getColor() == null ? Scene.getInstance().getWallColor() : getColor());
}
public void connectedWalls() {
if (!isDrawable() || (neighbors[0] != null && neighbors[1] != null))
return;
for (final HousePart part : Scene.getInstance().getParts()) {
if (part instanceof Wall && part != this && part.isDrawCompleted()) {
final Wall otherWall = (Wall) part;
for (int index = 0; index < 2; index++)
if (neighbors[index] == null)
for (int otherIndex = 0; otherIndex < 2; otherIndex++) {
// if ((otherWall.neighbors[otherIndex] == null || otherWall.neighbors[otherIndex].getNeighborOf(otherWall) == this) && Util.isEqual(otherWall.getAbsPoint(otherIndex * 2), getAbsPoint(index * 2))) {
if (otherWall.neighbors[otherIndex] == null && Util.isEqual(otherWall.getAbsPoint(otherIndex * 2), getAbsPoint(index * 2))) {
setNeighbor(index * 2, new Snap(this, otherWall, index * 2, otherIndex * 2), true);
break;
}
}
}
}
}
public boolean windowsFit() {
for (final HousePart part : children)
if (part instanceof Window)
if (!fits((Window) part))
return false;
return true;
}
public boolean fits(final Window window) {
final List<Vector3> hole = computeWindowHole(window, Vector3.ZERO);
applyXYTransform(hole);
final double minDistanceToRoof = 0.3 / Scene.getInstance().getAnnotationScale();
final ArrayList<Vector3> polygon = new ArrayList<Vector3>(wallAndWindowsPoints.get(0).size());
for (int i = 0; i < wallAndWindowsPoints.get(0).size(); i++) {
final Vector3 p = wallAndWindowsPoints.get(0).get(i).clone();
if (i == 0 || i > 2)
p.subtractLocal(0, 0, minDistanceToRoof);
polygon.add(p);
}
applyXYTransform(polygon);
for (final Vector3 p : hole)
if (!Util.insidePolygon(p, polygon))
return false;
return true;
}
public void applyXYTransform(final List<Vector3> hole) {
for (final Vector3 p : hole) {
final Point point = new ArdorVector3Point(p);
toXY.transform(point);
p.set(point.getX(), point.getY(), point.getZ());
}
}
@Override
protected void computeArea() {
area = Util.computeArea(mesh);
}
@Override
public double getArea() {
double areaWithoutWindows = area;
for (final HousePart child : children)
if (child instanceof Window || child instanceof Door)
areaWithoutWindows -= child.getArea();
return areaWithoutWindows;
}
public Mesh getInvisibleMesh() {
return invisibleMesh;
}
@Override
protected boolean isHorizontal() {
return false;
}
public List<Vector3> getWallPolygonPoints() {
return wallAndWindowsPoints.get(0);
}
@Override
public Spatial getCollisionSpatial() {
if (SceneManager.getInstance().isTopView())
return root;
else
return invisibleMesh;
}
@Override
public void drawHeatFlux() {
double zmax = -Double.MAX_VALUE;
final List<Vector3> wallPolygonPoints = getWallPolygonPoints();
for (final Vector3 a : wallPolygonPoints) {
if (a.getZ() > zmax)
zmax = a.getZ();
}
final Path2D.Double path = new Path2D.Double();
path.moveTo(0, 0);
final Vector3 v1 = new Vector3();
final Vector3 v2 = new Vector3();
wallPolygonPoints.get(1).subtract(wallPolygonPoints.get(0), v1);
wallPolygonPoints.get(2).subtract(wallPolygonPoints.get(0), v2);
if (Util.isZero(v1.getX()) && Util.isZero(v2.getX())) {
path.moveTo(v1.getY(), v1.getZ());
path.lineTo(v2.getY(), v2.getZ());
for (int i = 3; i < wallPolygonPoints.size(); i++) {
wallPolygonPoints.get(i).subtract(wallPolygonPoints.get(0), v2);
path.lineTo(v2.getY(), v2.getZ());
}
} else { // always use the Y plane unless it is a X plane as above
path.moveTo(v1.getX(), v1.getZ());
path.lineTo(v2.getX(), v2.getZ());
for (int i = 3; i < wallPolygonPoints.size(); i++) {
wallPolygonPoints.get(i).subtract(wallPolygonPoints.get(0), v2);
path.lineTo(v2.getX(), v2.getZ());
}
}
path.lineTo(0, 0);
path.closePath();
heatFlux.getSceneHints().setCullHint(CullHint.Inherit);
FloatBuffer arrowsVertices = heatFlux.getMeshData().getVertexBuffer();
final int cols = (int) Math.max(2, getAbsPoint(0).distance(getAbsPoint(2)) / heatFluxUnitArea);
final int rows = (int) Math.max(2, zmax / heatFluxUnitArea);
arrowsVertices = BufferUtils.createVector3Buffer(rows * cols * 6);
heatFlux.getMeshData().setVertexBuffer(arrowsVertices);
final double heat = calculateHeatVector();
if (heat != 0) {
final ReadOnlyVector3 o = getAbsPoint(0);
final ReadOnlyVector3 u = getAbsPoint(2).subtract(o, null);
final ReadOnlyVector3 v = getAbsPoint(1).subtract(o, null);
final ReadOnlyVector3 normal = getFaceDirection();
final Vector3 a = new Vector3();
double g, h;
for (int j = 0; j < cols; j++) {
h = j + 0.5;
for (int i = 0; i < rows - 1; i++) {
g = i + 0.5;
a.setX(o.getX() + g * v.getX() / rows + h * u.getX() / cols);
a.setY(o.getY() + g * v.getY() / rows + h * u.getY() / cols);
a.setZ(o.getZ() + g * zmax / rows);
a.subtract(wallPolygonPoints.get(0), v1);
if (Util.isZero(v1.getX())) {
if (!path.contains(v1.getY(), v1.getZ()))
break;
} else {
if (!path.contains(v1.getX(), v1.getZ()))
break;
}
drawArrow(a, normal, arrowsVertices, heat);
}
}
heatFlux.getMeshData().updateVertexCount();
heatFlux.updateModelBound();
}
updateHeatFluxVisibility();
}
@Override
public void delete() {
if (roof != null) {
roof.remove(this);
}
}
}
|
package org.dasein.cloud.platform;
import java.util.HashMap;
import java.util.Map;
public class Alarm {
private String name;
private String description;
/**
* If function is set to true, expect the metric field to contain the alarm function or DSL.
* If set to false, expect statistic, comparisonOperator, and threshold to be populated and metric is set to the the associated metric.
*/
private boolean function;
private String metric;
private String metricNamespace;
private Map<String, String> metricMetadata;
private boolean enabled;
private String providerAlarmId;
private String[] providerAlarmActionIds;
private String[] providerInsufficientDataActionIds;
private String[] providerOKActionIds;
private int period;
private int evaluationPeriods;
private String statistic;
private String comparisonOperator;
private double threshold;
private String stateReason;
private String stateReasonData;
private long stateUpdatedTimestamp;
private AlarmState stateValue;
/**
* @return the alarm name
*/
public String getName() {
return name;
}
/**
* Sets the alarm name.
*
* @param name the alarm name
*/
public void setName( String name ) {
this.name = name;
}
/**
* @return the alarm description
*/
public String getDescription() {
return description;
}
/**
* Sets the alarm description.
*
* @param description the alarm description
*/
public void setDescription( String description ) {
this.description = description;
}
/**
* Some providers, such as Rackspace, use a custom DSL for evaluating metrics to determine alarm state. For these providers,
* {@link #function} should be true with and {@link #metric} should contain the DSL or function value.
* <p/>
* Other providers, such as Amazon Web Services, use distinct values to specify how metrics are evaluated to determine alarm state.
* For these providers, {@link #function} should be false and {@link #metric} should contain the metric name that's evaluated, with
* {@link #statistic}, {@link #comparisonOperator}, {@link #threshold}, {@link #period}, and {@link #evaluationPeriods} should be set.
*
* @return if the alarm is actually a function that is executed
*/
public boolean isFunction() {
return function;
}
/**
* Indicates if this alarm is evaluated with a function.
*
* @param function indicates if this alarm is evaluated with a function
*/
public void setFunction( boolean function ) {
this.function = function;
}
/**
* The metric name or function applied to the metric used for the alarm. See {@link #isFunction()} for more details.
*
* @return the metric name or function
*/
public String getMetric() {
return metric;
}
/**
* Sets the metric name or function. See {@link #getMetric()} for more details.
*
* @param metric the metric name or function
*/
public void setMetric( String metric ) {
this.metric = metric;
}
/**
* @return the metric metadata (or dimensions)
*/
public Map<String, String> getMetricMetadata() {
return metricMetadata;
}
/**
* Sets the metric metadata (or dimensions). Wipes all existing metadata.
*
* @param newMetadata the metric metadata (or dimensions)
*/
public void setMetricMetadata( Map<String, String> newMetadata ) {
this.metricMetadata = newMetadata;
}
/**
* Adds additional metric metadata (or dimensions). Replaces an existing value if present.
*
* @param name the metadata name or key
* @param value the metadata value
*/
public void addMetricMetadata( String name, String value ) {
if ( this.metricMetadata == null ) {
this.metricMetadata = new HashMap<String, String>();
}
this.metricMetadata.put( name, value );
}
/**
* Adds additional metric metadata (or dimensions). Replaces an existing value if present.
*
* @param newMetadata the metric metadata
*/
public void addMetricMetadata( Map<String, String> newMetadata ) {
if ( this.metricMetadata == null ) {
this.metricMetadata = new HashMap<String, String>();
}
this.metricMetadata.putAll( newMetadata );
}
/**
* @return the metric namespace
*/
public String getMetricNamespace() {
return metricNamespace;
}
/**
* Sets the metric namespace.
*
* @param metricNamespace the metric namespace
*/
public void setMetricNamespace( String metricNamespace ) {
this.metricNamespace = metricNamespace;
}
/**
* If the alarm and its actions are enabled.
*
* @return enabled value
*/
public boolean isEnabled() {
return enabled;
}
/**
* Sets if the alarm and its actions are enabled.
*
* @param enabled enabled value
*/
public void setEnabled( boolean enabled ) {
this.enabled = enabled;
}
/**
* @return the unique ID for this alarm as it is identified with the cloud provider
*/
public String getProviderAlarmId() {
return providerAlarmId;
}
/**
* Sets the unique ID for this alarm as it is identified with the cloud provider.
*
* @param providerAlarmId the unique ID for this alarm as it is identified with the cloud provider
*/
public void setProviderAlarmId( String providerAlarmId ) {
this.providerAlarmId = providerAlarmId;
}
/**
* @return the list of unique IDs of actions (as identified by the cloud provider) when the alarm is triggered as in "alarm" state
*/
public String[] getProviderAlarmActionIds() {
return providerAlarmActionIds;
}
/**
* Sets the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "alarm" state.
*
* @param providerAlarmActionIds the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "alarm" state
*/
public void setProviderAlarmActionIds( String[] providerAlarmActionIds ) {
this.providerAlarmActionIds = providerAlarmActionIds;
}
/**
* @return the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "insufficient data" state
*/
public String[] getProviderInsufficientDataActionIds() {
return providerInsufficientDataActionIds;
}
/**
* Sets the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "insufficient data" state.
*
* @param providerInsufficientDataActionIds
* the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "insufficient data" state
*/
public void setProviderInsufficientDataActionIds( String[] providerInsufficientDataActionIds ) {
this.providerInsufficientDataActionIds = providerInsufficientDataActionIds;
}
/**
* @return the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "ok" state
*/
public String[] getProviderOKActionIds() {
return providerOKActionIds;
}
/**
* Sets the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "ok" state.
*
* @param providerOKActionIds the list of unique IDs of actions (as identified by the cloud provider) when the alarm reaches "ok" state
*/
public void setProviderOKActionIds( String[] providerOKActionIds ) {
this.providerOKActionIds = providerOKActionIds;
}
/**
* @return the period over which the metric is measured to determine alarm state
*/
public int getPeriod() {
return period;
}
/**
* Sets the period of time in seconds over which the metric is measured to determine alarm state.
*
* @param period the period of time in seconds over which the metric is measured to determine alarm state
*/
public void setPeriod( int period ) {
this.period = period;
}
/**
* @return the number of periods evaluated before triggering a state change of an alarm
*/
public int getEvaluationPeriods() {
return evaluationPeriods;
}
/**
* Sets the number of periods evaluated before triggering a state change of an alarm.
*
* @param evaluationPeriods the number of periods evaluated before triggering a state change of an alarm
*/
public void setEvaluationPeriods( int evaluationPeriods ) {
this.evaluationPeriods = evaluationPeriods;
}
/**
* @return the statistic of the metric value to measure
*/
public String getStatistic() {
return statistic;
}
/**
* Sets the statistic of the metric value to measure. Example values are SampleCount | Average | Sum | Minimum | Maximum.
* The values here are different for each provider. No validation is done on these values currently.
*
* @param statistic the statistic of the metric value to measure
*/
public void setStatistic( String statistic ) {
this.statistic = statistic;
}
/**
* @return the comparison operator to use when evaluating the metric value against the {@link #threshold}
*/
public String getComparisonOperator() {
return comparisonOperator;
}
/**
* Sets the comparison operator to use when evaluating the metric value against the {@link #threshold}. Example values are
* GreaterThanOrEqualToThreshold | GreaterThanThreshold | LessThanThreshold | LessThanOrEqualToThreshold. The values here are
* different for each provider. No validation is done on these values currently.
*
* @param comparisonOperator the comparison operator to use when evaluating the metric value against the {@link #threshold}
*/
public void setComparisonOperator( String comparisonOperator ) {
this.comparisonOperator = comparisonOperator;
}
/**
* @return the threshold the metric (and statistic if applicable) is evaluated against
*/
public double getThreshold() {
return threshold;
}
/**
* Sets the threshold the metric (and statistic if applicable) is evaluated against.
*
* @param threshold the threshold the metric (and statistic if applicable) is evaluated against
*/
public void setThreshold( double threshold ) {
this.threshold = threshold;
}
/**
* @return the reason for the current state value
*/
public String getStateReason() {
return stateReason;
}
/**
* Sets the reason for the current state value.
*
* @param stateReason the reason for the current state value
*/
public void setStateReason( String stateReason ) {
this.stateReason = stateReason;
}
/**
* @return data associated with the alarm state change, in whatever format from the provider
*/
public String getStateReasonData() {
return stateReasonData;
}
/**
* Sets data associated with the alarm state change.
*
* @param stateReasonData data associated with the alarm state change
*/
public void setStateReasonData( String stateReasonData ) {
this.stateReasonData = stateReasonData;
}
/**
* @return timestamp when the alarm state changed
*/
public long getStateUpdatedTimestamp() {
return stateUpdatedTimestamp;
}
/**
* Sets the timestamp when the alarm state changed.
*
* @param stateUpdatedTimestamp
*/
public void setStateUpdatedTimestamp( long stateUpdatedTimestamp ) {
this.stateUpdatedTimestamp = stateUpdatedTimestamp;
}
/**
* @return the current state of the alarm
*/
public AlarmState getStateValue() {
return stateValue;
}
/**
* Sets current state of the alarm.
*
* @param stateValue current state of the alarm
*/
public void setStateValue( AlarmState stateValue ) {
this.stateValue = stateValue;
}
}
|
package org.fxmisc.flowless;
import java.util.Optional;
import java.util.function.Function;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.geometry.Orientation;
import javafx.geometry.Point2D;
import javafx.scene.control.ScrollBar;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.Region;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
public class VirtualFlow<T, C extends Cell<T, ?>> extends Region {
public static <T, C extends Cell<T, ?>> VirtualFlow<T, C> createHorizontal(
ObservableList<T> items,
Function<? super T, ? extends C> cellFactory) {
return new VirtualFlow<>(items, cellFactory, new HorizontalHelper());
}
public static <T, C extends Cell<T, ?>> VirtualFlow<T, C> createVertical(
ObservableList<T> items,
Function<? super T, ? extends C> cellFactory) {
return new VirtualFlow<>(items, cellFactory, new VerticalHelper());
}
private final ScrollBar hbar;
private final ScrollBar vbar;
private final VirtualFlowContent<T, C> content;
private VirtualFlow(
ObservableList<T> items,
Function<? super T, ? extends C> cellFactory,
OrientationHelper orientation) {
this.getStyleClass().add("virtual-flow");
this.content = new VirtualFlowContent<>(items, cellFactory, orientation);
// create scrollbars
hbar = new ScrollBar();
vbar = new ScrollBar();
hbar.setOrientation(Orientation.HORIZONTAL);
vbar.setOrientation(Orientation.VERTICAL);
// scrollbar ranges
hbar.setMin(0);
vbar.setMin(0);
hbar.maxProperty().bind(orientation.widthEstimateProperty(content));
vbar.maxProperty().bind(orientation.heightEstimateProperty(content));
// scrollbar increments
setupUnitIncrement(hbar);
setupUnitIncrement(vbar);
hbar.blockIncrementProperty().bind(hbar.visibleAmountProperty());
vbar.blockIncrementProperty().bind(vbar.visibleAmountProperty());
// scrollbar positions
Bindings.bindBidirectional(
Var.doubleVar(hbar.valueProperty()),
orientation.horizontalPositionProperty(content));
Bindings.bindBidirectional(
Var.doubleVar(vbar.valueProperty()),
orientation.verticalPositionProperty(content));
// scroll content by mouse scroll
this.addEventHandler(ScrollEvent.SCROLL, se -> {
scrollX(-se.getDeltaX());
scrollY(-se.getDeltaY());
se.consume();
});
// scrollbar visibility
Val<Double> layoutWidth = Val.map(layoutBoundsProperty(), Bounds::getWidth);
Val<Double> layoutHeight = Val.map(layoutBoundsProperty(), Bounds::getHeight);
Val<Boolean> needsHBar0 = Val.combine(
orientation.widthEstimateProperty(content),
layoutWidth,
(cw, lw) -> cw > lw);
Val<Boolean> needsVBar0 = Val.combine(
orientation.heightEstimateProperty(content),
layoutHeight,
(ch, lh) -> ch > lh);
Val<Boolean> needsHBar = Val.combine(
needsHBar0,
needsVBar0,
orientation.widthEstimateProperty(content),
vbar.widthProperty(),
layoutWidth,
(needsH, needsV, cw, vbw, lw) -> needsH || needsV && cw + vbw.doubleValue() > lw);
Val<Boolean> needsVBar = Val.combine(
needsVBar0,
needsHBar0,
orientation.heightEstimateProperty(content),
hbar.heightProperty(),
layoutHeight,
(needsV, needsH, ch, hbh, lh) -> needsV || needsH && ch + hbh.doubleValue() > lh);
hbar.visibleProperty().bind(needsHBar);
vbar.visibleProperty().bind(needsVBar);
// request layout later, because if currently in layout, the request is ignored
hbar.visibleProperty().addListener(obs -> Platform.runLater(() -> requestLayout()));
vbar.visibleProperty().addListener(obs -> Platform.runLater(() -> requestLayout()));
getChildren().addAll(content, hbar, vbar);
}
public void dispose() {
content.dispose();
}
@Override
public Orientation getContentBias() {
return content.getContentBias();
}
public double getViewportWidth() {
return content.getWidth();
}
public double getViewportHeight() {
return content.getHeight();
}
public ReadOnlyDoubleProperty breadthOffsetProperty() {
return content.breadthOffsetProperty();
}
public Bounds cellToViewport(C cell, Bounds bounds) {
return cell.getNode().localToParent(bounds);
}
public Point2D cellToViewport(C cell, Point2D point) {
return cell.getNode().localToParent(point);
}
public Point2D cellToViewport(C cell, double x, double y) {
return cell.getNode().localToParent(x, y);
}
public void show(int index) {
content.show(index);
}
public void show(double primaryAxisOffset) {
content.show(primaryAxisOffset);
}
public void showAsFirst(int itemIndex) {
content.showAsFirst(itemIndex);
}
public void showAsLast(int itemIndex) {
content.showAsLast(itemIndex);
}
public void showAtOffset(int itemIndex, double offset) {
content.showAtOffset(itemIndex, offset);
}
public void show(int itemIndex, Bounds region) {
content.showRegion(itemIndex, region);
}
/**
* Scroll the content horizontally by the given amount.
* @param deltaX positive value scrolls right, negative value scrolls left
*/
public void scrollX(double deltaX) {
content.scrollX(deltaX);
}
/**
* Scroll the content vertically by the given amount.
* @param deltaY positive value scrolls down, negative value scrolls up
*/
public void scrollY(double deltaY) {
content.scrollY(deltaY);
}
/**
* If the item is out of view, instantiates a new cell for the item.
* The returned cell will be properly sized, but not properly positioned
* relative to the cells in the viewport, unless it is itself in the
* viewport.
*
* @return Cell for the given item. The cell will be valid only until the
* next layout pass. It should therefore not be stored. It is intended to
* be used for measurement purposes only.
*/
public C getCell(int itemIndex) {
return content.getCellFor(itemIndex);
}
public Optional<C> getCellIfVisible(int itemIndex) {
return content.getCellIfVisible(itemIndex);
}
public ObservableList<C> visibleCells() {
return content.visibleCells();
}
/**
* Hits this virtual flow at the given coordinates.
* @param x x offset from the left edge of the viewport
* @param y y offset from the top edge of the viewport
* @return hit info containing the cell that was hit and coordinates
* relative to the cell. If the hit was before the cells (i.e. above a
* vertical flow content or left of a horizontal flow content), returns
* a <em>hit before cells</em> containing offset from the top left corner
* of the content. If the hit was after the cells (i.e. below a vertical
* flow content or right of a horizontal flow content), returns a
* <em>hit after cells</em> containing offset from the top right corner of
* the content of a horizontal flow or bottom left corner of the content of
* a vertical flow.
*/
public VirtualFlowHit<C> hit(double x, double y) {
return content.hit(x, y);
}
@Override
protected double computePrefWidth(double height) {
return content.prefWidth(height);
}
@Override
protected double computePrefHeight(double width) {
return content.prefHeight(width);
}
@Override
protected double computeMinWidth(double height) {
return vbar.minWidth(-1);
}
@Override
protected double computeMinHeight(double width) {
return hbar.minHeight(-1);
}
@Override
protected double computeMaxWidth(double height) {
return content.maxWidth(height);
}
@Override
protected double computeMaxHeight(double width) {
return content.maxHeight(width);
}
@Override
protected void layoutChildren() {
double layoutWidth = getLayoutBounds().getWidth();
double layoutHeight = getLayoutBounds().getHeight();
boolean vbarVisible = vbar.isVisible();
boolean hbarVisible = hbar.isVisible();
double vbarWidth = vbarVisible ? vbar.prefWidth(-1) : 0;
double hbarHeight = hbarVisible ? hbar.prefHeight(-1) : 0;
double w = layoutWidth - vbarWidth;
double h = layoutHeight - hbarHeight;
content.resize(w, h);
hbar.setVisibleAmount(w);
vbar.setVisibleAmount(h);
if(vbarVisible) {
vbar.resizeRelocate(layoutWidth - vbarWidth, 0, vbarWidth, h);
}
if(hbarVisible) {
hbar.resizeRelocate(0, layoutHeight - hbarHeight, w, hbarHeight);
}
}
private static void setupUnitIncrement(ScrollBar bar) {
bar.unitIncrementProperty().bind(new DoubleBinding() {
{ bind(bar.maxProperty(), bar.visibleAmountProperty()); }
@Override
protected double computeValue() {
double max = bar.getMax();
double visible = bar.getVisibleAmount();
return max > visible
? 16 / (max - visible) * max
: 0;
}
});
}
}
|
package org.jpacman.framework.ui;
import java.awt.BorderLayout;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jpacman.framework.controller.IController;
import org.jpacman.framework.controller.RandomGhostMover;
import org.jpacman.framework.factory.FactoryException;
import org.jpacman.framework.factory.IGameFactory;
import org.jpacman.framework.model.IGameInteractor;
import org.jpacman.framework.model.Level;
import org.jpacman.framework.view.Animator;
import org.jpacman.framework.view.BoardView;
/**
* The main user interface for jpacman.
*
* @author Arie van Deursen, TU Delft, Jan 14, 2012
*/
public class MainUI extends JFrame implements Observer, IDisposable {
/**
* Universal version ID for serialization.
*/
static final long serialVersionUID = -59470379321937183L;
/**
* The level we're currently playing.
*/
private final Level level;
/**
* The underlying game.
*/
private transient IGameInteractor theGame;
/**
* Mapping of UI events to model actions.
*/
private transient PacmanInteraction pi;
/**
* The main window components.
*/
private PointsPanel points;
private BoardView boardView;
private ButtonPanel buttonPanel;
private JTextField statusField;
private JPanel statusPanel;
/**
* Controllers that will trigger certain events.
*/
private transient IController ghostController;
private transient Animator animator;
/**
* Create a new UI for the default board.
*/
public MainUI() {
level = new Level();
}
/**
* Create all the ui components and attach appropriate
* listeners.
* @throws FactoryException If resources for game can't be loaded.
* @return The main UI object
*/
public MainUI createUI() throws FactoryException {
assert getGame() != null;
assert ghostController != null;
boardView = createBoardView();
animator = new Animator(boardView);
if (pi == null) { pi = new PacmanInteraction(); }
pi.withDisposable(this)
.withGameInteractor(getGame())
.controlling(ghostController)
.controlling(animator);
addKeyListener(new PacmanKeyListener(pi));
getGame().attach(pi);
createButtonPanel(pi).initialize();
createStatusPanel();
JPanel mainGrid = createMainGrid();
getContentPane().add(mainGrid);
setGridSize();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setName("jpacman.main");
setTitle("JPacman");
return this;
}
/**
* Create a panel containing the start/stop buttons.
* @param pi Interactor capable of performing requested actions.
* @return The new panel with buttons.
*/
protected ButtonPanel createButtonPanel(PacmanInteraction pi) {
assert pi != null;
if (buttonPanel == null) {
buttonPanel = new ButtonPanel();
}
return buttonPanel
.withParent(this)
.withInteractor(pi);
}
/**
* Create the main grid containing all UI elements.
* @return The newly created main grid.
*/
private JPanel createMainGrid() {
JPanel mainGrid = new JPanel();
mainGrid.setLayout(new BorderLayout());
mainGrid.setName("jpacman.topdown");
mainGrid.add(statusPanel, BorderLayout.NORTH);
mainGrid.add(boardView, BorderLayout.CENTER);
mainGrid.add(buttonPanel, BorderLayout.SOUTH);
return mainGrid;
}
/**
* Establish the appropriate size of the main window,
* based on the sizes of the underlying components.
*/
private void setGridSize() {
int width = Math.max(boardView.windowWidth(),
buttonPanel.getWidth());
int height =
points.getHeight()
+ boardView.windowHeight()
+ buttonPanel.getHeight();
setSize(width, height);
}
private void createStatusField() {
final int statusWidth = 12;
statusField = new JTextField("", statusWidth);
statusField.setEditable(false);
statusField.setName("jpacman.status");
}
/**
* Create the status panel displaying points,
* whether the player is alive, etc.
*/
protected void createStatusPanel() {
statusPanel = new JPanel();
createStatusField();
points = new PointsPanel();
points.initialize(getGame().getPointManager());
getGame().attach(points);
statusPanel.add(statusField);
statusPanel.add(points);
}
/**
* The state of the game has changed.
* Reset button enabling depending on the state.
* @param o Ignored
* @param arg Ignored
*/
@Override
public void update(Observable o, Object arg) {
statusField.setText(pi.getCurrentState().message());
boardView.repaint();
}
/**
* Create the controllers.
* @throws FactoryException If required resources can't be loaded.
* @return The main UI object.
*/
public MainUI initialize() throws FactoryException {
theGame = createModel();
getGame().attach(this);
return this;
}
/**
* Creates the controllers, sets a ghostmover and creates the ui.
* Quickstart for normal gameplay.
* @throws FactoryException If required resources can't be loaded.
* @return The main UI object.
*/
public MainUI initializeNormalGame() throws FactoryException {
initialize();
withGhostController(new RandomGhostMover(getGame()));
createUI();
return this;
}
/**
* Actually start the the controllers, and show the UI.
*/
public void start() {
animator.start();
setVisible(true);
requestFocus();
}
private BoardView createBoardView() throws FactoryException {
return new BoardView(getGame().getBoardInspector());
}
/**
* Read a board from file and load it.
* @return The resulting game.
* @throws FactoryException
*/
private IGameInteractor createModel() throws FactoryException {
return level.parseMap();
}
/**
* @return The mapping between keyboard events and model events.
*/
public PacmanInteraction eventHandler() {
return pi;
}
/**
* @return The underlying game.
*/
public IGameInteractor getGame() {
return theGame;
}
/**
* @return The ghostController
*/
public IController getGhostController() {
return ghostController;
}
/**
* Provide a given ghost controller.
* This function can only be called before the createUI function.
* @param gc The new ghost controller.
* @return Itself for fluency.
*/
public MainUI withGhostController(IController gc) {
assert gc != null;
//The animator is not null if the createUI has already been called.
//If this is the case, the GhostController should not be allowed to change,
//because changes cannot be forwarded correctly.
assert animator == null;
ghostController = gc;
return this;
}
/**
* Provide the name of the file containing the board.
* @param fileName Board file name.
* @return Itself for fluency.
*/
public MainUI withBoard(String fileName) {
assert fileName != null;
level.setMapFile(fileName);
return this;
}
/**
* Provide a factory to create model elements.
* @param fact The actual factory
* @return Itself for fluency.
*/
public MainUI withFactory(IGameFactory fact) {
assert fact != null;
assert level != null;
level.setFactory(fact);
return this;
}
/**
* Provide the row of buttons.
* @param bp The new row of buttons
* @return Itself for fluency
*/
public MainUI withButtonPanel(ButtonPanel bp) {
assert bp != null;
buttonPanel = bp;
return this;
}
/**
* Proivde the interface to interact with the model.
* @param pi New model interactor.
* @return Itself for fluency.
*/
public MainUI withModelInteractor(PacmanInteraction pi) {
assert pi != null;
this.pi = pi;
return this;
}
/**
* Top level method creating the game, and
* starting up the interactions.
* @throws FactoryException If creating the game fails.
*/
public void main() throws FactoryException {
initializeNormalGame();
start();
}
/**
* Main starting point of the JPacman game.
* @param args Ignored
* @throws FactoryException If reading game map fails.
*/
public static void main(String[] args) throws FactoryException {
new MainUI().main();
}
}
|
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.ConnectionContainer;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.LogUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author Levan Tsinadze
* @since 0.0.45-SNAPSHOT
*/
public class Watcher implements Runnable {
// Name of deployment watch service thread
private static final String DEPLOY_THREAD_NAME = "watch_thread";
// Priority of deployment watch service thread
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
// Sleep time of thread between watch service status scans
private static final long SLEEP_TIME = 5500L;
// Thread pool for watch service threads
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
// Sets of directories of application deployments
private Set<DeploymentDirectory> deployments;
// Sets of data source descriptor file paths
private Set<String> dataSources;
// Zero / default status for watch service
private static final int ZERO_WATCH_STATUS = 0;
// Error code for java main process exit
private static final int ERROR_EXIT = -1;
private static final Logger LOG = Logger.getLogger(Watcher.class);
/**
* Defines file types for watch service
*
* @author Levan
* @since 0.0.45-SNAPSHOT
*/
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
* @since 0.0.45-SNAPSHOT
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
/**
* Clears and gets file {@link URL} by file name
*
* @param fileName
* @return {@link URL}
* @throws IOException
*/
private static URL getAppropriateURL(String fileName) throws IOException {
URL url;
File file = new File(fileName);
url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
/**
* Gets {@link Set} of {@link DeploymentDirectory} instances from
* configuration
*
* @return {@link Set}<code><DeploymentDirectory></code>
*/
private static Set<DeploymentDirectory> getDeployDirectories() {
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
/**
* Gets {@link Set} of data source paths from configuration
*
* @return {@link Set}<code><String></code>
*/
private static Set<String> getDataSourcePaths() {
Set<String> paths = new HashSet<String>();
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
/**
* Checks and gets appropriated {@link WatchFileType} by passed file name
*
* @param fileName
* @return {@link WatchFileType}
*/
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (CollectionUtils.valid(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = ObjectUtils.notEquals(deploymantPath,
parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (CollectionUtils.valid(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
/**
* Fills passed {@link List} of {@link File}s by passed {@link File} array
*
* @param files
* @param list
*/
private static void fillFileList(File[] files, List<File> list) {
if (CollectionUtils.valid(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
List<File> list = new ArrayList<File>();
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (CollectionUtils.valid(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
if (CollectionUtils.valid(deploymetDirss)) {
String path;
DeployFiletr filter = new DeployFiletr();
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(filter);
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
List<File> list = new ArrayList<File>();
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (CollectionUtils.valid(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
if (CollectionUtils.valid(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
/**
* Deploys application or data source file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
/**
* Deploys application or data source file by passed {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
/**
* Removes from deployments application or data source file by passed
* {@link URL} instance
*
* @param url
* @throws IOException
*/
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
/**
* Removes from deployments application or data source file by passed file
* name
*
* @param fileName
* @throws IOException
*/
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
/**
* Removes from deployments and deploys again application or data source
* file by passed file name
*
* @param fileName
* @throws IOException
*/
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
/**
* Handles file change event
*
* @param dir
* @param currentEvent
* @throws IOException
*/
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (ObjectUtils.notNull(currentEvent)) {
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count);
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count);
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count);
redeployFile(fileName);
}
}
}
/**
* Runs file watch service
*
* @param watch
* @throws IOException
*/
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = ZERO_WATCH_STATUS;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == ZERO_WATCH_STATUS
|| event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
/**
* Registers path to watch service
*
* @param fs
* @param path
* @param watch
* @throws IOException
*/
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
/**
* Registers passed {@link File} array to watch service
*
* @param files
* @param fs
* @param watch
* @throws IOException
*/
private void registerPaths(File[] files, FileSystem fs, WatchService watch)
throws IOException {
String path;
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
/**
* Registers deployments directories to watch service
*
* @param deploymentDirss
* @param fs
* @param watch
* @throws IOException
*/
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (CollectionUtils.valid(files)) {
registerPaths(files, fs, watch);
}
} else {
registerPath(fs, path, watch);
}
}
}
/**
* Registers data source path to watch service
*
* @param paths
* @param fs
* @param watch
* @throws IOException
*/
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (CollectionUtils.valid(deployments)) {
registerPaths(deployments, fs, watch);
}
if (CollectionUtils.valid(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
ConnectionContainer.closeConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(ERROR_EXIT);
} finally {
DEPLOY_POOL.shutdown();
}
}
/**
* Starts watch service for application and data source files
*/
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
}
|
package org.lightmare.deploy.fs;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import org.lightmare.cache.DeploymentDirectory;
import org.lightmare.cache.MetaContainer;
import org.lightmare.cache.RestContainer;
import org.lightmare.config.Configuration;
import org.lightmare.deploy.MetaCreator;
import org.lightmare.jpa.datasource.FileParsers;
import org.lightmare.jpa.datasource.Initializer;
import org.lightmare.rest.providers.RestProvider;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
import org.lightmare.utils.fs.WatchUtils;
/**
* Deployment manager, {@link Watcher#deployFile(URL)},
* {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and
* {@link File} modification event handler for deployments if java version is
* 1.7 or above
*
* @author levan
*
*/
public class Watcher implements Runnable {
private static final String DEPLOY_THREAD_NAME = "watch_thread";
private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5;
private static final long SLEEP_TIME = 5500L;
private static final ExecutorService DEPLOY_POOL = Executors
.newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME,
DEPLOY_POOL_PRIORITY));
private Set<DeploymentDirectory> deployments;
private Set<String> dataSources;
private static final Logger LOG = Logger.getLogger(Watcher.class);
private static enum WatchFileType {
DATA_SOURCE, DEPLOYMENT, NONE;
}
/**
* To filter only deployed sub files from directory
*
* @author levan
*
*/
private static class DeployFiletr implements FileFilter {
@Override
public boolean accept(File file) {
boolean accept;
try {
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
accept = MetaContainer.chackDeployment(url);
} catch (MalformedURLException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
accept = false;
}
return accept;
}
}
private Watcher() {
deployments = getDeployDirectories();
dataSources = getDataSourcePaths();
}
private static URL getAppropriateURL(String fileName) throws IOException {
File file = new File(fileName);
URL url = file.toURI().toURL();
url = WatchUtils.clearURL(url);
return url;
}
private static Set<DeploymentDirectory> getDeployDirectories() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (config.isWatchStatus()
&& ObjectUtils.available(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
return deploymetDirss;
}
private static Set<String> getDataSourcePaths() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (config.isWatchStatus() && ObjectUtils.available(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
return paths;
}
private static WatchFileType checkType(String fileName) {
WatchFileType type;
File file = new File(fileName);
String path = file.getPath();
String filePath = WatchUtils.clearPath(path);
path = file.getParent();
String parentPath = WatchUtils.clearPath(path);
Set<DeploymentDirectory> apps = getDeployDirectories();
Set<String> dss = getDataSourcePaths();
if (ObjectUtils.available(apps)) {
String deploymantPath;
Iterator<DeploymentDirectory> iterator = apps.iterator();
boolean notDeployment = Boolean.TRUE;
DeploymentDirectory deployment;
while (iterator.hasNext() && notDeployment) {
deployment = iterator.next();
deploymantPath = deployment.getPath();
notDeployment = !deploymantPath.equals(parentPath);
}
if (notDeployment) {
type = WatchFileType.NONE;
} else {
type = WatchFileType.DEPLOYMENT;
}
} else if (ObjectUtils.available(dss) && dss.contains(filePath)) {
type = WatchFileType.DATA_SOURCE;
} else {
type = WatchFileType.NONE;
}
return type;
}
private static void fillFileList(File[] files, List<File> list) {
if (ObjectUtils.available(files)) {
for (File file : files) {
list.add(file);
}
}
}
/**
* Lists all deployed {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDeployments() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>();
Set<DeploymentDirectory> deploymetDirssCurrent;
for (Configuration config : configs) {
deploymetDirssCurrent = config.getDeploymentPath();
if (ObjectUtils.available(deploymetDirssCurrent)) {
deploymetDirss.addAll(deploymetDirssCurrent);
}
}
File[] files;
List<File> list = new ArrayList<File>();
if (ObjectUtils.available(deploymetDirss)) {
String path;
for (DeploymentDirectory deployment : deploymetDirss) {
path = deployment.getPath();
files = new File(path).listFiles(new DeployFiletr());
fillFileList(files, list);
}
}
return list;
}
/**
* Lists all data source {@link File}s
*
* @return {@link List}<File>
*/
public static List<File> listDataSources() {
Collection<Configuration> configs = MetaContainer.CONFIGS.values();
Set<String> paths = new HashSet<String>();
Set<String> pathsCurrent;
for (Configuration config : configs) {
pathsCurrent = config.getDataSourcePath();
if (ObjectUtils.available(pathsCurrent)) {
paths.addAll(pathsCurrent);
}
}
File file;
List<File> list = new ArrayList<File>();
if (ObjectUtils.available(paths)) {
for (String path : paths) {
file = new File(path);
list.add(file);
}
}
return list;
}
public static void deployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
FileParsers fileParsers = new FileParsers();
fileParsers.parseStandaloneXml(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
deployFile(url);
}
}
public static void deployFile(URL url) throws IOException {
URL[] archives = { url };
MetaContainer.getCreator().scanForBeans(archives);
}
public static void undeployFile(URL url) throws IOException {
boolean valid = MetaContainer.undeploy(url);
if (valid && RestContainer.hasRest()) {
RestProvider.reload();
}
}
public static void undeployFile(String fileName) throws IOException {
WatchFileType type = checkType(fileName);
if (type.equals(WatchFileType.DATA_SOURCE)) {
Initializer.undeploy(fileName);
} else if (type.equals(WatchFileType.DEPLOYMENT)) {
URL url = getAppropriateURL(fileName);
undeployFile(url);
}
}
public static void redeployFile(String fileName) throws IOException {
undeployFile(fileName);
deployFile(fileName);
}
private void handleEvent(Path dir, WatchEvent<Path> currentEvent)
throws IOException {
if (currentEvent == null) {
return;
}
Path prePath = currentEvent.context();
Path path = dir.resolve(prePath);
String fileName = path.toString();
int count = currentEvent.count();
Kind<?> kind = currentEvent.kind();
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
LOG.info(String.format("Modify: %s, count: %s\n", fileName, count));
redeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
LOG.info(String.format("Delete: %s, count: %s\n", fileName, count));
undeployFile(fileName);
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
LOG.info(String.format("Create: %s, count: %s\n", fileName, count));
redeployFile(fileName);
}
}
private void runService(WatchService watch) throws IOException {
Path dir;
boolean toRun = true;
boolean valid;
while (toRun) {
try {
WatchKey key;
key = watch.take();
List<WatchEvent<?>> events = key.pollEvents();
WatchEvent<?> currentEvent = null;
WatchEvent<Path> typedCurrentEvent;
int times = 0;
dir = (Path) key.watchable();
for (WatchEvent<?> event : events) {
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (times == 0 || event.count() > currentEvent.count()) {
currentEvent = event;
}
times++;
valid = key.reset();
toRun = valid && key.isValid();
if (toRun) {
Thread.sleep(SLEEP_TIME);
typedCurrentEvent = ObjectUtils.cast(currentEvent);
handleEvent(dir, typedCurrentEvent);
}
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
}
}
private void registerPath(FileSystem fs, String path, WatchService watch)
throws IOException {
Path deployPath = fs.getPath(path);
deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.OVERFLOW,
StandardWatchEventKinds.ENTRY_DELETE);
runService(watch);
}
private void registerPaths(Collection<DeploymentDirectory> deploymentDirss,
FileSystem fs, WatchService watch) throws IOException {
String path;
boolean scan;
File directory;
File[] files;
for (DeploymentDirectory deployment : deploymentDirss) {
path = deployment.getPath();
scan = deployment.isScan();
if (scan) {
directory = new File(path);
files = directory.listFiles();
if (ObjectUtils.available(files)) {
for (File file : files) {
path = file.getPath();
registerPath(fs, path, watch);
}
}
} else {
registerPath(fs, path, watch);
}
}
}
private void registerDsPaths(Collection<String> paths, FileSystem fs,
WatchService watch) throws IOException {
for (String path : paths) {
registerPath(fs, path, watch);
}
}
@Override
public void run() {
try {
FileSystem fs = FileSystems.getDefault();
WatchService watch = null;
try {
watch = fs.newWatchService();
} catch (IOException ex) {
LOG.error(ex.getMessage(), ex);
throw ex;
}
if (ObjectUtils.available(deployments)) {
registerPaths(deployments, fs, watch);
}
if (ObjectUtils.available(dataSources)) {
registerDsPaths(dataSources, fs, watch);
}
} catch (IOException ex) {
LOG.fatal(ex.getMessage(), ex);
LOG.fatal("system going to shut down cause of hot deployment");
try {
MetaCreator.closeAllConnections();
} catch (IOException iex) {
LOG.fatal(iex.getMessage(), iex);
}
System.exit(-1);
} finally {
DEPLOY_POOL.shutdown();
}
}
public static void startWatch() {
Watcher watcher = new Watcher();
DEPLOY_POOL.submit(watcher);
}
}
|
package org.nnsoft.shs;
import static org.nnsoft.shs.lang.Preconditions.checkArgument;
import static java.nio.channels.SelectionKey.OP_ACCEPT;
import static java.nio.channels.ServerSocketChannel.open;
import static java.nio.channels.spi.SelectorProvider.provider;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static org.nnsoft.shs.HttpServer.Status.INITIALIZED;
import static org.nnsoft.shs.HttpServer.Status.RUNNING;
import static org.nnsoft.shs.HttpServer.Status.STOPPED;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import org.nnsoft.shs.dispatcher.RequestDispatcher;
import org.slf4j.Logger;
/**
* A simple {@link HttpServer} implementation.
*
* This class must NOT be shared across threads, consider it be used inside main(String...) method.
*/
public final class SimpleHttpServer
implements HttpServer, Runnable
{
private final Logger logger = getLogger( getClass() );
private ExecutorService requestsExecutor;
private RequestDispatcher dispatcher;
private ServerSocketChannel server;
private Selector selector;
private Status currentStatus = STOPPED;
/**
* {@inheritDoc}
*/
public void init( int port, int threads, RequestDispatcher dispatcher )
throws InitException
{
checkArgument( port > 0, "Impossible to listening on port %s, it must be a positive number", port );
checkArgument( threads > 0, "Impossible to serve requests with negative or none threads" );
checkArgument( dispatcher != null, "Impossible to serve requests with a null dispatcher" );
if ( currentStatus != STOPPED )
{
throw new InitException( "Current server cannot be configured while in %s status.", currentStatus );
}
logger.info( "Initializing server using {} threads...", threads );
requestsExecutor = newFixedThreadPool( threads );
logger.info( "Done! Initializing the request dispatcher..." );
this.dispatcher = dispatcher;
logger.info( "Done! listening on port {} ...", port );
try
{
server = open();
server.socket().bind( new InetSocketAddress( port ) );
server.configureBlocking( false );
selector = provider().openSelector();
server.register( selector, OP_ACCEPT );
}
catch ( IOException e )
{
throw new InitException( "Impossible to start server on port %s (with %s threads): %s",
port, threads, e.getMessage() );
}
logger.info( "Done! Server has been successfully initialized, it can be now started" );
currentStatus = INITIALIZED;
}
/**
* {@inheritDoc}
*/
public void start()
throws RunException
{
if ( currentStatus != INITIALIZED )
{
throw new RunException( "Current server cannot be configured while in %s status, stop then init again before.",
currentStatus );
}
logger.info( "Server is starting up..." );
requestsExecutor.submit( this );
logger.info( "Server successfully started! Waiting for new requests..." );
currentStatus = RUNNING;
}
/**
* {@inheritDoc}
*/
public void run()
{
while ( currentStatus == RUNNING )
{
// Wait for an event one of the registered channels
try
{
selector.select();
}
catch ( IOException ioe )
{
logger.error( "Something wrong happened while listening for connections: {}", ioe.getMessage() );
try
{
stop();
}
catch ( ShutdownException se )
{
logger.error( "Server not correctly shutdow, see nested exceptions", se );
}
throw new RuntimeException( new RunException( "A fatal error occurred while waiting for clients: %s",
ioe.getMessage() ) );
}
// Iterate over the set of keys for which events are available
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while ( selectedKeys.hasNext() )
{
SelectionKey key = selectedKeys.next();
selectedKeys.remove();
if ( !key.isValid() )
{
continue;
}
// Check what event is available and deal with it
if ( key.isAcceptable() )
{
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
try
{
SocketChannel socketChannel = serverSocketChannel.accept();
Socket socket = socketChannel.socket();
requestsExecutor.submit( new SocketRunnable( dispatcher, socket ) );
}
catch ( IOException e )
{
logger.warn( "Impossible to accept client request: {}", e.getMessage() );
}
}
}
}
}
/**
* {@inheritDoc}
*/
public void stop()
throws ShutdownException
{
if ( currentStatus != RUNNING )
{
throw new ShutdownException( "Current server cannot be stopped while in %s status.",
currentStatus );
}
logger.info( "Server is shutting down..." );
logger.info( "Closing the request listener..." );
try
{
if ( selector != null && selector.isOpen() )
{
selector.close();
}
}
catch ( IOException e )
{
throw new ShutdownException( "An error occurred while closing the request listener: %s", e.getMessage() );
}
finally
{
logger.info( "Done! Closing all server resources..." );
try
{
if ( server != null && server.isOpen() )
{
server.close();
}
}
catch ( IOException e )
{
throw new ShutdownException( "An error occurred while shutting down the server: %s", e.getMessage() );
}
finally
{
requestsExecutor.shutdown();
logger.info( "Done! Server is now stopped. Bye!" );
currentStatus = STOPPED;
}
}
}
/**
* {@inheritDoc}
*/
public Status getStatus()
{
return currentStatus;
}
}
|
package org.sqlite.jdbc3;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.Arrays;
import org.sqlite.ExtendedCommand;
import org.sqlite.ExtendedCommand.SQLExtension;
import org.sqlite.SQLiteConnection;
import org.sqlite.core.CoreStatement;
import org.sqlite.core.DB;
import org.sqlite.core.DB.ProgressObserver;
public abstract class JDBC3Statement extends CoreStatement {
// PUBLIC INTERFACE /////////////////////////////////////////////
protected JDBC3Statement(SQLiteConnection conn) {
super(conn);
}
/** @see java.sql.Statement#close() */
public void close() throws SQLException {
internalClose();
}
/** @see java.sql.Statement#execute(java.lang.String) */
public boolean execute(String sql) throws SQLException {
internalClose();
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
ext.execute(conn.getDatabase());
return false;
}
this.sql = sql;
conn.getDatabase().prepare(this);
return exec();
}
/** @see java.sql.Statement#execute(java.lang.String, int) */
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return execute(sql);
}
/**
* @param closeStmt Whether to close this statement when the resultset is closed.
* @see java.sql.Statement#executeQuery(java.lang.String)
*/
public ResultSet executeQuery(String sql, boolean closeStmt) throws SQLException {
rs.closeStmt = closeStmt;
return executeQuery(sql);
}
/** @see java.sql.Statement#executeQuery(java.lang.String) */
public ResultSet executeQuery(String sql) throws SQLException {
internalClose();
this.sql = sql;
conn.getDatabase().prepare(this);
if (!exec()) {
internalClose();
throw new SQLException("query does not return ResultSet", "SQLITE_DONE", SQLITE_DONE);
}
return getResultSet();
}
static class BackupObserver implements ProgressObserver {
public void progress(int remaining, int pageCount) {
System.out.println(String.format("remaining:%d, page count:%d", remaining, pageCount));
}
}
/** @see java.sql.Statement#executeUpdate(java.lang.String) */
public int executeUpdate(String sql) throws SQLException {
return (int) executeLargeUpdate(sql);
}
/** @see java.sql.Statement#executeUpdate(java.lang.String, int) */
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return executeUpdate(sql);
}
/** @see java.sql.Statement#executeLargeUpdate(java.lang.String) */
public long executeLargeUpdate(String sql) throws SQLException {
internalClose();
this.sql = sql;
DB db = conn.getDatabase();
long changes = 0;
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
// execute extended command
ext.execute(db);
} else {
try {
changes = db.total_changes();
// directly invokes the exec API to support multiple SQL statements
int statusCode = db._exec(sql);
if (statusCode != SQLITE_OK) throw DB.newSQLException(statusCode, "");
changes = db.total_changes() - changes;
} finally {
internalClose();
}
}
return changes;
}
/** @see java.sql.Statement#executeLargeUpdate(java.lang.String, int) */
public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return executeLargeUpdate(sql);
}
/** @see java.sql.Statement#getResultSet() */
public ResultSet getResultSet() throws SQLException {
checkOpen();
if (rs.isOpen()) {
throw new SQLException("ResultSet already requested");
}
if (pointer.safeRunInt(DB::column_count) == 0) {
return null;
}
if (rs.colsMeta == null) {
rs.colsMeta = pointer.safeRun(DB::column_names);
}
rs.cols = rs.colsMeta;
rs.emptyResultSet = !resultsWaiting;
rs.open = true;
resultsWaiting = false;
return (ResultSet) rs;
}
/**
* This function has a complex behaviour best understood by carefully reading the JavaDoc for
* getMoreResults() and considering the test StatementTest.execute().
*
* @see java.sql.Statement#getUpdateCount()
*/
public int getUpdateCount() throws SQLException {
return (int) getLargeUpdateCount();
}
/**
* This function has a complex behaviour best understood by carefully reading the JavaDoc for
* getMoreResults() and considering the test StatementTest.execute().
*
* @see java.sql.Statement#getLargeUpdateCount()
*/
public long getLargeUpdateCount() throws SQLException {
DB db = conn.getDatabase();
if (!pointer.isClosed()
&& !rs.isOpen()
&& !resultsWaiting
&& pointer.safeRunInt(DB::column_count) == 0) return db.changes();
return -1;
}
/** @see java.sql.Statement#addBatch(java.lang.String) */
public void addBatch(String sql) throws SQLException {
internalClose();
if (batch == null || batchPos + 1 >= batch.length) {
Object[] nb = new Object[Math.max(10, batchPos * 2)];
if (batch != null) System.arraycopy(batch, 0, nb, 0, batch.length);
batch = nb;
}
batch[batchPos++] = sql;
}
/** @see java.sql.Statement#clearBatch() */
public void clearBatch() throws SQLException {
batchPos = 0;
if (batch != null) for (int i = 0; i < batch.length; i++) batch[i] = null;
}
/** @see java.sql.Statement#executeBatch() */
public int[] executeBatch() throws SQLException {
return Arrays.stream(executeLargeBatch()).mapToInt(l -> (int) l).toArray();
}
/** @see java.sql.Statement#executeLargeBatch() */
public long[] executeLargeBatch() throws SQLException {
// TODO: optimize
internalClose();
if (batch == null || batchPos == 0) return new long[] {};
long[] changes = new long[batchPos];
DB db = conn.getDatabase();
synchronized (db) {
try {
for (int i = 0; i < changes.length; i++) {
try {
this.sql = (String) batch[i];
db.prepare(this);
changes[i] = db.executeUpdate(this, null);
} catch (SQLException e) {
throw new BatchUpdateException(
"batch entry " + i + ": " + e.getMessage(), null, 0, changes, e);
} finally {
if (pointer != null) pointer.close();
}
}
} finally {
clearBatch();
}
}
return changes;
}
/** @see java.sql.Statement#setCursorName(java.lang.String) */
public void setCursorName(String name) {}
/** @see java.sql.Statement#getWarnings() */
public SQLWarning getWarnings() throws SQLException {
return null;
}
/** @see java.sql.Statement#clearWarnings() */
public void clearWarnings() throws SQLException {}
/** @see java.sql.Statement#getConnection() */
public Connection getConnection() throws SQLException {
return conn;
}
/** @see java.sql.Statement#cancel() */
public void cancel() throws SQLException {
conn.getDatabase().interrupt();
}
/** @see java.sql.Statement#getQueryTimeout() */
public int getQueryTimeout() throws SQLException {
return conn.getBusyTimeout();
}
/** @see java.sql.Statement#setQueryTimeout(int) */
public void setQueryTimeout(int seconds) throws SQLException {
if (seconds < 0) throw new SQLException("query timeout must be >= 0");
conn.setBusyTimeout(1000 * seconds);
}
// TODO: write test
/** @see java.sql.Statement#getMaxRows() */
public int getMaxRows() throws SQLException {
// checkOpen();
return (int) rs.maxRows;
}
/** @see java.sql.Statement#getLargeMaxRows() */
public long getLargeMaxRows() throws SQLException {
// checkOpen();
return rs.maxRows;
}
/** @see java.sql.Statement#setMaxRows(int) */
public void setMaxRows(int max) throws SQLException {
setLargeMaxRows(max);
}
/** @see java.sql.Statement#setLargeMaxRows(long) */
public void setLargeMaxRows(long max) throws SQLException {
// checkOpen();
if (max < 0) throw new SQLException("max row count must be >= 0");
rs.maxRows = max;
}
/** @see java.sql.Statement#getMaxFieldSize() */
public int getMaxFieldSize() throws SQLException {
return 0;
}
/** @see java.sql.Statement#setMaxFieldSize(int) */
public void setMaxFieldSize(int max) throws SQLException {
if (max < 0) throw new SQLException("max field size " + max + " cannot be negative");
}
/** @see java.sql.Statement#getFetchSize() */
public int getFetchSize() throws SQLException {
return ((ResultSet) rs).getFetchSize();
}
/** @see java.sql.Statement#setFetchSize(int) */
public void setFetchSize(int r) throws SQLException {
((ResultSet) rs).setFetchSize(r);
}
/** @see java.sql.Statement#getFetchDirection() */
public int getFetchDirection() throws SQLException {
return ResultSet.FETCH_FORWARD;
}
/** @see java.sql.Statement#setFetchDirection(int) */
public void setFetchDirection(int direction) throws SQLException {
switch (direction) {
case ResultSet.FETCH_FORWARD:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_UNKNOWN:
// No-op: SQLite does not support a value other than FETCH_FORWARD
break;
default:
throw new SQLException(
"Unknown fetch direction "
+ direction
+ ". "
+ "Must be one of FETCH_FORWARD, FETCH_REVERSE, or FETCH_UNKNOWN in java.sql.ResultSet");
}
}
/**
* As SQLite's last_insert_rowid() function is DB-specific not statement specific, this function
* introduces a race condition if the same connection is used by two threads and both insert.
*
* @see java.sql.Statement#getGeneratedKeys()
*/
public ResultSet getGeneratedKeys() throws SQLException {
return conn.getSQLiteDatabaseMetaData().getGeneratedKeys();
}
/**
* SQLite does not support multiple results from execute().
*
* @see java.sql.Statement#getMoreResults()
*/
public boolean getMoreResults() throws SQLException {
return getMoreResults(0);
}
/** @see java.sql.Statement#getMoreResults(int) */
public boolean getMoreResults(int c) throws SQLException {
checkOpen();
internalClose(); // as we never have another result, clean up pointer
return false;
}
/** @see java.sql.Statement#getResultSetConcurrency() */
public int getResultSetConcurrency() throws SQLException {
return ResultSet.CONCUR_READ_ONLY;
}
/** @see java.sql.Statement#getResultSetHoldability() */
public int getResultSetHoldability() throws SQLException {
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
/** @see java.sql.Statement#getResultSetType() */
public int getResultSetType() throws SQLException {
return ResultSet.TYPE_FORWARD_ONLY;
}
/** @see java.sql.Statement#setEscapeProcessing(boolean) */
public void setEscapeProcessing(boolean enable) throws SQLException {
if (enable) {
throw unused();
}
}
protected SQLException unused() {
return new SQLException("not implemented by SQLite JDBC driver");
}
// Statement ////////////////////////////////////////////////////
public boolean execute(String sql, int[] colinds) throws SQLException {
throw unused();
}
public boolean execute(String sql, String[] colnames) throws SQLException {
throw unused();
}
public int executeUpdate(String sql, int[] colinds) throws SQLException {
throw unused();
}
public int executeUpdate(String sql, String[] cols) throws SQLException {
throw unused();
}
}
|
package org.testng.reporters;
import org.testng.IReporter;
import org.testng.IResultMap;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.collections.ListMultiMap;
import org.testng.collections.Maps;
import org.testng.internal.Utils;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JqReporter implements IReporter {
private String m_outputDirectory;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
String outputDirectory) {
m_outputDirectory = "/Users/cedric/java/misc/jquery";
XMLStringBuffer xsb = new XMLStringBuffer(" ");
xsb.push("div", "id", "suites");
generateSuites(xmlSuites, suites, xsb);
xsb.pop("div");
String all;
try {
all = Files.readFile(new File("/Users/cedric/java/misc/jquery/head"));
Utils.writeFile(m_outputDirectory, "index2.html", all + xsb.toXML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private XMLStringBuffer generateSuites(List<XmlSuite> xmlSuites,
List<ISuite> suites, XMLStringBuffer xsb) {
for (ISuite suite : suites) {
if (suite.getResults().size() == 0) {
continue;
}
xsb.push("div", "class", "suite");
xsb.addOptional("span", suite.getName(), "class", "suite-name");
xsb.push("div", "class", "suite-content");
Map<String, ISuiteResult> results = suite.getResults();
XMLStringBuffer xs1 = new XMLStringBuffer(" ");
XMLStringBuffer xs2 = new XMLStringBuffer(" ");
XMLStringBuffer xs3 = new XMLStringBuffer(" ");
for (ISuiteResult result : results.values()) {
ITestContext context = result.getTestContext();
generateTests("failed", context.getFailedTests(), context, xs1);
generateTests("skipped", context.getSkippedTests(), context, xs2);
generateTests("passed", context.getPassedTests(), context, xs3);
}
xsb.addOptional("div", "Failed" + " tests", "class", "result-banner " + "failed");
xsb.addString(xs1.toXML());
xsb.addOptional("div", "Skipped" + " tests", "class", "result-banner " + "skipped");
xsb.addString(xs2.toXML());
xsb.addOptional("div", "Passed" + " tests", "class", "result-banner " + "passed");
xsb.addString(xs3.toXML());
}
xsb.pop("div");
xsb.pop("div");
return xsb;
}
private String capitalize(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
private void generateTests(String tagClass, IResultMap tests, ITestContext context,
XMLStringBuffer xsb) {
if (tests.getAllMethods().isEmpty()) return;
xsb.push("div", "class", "test" + (tagClass != null ? " " + tagClass : ""));
ListMultiMap<Class<?>, ITestResult> map = Maps.newListMultiMap();
for (ITestResult m : tests.getAllResults()) {
map.put(m.getTestClass().getRealClass(), m);
}
xsb.push("a", "href", "
xsb.addOptional("span", context.getName(), "class", "test-name");
xsb.pop("a");
xsb.push("div", "class", "test-content");
for (Class<?> c : map.getKeys()) {
xsb.push("div", "class", "class");
xsb.addOptional("span", c.getName(), "class", "class-name");
xsb.push("div", "class", "class-content");
List<ITestResult> l = map.get(c);
for (ITestResult m : l) {
generateMethod(tagClass, m, context, xsb);
}
xsb.pop("div");
xsb.pop("div");
}
xsb.pop("div");
xsb.pop("div");
}
private void generateMethod(String tagClass, ITestResult tr,
ITestContext context, XMLStringBuffer xsb) {
long time = tr.getEndMillis() - tr.getStartMillis();
xsb.push("div", "class", "method");
xsb.push("div", "class", "method-content");
xsb.addOptional("span", tr.getMethod().getMethodName(), "class", "method-name");
xsb.addOptional("span", " (" + Long.toString(time) + " ms)", "class", "method-time");
xsb.pop("div");
xsb.pop("div");
}
/**
* Overridable by subclasses to create different directory names (e.g. with timestamps).
* @param outputDirectory the output directory specified by the user
*/
protected String generateOutputDirectoryName(String outputDirectory) {
return outputDirectory;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.