diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/components/bio-formats/src/loci/formats/in/SlidebookReader.java b/components/bio-formats/src/loci/formats/in/SlidebookReader.java
index fe94ce96b..c6699f747 100644
--- a/components/bio-formats/src/loci/formats/in/SlidebookReader.java
+++ b/components/bio-formats/src/loci/formats/in/SlidebookReader.java
@@ -1,629 +1,630 @@
//
// SlidebookReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.RandomAccessInputStream;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
/**
* SlidebookReader is the file format reader for 3I Slidebook files.
* The strategies employed by this reader are highly suboptimal, as we
* have very little information on the Slidebook format.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/SlidebookReader.java">SVN</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class SlidebookReader extends FormatReader {
// -- Constants --
public static final long SLD_MAGIC_BYTES_1 = 0x6c000001L;
public static final long SLD_MAGIC_BYTES_2 = 0xf5010201L;
public static final long SLD_MAGIC_BYTES_3 = 0xf6010101L;
// -- Fields --
private Vector<Long> metadataOffsets;
private Vector<Long> pixelOffsets;
private Vector<Long> pixelLengths;
private Vector<Double> ndFilters;
private boolean adjust = true;
private boolean isSpool;
private Hashtable<Integer, Integer> metadataInPlanes;
// -- Constructor --
/** Constructs a new Slidebook reader. */
public SlidebookReader() {
super("Olympus Slidebook", new String[] {"sld", "spl"});
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 8;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
long magicBytes = stream.readInt();
return magicBytes == SLD_MAGIC_BYTES_1 || magicBytes == SLD_MAGIC_BYTES_2;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int plane = FormatTools.getPlaneSize(this);
long offset = pixelOffsets.get(series).longValue() + plane * no;
in.seek(offset);
// if this is a spool file, there may be an extra metadata block here
if (isSpool) {
Integer[] keys = metadataInPlanes.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
for (int key : keys) {
if (key < no) {
in.skipBytes(256);
}
}
in.order(false);
long magicBytes = (long) in.readInt() & 0xffffffffL;
in.order(isLittleEndian());
if (magicBytes == SLD_MAGIC_BYTES_3 && !metadataInPlanes.contains(no)) {
metadataInPlanes.put(no, 0);
in.skipBytes(252);
}
else in.seek(in.getFilePointer() - 4);
}
readPlane(in, x, y, w, h, buf);
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
metadataOffsets = pixelOffsets = pixelLengths = null;
ndFilters = null;
isSpool = false;
metadataInPlanes = null;
adjust = true;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0 &&
buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i') &&
buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
pixelLengths.add(new Long(length));
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[pixelOffsets.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
if (totalBlocks > 100) totalBlocks = 1;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) break;
in.seek(off + q * 128);
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (core[j].sizeX == 0) {
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core[j].sizeX /= (div == 0 ? 1 : div);
div = in.readShort();
core[j].sizeY /= (div == 0 ? 1 : div);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
core[j].sizeC = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
core[j].sizeZ = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < core[nextName - 1].sizeX ||
core[nextName - 1].sizeX == 0) && y > 16 &&
(y < core[nextName - 1].sizeY || core[nextName - 1].sizeY == 0))
{
core[nextName - 1].sizeX = x;
core[nextName - 1].sizeY = y;
adjust = false;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
+ adjust = false;
break;
}
}
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
long pixels = pixelLengths.get(i).longValue() / 2;
boolean x = true;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
long plane = pixels / (getSizeC() * getSizeZ());
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
// -- Helper methods --
private boolean withinPixels(long offset) {
for (int i=0; i<pixelOffsets.size(); i++) {
long pixelOffset = pixelOffsets.get(i).longValue();
long pixelLength = pixelLengths.get(i).longValue();
if (offset >= pixelOffset && offset < (pixelOffset + pixelLength)) {
return true;
}
}
return false;
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0 &&
buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i') &&
buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
pixelLengths.add(new Long(length));
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[pixelOffsets.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
if (totalBlocks > 100) totalBlocks = 1;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) break;
in.seek(off + q * 128);
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (core[j].sizeX == 0) {
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core[j].sizeX /= (div == 0 ? 1 : div);
div = in.readShort();
core[j].sizeY /= (div == 0 ? 1 : div);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
core[j].sizeC = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
core[j].sizeZ = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < core[nextName - 1].sizeX ||
core[nextName - 1].sizeX == 0) && y > 16 &&
(y < core[nextName - 1].sizeY || core[nextName - 1].sizeY == 0))
{
core[nextName - 1].sizeX = x;
core[nextName - 1].sizeY = y;
adjust = false;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
break;
}
}
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
long pixels = pixelLengths.get(i).longValue() / 2;
boolean x = true;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
long plane = pixels / (getSizeC() * getSizeZ());
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
isSpool = checkSuffix(id, "spl");
if (isSpool) {
metadataInPlanes = new Hashtable<Integer, Integer>();
}
LOGGER.info("Finding offsets to pixel data");
// Slidebook files appear to be comprised of four types of blocks:
// variable length pixel data blocks, 512 byte metadata blocks,
// 128 byte metadata blocks, and variable length metadata blocks.
//
// Fixed-length metadata blocks begin with a 2 byte identifier,
// e.g. 'i' or 'h'.
// Following this are two unknown bytes (usually 256), then a 2 byte
// endianness identifier - II or MM, for little or big endian, respectively.
// Presumably these blocks contain useful information, but for the most
// part we aren't sure what it is or how to extract it.
//
// Variable length metadata blocks begin with 0xffff and are
// (as far as I know) always between two fixed-length metadata blocks.
// These appear to be a relatively new addition to the format - they are
// only present in files received on/after March 30, 2008.
//
// Each pixel data block corresponds to one series.
// The first 'i' metadata block after each pixel data block contains
// the width and height of the planes in that block - this can (and does)
// vary between blocks.
//
// Z, C, and T sizes are computed heuristically based on the number of
// metadata blocks of a specific type.
in.skipBytes(4);
core[0].littleEndian = in.read() == 0x49;
in.order(isLittleEndian());
metadataOffsets = new Vector<Long>();
pixelOffsets = new Vector<Long>();
pixelLengths = new Vector<Long>();
ndFilters = new Vector<Double>();
in.seek(0);
// gather offsets to metadata and pixel data blocks
while (in.getFilePointer() < in.length() - 8) {
LOGGER.debug("Looking for block at {}", in.getFilePointer());
in.skipBytes(4);
int checkOne = in.read();
int checkTwo = in.read();
if ((checkOne == 'I' && checkTwo == 'I') ||
(checkOne == 'M' && checkTwo == 'M'))
{
LOGGER.debug("Found metadata offset: {}", (in.getFilePointer() - 6));
metadataOffsets.add(new Long(in.getFilePointer() - 6));
in.skipBytes(in.readShort() - 8);
}
else if (checkOne == -1 && checkTwo == -1) {
boolean foundBlock = false;
byte[] block = new byte[8192];
in.read(block);
while (!foundBlock) {
for (int i=0; i<block.length-2; i++) {
if ((block[i] == 'M' && block[i + 1] == 'M') ||
(block[i] == 'I' && block[i + 1] == 'I'))
{
foundBlock = true;
in.seek(in.getFilePointer() - block.length + i - 2);
LOGGER.debug("Found metadata offset: {}",
(in.getFilePointer() - 2));
metadataOffsets.add(new Long(in.getFilePointer() - 2));
in.skipBytes(in.readShort() - 5);
break;
}
}
if (!foundBlock) {
block[0] = block[block.length - 2];
block[1] = block[block.length - 1];
in.read(block, 2, block.length - 2);
}
}
}
else {
String s = null;
long fp = in.getFilePointer() - 6;
in.seek(fp);
int len = in.read();
if (len > 0 && len <= 32) {
s = in.readString(len);
}
if (s != null && s.indexOf("Annotation") != -1) {
if (s.equals("CTimelapseAnnotation")) {
in.skipBytes(41);
if (in.read() == 0) in.skipBytes(10);
else in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CIntensityBarAnnotation")) {
in.skipBytes(56);
int n = in.read();
while (n == 0 || n < 6 || n > 0x80) n = in.read();
in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CCubeAnnotation")) {
in.skipBytes(66);
int n = in.read();
if (n != 0) in.seek(in.getFilePointer() - 1);
}
else if (s.equals("CScaleBarAnnotation")) {
in.skipBytes(38);
int extra = in.read();
if (extra <= 16) in.skipBytes(3 + extra);
else in.skipBytes(2);
}
}
else if (s != null && s.indexOf("Decon") != -1) {
in.seek(fp);
while (in.read() != ']');
}
else {
if ((fp % 2) == 1) fp -= 2;
in.seek(fp);
// make sure there isn't another block nearby
String checkString = in.readString(64);
if (checkString.indexOf("II") != -1 ||
checkString.indexOf("MM") != -1)
{
int index = checkString.indexOf("II");
if (index == -1) index = checkString.indexOf("MM");
in.seek(fp + index - 4);
continue;
}
else in.seek(fp);
LOGGER.debug("Found pixel offset at {}", fp);
pixelOffsets.add(new Long(fp));
try {
byte[] buf = new byte[8192];
boolean found = false;
int n = in.read(buf);
while (!found && in.getFilePointer() < in.length()) {
for (int i=0; i<n-6; i++) {
if (((buf[i] == 'h' || buf[i] == 'i') && buf[i + 1] == 0 &&
buf[i + 4] == 'I' && buf[i + 5] == 'I') ||
(buf[i] == 0 && (buf[i + 1] == 'h' || buf[i + 1] == 'i') &&
buf[i + 4] == 'M' && buf[i + 5] == 'M'))
{
found = true;
in.seek(in.getFilePointer() - n + i - 20);
if (buf[i] == 'i' || buf[i + 1] == 'i') {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
break;
}
}
if (!found) {
byte[] tmp = buf;
buf = new byte[8192];
System.arraycopy(tmp, tmp.length - 20, buf, 0, 20);
n = in.read(buf, 20, buf.length - 20);
}
}
if (in.getFilePointer() <= in.length()) {
if (pixelOffsets.size() > pixelLengths.size()) {
long length = in.getFilePointer() - fp;
if (((length / 2) % 2) == 1) {
pixelOffsets.setElementAt(fp + 2, pixelOffsets.size() - 1);
length -= 2;
}
pixelLengths.add(new Long(length));
}
}
else pixelOffsets.remove(pixelOffsets.size() - 1);
}
catch (EOFException e) {
pixelOffsets.remove(pixelOffsets.size() - 1);
}
}
}
}
for (int i=0; i<pixelOffsets.size(); i++) {
long length = pixelLengths.get(i).longValue();
long offset = pixelOffsets.get(i).longValue();
int padding = isSpool ? 0 : 7;
if (length + offset + padding > in.length()) {
pixelOffsets.remove(i);
pixelLengths.remove(i);
i--;
}
}
if (pixelOffsets.size() > 1) {
boolean little = isLittleEndian();
core = new CoreMetadata[pixelOffsets.size()];
for (int i=0; i<getSeriesCount(); i++) {
core[i] = new CoreMetadata();
core[i].littleEndian = little;
}
}
LOGGER.info("Determining dimensions");
// determine total number of pixel bytes
Vector<Float> pixelSize = new Vector<Float>();
String objective = null;
Vector<Double> pixelSizeZ = new Vector<Double>();
long pixelBytes = 0;
for (int i=0; i<pixelLengths.size(); i++) {
pixelBytes += pixelLengths.get(i).longValue();
}
String[] imageNames = new String[getSeriesCount()];
Vector<String> channelNames = new Vector<String>();
int nextName = 0;
// try to find the width and height
int iCount = 0;
int hCount = 0;
int uCount = 0;
int prevSeries = -1;
int prevSeriesU = -1;
int nextChannel = 0;
for (int i=0; i<metadataOffsets.size(); i++) {
long off = metadataOffsets.get(i).longValue();
in.seek(off);
long next = i == metadataOffsets.size() - 1 ? in.length() :
metadataOffsets.get(i + 1).longValue();
int totalBlocks = (int) ((next - off) / 128);
// if there are more than 100 blocks, we probably found a pixel block
// by accident (but we'll check the first block anyway)
if (totalBlocks > 100) totalBlocks = 1;
for (int q=0; q<totalBlocks; q++) {
if (withinPixels(off + q * 128)) break;
in.seek(off + q * 128);
char n = (char) in.readShort();
if (n == 'i') {
iCount++;
in.skipBytes(94);
pixelSizeZ.add(new Double(in.readFloat()));
in.seek(in.getFilePointer() - 20);
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (core[j].sizeX == 0) {
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
int checkX = in.readShort();
int checkY = in.readShort();
int div = in.readShort();
core[j].sizeX /= (div == 0 ? 1 : div);
div = in.readShort();
core[j].sizeY /= (div == 0 ? 1 : div);
}
if (prevSeries != j) {
iCount = 1;
}
prevSeries = j;
core[j].sizeC = iCount;
break;
}
}
}
else if (n == 'u') {
uCount++;
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
if (prevSeriesU != j) {
uCount = 1;
}
prevSeriesU = j;
core[j].sizeZ = uCount;
break;
}
}
}
else if (n == 'h') hCount++;
else if (n == 'j') {
in.skipBytes(2);
String check = in.readString(2);
if (check.equals("II") || check.equals("MM")) {
// this block should contain an image name
in.skipBytes(10);
if (nextName < imageNames.length) {
imageNames[nextName++] = in.readCString().trim();
}
long fp = in.getFilePointer();
if ((in.getFilePointer() % 2) == 1) in.skipBytes(1);
while (in.readShort() == 0);
in.skipBytes(18);
if (in.getFilePointer() - fp > 123 && (fp % 2) == 0) {
in.seek(fp + 123);
}
int x = in.readInt();
int y = in.readInt();
int div = in.readShort();
x /= (div == 0 ? 1 : div);
div = in.readShort();
y /= (div == 0 ? 1 : div);
if (x > 16 && (x < core[nextName - 1].sizeX ||
core[nextName - 1].sizeX == 0) && y > 16 &&
(y < core[nextName - 1].sizeY || core[nextName - 1].sizeY == 0))
{
core[nextName - 1].sizeX = x;
core[nextName - 1].sizeY = y;
adjust = false;
}
}
}
else if (n == 'm') {
// this block should contain a channel name
if (in.getFilePointer() > pixelOffsets.get(0).longValue()) {
in.skipBytes(14);
channelNames.add(in.readCString().trim());
}
}
else if (n == 'd') {
// objective info and pixel size X/Y
in.skipBytes(6);
long fp = in.getFilePointer();
objective = in.readCString();
in.seek(fp + 144);
pixelSize.add(in.readFloat());
}
else if (n == 'e') {
in.skipBytes(174);
ndFilters.add(new Double(in.readFloat()));
in.skipBytes(40);
setSeries(nextName);
addSeriesMeta("channel " + ndFilters.size() + " intensification",
in.readShort());
}
else if (n == 'k') {
in.skipBytes(14);
if (nextName > 0) setSeries(nextName - 1);
addSeriesMeta("Mag. changer", in.readCString());
}
else if (isSpool) {
// spool files don't necessarily have block identifiers
for (int j=0; j<pixelOffsets.size(); j++) {
long end = j == pixelOffsets.size() - 1 ? in.length() :
pixelOffsets.get(j + 1).longValue();
if (in.getFilePointer() < end) {
in.skipBytes(16);
core[j].sizeX = in.readShort();
core[j].sizeY = in.readShort();
adjust = false;
break;
}
}
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
long pixels = pixelLengths.get(i).longValue() / 2;
boolean x = true;
if (getSizeC() == 0) core[i].sizeC = 1;
if (getSizeZ() == 0) core[i].sizeZ = 1;
long plane = pixels / (getSizeC() * getSizeZ());
if (adjust) {
boolean widthGreater = getSizeX() > getSizeY();
while (getSizeX() * getSizeY() > plane) {
if (x) core[i].sizeX /= 2;
else core[i].sizeY /= 2;
x = !x;
}
while (getSizeX() * getSizeY() < plane ||
(getSizeX() < getSizeY() && widthGreater))
{
core[i].sizeX++;
core[i].sizeY = (int) (plane / getSizeX());
}
}
int nPlanes = getSizeZ() * getSizeC();
core[i].sizeT = (int) (pixels / (getSizeX() * getSizeY() * nPlanes));
while (getSizeX() * getSizeY() * nPlanes * getSizeT() > pixels) {
core[i].sizeT--;
}
if (getSizeT() == 0) core[i].sizeT = 1;
core[i].imageCount = nPlanes * getSizeT();
core[i].pixelType = FormatTools.UINT16;
core[i].dimensionOrder = "XYZTC";
core[i].indexed = false;
core[i].falseColor = false;
core[i].metadataComplete = true;
}
setSeries(0);
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
// populate Image data
for (int i=0; i<getSeriesCount(); i++) {
if (imageNames[i] != null) store.setImageName(imageNames[i], i);
MetadataTools.setDefaultCreationDate(store, id, i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
store.setImageInstrumentRef(instrumentID, 0);
int index = 0;
// populate Objective data
store.setObjectiveModel(objective, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
// link Objective to Image
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setImageObjectiveSettingsID(objectiveID, 0);
// populate Dimensions data
for (int i=0; i<getSeriesCount(); i++) {
if (i < pixelSize.size()) {
store.setPixelsPhysicalSizeX(new Double(pixelSize.get(i)), i);
store.setPixelsPhysicalSizeY(new Double(pixelSize.get(i)), i);
}
int idx = 0;
for (int q=0; q<i; q++) {
idx += core[q].sizeC;
}
if (idx < pixelSizeZ.size() && pixelSizeZ.get(idx) != null) {
store.setPixelsPhysicalSizeZ(pixelSizeZ.get(idx), i);
}
}
// populate LogicalChannel data
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
for (int c=0; c<getSizeC(); c++) {
if (index < channelNames.size() && channelNames.get(index) != null) {
store.setChannelName(channelNames.get(index), i, c);
addSeriesMeta("channel " + c, channelNames.get(index));
}
if (index < ndFilters.size() && ndFilters.get(index) != null) {
store.setChannelNDFilter(ndFilters.get(index), i, c);
addSeriesMeta("channel " + c + " Neutral density",
ndFilters.get(index));
}
index++;
}
}
setSeries(0);
}
}
|
diff --git a/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java b/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
index 2a4bcbcec..89a9ecb93 100644
--- a/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
+++ b/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
@@ -1,861 +1,867 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.search.grouping;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
import java.io.IOException;
import java.util.*;
// TODO
// - should test relevance sort too
// - test null
// - test ties
// - test compound sort
public class TestGrouping extends LuceneTestCase {
public void testBasic() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
final Sort groupSort = Sort.RELEVANCE;
final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector(groupField, groupSort, 10);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector(groupField, c1.getTopGroups(0, true), groupSort, null, 5, true, false, true);
indexSearcher.search(new TermQuery(new Term("content", "random")), c2);
final TopGroups groups = c2.getTopGroups(0);
assertEquals(7, groups.totalHitCount);
assertEquals(7, groups.totalGroupedHitCount);
assertEquals(4, groups.groups.length);
// relevance order: 5, 0, 3, 4, 1, 2, 6
// the later a document is added the higher this docId
// value
GroupDocs group = groups.groups[0];
assertEquals(new BytesRef("author3"), group.groupValue);
assertEquals(2, group.scoreDocs.length);
assertEquals(5, group.scoreDocs[0].doc);
assertEquals(4, group.scoreDocs[1].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
group = groups.groups[1];
assertEquals(new BytesRef("author1"), group.groupValue);
assertEquals(3, group.scoreDocs.length);
assertEquals(0, group.scoreDocs[0].doc);
assertEquals(1, group.scoreDocs[1].doc);
assertEquals(2, group.scoreDocs[2].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
assertTrue(group.scoreDocs[1].score > group.scoreDocs[2].score);
group = groups.groups[2];
assertEquals(new BytesRef("author2"), group.groupValue);
assertEquals(1, group.scoreDocs.length);
assertEquals(3, group.scoreDocs[0].doc);
group = groups.groups[3];
assertNull(group.groupValue);
assertEquals(1, group.scoreDocs.length);
assertEquals(6, group.scoreDocs[0].doc);
indexSearcher.getIndexReader().close();
dir.close();
}
private static class GroupDoc {
final int id;
final BytesRef group;
final BytesRef sort1;
final BytesRef sort2;
// content must be "realN ..."
final String content;
float score;
float score2;
public GroupDoc(int id, BytesRef group, BytesRef sort1, BytesRef sort2, String content) {
this.id = id;
this.group = group;
this.sort1 = sort1;
this.sort2 = sort2;
this.content = content;
}
}
private Sort getRandomSort() {
final List<SortField> sortFields = new ArrayList<SortField>();
if (random.nextInt(7) == 2) {
sortFields.add(SortField.FIELD_SCORE);
} else {
if (random.nextBoolean()) {
if (random.nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.STRING, random.nextBoolean()));
} else {
sortFields.add(new SortField("sort2", SortField.STRING, random.nextBoolean()));
}
} else if (random.nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.STRING, random.nextBoolean()));
sortFields.add(new SortField("sort2", SortField.STRING, random.nextBoolean()));
}
}
// Break ties:
sortFields.add(new SortField("id", SortField.INT));
return new Sort(sortFields.toArray(new SortField[sortFields.size()]));
}
private Comparator<GroupDoc> getComparator(Sort sort) {
final SortField[] sortFields = sort.getSort();
return new Comparator<GroupDoc>() {
// @Override -- Not until Java 1.6
public int compare(GroupDoc d1, GroupDoc d2) {
for(SortField sf : sortFields) {
final int cmp;
if (sf.getType() == SortField.SCORE) {
if (d1.score > d2.score) {
cmp = -1;
} else if (d1.score < d2.score) {
cmp = 1;
} else {
cmp = 0;
}
} else if (sf.getField().equals("sort1")) {
cmp = d1.sort1.compareTo(d2.sort1);
} else if (sf.getField().equals("sort2")) {
cmp = d1.sort2.compareTo(d2.sort2);
} else {
assertEquals(sf.getField(), "id");
cmp = d1.id - d2.id;
}
if (cmp != 0) {
return sf.getReverse() ? -cmp : cmp;
}
}
// Our sort always fully tie breaks:
fail();
return 0;
}
};
}
private Comparable<?>[] fillFields(GroupDoc d, Sort sort) {
final SortField[] sortFields = sort.getSort();
final Comparable<?>[] fields = new Comparable[sortFields.length];
for(int fieldIDX=0;fieldIDX<sortFields.length;fieldIDX++) {
final Comparable<?> c;
final SortField sf = sortFields[fieldIDX];
if (sf.getType() == SortField.SCORE) {
c = new Float(d.score);
} else if (sf.getField().equals("sort1")) {
c = d.sort1;
} else if (sf.getField().equals("sort2")) {
c = d.sort2;
} else {
assertEquals("id", sf.getField());
c = new Integer(d.id);
}
fields[fieldIDX] = c;
}
return fields;
}
/*
private String groupToString(BytesRef b) {
if (b == null) {
return "null";
} else {
return b.utf8ToString();
}
}
*/
private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs,
String searchTerm,
boolean fillFields,
boolean getScores,
boolean getMaxScores,
boolean doAllGroups,
Sort groupSort,
Sort docSort,
int topNGroups,
int docsPerGroup,
int groupOffset,
int docOffset) {
final Comparator<GroupDoc> groupSortComp = getComparator(groupSort);
Arrays.sort(groupDocs, groupSortComp);
final HashMap<BytesRef,List<GroupDoc>> groups = new HashMap<BytesRef,List<GroupDoc>>();
final List<BytesRef> sortedGroups = new ArrayList<BytesRef>();
final List<Comparable<?>[]> sortedGroupFields = new ArrayList<Comparable<?>[]>();
int totalHitCount = 0;
Set<BytesRef> knownGroups = new HashSet<BytesRef>();
//System.out.println("TEST: slowGrouping");
for(GroupDoc d : groupDocs) {
// TODO: would be better to filter by searchTerm before sorting!
if (!d.content.startsWith(searchTerm)) {
continue;
}
totalHitCount++;
//System.out.println(" match id=" + d.id + " score=" + d.score);
if (doAllGroups) {
if (!knownGroups.contains(d.group)) {
knownGroups.add(d.group);
//System.out.println(" add group=" + groupToString(d.group));
}
}
List<GroupDoc> l = groups.get(d.group);
if (l == null) {
//System.out.println(" add sortedGroup=" + groupToString(d.group));
sortedGroups.add(d.group);
if (fillFields) {
sortedGroupFields.add(fillFields(d, groupSort));
}
l = new ArrayList<GroupDoc>();
groups.put(d.group, l);
}
l.add(d);
}
if (groupOffset >= sortedGroups.size()) {
// slice is out of bounds
return null;
}
final int limit = Math.min(groupOffset + topNGroups, groups.size());
final Comparator<GroupDoc> docSortComp = getComparator(docSort);
@SuppressWarnings("unchecked")
final GroupDocs<BytesRef>[] result = new GroupDocs[limit-groupOffset];
int totalGroupedHitCount = 0;
for(int idx=groupOffset;idx < limit;idx++) {
final BytesRef group = sortedGroups.get(idx);
final List<GroupDoc> docs = groups.get(group);
totalGroupedHitCount += docs.size();
Collections.sort(docs, docSortComp);
final ScoreDoc[] hits;
if (docs.size() > docOffset) {
final int docIDXLimit = Math.min(docOffset + docsPerGroup, docs.size());
hits = new ScoreDoc[docIDXLimit - docOffset];
for(int docIDX=docOffset; docIDX < docIDXLimit; docIDX++) {
final GroupDoc d = docs.get(docIDX);
final FieldDoc fd;
if (fillFields) {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN, fillFields(d, docSort));
} else {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN);
}
hits[docIDX-docOffset] = fd;
}
} else {
hits = new ScoreDoc[0];
}
result[idx-groupOffset] = new GroupDocs<BytesRef>(0.0f,
docs.size(),
hits,
group,
fillFields ? sortedGroupFields.get(idx) : null);
}
if (doAllGroups) {
return new TopGroups<BytesRef>(
new TopGroups<BytesRef>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result),
knownGroups.size()
);
} else {
return new TopGroups<BytesRef>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result);
}
}
private IndexReader getDocBlockReader(Directory dir, GroupDoc[] groupDocs) throws IOException {
// Coalesce by group, but in random order:
Collections.shuffle(Arrays.asList(groupDocs), random);
final Map<BytesRef,List<GroupDoc>> groupMap = new HashMap<BytesRef,List<GroupDoc>>();
final List<BytesRef> groupValues = new ArrayList<BytesRef>();
for(GroupDoc groupDoc : groupDocs) {
if (!groupMap.containsKey(groupDoc.group)) {
groupValues.add(groupDoc.group);
groupMap.put(groupDoc.group, new ArrayList<GroupDoc>());
}
groupMap.get(groupDoc.group).add(groupDoc);
}
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)));
final List<List<Document>> updateDocs = new ArrayList<List<Document>>();
//System.out.println("TEST: index groups");
for(BytesRef group : groupValues) {
final List<Document> docs = new ArrayList<Document>();
//System.out.println("TEST: group=" + (group == null ? "null" : group.utf8ToString()));
for(GroupDoc groupValue : groupMap.get(group)) {
Document doc = new Document();
docs.add(doc);
if (groupValue.group != null) {
doc.add(newField("group", groupValue.group.utf8ToString(), Field.Index.NOT_ANALYZED));
}
doc.add(newField("sort1", groupValue.sort1.utf8ToString(), Field.Index.NOT_ANALYZED));
doc.add(newField("sort2", groupValue.sort2.utf8ToString(), Field.Index.NOT_ANALYZED));
doc.add(new NumericField("id").setIntValue(groupValue.id));
doc.add(newField("content", groupValue.content, Field.Index.ANALYZED));
//System.out.println("TEST: doc content=" + groupValue.content + " group=" + (groupValue.group == null ? "null" : groupValue.group.utf8ToString()) + " sort1=" + groupValue.sort1.utf8ToString() + " id=" + groupValue.id);
}
// So we can pull filter marking last doc in block:
final Field groupEnd = newField("groupend", "x", Field.Index.NOT_ANALYZED);
groupEnd.setOmitTermFreqAndPositions(true);
groupEnd.setOmitNorms(true);
docs.get(docs.size()-1).add(groupEnd);
// Add as a doc block:
w.addDocuments(docs);
if (group != null && random.nextInt(7) == 4) {
updateDocs.add(docs);
}
}
for(List<Document> docs : updateDocs) {
// Just replaces docs w/ same docs:
w.updateDocuments(new Term("group", docs.get(0).get("group")),
docs);
}
final IndexReader r = w.getReader();
w.close();
return r;
}
public void testRandom() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER;
//final int numDocs = _TestUtil.nextInt(random, 5, 20);
final int numGroups = _TestUtil.nextInt(random, 1, numDocs);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);
}
final List<BytesRef> groups = new ArrayList<BytesRef>();
for(int i=0;i<numGroups;i++) {
groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random)));
//groups.add(new BytesRef(_TestUtil.randomSimpleString(random)));
}
final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)];
if (VERBOSE) {
System.out.println("TEST: create fake content");
}
for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) {
final StringBuilder sb = new StringBuilder();
sb.append("real" + random.nextInt(3)).append(' ');
final int fakeCount = random.nextInt(10);
for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) {
sb.append("fake ");
}
contentStrings[contentIDX] = sb.toString();
if (VERBOSE) {
System.out.println(" content=" + sb.toString());
}
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)));
Document doc = new Document();
Document docNoGroup = new Document();
Field group = newField("group", "", Field.Index.NOT_ANALYZED);
doc.add(group);
Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED);
doc.add(sort1);
docNoGroup.add(sort1);
Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED);
doc.add(sort2);
docNoGroup.add(sort2);
Field content = newField("content", "", Field.Index.ANALYZED);
doc.add(content);
docNoGroup.add(content);
NumericField id = new NumericField("id");
doc.add(id);
docNoGroup.add(id);
final GroupDoc[] groupDocs = new GroupDoc[numDocs];
for(int i=0;i<numDocs;i++) {
final BytesRef groupValue;
if (random.nextInt(24) == 17) {
// So we test the "doc doesn't have the group'd
// field" case:
groupValue = null;
} else {
groupValue = groups.get(random.nextInt(groups.size()));
}
final GroupDoc groupDoc = new GroupDoc(i,
groupValue,
groups.get(random.nextInt(groups.size())),
groups.get(random.nextInt(groups.size())),
contentStrings[random.nextInt(contentStrings.length)]);
if (VERBOSE) {
System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString());
}
groupDocs[i] = groupDoc;
if (groupDoc.group != null) {
group.setValue(groupDoc.group.utf8ToString());
}
sort1.setValue(groupDoc.sort1.utf8ToString());
sort2.setValue(groupDoc.sort2.utf8ToString());
content.setValue(groupDoc.content);
id.setIntValue(groupDoc.id);
if (groupDoc.group == null) {
w.addDocument(docNoGroup);
} else {
w.addDocument(doc);
}
}
final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length];
System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length);
final IndexReader r = w.getReader();
w.close();
// NOTE: intentional but temporary field cache insanity!
final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id");
IndexReader r2 = null;
Directory dir2 = null;
try {
final IndexSearcher s = new IndexSearcher(r);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocs[docIDToID[hit.doc]];
assertTrue(gd.score == 0.0);
gd.score = hit.score;
assertEquals(gd.id, docIDToID[hit.doc]);
//System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]);
}
}
for(GroupDoc gd : groupDocs) {
assertTrue(gd.score != 0.0);
}
// Build 2nd index, where docs are added in blocks by
// group, so we can use single pass collector
dir2 = newDirectory();
r2 = getDocBlockReader(dir2, groupDocs);
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id");
final IndexSearcher s2 = new IndexSearcher(r2);
// Reader2 only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
// reliably remap them w/ Map:
- final Map<Float,Float> scoreMap = new HashMap<Float,Float>();
+ final Map<String,Map<Float,Float>> scoreMap = new HashMap<String,Map<Float,Float>>();
// Tricky: must separately set .score2, because the doc
// block index was created with possible deletions!
+ //System.out.println("fixup score2");
for(int contentID=0;contentID<3;contentID++) {
+ //System.out.println(" term=real" + contentID);
+ final Map<Float,Float> termScoreMap = new HashMap<Float,Float>();
+ scoreMap.put("real"+contentID, termScoreMap);
//System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) +
//" dfnew=" + s2.docFreq(new Term("content", "real"+contentID)));
final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]];
assertTrue(gd.score2 == 0.0);
gd.score2 = hit.score;
assertEquals(gd.id, docIDToID2[hit.doc]);
- //System.out.println(" score=" + hit.score + " id=" + docIDToID2[hit.doc]);
- scoreMap.put(gd.score, gd.score2);
+ //System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToID2[hit.doc]);
+ termScoreMap.put(gd.score, gd.score2);
}
}
for(int searchIter=0;searchIter<100;searchIter++) {
if (VERBOSE) {
System.out.println("TEST: searchIter=" + searchIter);
}
final String searchTerm = "real" + random.nextInt(3);
final boolean fillFields = random.nextBoolean();
boolean getScores = random.nextBoolean();
final boolean getMaxScores = random.nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
// TODO: also test null (= sort by relevance)
final Sort docSort = getRandomSort();
for(SortField sf : docSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
for(SortField sf : groupSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
final int topNGroups = _TestUtil.nextInt(random, 1, 30);
//final int topNGroups = 4;
final int docsPerGroup = _TestUtil.nextInt(random, 1, 50);
final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2);
//final int groupOffset = 0;
final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1);
//final int docOffset = 0;
final boolean doCache = random.nextBoolean();
final boolean doAllGroups = random.nextBoolean();
if (VERBOSE) {
System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
}
final TermAllGroupsCollector allGroupsCollector;
if (doAllGroups) {
allGroupsCollector = new TermAllGroupsCollector("group");
} else {
allGroupsCollector = null;
}
final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups);
final CachingCollector cCache;
final Collector c;
final boolean useWrappingCollector = random.nextBoolean();
if (doCache) {
final double maxCacheMB = random.nextDouble();
if (VERBOSE) {
System.out.println("TEST: maxCacheMB=" + maxCacheMB);
}
if (useWrappingCollector) {
if (doAllGroups) {
cCache = CachingCollector.create(c1, true, maxCacheMB);
c = MultiCollector.wrap(cCache, allGroupsCollector);
} else {
c = cCache = CachingCollector.create(c1, true, maxCacheMB);
}
} else {
// Collect only into cache, then replay multiple times:
c = cCache = CachingCollector.create(false, true, maxCacheMB);
}
} else {
cCache = null;
if (doAllGroups) {
c = MultiCollector.wrap(c1, allGroupsCollector);
} else {
c = c1;
}
}
s.search(new TermQuery(new Term("content", searchTerm)), c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
// Replay for first-pass grouping
cCache.replay(c1);
if (doAllGroups) {
// Replay for all groups:
cCache.replay(allGroupsCollector);
}
} else {
// Replay by re-running search:
s.search(new TermQuery(new Term("content", searchTerm)), c1);
if (doAllGroups) {
s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector);
}
}
}
final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields);
final TopGroups groupsResult;
if (topGroups != null) {
if (VERBOSE) {
System.out.println("TEST: topGroups");
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
System.out.println("TEST: cache is intact");
}
cCache.replay(c2);
} else {
if (VERBOSE) {
System.out.println("TEST: cache was too large");
}
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
} else {
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
if (doAllGroups) {
TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset);
groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount());
} else {
groupsResult = c2.getTopGroups(docOffset);
}
} else {
groupsResult = null;
if (VERBOSE) {
System.out.println("TEST: no results");
}
}
final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
System.out.println("TEST: no expected groups");
} else {
System.out.println("TEST: expected groups");
for(GroupDocs<BytesRef> gd : expectedGroups.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString()));
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + sd.doc + " score=" + sd.score);
}
}
}
}
assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores);
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
final TermAllGroupsCollector allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
allGroupsCollector2 = new TermAllGroupsCollector("group");
c4 = MultiCollector.wrap(c3, allGroupsCollector2);
} else {
allGroupsCollector2 = null;
c4 = c3;
}
s2.search(new TermQuery(new Term("content", searchTerm)), c4);
@SuppressWarnings("unchecked")
final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields);
final TopGroups groupsResult2;
if (doAllGroups && tempTopGroups2 != null) {
assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount());
groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount());
} else {
groupsResult2 = tempTopGroups2;
}
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc hit : groupDocsHits.scoreDocs) {
final GroupDoc gd = groupDocsByID[hit.doc];
assertEquals(gd.id, hit.doc);
//System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score);
hit.score = gd.score2;
}
}
final SortField[] sortFields = groupSort.getSort();
+ final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm);
for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) {
if (sortFields[groupSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
if (groupDocsHits.groupSortValues != null) {
- groupDocsHits.groupSortValues[groupSortIDX] = scoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
+ //System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]));
+ groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]);
}
}
}
}
final SortField[] docSortFields = docSort.getSort();
for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) {
if (docSortFields[docSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc _hit : groupDocsHits.scoreDocs) {
FieldDoc hit = (FieldDoc) _hit;
if (hit.fields != null) {
- hit.fields[docSortIDX] = scoreMap.get(hit.fields[docSortIDX]);
+ hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]);
assertNotNull(hit.fields[docSortIDX]);
}
}
}
}
}
}
assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores);
}
} finally {
FieldCache.DEFAULT.purge(r);
if (r2 != null) {
FieldCache.DEFAULT.purge(r2);
}
}
r.close();
dir.close();
r2.close();
dir2.close();
}
}
private void assertEquals(int[] docIDtoID, TopGroups expected, TopGroups actual, boolean verifyGroupValues, boolean testScores) {
if (expected == null) {
assertNull(actual);
return;
}
assertNotNull(actual);
assertEquals(expected.groups.length, actual.groups.length);
assertEquals(expected.totalHitCount, actual.totalHitCount);
assertEquals(expected.totalGroupedHitCount, actual.totalGroupedHitCount);
if (expected.totalGroupCount != null) {
assertEquals(expected.totalGroupCount, actual.totalGroupCount);
}
for(int groupIDX=0;groupIDX<expected.groups.length;groupIDX++) {
if (VERBOSE) {
System.out.println(" check groupIDX=" + groupIDX);
}
final GroupDocs expectedGroup = expected.groups[groupIDX];
final GroupDocs actualGroup = actual.groups[groupIDX];
if (verifyGroupValues) {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues);
// TODO
// assertEquals(expectedGroup.maxScore, actualGroup.maxScore);
assertEquals(expectedGroup.totalHits, actualGroup.totalHits);
final ScoreDoc[] expectedFDs = expectedGroup.scoreDocs;
final ScoreDoc[] actualFDs = actualGroup.scoreDocs;
assertEquals(expectedFDs.length, actualFDs.length);
for(int docIDX=0;docIDX<expectedFDs.length;docIDX++) {
final FieldDoc expectedFD = (FieldDoc) expectedFDs[docIDX];
final FieldDoc actualFD = (FieldDoc) actualFDs[docIDX];
//System.out.println(" actual doc=" + docIDtoID[actualFD.doc] + " score=" + actualFD.score);
assertEquals(expectedFD.doc, docIDtoID[actualFD.doc]);
if (testScores) {
assertEquals(expectedFD.score, actualFD.score);
} else {
// TODO: too anal for now
//assertEquals(Float.NaN, actualFD.score);
}
assertArrayEquals(expectedFD.fields, actualFD.fields);
}
}
}
}
| false | true | public void testRandom() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER;
//final int numDocs = _TestUtil.nextInt(random, 5, 20);
final int numGroups = _TestUtil.nextInt(random, 1, numDocs);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);
}
final List<BytesRef> groups = new ArrayList<BytesRef>();
for(int i=0;i<numGroups;i++) {
groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random)));
//groups.add(new BytesRef(_TestUtil.randomSimpleString(random)));
}
final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)];
if (VERBOSE) {
System.out.println("TEST: create fake content");
}
for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) {
final StringBuilder sb = new StringBuilder();
sb.append("real" + random.nextInt(3)).append(' ');
final int fakeCount = random.nextInt(10);
for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) {
sb.append("fake ");
}
contentStrings[contentIDX] = sb.toString();
if (VERBOSE) {
System.out.println(" content=" + sb.toString());
}
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)));
Document doc = new Document();
Document docNoGroup = new Document();
Field group = newField("group", "", Field.Index.NOT_ANALYZED);
doc.add(group);
Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED);
doc.add(sort1);
docNoGroup.add(sort1);
Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED);
doc.add(sort2);
docNoGroup.add(sort2);
Field content = newField("content", "", Field.Index.ANALYZED);
doc.add(content);
docNoGroup.add(content);
NumericField id = new NumericField("id");
doc.add(id);
docNoGroup.add(id);
final GroupDoc[] groupDocs = new GroupDoc[numDocs];
for(int i=0;i<numDocs;i++) {
final BytesRef groupValue;
if (random.nextInt(24) == 17) {
// So we test the "doc doesn't have the group'd
// field" case:
groupValue = null;
} else {
groupValue = groups.get(random.nextInt(groups.size()));
}
final GroupDoc groupDoc = new GroupDoc(i,
groupValue,
groups.get(random.nextInt(groups.size())),
groups.get(random.nextInt(groups.size())),
contentStrings[random.nextInt(contentStrings.length)]);
if (VERBOSE) {
System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString());
}
groupDocs[i] = groupDoc;
if (groupDoc.group != null) {
group.setValue(groupDoc.group.utf8ToString());
}
sort1.setValue(groupDoc.sort1.utf8ToString());
sort2.setValue(groupDoc.sort2.utf8ToString());
content.setValue(groupDoc.content);
id.setIntValue(groupDoc.id);
if (groupDoc.group == null) {
w.addDocument(docNoGroup);
} else {
w.addDocument(doc);
}
}
final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length];
System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length);
final IndexReader r = w.getReader();
w.close();
// NOTE: intentional but temporary field cache insanity!
final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id");
IndexReader r2 = null;
Directory dir2 = null;
try {
final IndexSearcher s = new IndexSearcher(r);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocs[docIDToID[hit.doc]];
assertTrue(gd.score == 0.0);
gd.score = hit.score;
assertEquals(gd.id, docIDToID[hit.doc]);
//System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]);
}
}
for(GroupDoc gd : groupDocs) {
assertTrue(gd.score != 0.0);
}
// Build 2nd index, where docs are added in blocks by
// group, so we can use single pass collector
dir2 = newDirectory();
r2 = getDocBlockReader(dir2, groupDocs);
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id");
final IndexSearcher s2 = new IndexSearcher(r2);
// Reader2 only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
// reliably remap them w/ Map:
final Map<Float,Float> scoreMap = new HashMap<Float,Float>();
// Tricky: must separately set .score2, because the doc
// block index was created with possible deletions!
for(int contentID=0;contentID<3;contentID++) {
//System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) +
//" dfnew=" + s2.docFreq(new Term("content", "real"+contentID)));
final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]];
assertTrue(gd.score2 == 0.0);
gd.score2 = hit.score;
assertEquals(gd.id, docIDToID2[hit.doc]);
//System.out.println(" score=" + hit.score + " id=" + docIDToID2[hit.doc]);
scoreMap.put(gd.score, gd.score2);
}
}
for(int searchIter=0;searchIter<100;searchIter++) {
if (VERBOSE) {
System.out.println("TEST: searchIter=" + searchIter);
}
final String searchTerm = "real" + random.nextInt(3);
final boolean fillFields = random.nextBoolean();
boolean getScores = random.nextBoolean();
final boolean getMaxScores = random.nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
// TODO: also test null (= sort by relevance)
final Sort docSort = getRandomSort();
for(SortField sf : docSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
for(SortField sf : groupSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
final int topNGroups = _TestUtil.nextInt(random, 1, 30);
//final int topNGroups = 4;
final int docsPerGroup = _TestUtil.nextInt(random, 1, 50);
final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2);
//final int groupOffset = 0;
final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1);
//final int docOffset = 0;
final boolean doCache = random.nextBoolean();
final boolean doAllGroups = random.nextBoolean();
if (VERBOSE) {
System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
}
final TermAllGroupsCollector allGroupsCollector;
if (doAllGroups) {
allGroupsCollector = new TermAllGroupsCollector("group");
} else {
allGroupsCollector = null;
}
final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups);
final CachingCollector cCache;
final Collector c;
final boolean useWrappingCollector = random.nextBoolean();
if (doCache) {
final double maxCacheMB = random.nextDouble();
if (VERBOSE) {
System.out.println("TEST: maxCacheMB=" + maxCacheMB);
}
if (useWrappingCollector) {
if (doAllGroups) {
cCache = CachingCollector.create(c1, true, maxCacheMB);
c = MultiCollector.wrap(cCache, allGroupsCollector);
} else {
c = cCache = CachingCollector.create(c1, true, maxCacheMB);
}
} else {
// Collect only into cache, then replay multiple times:
c = cCache = CachingCollector.create(false, true, maxCacheMB);
}
} else {
cCache = null;
if (doAllGroups) {
c = MultiCollector.wrap(c1, allGroupsCollector);
} else {
c = c1;
}
}
s.search(new TermQuery(new Term("content", searchTerm)), c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
// Replay for first-pass grouping
cCache.replay(c1);
if (doAllGroups) {
// Replay for all groups:
cCache.replay(allGroupsCollector);
}
} else {
// Replay by re-running search:
s.search(new TermQuery(new Term("content", searchTerm)), c1);
if (doAllGroups) {
s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector);
}
}
}
final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields);
final TopGroups groupsResult;
if (topGroups != null) {
if (VERBOSE) {
System.out.println("TEST: topGroups");
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
System.out.println("TEST: cache is intact");
}
cCache.replay(c2);
} else {
if (VERBOSE) {
System.out.println("TEST: cache was too large");
}
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
} else {
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
if (doAllGroups) {
TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset);
groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount());
} else {
groupsResult = c2.getTopGroups(docOffset);
}
} else {
groupsResult = null;
if (VERBOSE) {
System.out.println("TEST: no results");
}
}
final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
System.out.println("TEST: no expected groups");
} else {
System.out.println("TEST: expected groups");
for(GroupDocs<BytesRef> gd : expectedGroups.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString()));
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + sd.doc + " score=" + sd.score);
}
}
}
}
assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores);
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
final TermAllGroupsCollector allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
allGroupsCollector2 = new TermAllGroupsCollector("group");
c4 = MultiCollector.wrap(c3, allGroupsCollector2);
} else {
allGroupsCollector2 = null;
c4 = c3;
}
s2.search(new TermQuery(new Term("content", searchTerm)), c4);
@SuppressWarnings("unchecked")
final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields);
final TopGroups groupsResult2;
if (doAllGroups && tempTopGroups2 != null) {
assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount());
groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount());
} else {
groupsResult2 = tempTopGroups2;
}
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc hit : groupDocsHits.scoreDocs) {
final GroupDoc gd = groupDocsByID[hit.doc];
assertEquals(gd.id, hit.doc);
//System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score);
hit.score = gd.score2;
}
}
final SortField[] sortFields = groupSort.getSort();
for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) {
if (sortFields[groupSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
if (groupDocsHits.groupSortValues != null) {
groupDocsHits.groupSortValues[groupSortIDX] = scoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]);
}
}
}
}
final SortField[] docSortFields = docSort.getSort();
for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) {
if (docSortFields[docSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc _hit : groupDocsHits.scoreDocs) {
FieldDoc hit = (FieldDoc) _hit;
if (hit.fields != null) {
hit.fields[docSortIDX] = scoreMap.get(hit.fields[docSortIDX]);
assertNotNull(hit.fields[docSortIDX]);
}
}
}
}
}
}
assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores);
}
} finally {
FieldCache.DEFAULT.purge(r);
if (r2 != null) {
FieldCache.DEFAULT.purge(r2);
}
}
r.close();
dir.close();
r2.close();
dir2.close();
}
}
| public void testRandom() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER;
//final int numDocs = _TestUtil.nextInt(random, 5, 20);
final int numGroups = _TestUtil.nextInt(random, 1, numDocs);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);
}
final List<BytesRef> groups = new ArrayList<BytesRef>();
for(int i=0;i<numGroups;i++) {
groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random)));
//groups.add(new BytesRef(_TestUtil.randomSimpleString(random)));
}
final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)];
if (VERBOSE) {
System.out.println("TEST: create fake content");
}
for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) {
final StringBuilder sb = new StringBuilder();
sb.append("real" + random.nextInt(3)).append(' ');
final int fakeCount = random.nextInt(10);
for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) {
sb.append("fake ");
}
contentStrings[contentIDX] = sb.toString();
if (VERBOSE) {
System.out.println(" content=" + sb.toString());
}
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)));
Document doc = new Document();
Document docNoGroup = new Document();
Field group = newField("group", "", Field.Index.NOT_ANALYZED);
doc.add(group);
Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED);
doc.add(sort1);
docNoGroup.add(sort1);
Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED);
doc.add(sort2);
docNoGroup.add(sort2);
Field content = newField("content", "", Field.Index.ANALYZED);
doc.add(content);
docNoGroup.add(content);
NumericField id = new NumericField("id");
doc.add(id);
docNoGroup.add(id);
final GroupDoc[] groupDocs = new GroupDoc[numDocs];
for(int i=0;i<numDocs;i++) {
final BytesRef groupValue;
if (random.nextInt(24) == 17) {
// So we test the "doc doesn't have the group'd
// field" case:
groupValue = null;
} else {
groupValue = groups.get(random.nextInt(groups.size()));
}
final GroupDoc groupDoc = new GroupDoc(i,
groupValue,
groups.get(random.nextInt(groups.size())),
groups.get(random.nextInt(groups.size())),
contentStrings[random.nextInt(contentStrings.length)]);
if (VERBOSE) {
System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString());
}
groupDocs[i] = groupDoc;
if (groupDoc.group != null) {
group.setValue(groupDoc.group.utf8ToString());
}
sort1.setValue(groupDoc.sort1.utf8ToString());
sort2.setValue(groupDoc.sort2.utf8ToString());
content.setValue(groupDoc.content);
id.setIntValue(groupDoc.id);
if (groupDoc.group == null) {
w.addDocument(docNoGroup);
} else {
w.addDocument(doc);
}
}
final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length];
System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length);
final IndexReader r = w.getReader();
w.close();
// NOTE: intentional but temporary field cache insanity!
final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id");
IndexReader r2 = null;
Directory dir2 = null;
try {
final IndexSearcher s = new IndexSearcher(r);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocs[docIDToID[hit.doc]];
assertTrue(gd.score == 0.0);
gd.score = hit.score;
assertEquals(gd.id, docIDToID[hit.doc]);
//System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]);
}
}
for(GroupDoc gd : groupDocs) {
assertTrue(gd.score != 0.0);
}
// Build 2nd index, where docs are added in blocks by
// group, so we can use single pass collector
dir2 = newDirectory();
r2 = getDocBlockReader(dir2, groupDocs);
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id");
final IndexSearcher s2 = new IndexSearcher(r2);
// Reader2 only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
// reliably remap them w/ Map:
final Map<String,Map<Float,Float>> scoreMap = new HashMap<String,Map<Float,Float>>();
// Tricky: must separately set .score2, because the doc
// block index was created with possible deletions!
//System.out.println("fixup score2");
for(int contentID=0;contentID<3;contentID++) {
//System.out.println(" term=real" + contentID);
final Map<Float,Float> termScoreMap = new HashMap<Float,Float>();
scoreMap.put("real"+contentID, termScoreMap);
//System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) +
//" dfnew=" + s2.docFreq(new Term("content", "real"+contentID)));
final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]];
assertTrue(gd.score2 == 0.0);
gd.score2 = hit.score;
assertEquals(gd.id, docIDToID2[hit.doc]);
//System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToID2[hit.doc]);
termScoreMap.put(gd.score, gd.score2);
}
}
for(int searchIter=0;searchIter<100;searchIter++) {
if (VERBOSE) {
System.out.println("TEST: searchIter=" + searchIter);
}
final String searchTerm = "real" + random.nextInt(3);
final boolean fillFields = random.nextBoolean();
boolean getScores = random.nextBoolean();
final boolean getMaxScores = random.nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
// TODO: also test null (= sort by relevance)
final Sort docSort = getRandomSort();
for(SortField sf : docSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
for(SortField sf : groupSort.getSort()) {
if (sf.getType() == SortField.SCORE) {
getScores = true;
}
}
final int topNGroups = _TestUtil.nextInt(random, 1, 30);
//final int topNGroups = 4;
final int docsPerGroup = _TestUtil.nextInt(random, 1, 50);
final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2);
//final int groupOffset = 0;
final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1);
//final int docOffset = 0;
final boolean doCache = random.nextBoolean();
final boolean doAllGroups = random.nextBoolean();
if (VERBOSE) {
System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
}
final TermAllGroupsCollector allGroupsCollector;
if (doAllGroups) {
allGroupsCollector = new TermAllGroupsCollector("group");
} else {
allGroupsCollector = null;
}
final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups);
final CachingCollector cCache;
final Collector c;
final boolean useWrappingCollector = random.nextBoolean();
if (doCache) {
final double maxCacheMB = random.nextDouble();
if (VERBOSE) {
System.out.println("TEST: maxCacheMB=" + maxCacheMB);
}
if (useWrappingCollector) {
if (doAllGroups) {
cCache = CachingCollector.create(c1, true, maxCacheMB);
c = MultiCollector.wrap(cCache, allGroupsCollector);
} else {
c = cCache = CachingCollector.create(c1, true, maxCacheMB);
}
} else {
// Collect only into cache, then replay multiple times:
c = cCache = CachingCollector.create(false, true, maxCacheMB);
}
} else {
cCache = null;
if (doAllGroups) {
c = MultiCollector.wrap(c1, allGroupsCollector);
} else {
c = c1;
}
}
s.search(new TermQuery(new Term("content", searchTerm)), c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
// Replay for first-pass grouping
cCache.replay(c1);
if (doAllGroups) {
// Replay for all groups:
cCache.replay(allGroupsCollector);
}
} else {
// Replay by re-running search:
s.search(new TermQuery(new Term("content", searchTerm)), c1);
if (doAllGroups) {
s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector);
}
}
}
final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields);
final TopGroups groupsResult;
if (topGroups != null) {
if (VERBOSE) {
System.out.println("TEST: topGroups");
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
System.out.println("TEST: cache is intact");
}
cCache.replay(c2);
} else {
if (VERBOSE) {
System.out.println("TEST: cache was too large");
}
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
} else {
s.search(new TermQuery(new Term("content", searchTerm)), c2);
}
if (doAllGroups) {
TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset);
groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount());
} else {
groupsResult = c2.getTopGroups(docOffset);
}
} else {
groupsResult = null;
if (VERBOSE) {
System.out.println("TEST: no results");
}
}
final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
System.out.println("TEST: no expected groups");
} else {
System.out.println("TEST: expected groups");
for(GroupDocs<BytesRef> gd : expectedGroups.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString()));
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + sd.doc + " score=" + sd.score);
}
}
}
}
assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores);
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
final TermAllGroupsCollector allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
allGroupsCollector2 = new TermAllGroupsCollector("group");
c4 = MultiCollector.wrap(c3, allGroupsCollector2);
} else {
allGroupsCollector2 = null;
c4 = c3;
}
s2.search(new TermQuery(new Term("content", searchTerm)), c4);
@SuppressWarnings("unchecked")
final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields);
final TopGroups groupsResult2;
if (doAllGroups && tempTopGroups2 != null) {
assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount());
groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount());
} else {
groupsResult2 = tempTopGroups2;
}
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc hit : groupDocsHits.scoreDocs) {
final GroupDoc gd = groupDocsByID[hit.doc];
assertEquals(gd.id, hit.doc);
//System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score);
hit.score = gd.score2;
}
}
final SortField[] sortFields = groupSort.getSort();
final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm);
for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) {
if (sortFields[groupSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
if (groupDocsHits.groupSortValues != null) {
//System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]));
groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]);
}
}
}
}
final SortField[] docSortFields = docSort.getSort();
for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) {
if (docSortFields[docSortIDX].getType() == SortField.SCORE) {
for (GroupDocs groupDocsHits : expectedGroups.groups) {
for(ScoreDoc _hit : groupDocsHits.scoreDocs) {
FieldDoc hit = (FieldDoc) _hit;
if (hit.fields != null) {
hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]);
assertNotNull(hit.fields[docSortIDX]);
}
}
}
}
}
}
assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores);
}
} finally {
FieldCache.DEFAULT.purge(r);
if (r2 != null) {
FieldCache.DEFAULT.purge(r2);
}
}
r.close();
dir.close();
r2.close();
dir2.close();
}
}
|
diff --git a/src/gui/GUI_KitStand.java b/src/gui/GUI_KitStand.java
index 27d6541..f271b98 100644
--- a/src/gui/GUI_KitStand.java
+++ b/src/gui/GUI_KitStand.java
@@ -1,101 +1,101 @@
package gui;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import agents.Kit;
public class GUI_KitStand implements GUI_Component {
GUI_Stand[] stands;
// This is the constructor. It creates the array( size 3) of stands and sets
// each stands. Then it sets stands[0] and stand[1] to normals stand objs
// and stands[2] to inspection area obj.
public GUI_KitStand(int x, int y) {
stands = new GUI_Stand[3];
for (int i = 0; i < 3; i++)
stands[i] = new GUI_Stand(x, i*150 + y);
}
public void DoAddKit(Kit k) {
- for (int s = 0; s>=0; s++){
+ for (int s = 2; s>=0; s--){
if (stands[s].kit == null){
stands[s].kit = new GUI_Kit(k,getX(s),getY(s));
break;
}
}
}
public void DoAddKitToInspection(Kit k){
stands[0].kit = new GUI_Kit(k, getX(0),getY(0));
}
public void DoRemoveKit(Kit k) {
for (int s = 1; s<=2; s++){
if (stands[s].kit!= null){
stands[s].removeKit();
break;
}
}
}
// The paint function calls the drawing of each of the stands in the array.
public void paintComponent(JPanel j, Graphics2D g) {
for (GUI_Stand s : stands)
s.paintComponent(j, g);
}
public void updateGraphics() {
for (GUI_Stand s : stands)
s.updateGraphics();
}
public int getX(int i) {
return stands[i].x;
}
public int getY(int i) {
return stands[i].y;
}
public void addPart(int number, GUI_Part p) {
stands[number].kit.addPart(p);
}
public boolean positionOpen(int i) {
if (stands[i].kit == null){
return true;
}
else{
return false;
}
}
public void addkit(GUI_Kit k, int number){
/*stands[number].kit = k;
k.setX(stands[number].x);
k.setY(stands[number].y);*/
}
public GUI_Kit checkKit(int number){
return stands[number].kit;
}
// the check status function will see if a GUIKit is done with it�s part
// annimation and is ready to be inspected or if it being inspected will
// make sure it gets picked up.
// NOT NEEDED THIS VERSION!
/*
* void checkStatus(){
*
* }
*/
}
| true | true | public void DoAddKit(Kit k) {
for (int s = 0; s>=0; s++){
if (stands[s].kit == null){
stands[s].kit = new GUI_Kit(k,getX(s),getY(s));
break;
}
}
}
| public void DoAddKit(Kit k) {
for (int s = 2; s>=0; s--){
if (stands[s].kit == null){
stands[s].kit = new GUI_Kit(k,getX(s),getY(s));
break;
}
}
}
|
diff --git a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
index 1e0ee1f49..335902cf5 100644
--- a/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
+++ b/src/eclipse/plugins/com.ibm.sbt.core/src/com/ibm/sbt/services/client/connections/files/model/FileCreationParameters.java
@@ -1,132 +1,132 @@
package com.ibm.sbt.services.client.connections.files.model;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* @author Lorenzo Boccaccia
* @date May 28, 2013
*/
public class FileCreationParameters {
/**
* Specifies whether you want to get a notification when someone adds or updates a comment on a file. Options are on or off. The default value is on.
*/
public NotificationFlag commentNotification;
/**
* Date to use as the creation date of the file. This value can be set by the user, and defaults to the current system time on the server.
* Sent as the time in the number of milliseconds since January 1, 1970, 00:00:00 GMT time.
*/
public Date created;
/**
* Specifies whether you want to show the file path to the file. if true,
* adds an entry extension <td:path> element that specifies the file path to the object.
*/
public Boolean includePath;
/**
* Specifies whether the person updating the file wants to get a notification when someone subsequently updates the file.
* Options are on or off. The default value is off.
*/
public NotificationFlag mediaNotification;
public enum NotificationFlag {
ON, OFF
}
/**
* Date to use as the last modified date of the file. This value can be set by the user, and defaults to the current system time on the server.
* Sent as the time in the number of milliseconds since January 1, 1970, 00:00:00 GMT time.
*/
public Date modified;
/**
* Indicates if users that are shared with can share this document. The default value is false.
*/
public Boolean propagate;
/**
* Defines the level of permission that the people listed in the sharedWith parameter have to the file. Only applicable if the sharedWith parameter is passed.
* Permission level options are Edit or View.
* The default value is View.
*/
public Permission sharePermission;
public enum Permission {
EDIT, VIEW
}
/**
* Text. Explanation of the share.
*/
public String shareSummary;
/**
* User ID of the user to share the content with. This parameter can be applied multiple times.
*/
public Collection<String> shareWith = new LinkedList<String>();
/**
* String. Keyword that helps to classify the file. This parameter can be applied multiple times if multiple tags are passed.
*/
public Collection<String> tags = new LinkedList<String>();
/**
* Specifies who can see the file. Options are private or public. A public file is visible to all users and can be shared by all users.
* The default value is private.
*/
public Visibility visibility;
public enum Visibility {
PUBLIC, PRIVATE
}
public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
- ret.put("tags", tags.iterator().next());
+ ret.put("tag", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
}
| true | true | public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
ret.put("tags", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
| public Map<String, String> buildParameters() {
Map<String, String> ret = new HashMap<String, String>();
if (commentNotification!=null) {
ret.put("commentNotification", commentNotification.toString().toLowerCase());
}
if (mediaNotification!=null) {
ret.put("mediaNotification", mediaNotification.toString().toLowerCase());
}
if (created!=null) {
ret.put("created", Long.toString(created.getTime()));
}
if (includePath!=null) {
ret.put("includePath", includePath.toString());
}
if (modified!=null) {
ret.put("modified", Long.toString(modified.getTime()));
}
if (propagate!=null) {
ret.put("propagate", propagate.toString());
}
if (sharePermission!=null) {
ret.put("sharePermission", sharePermission.toString().toLowerCase());
}
if (shareSummary!=null) {
ret.put("shareSummary", shareSummary.toString());
}
if (shareWith!=null && shareWith.size()>0) {
if ( shareWith.size()>1)
throw new UnsupportedOperationException("multivalue shareWith args not yet supported");
ret.put("shareWith", shareWith.iterator().next());
}
if (tags!=null && tags.size()>0) {
if ( tags.size()>1)
throw new UnsupportedOperationException("multivalue tags args not yet supported");
ret.put("tag", tags.iterator().next());
}
if (visibility!=null) {
ret.put("visibility", visibility.toString().toLowerCase());
}
return ret;
}
|
diff --git a/client/api/src/test/java/com/github/podd/client/api/test/AbstractPoddClientTest.java b/client/api/src/test/java/com/github/podd/client/api/test/AbstractPoddClientTest.java
index e783292e..99621fbb 100644
--- a/client/api/src/test/java/com/github/podd/client/api/test/AbstractPoddClientTest.java
+++ b/client/api/src/test/java/com/github/podd/client/api/test/AbstractPoddClientTest.java
@@ -1,773 +1,773 @@
/**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.client.api.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openrdf.model.Model;
import org.openrdf.model.URI;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.ansell.restletutils.RestletUtilRole;
import com.github.podd.api.file.DataReference;
import com.github.podd.client.api.PoddClient;
import com.github.podd.utils.DebugUtils;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.PoddRdfConstants;
import com.github.podd.utils.PoddRoles;
import com.github.podd.utils.PoddUser;
import com.github.podd.utils.PoddUserStatus;
/**
* Abstract tests for {@link PoddClient}.
* <p>
* IMPORTANT: Never run these tests against a server containing real data, such as a production
* server. After each test, the test attempts to reset the server, to enable other tests to be
* easily verified.
*
* @author Peter Ansell [email protected]
*/
public abstract class AbstractPoddClientTest
{
protected final Logger log = LoggerFactory.getLogger(this.getClass());
protected static final String TEST_ADMIN_USER = "testAdminUser";
protected static final String TEST_ADMIN_PASSWORD = "testAdminPassword";
private PoddClient testClient;
private static final int BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES = 24;
/**
* Instruct the implementors of this test to attempt to deploy a file reference that has the
* given label and return a partial DataReference object that contains the specific details of
* how and where the file reference is located.
* <p>
* The {@link DataReference#getArtifactID()}, {@link DataReference#getObjectIri()},
* {@link DataReference#getParentIri()}, and {@link DataReference#getParentPredicateIRI()}
* SHOULD not be populated, as they will be overwritten.
* <p>
* The {@link DataReference#getRepositoryAlias()} MUST be populated, and MUST match an alias
* returned from {@link PoddClient#listDataReferenceRepositories()}.
* <p>
* Successive calls with different labels must return distinct FileReferences.
* <p>
* Successive calls with the same label must return a DataReference containing the same
* essential details.
*
* @param label
* The label to give the file reference.
* @return A partially populated {@link DataReference} object.
* @throws Exception
* If there were any issues deploying a file reference for this label.
*/
protected abstract DataReference deployFileReference(String label) throws Exception;
/**
* Any file repositories that were made active for this test can now be shutdown.
* <p>
* For example, an SSH server created specifically for this test may be cleaned up and shutdown.
*/
protected abstract void endFileRepositoryTest() throws Exception;
/**
* Implementing test classes must return a new instance of {@link PoddClient} for each call to
* this method.
*
* @return A new instance of {@link PoddClient}.
*/
protected abstract PoddClient getNewPoddClientInstance();
/**
* Returns the URL of a running PODD Server to test the client against.
*
* @return The URL of the PODD Server to test using.
*/
protected abstract String getTestPoddServerUrl();
protected Model parseRdf(final InputStream inputStream, final RDFFormat format, final int expectedStatements)
throws RDFParseException, RDFHandlerException, IOException
{
final Model model = Rio.parse(inputStream, "", format);
if(model.size() != expectedStatements)
{
this.log.error("--- Regression ---");
this.log.error("Expected: {} Actual: {}", expectedStatements, model.size());
DebugUtils.printContents(model);
}
Assert.assertEquals(expectedStatements, model.size());
return model;
}
/**
* Resets the test PODD server if possible. If not possible it is not recommended to rely on
* these tests for extensive verification.
*
* @throws IOException
*/
protected abstract void resetTestPoddServer() throws IOException;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
this.testClient = this.getNewPoddClientInstance();
Assert.assertNotNull("PODD Client implementation was null", this.testClient);
this.testClient.setPoddServerUrl(this.getTestPoddServerUrl());
}
/**
* Any file repositories necessary to perform file reference attachment tests must be available
* after this method completes.
*/
protected abstract void startFileRepositoryTest() throws Exception;
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
this.resetTestPoddServer();
this.testClient = null;
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#addRole(String, RestletUtilRole, InferredOWLOntologyID)}
* .
*/
@Test
public final void testAddRolesArtifact() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
final Map<RestletUtilRole, Collection<String>> roles = this.testClient.listRoles(newArtifact);
Assert.assertEquals(2, roles.size());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_ADMIN));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_ADMIN).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_ADMIN).iterator()
.next());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR)
.iterator().next());
this.testClient.addRole(AbstractPoddClientTest.TEST_ADMIN_USER, PoddRoles.PROJECT_OBSERVER, newArtifact);
final Map<RestletUtilRole, Collection<String>> afterRoles = this.testClient.listRoles(newArtifact);
Assert.assertEquals(3, afterRoles.size());
Assert.assertTrue(afterRoles.containsKey(PoddRoles.PROJECT_ADMIN));
Assert.assertEquals(1, afterRoles.get(PoddRoles.PROJECT_ADMIN).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, afterRoles.get(PoddRoles.PROJECT_ADMIN).iterator()
.next());
Assert.assertTrue(afterRoles.containsKey(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR));
Assert.assertEquals(1, afterRoles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER,
afterRoles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).iterator().next());
Assert.assertTrue(afterRoles.containsKey(PoddRoles.PROJECT_OBSERVER));
Assert.assertEquals(1, afterRoles.get(PoddRoles.PROJECT_OBSERVER).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, afterRoles.get(PoddRoles.PROJECT_OBSERVER)
.iterator().next());
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#appendArtifact(OWLOntologyID, InputStream, RDFFormat)}
* .
*/
@Ignore
@Test
public final void testAppendArtifact() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#attachFileReference(OWLOntologyID, org.semanticweb.owlapi.model.IRI, String, String, String)}
* .
*/
@Test
public final void testAttachFileReference() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
try
{
this.startFileRepositoryTest();
// TODO: Pick a project with more child objects
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
final Model parseRdf =
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
final Model topObject =
parseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, topObject.size());
final DataReference testRef = this.deployFileReference("test-file-label");
testRef.setArtifactID(newArtifact);
testRef.setParentIri(IRI.create(topObject.objectURI()));
testRef.setParentPredicateIRI(IRI.create(PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE));
// TODO: If this breaks then need to attach it to a different part of an extended
// project
testRef.setObjectIri(IRI.create("urn:temp:uuid:dataReference:1"));
final InferredOWLOntologyID afterFileAttachment = this.testClient.attachDataReference(testRef);
Assert.assertNotNull(afterFileAttachment);
Assert.assertNotNull(afterFileAttachment.getOntologyIRI());
Assert.assertNotNull(afterFileAttachment.getVersionIRI());
Assert.assertEquals(newArtifact.getOntologyIRI(), afterFileAttachment.getOntologyIRI());
// Version should have been updated by the operation
Assert.assertNotEquals(newArtifact.getVersionIRI(), afterFileAttachment.getVersionIRI());
final ByteArrayOutputStream afterOutputStream = new ByteArrayOutputStream(8096);
- this.testClient.downloadArtifact(newArtifact, afterOutputStream, RDFFormat.RDFJSON);
+ this.testClient.downloadArtifact(afterFileAttachment, afterOutputStream, RDFFormat.RDFJSON);
final Model afterParseRdf =
this.parseRdf(new ByteArrayInputStream(afterOutputStream.toByteArray()), RDFFormat.RDFJSON, 32);
final Model afterTopObject =
afterParseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, afterTopObject.size());
// If this starts to fail it is okay, as the server may reassign URIs as it desires,
// just comment it out if this occurs
Assert.assertEquals(afterTopObject.objectURI(), topObject.objectURI());
final Model afterDataReferenceURI =
afterParseRdf.filter(topObject.objectURI(), PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE, null);
Assert.assertNotEquals(topObject.objectURI(), afterDataReferenceURI.objectURI());
final Model afterDataReferenceTriples = afterParseRdf.filter(afterDataReferenceURI.objectURI(), null, null);
Assert.assertEquals("Found unexpected number of triples for data reference", 7,
afterDataReferenceTriples.size());
}
finally
{
this.endFileRepositoryTest();
}
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#createUser(PoddUser)}
*/
@Test
public final void testCreateUser() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final PoddUser testUser =
new PoddUser("theNextUser", "theNextPassword".toCharArray(), "The Next", "User",
"[email protected]", PoddUserStatus.ACTIVE,
PoddRdfConstants.VF.createURI("http://example.com/thenext/"), "UQ", null, "Dr", "0912348765",
"Brisbane", "Adjunct Professor");
final PoddUser userDetails = this.testClient.createUser(testUser);
Assert.assertEquals("theNextUser", userDetails.getIdentifier());
Assert.assertNull(userDetails.getSecret());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#deleteArtifact(OWLOntologyID)} .
*/
@Test
public final void testDeleteArtifact() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
// verify that the artifact is accessible and complete
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
final Model parseRdf =
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
Assert.assertTrue(this.testClient.deleteArtifact(newArtifact));
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#downloadArtifact(InferredOWLOntologyID, java.io.OutputStream, RDFFormat)}
* .
*/
@Ignore
@Test
public final void testDownloadArtifactCurrentVersion() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#downloadArtifact(InferredOWLOntologyID, java.io.OutputStream, RDFFormat)}
* .
*/
@Ignore
@Test
public final void testDownloadArtifactDummyVersion() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#downloadArtifact(InferredOWLOntologyID, java.io.OutputStream, RDFFormat)}
* .
*/
@Test
public final void testDownloadArtifactNoVersion() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#downloadArtifact(InferredOWLOntologyID, java.io.OutputStream, RDFFormat)}
* .
*/
@Ignore
@Test
public final void testDownloadArtifactOldVersion() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#getPoddServerUrl()}.
*/
@Test
public final void testGetPoddServerUrlNull() throws Exception
{
Assert.assertNotNull(this.testClient.getPoddServerUrl());
this.testClient.setPoddServerUrl(null);
Assert.assertNull(this.testClient.getPoddServerUrl());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#getUserDetails(String)}
*/
@Test
public final void testGetUserDetails() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final PoddUser userDetails = this.testClient.getUserDetails(AbstractPoddClientTest.TEST_ADMIN_USER);
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, userDetails.getIdentifier());
Assert.assertNull(userDetails.getSecret());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listDataReferenceRepositories()}
* .
*/
@Test
public final void testListDataReferenceRepositories() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final List<String> repositories = this.testClient.listDataReferenceRepositories();
System.out.println(repositories);
Assert.assertEquals(2, repositories.size());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listPublishedArtifacts()}.
*/
@Test
public final void testListPublishedArtifactsEmpty() throws Exception
{
final Collection<InferredOWLOntologyID> results = this.testClient.listPublishedArtifacts();
Assert.assertTrue(results.isEmpty());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listPublishedArtifacts()}.
*/
@Ignore
@Test
public final void testListPublishedArtifactsMultiple() throws Exception
{
// TODO: Create 50 artifacts
Assert.fail("TODO: Implement me!");
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final Collection<InferredOWLOntologyID> results = this.testClient.listPublishedArtifacts();
Assert.assertFalse(results.isEmpty());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listPublishedArtifacts()}.
*/
@Ignore
@Test
public final void testListPublishedArtifactsSingle() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
// Returns a new version, as when the artifact is published it gets a new version
final InferredOWLOntologyID publishedArtifact = this.testClient.publishArtifact(newArtifact);
this.testClient.logout();
final Collection<InferredOWLOntologyID> results = this.testClient.listPublishedArtifacts();
Assert.assertFalse(results.isEmpty());
Assert.assertEquals(-1, results.size());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listRoles(String)} .
*/
@Test
public final void testListRolesArtifact() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
final Map<RestletUtilRole, Collection<String>> roles = this.testClient.listRoles(newArtifact);
Assert.assertEquals(2, roles.size());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_ADMIN));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_ADMIN).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_ADMIN).iterator()
.next());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR)
.iterator().next());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listRoles(String)} .
*/
@Test
public final void testListRolesUser() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final Map<RestletUtilRole, Collection<URI>> roles =
this.testClient.listRoles(AbstractPoddClientTest.TEST_ADMIN_USER);
Assert.assertEquals(1, roles.size());
Assert.assertTrue(roles.containsKey(PoddRoles.ADMIN));
Assert.assertEquals(1, roles.get(PoddRoles.ADMIN).size());
Assert.assertNull(roles.get(PoddRoles.ADMIN).iterator().next());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listUnpublishedArtifacts()}.
*/
@Test
public final void testListUnpublishedArtifactsEmpty() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final Collection<InferredOWLOntologyID> results = this.testClient.listUnpublishedArtifacts();
this.log.info("unpublished artifacts which should be empty: {}", results);
Assert.assertTrue(results.isEmpty());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listUnpublishedArtifacts()}.
*/
@Ignore
@Test
public final void testListUnpublishedArtifactsMultiple() throws Exception
{
// TODO: Create 50 artifacts
Assert.fail("TODO: Implement me!");
final Collection<InferredOWLOntologyID> results = this.testClient.listUnpublishedArtifacts();
Assert.assertFalse(results.isEmpty());
Assert.assertEquals(50, results.size());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#listUnpublishedArtifacts()}.
*/
@Test
public final void testListUnpublishedArtifactsSingle() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
final Collection<InferredOWLOntologyID> results = this.testClient.listUnpublishedArtifacts();
Assert.assertFalse(results.isEmpty());
Assert.assertEquals(1, results.size());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#login(java.lang.String, String)}
* .
*/
@Test
public final void testLogin() throws Exception
{
Assert.assertFalse(this.testClient.isLoggedIn());
Assert.assertTrue("Client was not successfully logged in",
this.testClient.login("testAdminUser", "testAdminPassword"));
Assert.assertTrue(this.testClient.isLoggedIn());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#logout()}.
*/
@Test
public final void testLogout() throws Exception
{
this.testClient.setPoddServerUrl(this.getTestPoddServerUrl());
Assert.assertFalse(this.testClient.isLoggedIn());
Assert.assertTrue("Client was not successfully logged in",
this.testClient.login("testAdminUser", "testAdminPassword"));
Assert.assertTrue(this.testClient.isLoggedIn());
Assert.assertTrue("Client was not successfully logged out", this.testClient.logout());
Assert.assertFalse(this.testClient.isLoggedIn());
}
/**
* Test method for {@link com.github.podd.client.api.PoddClient#publishArtifact(OWLOntologyID)}
* .
*/
@Ignore
@Test
public final void testPublishArtifact() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#removeRole(String, RestletUtilRole, InferredOWLOntologyID)}
* .
*/
@Test
public final void testRemoveRolesArtifact() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
final Map<RestletUtilRole, Collection<String>> roles = this.testClient.listRoles(newArtifact);
Assert.assertEquals(2, roles.size());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_ADMIN));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_ADMIN).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_ADMIN).iterator()
.next());
Assert.assertTrue(roles.containsKey(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR));
Assert.assertEquals(1, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER, roles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR)
.iterator().next());
this.testClient.removeRole(AbstractPoddClientTest.TEST_ADMIN_USER, PoddRoles.PROJECT_ADMIN, newArtifact);
final Map<RestletUtilRole, Collection<String>> afterRoles = this.testClient.listRoles(newArtifact);
Assert.assertEquals(1, afterRoles.size());
Assert.assertTrue(afterRoles.containsKey(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR));
Assert.assertEquals(1, afterRoles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).size());
Assert.assertEquals(AbstractPoddClientTest.TEST_ADMIN_USER,
afterRoles.get(PoddRoles.PROJECT_PRINCIPAL_INVESTIGATOR).iterator().next());
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#setPoddServerUrl(java.lang.String)}.
*/
@Test
public final void testSetPoddServerUrl() throws Exception
{
Assert.assertNotNull(this.testClient.getPoddServerUrl());
this.testClient.setPoddServerUrl(null);
Assert.assertNull(this.testClient.getPoddServerUrl());
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#unpublishArtifact(InferredOWLOntologyID)} .
*/
@Ignore
@Test
public final void testUnpublishArtifact()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#updateArtifact(InferredOWLOntologyID, InputStream, RDFFormat)}
* .
*/
@Ignore
@Test
public final void testUpdateArtifact() throws Exception
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.client.api.PoddClient#uploadNewArtifact(java.io.InputStream, org.openrdf.rio.RDFFormat)}
* .
*/
@Test
public final void testUploadNewArtifact() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
final Model model =
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
Assert.assertTrue(model.contains(newArtifact.getOntologyIRI().toOpenRDFURI(), RDF.TYPE, OWL.ONTOLOGY));
Assert.assertTrue(model.contains(newArtifact.getOntologyIRI().toOpenRDFURI(), OWL.VERSIONIRI, newArtifact
.getVersionIRI().toOpenRDFURI()));
}
}
| true | true | public final void testAttachFileReference() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
try
{
this.startFileRepositoryTest();
// TODO: Pick a project with more child objects
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
final Model parseRdf =
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
final Model topObject =
parseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, topObject.size());
final DataReference testRef = this.deployFileReference("test-file-label");
testRef.setArtifactID(newArtifact);
testRef.setParentIri(IRI.create(topObject.objectURI()));
testRef.setParentPredicateIRI(IRI.create(PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE));
// TODO: If this breaks then need to attach it to a different part of an extended
// project
testRef.setObjectIri(IRI.create("urn:temp:uuid:dataReference:1"));
final InferredOWLOntologyID afterFileAttachment = this.testClient.attachDataReference(testRef);
Assert.assertNotNull(afterFileAttachment);
Assert.assertNotNull(afterFileAttachment.getOntologyIRI());
Assert.assertNotNull(afterFileAttachment.getVersionIRI());
Assert.assertEquals(newArtifact.getOntologyIRI(), afterFileAttachment.getOntologyIRI());
// Version should have been updated by the operation
Assert.assertNotEquals(newArtifact.getVersionIRI(), afterFileAttachment.getVersionIRI());
final ByteArrayOutputStream afterOutputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, afterOutputStream, RDFFormat.RDFJSON);
final Model afterParseRdf =
this.parseRdf(new ByteArrayInputStream(afterOutputStream.toByteArray()), RDFFormat.RDFJSON, 32);
final Model afterTopObject =
afterParseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, afterTopObject.size());
// If this starts to fail it is okay, as the server may reassign URIs as it desires,
// just comment it out if this occurs
Assert.assertEquals(afterTopObject.objectURI(), topObject.objectURI());
final Model afterDataReferenceURI =
afterParseRdf.filter(topObject.objectURI(), PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE, null);
Assert.assertNotEquals(topObject.objectURI(), afterDataReferenceURI.objectURI());
final Model afterDataReferenceTriples = afterParseRdf.filter(afterDataReferenceURI.objectURI(), null, null);
Assert.assertEquals("Found unexpected number of triples for data reference", 7,
afterDataReferenceTriples.size());
}
finally
{
this.endFileRepositoryTest();
}
}
| public final void testAttachFileReference() throws Exception
{
this.testClient.login(AbstractPoddClientTest.TEST_ADMIN_USER, AbstractPoddClientTest.TEST_ADMIN_PASSWORD);
try
{
this.startFileRepositoryTest();
// TODO: Pick a project with more child objects
final InputStream input = this.getClass().getResourceAsStream("/test/artifacts/basicProject-1.rdf");
Assert.assertNotNull("Test resource missing", input);
final InferredOWLOntologyID newArtifact = this.testClient.uploadNewArtifact(input, RDFFormat.RDFXML);
Assert.assertNotNull(newArtifact);
Assert.assertNotNull(newArtifact.getOntologyIRI());
Assert.assertNotNull(newArtifact.getVersionIRI());
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(newArtifact, outputStream, RDFFormat.RDFJSON);
final Model parseRdf =
this.parseRdf(new ByteArrayInputStream(outputStream.toByteArray()), RDFFormat.RDFJSON,
AbstractPoddClientTest.BASIC_PROJECT_1_EXPECTED_CONCRETE_TRIPLES);
final Model topObject =
parseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, topObject.size());
final DataReference testRef = this.deployFileReference("test-file-label");
testRef.setArtifactID(newArtifact);
testRef.setParentIri(IRI.create(topObject.objectURI()));
testRef.setParentPredicateIRI(IRI.create(PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE));
// TODO: If this breaks then need to attach it to a different part of an extended
// project
testRef.setObjectIri(IRI.create("urn:temp:uuid:dataReference:1"));
final InferredOWLOntologyID afterFileAttachment = this.testClient.attachDataReference(testRef);
Assert.assertNotNull(afterFileAttachment);
Assert.assertNotNull(afterFileAttachment.getOntologyIRI());
Assert.assertNotNull(afterFileAttachment.getVersionIRI());
Assert.assertEquals(newArtifact.getOntologyIRI(), afterFileAttachment.getOntologyIRI());
// Version should have been updated by the operation
Assert.assertNotEquals(newArtifact.getVersionIRI(), afterFileAttachment.getVersionIRI());
final ByteArrayOutputStream afterOutputStream = new ByteArrayOutputStream(8096);
this.testClient.downloadArtifact(afterFileAttachment, afterOutputStream, RDFFormat.RDFJSON);
final Model afterParseRdf =
this.parseRdf(new ByteArrayInputStream(afterOutputStream.toByteArray()), RDFFormat.RDFJSON, 32);
final Model afterTopObject =
afterParseRdf.filter(newArtifact.getOntologyIRI().toOpenRDFURI(),
PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT, null);
Assert.assertEquals("Did not find unique top object in artifact", 1, afterTopObject.size());
// If this starts to fail it is okay, as the server may reassign URIs as it desires,
// just comment it out if this occurs
Assert.assertEquals(afterTopObject.objectURI(), topObject.objectURI());
final Model afterDataReferenceURI =
afterParseRdf.filter(topObject.objectURI(), PoddRdfConstants.PODD_BASE_HAS_DATA_REFERENCE, null);
Assert.assertNotEquals(topObject.objectURI(), afterDataReferenceURI.objectURI());
final Model afterDataReferenceTriples = afterParseRdf.filter(afterDataReferenceURI.objectURI(), null, null);
Assert.assertEquals("Found unexpected number of triples for data reference", 7,
afterDataReferenceTriples.size());
}
finally
{
this.endFileRepositoryTest();
}
}
|
diff --git a/mifos/src/org/mifos/framework/components/cronjobs/helpers/SavingsIntPostingHelper.java b/mifos/src/org/mifos/framework/components/cronjobs/helpers/SavingsIntPostingHelper.java
index 2017fca53..b7534449b 100644
--- a/mifos/src/org/mifos/framework/components/cronjobs/helpers/SavingsIntPostingHelper.java
+++ b/mifos/src/org/mifos/framework/components/cronjobs/helpers/SavingsIntPostingHelper.java
@@ -1,45 +1,42 @@
package org.mifos.framework.components.cronjobs.helpers;
import java.util.Calendar;
import java.util.List;
import org.mifos.application.accounts.savings.business.SavingsBO;
import org.mifos.application.accounts.savings.persistence.SavingsPersistence;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.components.cronjobs.TaskHelper;
import org.mifos.framework.hibernate.helper.HibernateUtil;
public class SavingsIntPostingHelper extends TaskHelper{
public void execute(long timeInMillis) {
try{
Calendar cal = Calendar.getInstance(Configuration.getInstance().getSystemConfig().getMifosTimeZone());
cal.setTimeInMillis(timeInMillis);
SavingsPersistence persistence = new SavingsPersistence();
List<Integer> accountList=persistence.retreiveAccountsPendingForIntPosting(cal.getTime());
HibernateUtil.closeSession();
- System.out.println("----------size: "+ accountList.size());
for(Integer accountId: accountList){
try{
SavingsBO savings = persistence.findById(accountId);
- System.out.println("--------before: "+ savings.getInterestToBePosted());
savings.postInterest();
- System.out.println("--------after: "+ savings.getInterestToBePosted());
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}catch(Exception e){
HibernateUtil.rollbackTransaction();
}finally {
HibernateUtil.closeSession();
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
HibernateUtil.closeSession();
}
}
public boolean isTaskAllowedToRun() {
return true;
}
}
| false | true | public void execute(long timeInMillis) {
try{
Calendar cal = Calendar.getInstance(Configuration.getInstance().getSystemConfig().getMifosTimeZone());
cal.setTimeInMillis(timeInMillis);
SavingsPersistence persistence = new SavingsPersistence();
List<Integer> accountList=persistence.retreiveAccountsPendingForIntPosting(cal.getTime());
HibernateUtil.closeSession();
System.out.println("----------size: "+ accountList.size());
for(Integer accountId: accountList){
try{
SavingsBO savings = persistence.findById(accountId);
System.out.println("--------before: "+ savings.getInterestToBePosted());
savings.postInterest();
System.out.println("--------after: "+ savings.getInterestToBePosted());
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}catch(Exception e){
HibernateUtil.rollbackTransaction();
}finally {
HibernateUtil.closeSession();
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
HibernateUtil.closeSession();
}
}
| public void execute(long timeInMillis) {
try{
Calendar cal = Calendar.getInstance(Configuration.getInstance().getSystemConfig().getMifosTimeZone());
cal.setTimeInMillis(timeInMillis);
SavingsPersistence persistence = new SavingsPersistence();
List<Integer> accountList=persistence.retreiveAccountsPendingForIntPosting(cal.getTime());
HibernateUtil.closeSession();
for(Integer accountId: accountList){
try{
SavingsBO savings = persistence.findById(accountId);
savings.postInterest();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}catch(Exception e){
HibernateUtil.rollbackTransaction();
}finally {
HibernateUtil.closeSession();
}
}
}
catch(Exception e){
e.printStackTrace();
}finally {
HibernateUtil.closeSession();
}
}
|
diff --git a/mixer2-fruitshop-springboot/src/main/java/org/mixer2/sample/config/SessionTrackingConfigListener.java b/mixer2-fruitshop-springboot/src/main/java/org/mixer2/sample/config/SessionTrackingConfigListener.java
index 6d6bbbd..c0ff82f 100644
--- a/mixer2-fruitshop-springboot/src/main/java/org/mixer2/sample/config/SessionTrackingConfigListener.java
+++ b/mixer2-fruitshop-springboot/src/main/java/org/mixer2/sample/config/SessionTrackingConfigListener.java
@@ -1,37 +1,37 @@
package org.mixer2.sample.config;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import org.springframework.boot.context.embedded.ServletContextInitializer;
/**
* <p>
* セッション情報をcookieに格納するときのcookie名の指定。<br />
* urlrewritingによるセッション維持も無効にする。<br />
* set-cookieヘッダにhttpOnly属性も付けるようにする
* </p>
* <p>
* 通常のWebApplicationであればWEB-INF/web.xmlの
* session-configタグやcookie-configタグを使って設定するのと等価。
* </p>
*/
public class SessionTrackingConfigListener implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
SessionCookieConfig sessionCookieConfig = servletContext
.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setName("SAMPLESESSIONID");
- Set<SessionTrackingMode> stmSet = new HashSet<>();
+ Set<SessionTrackingMode> stmSet = new HashSet<SessionTrackingMode>();
stmSet.add(SessionTrackingMode.COOKIE);
servletContext.setSessionTrackingModes(stmSet);
}
}
| true | true | public void onStartup(ServletContext servletContext)
throws ServletException {
SessionCookieConfig sessionCookieConfig = servletContext
.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setName("SAMPLESESSIONID");
Set<SessionTrackingMode> stmSet = new HashSet<>();
stmSet.add(SessionTrackingMode.COOKIE);
servletContext.setSessionTrackingModes(stmSet);
}
| public void onStartup(ServletContext servletContext)
throws ServletException {
SessionCookieConfig sessionCookieConfig = servletContext
.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
sessionCookieConfig.setName("SAMPLESESSIONID");
Set<SessionTrackingMode> stmSet = new HashSet<SessionTrackingMode>();
stmSet.add(SessionTrackingMode.COOKIE);
servletContext.setSessionTrackingModes(stmSet);
}
|
diff --git a/src/edu/victone/scrabblah/logic/player/AIPlayer.java b/src/edu/victone/scrabblah/logic/player/AIPlayer.java
index f616983..5498027 100644
--- a/src/edu/victone/scrabblah/logic/player/AIPlayer.java
+++ b/src/edu/victone/scrabblah/logic/player/AIPlayer.java
@@ -1,27 +1,28 @@
package edu.victone.scrabblah.logic.player;
/**
* Created with IntelliJ IDEA.
* User: vwilson
* Date: 9/11/13
* Time: 5:23 PM
*/
public class AIPlayer extends Player {
public static String[] playerNames = {"Charles B.", "Bill G.", "Steve J.", "Steve W.", "Alan T.", "John V.N.", "Bob H.", "Ken S.", "John J."};
private double skillLevel;
public AIPlayer(String name, int rank) {
this(name, rank, 1.0); //creates godlike scrabble players
}
public AIPlayer(String name, int rank, double skillLevel) {
super(name, rank);
+ this.skillLevel = skillLevel;
}
@Override
public String toString() {
return "P" + rank + ": " + name + " (AI) - Score: " + score;
}
}
| true | true | public AIPlayer(String name, int rank, double skillLevel) {
super(name, rank);
}
| public AIPlayer(String name, int rank, double skillLevel) {
super(name, rank);
this.skillLevel = skillLevel;
}
|
diff --git a/src/core/cascading/tap/GlobHfs.java b/src/core/cascading/tap/GlobHfs.java
index 0d91e29e..5fc294ca 100644
--- a/src/core/cascading/tap/GlobHfs.java
+++ b/src/core/cascading/tap/GlobHfs.java
@@ -1,178 +1,178 @@
/*
* Copyright (c) 2007-2010 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Cascading is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cascading is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cascading. If not, see <http://www.gnu.org/licenses/>.
*/
package cascading.tap;
import java.beans.ConstructorProperties;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cascading.scheme.Scheme;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.mapred.JobConf;
/**
* Class GlobHfs is a type of {@link MultiSourceTap} that accepts Hadoop style 'file globing' expressions so
* multiple files that match the given pattern may be used as the input sources for a given {@link cascading.flow.Flow}.
* <p/>
* See {@link FileSystem#globStatus(org.apache.hadoop.fs.Path)} for details on the globing syntax. But in short
* it is similar to standard regular expressions except alternation is done via {foo,bar} instead of (foo|bar).
* <p/>
* Note that a {@link cascading.flow.Flow} sourcing from GlobHfs is not currently compatible with the {@link cascading.cascade.Cascade}
* scheduler. GlobHfs expects the files and paths to exist so the wildcards can be resolved into concrete values so
* that the scheduler can order the Flows properly.
* <p/>
* Note that globing can match files or directories. It may consume less resources to match directories and let
* Hadoop include all sub-files immediately contained in the directory instead of enumerating every individual file.
* Ending the glob path with a {@code /} should match only directories.
*
* @see Hfs
* @see MultiSourceTap
* @see FileSystem
*/
public class GlobHfs extends MultiSourceTap
{
/** Field pathPattern */
private String pathPattern;
/** Field pathFilter */
private PathFilter pathFilter;
/**
* Constructor GlobHfs creates a new GlobHfs instance.
*
* @param scheme of type Scheme
* @param pathPattern of type String
*/
@ConstructorProperties({"scheme", "pathPattern"})
public GlobHfs( Scheme scheme, String pathPattern )
{
this( scheme, pathPattern, null );
}
/**
* Constructor GlobHfs creates a new GlobHfs instance.
*
* @param scheme of type Scheme
* @param pathPattern of type String
* @param pathFilter of type PathFilter
*/
@ConstructorProperties({"scheme", "pathPattern", "pathFilter"})
public GlobHfs( Scheme scheme, String pathPattern, PathFilter pathFilter )
{
super( scheme );
this.pathPattern = pathPattern;
this.pathFilter = pathFilter;
}
@Override
protected Tap[] getTaps()
{
if( taps != null )
return taps;
try
{
taps = makeTaps( new JobConf() );
}
catch( IOException exception )
{
throw new TapException( "unable to resolve taps for globbing path: " + pathPattern );
}
return taps;
}
private Tap[] makeTaps( JobConf conf ) throws IOException
{
FileStatus[] statusList = null;
Path path = new Path( pathPattern );
FileSystem fileSystem = path.getFileSystem( conf );
if( pathFilter == null )
statusList = fileSystem.globStatus( path );
else
statusList = fileSystem.globStatus( path, pathFilter );
if( statusList == null || statusList.length == 0 )
throw new TapException( "unable to find paths matching path pattern: " + pathPattern );
List<Hfs> notEmpty = new ArrayList<Hfs>();
for( int i = 0; i < statusList.length; i++ )
{
- if( statusList[ i ].getLen() != 0 )
+ if( statusList[ i ].isDir() || statusList[ i ].getLen() != 0 )
notEmpty.add( new Hfs( getScheme(), statusList[ i ].getPath().toString() ) );
}
if( notEmpty.isEmpty() )
throw new TapException( "all paths matching path pattern are zero length: " + pathPattern );
return notEmpty.toArray( new Tap[ notEmpty.size() ] );
}
@Override
public void sourceInit( JobConf conf ) throws IOException
{
taps = makeTaps( conf );
super.sourceInit( conf );
}
@Override
public boolean equals( Object object )
{
if( this == object )
return true;
if( object == null || getClass() != object.getClass() )
return false;
GlobHfs globHfs = (GlobHfs) object;
// do not compare tap arrays, these values should be sufficient to show identity
if( getScheme() != null ? !getScheme().equals( globHfs.getScheme() ) : globHfs.getScheme() != null )
return false;
if( pathFilter != null ? !pathFilter.equals( globHfs.pathFilter ) : globHfs.pathFilter != null )
return false;
if( pathPattern != null ? !pathPattern.equals( globHfs.pathPattern ) : globHfs.pathPattern != null )
return false;
return true;
}
@Override
public int hashCode()
{
int result = pathPattern != null ? pathPattern.hashCode() : 0;
result = 31 * result + ( pathFilter != null ? pathFilter.hashCode() : 0 );
return result;
}
@Override
public String toString()
{
return "GlobHfs[" + pathPattern + ']';
}
}
| true | true | private Tap[] makeTaps( JobConf conf ) throws IOException
{
FileStatus[] statusList = null;
Path path = new Path( pathPattern );
FileSystem fileSystem = path.getFileSystem( conf );
if( pathFilter == null )
statusList = fileSystem.globStatus( path );
else
statusList = fileSystem.globStatus( path, pathFilter );
if( statusList == null || statusList.length == 0 )
throw new TapException( "unable to find paths matching path pattern: " + pathPattern );
List<Hfs> notEmpty = new ArrayList<Hfs>();
for( int i = 0; i < statusList.length; i++ )
{
if( statusList[ i ].getLen() != 0 )
notEmpty.add( new Hfs( getScheme(), statusList[ i ].getPath().toString() ) );
}
if( notEmpty.isEmpty() )
throw new TapException( "all paths matching path pattern are zero length: " + pathPattern );
return notEmpty.toArray( new Tap[ notEmpty.size() ] );
}
| private Tap[] makeTaps( JobConf conf ) throws IOException
{
FileStatus[] statusList = null;
Path path = new Path( pathPattern );
FileSystem fileSystem = path.getFileSystem( conf );
if( pathFilter == null )
statusList = fileSystem.globStatus( path );
else
statusList = fileSystem.globStatus( path, pathFilter );
if( statusList == null || statusList.length == 0 )
throw new TapException( "unable to find paths matching path pattern: " + pathPattern );
List<Hfs> notEmpty = new ArrayList<Hfs>();
for( int i = 0; i < statusList.length; i++ )
{
if( statusList[ i ].isDir() || statusList[ i ].getLen() != 0 )
notEmpty.add( new Hfs( getScheme(), statusList[ i ].getPath().toString() ) );
}
if( notEmpty.isEmpty() )
throw new TapException( "all paths matching path pattern are zero length: " + pathPattern );
return notEmpty.toArray( new Tap[ notEmpty.size() ] );
}
|
diff --git a/cilla-admin/src/main/java/org/shredzone/cilla/admin/AbstractImageBean.java b/cilla-admin/src/main/java/org/shredzone/cilla/admin/AbstractImageBean.java
index 30cabcc..6ef3d65 100644
--- a/cilla-admin/src/main/java/org/shredzone/cilla/admin/AbstractImageBean.java
+++ b/cilla-admin/src/main/java/org/shredzone/cilla/admin/AbstractImageBean.java
@@ -1,185 +1,186 @@
/*
* cilla - Blog Management System
*
* Copyright (C) 2012 Richard "Shred" Körber
* http://cilla.shredzone.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.shredzone.cilla.admin;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.WeakHashMap;
import javax.activation.DataHandler;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.shredzone.cilla.ws.ImageProcessing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Abstract superclass for image providing beans.
* <p>
* It provides methods for fetching image IDs or indexes, and helps creating
* {@link StreamedContent} for the resulting image.
*
* @author Richard "Shred" Körber
*/
@Component
public abstract class AbstractImageBean implements Serializable {
private static final long serialVersionUID = 3624378631087966758L;
private final Logger log = LoggerFactory.getLogger(getClass());
private @Value("${previewImageMaxCache}") int maxCache;
private final Map<DataHandler, byte[]> weakScaleCache = new WeakHashMap<>();
/**
* Gets the "renderId" request parameter used for rendering images by their ID.
*/
protected Long getFacesRenderId() {
String renderId = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("renderId");
return (renderId != null ? Long.valueOf(renderId) : null);
}
/**
* Gets the "index" request parameter used for rendering images by their index.
*/
protected Integer getFacesIndex() {
String index = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("index");
return (index != null ? Integer.valueOf(index) : null);
}
/**
* Creates an empty {@link StreamedContent}. Should be used when no image can be
* streamed.
*
* @return {@link StreamedContent} containing an empty file
*/
protected StreamedContent createEmptyStreamedContent() {
return new DefaultStreamedContent(new ByteArrayInputStream(new byte[0]), "image/png");
}
/**
* Creates a {@link StreamedContent} for the given {@link DataHandler}.
*
* @param dh
* {@link DataHandler} to stream
* @return {@link StreamedContent} containing that image
*/
protected StreamedContent createStreamedContent(DataHandler dh) {
if (dh != null) {
try {
return new DefaultStreamedContent(dh.getInputStream(), dh.getContentType());
} catch (IOException ex) {
log.error("Exception while streaming content", ex);
}
}
return createEmptyStreamedContent();
}
/**
* Creates a {@link StreamedContent} for the given {@link DataHandler}, with the image
* having the given width and height. The aspect ratio is kept. A PNG type image is
* returned.
* <p>
* <em>NOTE:</em> The scaled image is cached related to the {@link DataHandler}. Thus,
* it is not possible to create different sizes of the same {@link DataHandler} using
* this method. A weak cache is used, to keep the memory footprint as small as
* possible.
*
* @param dh
* {@link DataHandler} to stream
* @param width
* Maximum image width
* @param height
* Maximum image height
* @return {@link StreamedContent} containing that image
*/
protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) {
byte[] scaledData = null;
if (dh != null) {
scaledData = weakScaleCache.get(dh);
if (scaledData == null) {
try {
BufferedImage image = ImageIO.read(dh.getInputStream());
if (image != null) {
BufferedImage scaled = scale(image, process.getWidth(), process.getHeight());
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
ImageIO.write(scaled, process.getType().getFormatName(), bos);
scaledData = bos.toByteArray();
}
if (weakScaleCache.size() < maxCache) {
weakScaleCache.put(dh, scaledData);
}
}
} catch (IOException ex) {
log.error("Exception while streaming scaled content: " + dh.getName(), ex);
}
}
}
if (scaledData != null) {
- return new DefaultStreamedContent(new ByteArrayInputStream(scaledData), "image/png");
+ return new DefaultStreamedContent(new ByteArrayInputStream(scaledData),
+ process.getType().getContentType());
} else {
return createEmptyStreamedContent();
}
}
/**
* Scales a {@link BufferedImage} to the given size, keeping the aspect ratio. If the
* image is smaller than the resulting size, it will be magnified.
*
* @param image
* {@link BufferedImage} to scale
* @param width
* Maximum result width
* @param height
* Maximum result height
* @return {@link BufferedImage} with the scaled image
*/
private BufferedImage scale(BufferedImage image, int width, int height) {
ImageObserver observer = null;
Image scaled = null;
if (image.getWidth() > image.getHeight()) {
scaled = image.getScaledInstance(width, -1, Image.SCALE_SMOOTH);
} else {
scaled = image.getScaledInstance(-1, height, Image.SCALE_SMOOTH);
}
BufferedImage result = new BufferedImage(
scaled.getWidth(observer), scaled.getHeight(observer),
BufferedImage.TYPE_INT_RGB);
result.createGraphics().drawImage(scaled, 0, 0, observer);
return result;
}
}
| true | true | protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) {
byte[] scaledData = null;
if (dh != null) {
scaledData = weakScaleCache.get(dh);
if (scaledData == null) {
try {
BufferedImage image = ImageIO.read(dh.getInputStream());
if (image != null) {
BufferedImage scaled = scale(image, process.getWidth(), process.getHeight());
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
ImageIO.write(scaled, process.getType().getFormatName(), bos);
scaledData = bos.toByteArray();
}
if (weakScaleCache.size() < maxCache) {
weakScaleCache.put(dh, scaledData);
}
}
} catch (IOException ex) {
log.error("Exception while streaming scaled content: " + dh.getName(), ex);
}
}
}
if (scaledData != null) {
return new DefaultStreamedContent(new ByteArrayInputStream(scaledData), "image/png");
} else {
return createEmptyStreamedContent();
}
}
| protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) {
byte[] scaledData = null;
if (dh != null) {
scaledData = weakScaleCache.get(dh);
if (scaledData == null) {
try {
BufferedImage image = ImageIO.read(dh.getInputStream());
if (image != null) {
BufferedImage scaled = scale(image, process.getWidth(), process.getHeight());
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
ImageIO.write(scaled, process.getType().getFormatName(), bos);
scaledData = bos.toByteArray();
}
if (weakScaleCache.size() < maxCache) {
weakScaleCache.put(dh, scaledData);
}
}
} catch (IOException ex) {
log.error("Exception while streaming scaled content: " + dh.getName(), ex);
}
}
}
if (scaledData != null) {
return new DefaultStreamedContent(new ByteArrayInputStream(scaledData),
process.getType().getContentType());
} else {
return createEmptyStreamedContent();
}
}
|
diff --git a/PadgetsREST/PadgetsREST-web/src/main/java/de/fhg/fokus/service/UserResource.java b/PadgetsREST/PadgetsREST-web/src/main/java/de/fhg/fokus/service/UserResource.java
index ca6c46f..b7a59e6 100644
--- a/PadgetsREST/PadgetsREST-web/src/main/java/de/fhg/fokus/service/UserResource.java
+++ b/PadgetsREST/PadgetsREST-web/src/main/java/de/fhg/fokus/service/UserResource.java
@@ -1,115 +1,116 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.fhg.fokus.service;
import de.fhg.fokus.facades.UserdataFacade;
import de.fhg.fokus.persistence.Campaign;
import de.fhg.fokus.persistence.Userdata;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
/**
*
* @author Hannes Gorges
*/
@Stateless
@Path("user")
public class UserResource {
@EJB
private UserdataFacade userdataFacade;
@EJB
private SampleSessionBean sampleSessionBean;
/**
* Returns the user object for the given session id.<br />
*
* Address: GET [server]/resources/user?sid=test_user
*
* @param sid session id
* @return
*/
@GET
@Produces({"application/xml", "application/json"})
public Userdata getUser(@DefaultValue("test_user") @QueryParam("sid") String sid) {
if (sid.equals("test_user")) {//return test data
return sampleSessionBean.makeSampleUser();
}
List<Userdata> udList = userdataFacade.executeNamedQuery("Userdata.findByUserSIGN", "userSIGN", sid);
if (udList.isEmpty()) {
Userdata u = new Userdata();
u.setUsername("The session id is not valid!");
return u;
}
return udList.get(0);
}
/**
* Updates the user object.<br />
*
* Address: PUT [server]/resources/user?sid=test_user
*
* @param user user object with new data
* @param sid session id
* @return
*/
@PUT
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public Userdata updateUser(Userdata user, @DefaultValue("test_user") @QueryParam("sid") String sid) {
if (sid.equals("test_user")) {//return test data
return sampleSessionBean.makeSampleUser();
}
List<Userdata> udList = userdataFacade.executeNamedQuery("Userdata.findByUserSIGN", "userSIGN", sid);
if (udList.isEmpty()) {
Userdata u = new Userdata();
u.setUsername("The session id is not valid!");
return u;
}
Userdata ud = udList.get(0);
ud.setAge(new Date());
ud.setEmail(user.getEmail());
ud.setFirstname(user.getFirstname());
ud.setGender(user.getGender());
ud.setOrganization(user.getOrganization());
ud.setLastname(user.getLastname());
ud.setUsername(user.getUsername());
ud.setViewLanguage(user.getViewLanguage());
+ ud.setFirstLogin(user.getFirstLogin());
userdataFacade.edit(ud);
return ud;
}
/**
* Deletes the user with the given id if the session id is from the same user.<br />
*
* Address: DELETE [server]/resources/user/[userId]?sid=test_user
*
* @param sid
* @param userId
*/
@DELETE
@Path("{id}")
public void deleteUser(@DefaultValue("test_user") @QueryParam("sid") String sid, @PathParam("id") Integer userId) {
if (sid.equals("test_user")) {//return test data
return;
}
List<Userdata> udList = userdataFacade.executeNamedQuery("Userdata.findByUserSIGN", "userSIGN", sid);
if (udList != null && udList.get(0).getIdUserData() == userId) {
userdataFacade.remove(udList.get(0));
}
}
}
| true | true | public Userdata updateUser(Userdata user, @DefaultValue("test_user") @QueryParam("sid") String sid) {
if (sid.equals("test_user")) {//return test data
return sampleSessionBean.makeSampleUser();
}
List<Userdata> udList = userdataFacade.executeNamedQuery("Userdata.findByUserSIGN", "userSIGN", sid);
if (udList.isEmpty()) {
Userdata u = new Userdata();
u.setUsername("The session id is not valid!");
return u;
}
Userdata ud = udList.get(0);
ud.setAge(new Date());
ud.setEmail(user.getEmail());
ud.setFirstname(user.getFirstname());
ud.setGender(user.getGender());
ud.setOrganization(user.getOrganization());
ud.setLastname(user.getLastname());
ud.setUsername(user.getUsername());
ud.setViewLanguage(user.getViewLanguage());
userdataFacade.edit(ud);
return ud;
}
| public Userdata updateUser(Userdata user, @DefaultValue("test_user") @QueryParam("sid") String sid) {
if (sid.equals("test_user")) {//return test data
return sampleSessionBean.makeSampleUser();
}
List<Userdata> udList = userdataFacade.executeNamedQuery("Userdata.findByUserSIGN", "userSIGN", sid);
if (udList.isEmpty()) {
Userdata u = new Userdata();
u.setUsername("The session id is not valid!");
return u;
}
Userdata ud = udList.get(0);
ud.setAge(new Date());
ud.setEmail(user.getEmail());
ud.setFirstname(user.getFirstname());
ud.setGender(user.getGender());
ud.setOrganization(user.getOrganization());
ud.setLastname(user.getLastname());
ud.setUsername(user.getUsername());
ud.setViewLanguage(user.getViewLanguage());
ud.setFirstLogin(user.getFirstLogin());
userdataFacade.edit(ud);
return ud;
}
|
diff --git a/src/gov/nih/nci/camod/webapp/util/SidebarUtil.java b/src/gov/nih/nci/camod/webapp/util/SidebarUtil.java
index f2487481..9c1ed2dd 100755
--- a/src/gov/nih/nci/camod/webapp/util/SidebarUtil.java
+++ b/src/gov/nih/nci/camod/webapp/util/SidebarUtil.java
@@ -1,100 +1,101 @@
package gov.nih.nci.camod.webapp.util;
import gov.nih.nci.camod.Constants;
import javax.servlet.http.HttpServletRequest;
public class SidebarUtil extends gov.nih.nci.camod.webapp.action.BaseAction {
public String findSubMenu( HttpServletRequest request, String jspName )
{
System.out.println("<sidebar.jsp> String jspName=" + jspName );
if( jspName.equals("searchSimple.jsp") ||
jspName.equals("searchHelp.jsp") ||
jspName.equals("searchAdvanced.jsp") ||
jspName.equals("searchDrugScreening.jsp") ||
jspName.equals("searchTableOfContents.jsp") ||
jspName.equals("searchResultsDrugScreen.jsp") ||
jspName.equals("searchResults.jsp")||
jspName.equals("expDesignStage0.jsp")||
jspName.equals("expDesignStage1.jsp")||
jspName.equals("expDesignStage2.jsp")||
jspName.equals("yeastStrainsStage01.jsp")||
jspName.equals("yeastStrainsStage2.jsp")) {
return "subSearchMenu.jsp";
}
else if ( jspName.equals("viewModelCharacteristics.jsp") ||
jspName.equals("viewTransplantXenograft.jsp") ||
jspName.equals("viewGeneticDescription.jsp") ||
jspName.equals("viewInvivoDetails.jsp") ||
jspName.equals("viewPublications.jsp") ||
jspName.equals("viewCarcinogenicInterventions.jsp") ||
jspName.equals("viewHistopathology.jsp") ||
jspName.equals("viewTherapeuticApproaches.jsp") ||
+ jspName.equals("viewTransientInterference.jsp") ||
jspName.equals("viewCellLines.jsp") ||
jspName.equals("viewImages.jsp") ||
jspName.equals("viewMicroarrays.jsp") ){
String theSubMenu = "subViewModelMenu.jsp";
// For special cases when we don't have an animal model
if (request.getSession().getAttribute(Constants.ANIMALMODEL) == null) {
theSubMenu = "subSearchMenu.jsp";
}
return theSubMenu;
}
else if ( jspName.equals("adminRoles.jsp") ||
jspName.equals("helpAdmin.jsp") ||
jspName.equals("adminModelsAssignment.jsp") ||
jspName.equals("adminCommentsAssignment.jsp") ||
jspName.equals("adminRolesAssignment.jsp") ||
jspName.equals("adminEditUserRoles.jsp") ||
jspName.equals("adminEditUser.jsp") ||
jspName.equals("adminEditModels.jsp") ||
jspName.equals("adminUserManagement.jsp") ||
jspName.equals("helpDesk.jsp") ) {
return "subAdminMenu.jsp";
}
else if ( jspName.equals("submitOverview.jsp") ||
jspName.equals("submitAssocExpression.jsp") ||
jspName.equals("submitAssocMetastasis.jsp") ||
jspName.equals("submitSpontaneousMutation.jsp") ||
jspName.equals("submitClinicalMarkers.jsp") ||
jspName.equals("submitGeneDelivery.jsp") ||
jspName.equals("submitModelCharacteristics.jsp") ||
jspName.equals("submitEngineeredTransgene.jsp") ||
jspName.equals("submitGenomicSegment.jsp") ||
jspName.equals("submitTargetedModification.jsp") ||
jspName.equals("submitInducedMutation.jsp") ||
jspName.equals("submitChemicalDrug.jsp") ||
jspName.equals("submitEnvironmentalFactors.jsp") ||
jspName.equals("submitNutritionalFactors.jsp") ||
jspName.equals("submitGrowthFactors.jsp") ||
jspName.equals("submitHormone.jsp") ||
jspName.equals("submitRadiation.jsp") ||
jspName.equals("submitViralTreatment.jsp")||
jspName.equals("submitTransplantXenograft.jsp") ||
jspName.equals("submitSurgeryOther.jsp") ||
jspName.equals("submitPublications.jsp") ||
jspName.equals("submitHistopathology.jsp")||
jspName.equals("submitCellLines.jsp") ||
jspName.equals("submitTherapy.jsp") ||
jspName.equals("submitImages.jsp") ||
jspName.equals("submitMicroarrayData.jsp") ||
jspName.equals("submitJacksonLab.jsp") ||
jspName.equals("submitMMHCCRepo.jsp") ||
jspName.equals("submitInvestigator.jsp") ||
jspName.equals("submitMorpholino.jsp") ||
jspName.equals("submitIMSR.jsp") ) {
return "subSubmitMenu.jsp";
}
else if ( jspName.equals("submitModels.jsp") ||
jspName.equals("submitNewModel.jsp") ) {
return "subEmptyMenu.jsp";
} else {
return "subEmptyMenu.jsp";
}
}
}
| true | true | public String findSubMenu( HttpServletRequest request, String jspName )
{
System.out.println("<sidebar.jsp> String jspName=" + jspName );
if( jspName.equals("searchSimple.jsp") ||
jspName.equals("searchHelp.jsp") ||
jspName.equals("searchAdvanced.jsp") ||
jspName.equals("searchDrugScreening.jsp") ||
jspName.equals("searchTableOfContents.jsp") ||
jspName.equals("searchResultsDrugScreen.jsp") ||
jspName.equals("searchResults.jsp")||
jspName.equals("expDesignStage0.jsp")||
jspName.equals("expDesignStage1.jsp")||
jspName.equals("expDesignStage2.jsp")||
jspName.equals("yeastStrainsStage01.jsp")||
jspName.equals("yeastStrainsStage2.jsp")) {
return "subSearchMenu.jsp";
}
else if ( jspName.equals("viewModelCharacteristics.jsp") ||
jspName.equals("viewTransplantXenograft.jsp") ||
jspName.equals("viewGeneticDescription.jsp") ||
jspName.equals("viewInvivoDetails.jsp") ||
jspName.equals("viewPublications.jsp") ||
jspName.equals("viewCarcinogenicInterventions.jsp") ||
jspName.equals("viewHistopathology.jsp") ||
jspName.equals("viewTherapeuticApproaches.jsp") ||
jspName.equals("viewCellLines.jsp") ||
jspName.equals("viewImages.jsp") ||
jspName.equals("viewMicroarrays.jsp") ){
String theSubMenu = "subViewModelMenu.jsp";
// For special cases when we don't have an animal model
if (request.getSession().getAttribute(Constants.ANIMALMODEL) == null) {
theSubMenu = "subSearchMenu.jsp";
}
return theSubMenu;
}
else if ( jspName.equals("adminRoles.jsp") ||
jspName.equals("helpAdmin.jsp") ||
jspName.equals("adminModelsAssignment.jsp") ||
jspName.equals("adminCommentsAssignment.jsp") ||
jspName.equals("adminRolesAssignment.jsp") ||
jspName.equals("adminEditUserRoles.jsp") ||
jspName.equals("adminEditUser.jsp") ||
jspName.equals("adminEditModels.jsp") ||
jspName.equals("adminUserManagement.jsp") ||
jspName.equals("helpDesk.jsp") ) {
return "subAdminMenu.jsp";
}
else if ( jspName.equals("submitOverview.jsp") ||
jspName.equals("submitAssocExpression.jsp") ||
jspName.equals("submitAssocMetastasis.jsp") ||
jspName.equals("submitSpontaneousMutation.jsp") ||
jspName.equals("submitClinicalMarkers.jsp") ||
jspName.equals("submitGeneDelivery.jsp") ||
jspName.equals("submitModelCharacteristics.jsp") ||
jspName.equals("submitEngineeredTransgene.jsp") ||
jspName.equals("submitGenomicSegment.jsp") ||
jspName.equals("submitTargetedModification.jsp") ||
jspName.equals("submitInducedMutation.jsp") ||
jspName.equals("submitChemicalDrug.jsp") ||
jspName.equals("submitEnvironmentalFactors.jsp") ||
jspName.equals("submitNutritionalFactors.jsp") ||
jspName.equals("submitGrowthFactors.jsp") ||
jspName.equals("submitHormone.jsp") ||
jspName.equals("submitRadiation.jsp") ||
jspName.equals("submitViralTreatment.jsp")||
jspName.equals("submitTransplantXenograft.jsp") ||
jspName.equals("submitSurgeryOther.jsp") ||
jspName.equals("submitPublications.jsp") ||
jspName.equals("submitHistopathology.jsp")||
jspName.equals("submitCellLines.jsp") ||
jspName.equals("submitTherapy.jsp") ||
jspName.equals("submitImages.jsp") ||
jspName.equals("submitMicroarrayData.jsp") ||
jspName.equals("submitJacksonLab.jsp") ||
jspName.equals("submitMMHCCRepo.jsp") ||
jspName.equals("submitInvestigator.jsp") ||
jspName.equals("submitMorpholino.jsp") ||
jspName.equals("submitIMSR.jsp") ) {
return "subSubmitMenu.jsp";
}
else if ( jspName.equals("submitModels.jsp") ||
jspName.equals("submitNewModel.jsp") ) {
return "subEmptyMenu.jsp";
} else {
return "subEmptyMenu.jsp";
}
}
| public String findSubMenu( HttpServletRequest request, String jspName )
{
System.out.println("<sidebar.jsp> String jspName=" + jspName );
if( jspName.equals("searchSimple.jsp") ||
jspName.equals("searchHelp.jsp") ||
jspName.equals("searchAdvanced.jsp") ||
jspName.equals("searchDrugScreening.jsp") ||
jspName.equals("searchTableOfContents.jsp") ||
jspName.equals("searchResultsDrugScreen.jsp") ||
jspName.equals("searchResults.jsp")||
jspName.equals("expDesignStage0.jsp")||
jspName.equals("expDesignStage1.jsp")||
jspName.equals("expDesignStage2.jsp")||
jspName.equals("yeastStrainsStage01.jsp")||
jspName.equals("yeastStrainsStage2.jsp")) {
return "subSearchMenu.jsp";
}
else if ( jspName.equals("viewModelCharacteristics.jsp") ||
jspName.equals("viewTransplantXenograft.jsp") ||
jspName.equals("viewGeneticDescription.jsp") ||
jspName.equals("viewInvivoDetails.jsp") ||
jspName.equals("viewPublications.jsp") ||
jspName.equals("viewCarcinogenicInterventions.jsp") ||
jspName.equals("viewHistopathology.jsp") ||
jspName.equals("viewTherapeuticApproaches.jsp") ||
jspName.equals("viewTransientInterference.jsp") ||
jspName.equals("viewCellLines.jsp") ||
jspName.equals("viewImages.jsp") ||
jspName.equals("viewMicroarrays.jsp") ){
String theSubMenu = "subViewModelMenu.jsp";
// For special cases when we don't have an animal model
if (request.getSession().getAttribute(Constants.ANIMALMODEL) == null) {
theSubMenu = "subSearchMenu.jsp";
}
return theSubMenu;
}
else if ( jspName.equals("adminRoles.jsp") ||
jspName.equals("helpAdmin.jsp") ||
jspName.equals("adminModelsAssignment.jsp") ||
jspName.equals("adminCommentsAssignment.jsp") ||
jspName.equals("adminRolesAssignment.jsp") ||
jspName.equals("adminEditUserRoles.jsp") ||
jspName.equals("adminEditUser.jsp") ||
jspName.equals("adminEditModels.jsp") ||
jspName.equals("adminUserManagement.jsp") ||
jspName.equals("helpDesk.jsp") ) {
return "subAdminMenu.jsp";
}
else if ( jspName.equals("submitOverview.jsp") ||
jspName.equals("submitAssocExpression.jsp") ||
jspName.equals("submitAssocMetastasis.jsp") ||
jspName.equals("submitSpontaneousMutation.jsp") ||
jspName.equals("submitClinicalMarkers.jsp") ||
jspName.equals("submitGeneDelivery.jsp") ||
jspName.equals("submitModelCharacteristics.jsp") ||
jspName.equals("submitEngineeredTransgene.jsp") ||
jspName.equals("submitGenomicSegment.jsp") ||
jspName.equals("submitTargetedModification.jsp") ||
jspName.equals("submitInducedMutation.jsp") ||
jspName.equals("submitChemicalDrug.jsp") ||
jspName.equals("submitEnvironmentalFactors.jsp") ||
jspName.equals("submitNutritionalFactors.jsp") ||
jspName.equals("submitGrowthFactors.jsp") ||
jspName.equals("submitHormone.jsp") ||
jspName.equals("submitRadiation.jsp") ||
jspName.equals("submitViralTreatment.jsp")||
jspName.equals("submitTransplantXenograft.jsp") ||
jspName.equals("submitSurgeryOther.jsp") ||
jspName.equals("submitPublications.jsp") ||
jspName.equals("submitHistopathology.jsp")||
jspName.equals("submitCellLines.jsp") ||
jspName.equals("submitTherapy.jsp") ||
jspName.equals("submitImages.jsp") ||
jspName.equals("submitMicroarrayData.jsp") ||
jspName.equals("submitJacksonLab.jsp") ||
jspName.equals("submitMMHCCRepo.jsp") ||
jspName.equals("submitInvestigator.jsp") ||
jspName.equals("submitMorpholino.jsp") ||
jspName.equals("submitIMSR.jsp") ) {
return "subSubmitMenu.jsp";
}
else if ( jspName.equals("submitModels.jsp") ||
jspName.equals("submitNewModel.jsp") ) {
return "subEmptyMenu.jsp";
} else {
return "subEmptyMenu.jsp";
}
}
|
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/indels/MismatchIntervalWalker.java b/java/src/org/broadinstitute/sting/gatk/walkers/indels/MismatchIntervalWalker.java
index 4817e05df..af226c9ae 100755
--- a/java/src/org/broadinstitute/sting/gatk/walkers/indels/MismatchIntervalWalker.java
+++ b/java/src/org/broadinstitute/sting/gatk/walkers/indels/MismatchIntervalWalker.java
@@ -1,116 +1,117 @@
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.samtools.*;
import org.broadinstitute.sting.gatk.refdata.*;
import org.broadinstitute.sting.gatk.walkers.LocusWalker;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.filters.Platform454Filter;
import org.broadinstitute.sting.gatk.filters.ZeroMappingQualityReadFilter;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.gatk.walkers.WalkerName;
import org.broadinstitute.sting.gatk.walkers.ReadFilters;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import java.util.*;
@WalkerName("MismatchIntervals")
@ReadFilters({Platform454Filter.class, ZeroMappingQualityReadFilter.class})
public class MismatchIntervalWalker extends LocusWalker<Pair<GenomeLoc, Boolean>, Pair<LinkedList<Boolean>, GenomeLoc>> {
@Argument(fullName="windowSize", shortName="window", doc="window size for calculating entropy", required=false)
int windowSize = 10;
@Argument(fullName="mismatchFraction", shortName="mismatch", doc="fraction of mismatching base qualities threshold", required=false)
double mismatchThreshold = 0.15;
@Argument(fullName="allow454Reads", shortName="454", doc="process 454 reads", required=false)
boolean allow454 = false;
private final int minReadsAtInterval = 4;
public void initialize() {
if ( windowSize < 1)
throw new RuntimeException("Window Size must be a positive integer");
}
public Pair<GenomeLoc, Boolean> map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
char upperRef = Character.toUpperCase(ref.getBase());
List<SAMRecord> reads = context.getReads();
List<Integer> offsets = context.getOffsets();
int goodReads = 0, mismatchQualities = 0, totalQualities = 0;
for (int i = 0; i < reads.size(); i++) {
SAMRecord read = reads.get(i);
if ( read.getMappingQuality() == 0 ||
read.getAlignmentBlocks().size() > 1 ||
(!allow454 && Utils.is454Read(read)) )
continue;
goodReads++;
int offset = offsets.get(i);
int quality = (int)read.getBaseQualityString().charAt(offset) - 33;
totalQualities += quality;
char base = Character.toUpperCase((char)read.getReadBases()[offset]);
if ( base != upperRef )
mismatchQualities += quality;
}
boolean flag = false;
if ( goodReads >= minReadsAtInterval && (double)mismatchQualities / (double)totalQualities > mismatchThreshold )
flag = true;
return new Pair<GenomeLoc, Boolean>(context.getLocation(), flag);
}
public void onTraversalDone(Pair<LinkedList<Boolean>, GenomeLoc> sum) {
if (sum.second != null)
out.println(sum.second);
}
public Pair<LinkedList<Boolean>, GenomeLoc> reduceInit() {
return new Pair<LinkedList<Boolean>, GenomeLoc>(new LinkedList<Boolean>(), null);
}
public Pair<LinkedList<Boolean>, GenomeLoc> reduce(Pair<GenomeLoc, Boolean> value, Pair<LinkedList<Boolean>, GenomeLoc> sum) {
// if we hit a new contig, clear the list
if ( sum.second != null && sum.second.getContigIndex() != value.first.getContigIndex() ) {
+ out.println(sum.second);
sum.first.clear();
sum.second = null;
}
sum.first.addLast(value.second);
if ( sum.first.size() <= windowSize )
return sum;
sum.first.remove();
if ( !value.second )
return sum;
int mismatches = 0;
int firstMismatch = -1;
for (int i = 0; i < windowSize; i++) {
if ( sum.first.get(i) ) {
mismatches++;
if ( firstMismatch == -1 )
firstMismatch = i;
}
}
if ( mismatches > 1 ) {
// if there is no interval to the left, then this is the first one
if ( sum.second == null ) {
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second, sum.second.getStart() - windowSize + firstMismatch + 1);
}
// if the intervals don't overlap, print out the leftmost one and start a new one
else if ( value.first.getStop() - sum.second.getStop() > windowSize ) {
out.println(sum.second);
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second,sum.second.getStart() - windowSize + firstMismatch + 1);
}
// otherwise, merge them
else {
sum.second = GenomeLocParser.setStop(sum.second, value.first.getStop());
}
}
return sum;
}
}
| true | true | public Pair<LinkedList<Boolean>, GenomeLoc> reduce(Pair<GenomeLoc, Boolean> value, Pair<LinkedList<Boolean>, GenomeLoc> sum) {
// if we hit a new contig, clear the list
if ( sum.second != null && sum.second.getContigIndex() != value.first.getContigIndex() ) {
sum.first.clear();
sum.second = null;
}
sum.first.addLast(value.second);
if ( sum.first.size() <= windowSize )
return sum;
sum.first.remove();
if ( !value.second )
return sum;
int mismatches = 0;
int firstMismatch = -1;
for (int i = 0; i < windowSize; i++) {
if ( sum.first.get(i) ) {
mismatches++;
if ( firstMismatch == -1 )
firstMismatch = i;
}
}
if ( mismatches > 1 ) {
// if there is no interval to the left, then this is the first one
if ( sum.second == null ) {
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second, sum.second.getStart() - windowSize + firstMismatch + 1);
}
// if the intervals don't overlap, print out the leftmost one and start a new one
else if ( value.first.getStop() - sum.second.getStop() > windowSize ) {
out.println(sum.second);
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second,sum.second.getStart() - windowSize + firstMismatch + 1);
}
// otherwise, merge them
else {
sum.second = GenomeLocParser.setStop(sum.second, value.first.getStop());
}
}
return sum;
}
| public Pair<LinkedList<Boolean>, GenomeLoc> reduce(Pair<GenomeLoc, Boolean> value, Pair<LinkedList<Boolean>, GenomeLoc> sum) {
// if we hit a new contig, clear the list
if ( sum.second != null && sum.second.getContigIndex() != value.first.getContigIndex() ) {
out.println(sum.second);
sum.first.clear();
sum.second = null;
}
sum.first.addLast(value.second);
if ( sum.first.size() <= windowSize )
return sum;
sum.first.remove();
if ( !value.second )
return sum;
int mismatches = 0;
int firstMismatch = -1;
for (int i = 0; i < windowSize; i++) {
if ( sum.first.get(i) ) {
mismatches++;
if ( firstMismatch == -1 )
firstMismatch = i;
}
}
if ( mismatches > 1 ) {
// if there is no interval to the left, then this is the first one
if ( sum.second == null ) {
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second, sum.second.getStart() - windowSize + firstMismatch + 1);
}
// if the intervals don't overlap, print out the leftmost one and start a new one
else if ( value.first.getStop() - sum.second.getStop() > windowSize ) {
out.println(sum.second);
sum.second = value.first;
sum.second = GenomeLocParser.setStart(sum.second,sum.second.getStart() - windowSize + firstMismatch + 1);
}
// otherwise, merge them
else {
sum.second = GenomeLocParser.setStop(sum.second, value.first.getStop());
}
}
return sum;
}
|
diff --git a/trunk/appia/src/org/continuent/appia/protocols/nakfifo/multicast/NakFifoMulticastSession.java b/trunk/appia/src/org/continuent/appia/protocols/nakfifo/multicast/NakFifoMulticastSession.java
index 1dcc665..e9da4fb 100644
--- a/trunk/appia/src/org/continuent/appia/protocols/nakfifo/multicast/NakFifoMulticastSession.java
+++ b/trunk/appia/src/org/continuent/appia/protocols/nakfifo/multicast/NakFifoMulticastSession.java
@@ -1,963 +1,964 @@
/**
* Appia: Group communication and protocol composition framework library
* Copyright 2006 University of Lisbon
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Initial developer(s): Alexandre Pinto and Hugo Miranda.
* Contributor(s): See Appia web page for a list of contributors.
*/
/*
* NakFifoMulticastSession.java
*
* Created on 10 de Julho de 2003, 15:46
*/
package org.continuent.appia.protocols.nakfifo.multicast;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ListIterator;
import org.continuent.appia.core.*;
import org.continuent.appia.core.events.AppiaMulticast;
import org.continuent.appia.core.events.SendableEvent;
import org.continuent.appia.core.events.channel.ChannelClose;
import org.continuent.appia.core.events.channel.ChannelInit;
import org.continuent.appia.core.events.channel.Debug;
import org.continuent.appia.protocols.common.FIFOUndeliveredEvent;
import org.continuent.appia.protocols.common.InetWithPort;
import org.continuent.appia.protocols.frag.MaxPDUSizeEvent;
import org.continuent.appia.protocols.nakfifo.*;
import org.continuent.appia.xml.interfaces.InitializableSession;
import org.continuent.appia.xml.utils.SessionProperties;
/** Session of a protocol that provides reliable point-to-point communication.
* This protocol operates better when using network multicast support.
* <b>It only operates if destination is a <i>AppiaMulticast</i></b>.
* @author alexp
* @see org.continuent.appia.core.events.AppiaMulticast
*/
public class NakFifoMulticastSession extends Session implements InitializableSession {
/** The default duration of a round in milliseconds.
*/
public static final long DEFAULT_TIMER_PERIOD=700; // 0,7 secs
/** Default time, in milliseconds, to resend a NAK.
* <br>
* Must be a multiple of the round duration (DEFAULT_TIMER_PERIOD).
*/
public static final long DEFAULT_RESEND_TIME=5000; // 5 secs
/** Default maximum time without receiving an Application message.
* When this time is reached the peer is discarded.
* <br>
* Must be a multiple of the round duration (DEFAULT_TIMER_PERIOD).
*/
public static final long DEFAULT_MAX_APPL_TIME=180000; // 3 mins
/** Default maximum time, in milliseconds, to recieve a message from a peer.
* If this time is reached the peer is considered failed.
* <br>
* Must be a multiple of the round duration (DEFAULT_TIMER_PERIOD).
*/
public static final long DEFAULT_MAX_RECV_TIME=60000; // 60 secs
/** Default maximum time to send a message to a peer.
* If this time is reached a Ping message is sent.
* <br>
* Must be a multiple of the round duration (DEFAULT_TIMER_PERIOD).
*/
public static final long DEFAULT_MAX_SENT_TIME=45000; // 45 secs
/** Default number of rounds between confirms
*/
public static final long DEFAULT_CONFIRM_ROUNDS=0; // every round
private long param_TIMER_PERIOD=DEFAULT_TIMER_PERIOD;
private long param_RESEND_NACK_ROUNDS=DEFAULT_RESEND_TIME/param_TIMER_PERIOD;
private long param_MAX_APPL_ROUNDS=DEFAULT_MAX_APPL_TIME/param_TIMER_PERIOD;
private long param_MAX_RECV_ROUNDS=DEFAULT_MAX_RECV_TIME/param_TIMER_PERIOD;
private long param_MAX_SENT_ROUNDS=DEFAULT_MAX_SENT_TIME/param_TIMER_PERIOD;
private long param_CONFIRM_ROUNDS=DEFAULT_CONFIRM_ROUNDS;
/** Creates a new instance of NakFifoSession */
public NakFifoMulticastSession(Layer layer) {
super(layer);
last_msg_sent=System.currentTimeMillis() & MessageUtils.INIT_MASK;
if (last_msg_sent == MessageUtils.INIT_MASK)
last_msg_sent--;
first_msg_sent=last_msg_sent+1;
}
public void init(SessionProperties params) {
if (params.containsKey("timer_period"))
param_TIMER_PERIOD=params.getLong("timer_period");
if (params.containsKey("resend_nack_time"))
param_RESEND_NACK_ROUNDS=params.getLong("resend_nack_time")/param_TIMER_PERIOD;
if (params.containsKey("max_appl_time"))
param_MAX_APPL_ROUNDS=params.getLong("max_appl_time")/param_TIMER_PERIOD;
if (params.containsKey("max_recv_time"))
param_MAX_RECV_ROUNDS=params.getLong("max_recv_time")/param_TIMER_PERIOD;
if (params.containsKey("max_sent_time"))
param_MAX_SENT_ROUNDS=params.getLong("max_sent_time")/param_TIMER_PERIOD;
if (params.containsKey("confirm_rounds"))
param_CONFIRM_ROUNDS=params.getLong("confirm_rounds");
if (params.containsKey("debug"))
debugOn=params.getBoolean("debug");
}
/** Main Event handler. */
public void handle(Event event) {
if (event instanceof NackEvent) {
handleNack((NackEvent)event); return;
} else if (event instanceof IgnoreEvent) {
handleIgnore((IgnoreEvent)event); return;
} else if (event instanceof PingEvent) {
handlePing((PingEvent)event); return;
} else if (event instanceof UpdateEvent) {
handleUpdate((UpdateEvent)event); return;
} else if (event instanceof ConfirmEvent) {
handleConfirm((ConfirmEvent)event); return;
} else if (event instanceof NakFifoTimer) {
handleNakFifoTimer((NakFifoTimer)event); return;
} else if (event instanceof SendableEvent) {
handleSendable((SendableEvent)event); return;
} if (event instanceof ChannelInit) {
handleChannelInit((ChannelInit)event); return;
} if (event instanceof ChannelClose) {
handleChannelClose((ChannelClose)event); return;
} else if (event instanceof MaxPDUSizeEvent) {
handleMaxPDUSize((MaxPDUSizeEvent)event); return;
} else if (event instanceof Debug) {
Debug ev=(Debug)event;
if (ev.getQualifierMode() == EventQualifier.ON) {
debugOn=true;
if (ev.getOutput() instanceof java.io.PrintStream)
debug=(java.io.PrintStream)ev.getOutput();
else
debug=new java.io.PrintStream(ev.getOutput());
} else if (ev.getQualifierMode() == EventQualifier.OFF) {
debugOn=false;
}
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
return;
}
debug("Unwanted event (\""+event.getClass().getName()+"\") received. Continued...");
try { event.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
}
private long first_msg_sent;
private long last_msg_sent;
private long rounds_confirm=0;
private HashMap peers=new HashMap();
private Channel timerChannel=null;
private MessageUtils utils=new MessageUtils();
private void handleChannelInit(ChannelInit ev) {
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
if (timerChannel == null)
sendTimer(ev.getChannel());
//appia.protocols.drop.DropSession.dropRate=0.3;
debug("Params:\n\tTIMER_PERIOD="+param_TIMER_PERIOD+
"\n\tMAX_APPL_ROUNDS="+param_MAX_APPL_ROUNDS+
"\n\tMAX_RECV_ROUNDS="+param_MAX_RECV_ROUNDS+
"\n\tMAX_SENT_ROUNDS="+param_MAX_SENT_ROUNDS+
"\n\tRESEND_NACK_ROUNDS="+param_RESEND_NACK_ROUNDS+
"\n\tCONFIRM_ROUNDS="+param_CONFIRM_ROUNDS);
}
private void handleChannelClose(ChannelClose ev) {
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
if (ev.getChannel() == timerChannel) {
timerChannel=null;
Iterator iter=peers.values().iterator();
while (iter.hasNext() && (timerChannel == null)) {
Peer peer=(Peer)iter.next();
if (peer.last_channel != null)
sendTimer(peer.last_channel);
}
if (timerChannel != null)
debug("Sent new timer in channel "+timerChannel.getChannelID());
else
debug("Unable to send timer. Corret operation is not garanteed");
}
}
/*
private void handleRegisterSocket(RegisterSocketEvent ev) {
if ((ev.getDir() == Direction.UP) && !ev.error) {
InetWithPort addr=new InetWithPort(ev.localHost, ev.port);
registerAddr(addr);
}
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
}
*/
private void handleMaxPDUSize(MaxPDUSizeEvent event) {
if (event.getDir() == Direction.UP) {
event.pduSize-=5;
}
try {
event.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
}
private void handleSendable(SendableEvent event) {
if (event.getDir() == Direction.UP) {
byte flags=event.getMessage().popByte();
if ((flags & MessageUtils.IGNORE_FLAG) != 0) {
debug("Received msg with ignore flag. Ignoring.");
try { event.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
return;
}
Peer peer=(Peer)peers.get(event.source);
if (peer == null)
peer=createPeer(event.source,last_msg_sent,event.getChannel());
long seq;
if ((seq=utils.popSeq(event.getMessage(),peer.last_msg_delivered,false)) < 0) {
debug("Problems reading sequence number discarding event "+event+" from "+event.source.toString());
return;
}
receive(peer,event,seq,seq);
return;
}
if (event.getDir() == Direction.DOWN) {
if ((event.dest instanceof InetWithPort) && (((InetWithPort)event.dest).host.isMulticastAddress())) {
debug("Destination is a IP Multicast address. Ignored.");
event.getMessage().pushByte(MessageUtils.IGNORE_FLAG);
try { event.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
return;
}
last_msg_sent++;
try {
SendableEvent clone=(SendableEvent)event.cloneEvent();
// Puts peer counter
clone.getMessage().pushInt(0);
if (event.dest instanceof AppiaMulticast) {
Object[] dests=((AppiaMulticast)event.dest).getDestinations();
for (int i=0 ; i < dests.length ; i++)
sending(clone,dests[i],last_msg_sent);
} else {
sending(clone,event.dest,last_msg_sent);
}
utils.pushSeq(event.getMessage(),last_msg_sent);
event.getMessage().pushByte(MessageUtils.NOFLAGS);
event.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("To mantain coerence, sending undelivered.");
sendFIFOUndelivered(event,event.dest);
return;
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("To mantain coerence, sending undelivered.");
sendFIFOUndelivered(event,event.dest);
return;
}
return;
}
debug("Direction is wrong. Discarding event "+event);
}
private void handlePing(PingEvent ev) {
if (ev.getDir() != Direction.UP) {
debug("Discarding Ping event due to wrong diretion.");
return;
}
// Confirmed
Peer peer=(Peer)peers.get(ev.source);
if (peer == null) {
debug("Received Ping from unknown peer ("+ev.source+"). Ignoring confirm.");
ev.getMessage().discard(MessageUtils.SEQ_SIZE);
} else {
long confirmed;
if ((confirmed=utils.popSeq(ev.getMessage(),peer.last_msg_confirmed,false)) < 0) {
debug("Problems reading confirm sequence number from "+ev.source);
} else {
confirmed(peer,confirmed,ev.getChannel());
}
}
handleSendable(ev);
}
private void handleNack(NackEvent ev) {
Peer peer=(Peer)peers.get(ev.source);
if (peer == null) {
peer=createPeer(ev.source,last_msg_sent,ev.getChannel());
return;
}
long first;
long last;
if ((first=ev.getMessage().popLong()) < 0) {
debug("Ignoring Nack due to wrong first seq number.");
return;
}
if ((last=ev.getMessage().popLong()) < 0) {
debug("Ignoring Nack due to wrong last seq number.");
return;
}
if (first > last) {
debug("Ignoring Nack due to wrong seq numbers (first="+first+",last="+last+",confirmed="+peer.last_msg_confirmed+").");
return;
}
if ((first < first_msg_sent) || (last > last_msg_sent)) {
// Restart comunication
debug("Received Nack("+first+","+last+") for message not sent. Restarting communication.");
ignore(peer,ev.getChannel());
return;
}
if (debugFull)
debugPeer(peer,"handleNack("+first+","+last+")");
if (first <= peer.last_msg_confirmed) {
if (last <= peer.last_msg_confirmed) {
debug("Received Nack for messages already confirmed. Discarding.");
return;
}
first=peer.last_msg_confirmed+1;
debug("Received Nack for message already confirmed. Changig first to "+first);
}
if (last > peer.last_msg_sent) {
debug("Nack includes messages not sent to peer. Sending Update.");
if (first <= peer.last_msg_sent) {
debug("Nack partially includes messages sent to peer, resending.");
resend(peer,first,peer.last_msg_sent);
}
update(peer,last,ev.getChannel());
} else
resend(peer,first,last);
}
private void handleNakFifoTimer(NakFifoTimer ev) {
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
if (ev.getQualifierMode() != EventQualifier.NOTIFY)
return;
boolean doConfirm=false;
rounds_confirm++;
if (rounds_confirm > param_CONFIRM_ROUNDS) {
rounds_confirm=0;
doConfirm=true;
}
boolean changedSeq=false;
Iterator peers_iter=peers.values().iterator();
while (peers_iter.hasNext()) {
Peer peer=(Peer)peers_iter.next();
peer.rounds_appl_msg++;
peer.rounds_msg_recv++;
peer.rounds_msg_sent++;
if (debugFull)
debugPeer(peer,"Timer");
if (peer.nacked != null) {
peer.nacked.rounds++;
if (peer.nacked.rounds > param_RESEND_NACK_ROUNDS) {
nack(peer,peer.last_msg_delivered >= peer.nacked.first_msg ? peer.last_msg_delivered+1 : peer.nacked.first_msg, peer.nacked.last_msg, ((SendableEvent)peer.undelivered_msgs.getFirst()).getChannel());
peer.nacked.rounds=0;
}
} else {
if (peer.rounds_appl_msg > param_MAX_APPL_ROUNDS) {
peers_iter.remove();
peer=null;
}
}
if ((peer != null) && (peer.rounds_msg_recv > param_MAX_RECV_ROUNDS)) {
Iterator msgs=peer.unconfirmed_msgs.iterator();
while (msgs.hasNext()) {
sendFIFOUndelivered((SendableEvent)msgs.next(),peer.addr);
}
peers_iter.remove();
peer=null;
}
if ((peer != null) && (peer.rounds_msg_sent > param_MAX_SENT_ROUNDS)) {
try {
PingEvent e=new PingEvent(peer.last_channel,this);
+ e.getMessage().pushInt(0);
if (!changedSeq) {
last_msg_sent++;
changedSeq=true;
}
sending(e,peer.addr,last_msg_sent);
utils.pushSeq(e.getMessage(), last_msg_sent);
e.getMessage().pushByte(MessageUtils.NOFLAGS);
// Confirmed
utils.pushSeq(e.getMessage(), peer.last_msg_delivered);
peer.last_confirm_sent=peer.last_msg_delivered;
e.dest=peer.addr;
e.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
}
}
if (doConfirm && (peer != null) &&
(peer.last_msg_delivered > peer.last_confirm_sent)) {
confirm(peer);
}
}
}
private void handleIgnore(IgnoreEvent ev) {
Peer peer=(Peer)peers.get(ev.source);
if (peer == null)
peer=createPeer(ev.source,last_msg_sent,ev.getChannel());
if (debugFull)
debugPeer(peer,"handleIgnore");
peer.last_msg_delivered=ev.getMessage().popLong();
peer.undelivered_msgs.clear();
peer.nacked=null;
peer.rounds_msg_recv=0;
peer.last_channel=ev.getChannel();
//if (debugFull)
debug("Received Ignore from "+peer.addr.toString()+" with value "+peer.last_msg_delivered);
}
private void handleUpdate(UpdateEvent ev) {
Peer peer=(Peer)peers.get(ev.source);
if (peer == null)
peer=createPeer(ev.source,last_msg_sent,ev.getChannel());
if ((ev.from=utils.popSeq(ev.getMessage(),peer.last_msg_delivered, false)) < 0) {
debug("Received incorrect Update. Discarding.");
return;
}
if ((ev.to=utils.popSeq(ev.getMessage(),peer.last_msg_delivered,false)) < 0){
debug("Received incorrect Update. Discarding.");
return;
}
receive(peer,ev,ev.from,ev.to);
}
private void handleConfirm(ConfirmEvent ev) {
Peer peer=(Peer)peers.get(ev.source);
if (peer == null) {
debug("Received Confirm from unknown peer ("+ev.source+"). Discarding it.");
return;
}
long confirmed;
if ((confirmed=utils.popSeq(ev.getMessage(),peer.last_msg_confirmed,false)) < 0) {
debug("Problems reading confirm sequence number from "+ev.source);
return;
}
confirmed(peer,confirmed,ev.getChannel());
}
private void sending(SendableEvent ev, Object addr, long seq) throws AppiaEventException, CloneNotSupportedException {
Peer peer=(Peer)peers.get(addr);
if (peer == null)
peer=createPeer(addr,seq-1,ev.getChannel());
if (seq > peer.last_msg_sent+1)
update(peer,seq-1,ev.getChannel());
peer.last_msg_sent=seq;
storeUnconfirmed(peer,ev);
peer.rounds_msg_sent=0;
if (!(ev instanceof PingEvent))
peer.rounds_appl_msg=0;
}
private void receive(Peer peer, SendableEvent ev, long seqfrom, long seqto) {
// Rounds
peer.rounds_msg_recv=0;
if (!(ev instanceof PingEvent) && !(ev instanceof UpdateEvent))
peer.rounds_appl_msg=0;
if (debugFull)
debug("Received event "+ev+" from "+peer.addr+" with seq "+seqfrom+" -> "+seqto);
// Deliver
if ((seqfrom <= peer.last_msg_delivered+1) && (seqto >= peer.last_msg_delivered+1)) {
try {
if (!(ev instanceof PingEvent) && !(ev instanceof UpdateEvent))
ev.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
return;
}
peer.last_msg_delivered=seqto;
if (peer.undelivered_msgs.size() > 0) {
long undelivered=deliverUndelivered(peer);
if (debugFull)
debugPeer(peer,"receive1("+seqfrom+","+undelivered+")");
if (peer.nacked != null) {
if (peer.last_msg_delivered >= peer.nacked.last_msg)
peer.nacked=null;
}
if ((peer.nacked == null) && (undelivered >= 0))
nack(peer,peer.last_msg_delivered+1,undelivered-1,ev.getChannel());
}
} else { // Wrong seq number
if (seqto <= peer.last_msg_delivered) {
debug("Received old message from "+peer.addr.toString()+". Discarding.");
return;
}
if (debugFull)
debug("Storing undelivered from "+peer.addr+" with seq "+seqfrom);
storeUndelivered(peer,ev,seqfrom);
if (peer.nacked == null)
nack(peer,peer.last_msg_delivered+1,seqfrom-1,ev.getChannel());
}
}
private void confirmed(Peer peer, long peer_confirmed, Channel channel) {
// Confirmed
if ((peer_confirmed >= peer.first_msg_sent) && (peer_confirmed <= peer.last_msg_sent)) {
if (peer_confirmed > peer.last_msg_confirmed)
removeUnconfirmed(peer,peer_confirmed);
} else {
if (peer_confirmed > last_msg_sent) {
debug("Received wrong peer confirmed number (expected between "+peer.first_msg_sent+" and "+last_msg_sent+", received "+peer_confirmed+" from "+peer.addr+". Sending Ignore.");
ignore(peer,channel);
}
}
}
private void nack(Peer peer, long first, long last, Channel channel) {
//TODO: erase
if (first > last) {
debugPeer(peer,"nack error");
throw new AppiaError("first("+first+") > last("+last+")");
//return;
}
try {
NackEvent nack=new NackEvent(channel,this);
nack.getMessage().pushLong(last);
nack.getMessage().pushLong(first);
nack.dest=peer.addr;
nack.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Impossible to send Nack. Maybe next time.");
return;
}
peer.nacked=new Nacked(first,last);
if (debugFull)
debugPeer(peer,"nack");
}
private void ignore(Peer peer, Channel channel) {
try {
IgnoreEvent ev=new IgnoreEvent(channel,this);
ev.getMessage().pushLong(peer.last_msg_confirmed);
ev.dest=peer.addr;
ev.go();
if (debugFull)
debug("Sent Ignore with "+peer.last_msg_confirmed+" to "+peer.addr);
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Unable to send Ignore later it will be retransmited.");
return;
}
peer.rounds_msg_sent=0;
}
private void update(Peer peer, long to, Channel channel) {
try {
UpdateEvent update=new UpdateEvent(channel,this);
update.from=peer.last_msg_sent+1;
update.to=to;
update.dest=peer.addr;
UpdateEvent clone=(UpdateEvent)update.cloneEvent();
storeUnconfirmed(peer,clone);
utils.pushSeq(update.getMessage(),update.to);
utils.pushSeq(update.getMessage(),update.from);
update.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Unable to send or store update.");
throw new AppiaError("Don't know how to solve this problem. Aborting.");
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("Unable to send or store update.");
throw new AppiaError("Don't know how to solve this problem. Aborting.");
}
peer.last_msg_sent=to;
peer.rounds_msg_sent=0;
}
private void confirm(Peer peer) {
try {
ConfirmEvent ev=new ConfirmEvent(peer.last_channel,this);
utils.pushSeq(ev.getMessage(), peer.last_msg_delivered);
ev.dest=peer.addr;
ev.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Unable to send ConfirmEvent. Continuing.");
return;
}
peer.last_confirm_sent=peer.last_msg_delivered;
if (debugFull)
debug("Sent Confirm "+peer.last_confirm_sent+" to "+peer.addr);
}
private void storeUnconfirmed(Peer peer, SendableEvent ev) {
if (!(ev instanceof UpdateEvent)) {
// updates peer counter
ev.getMessage().pushInt(ev.getMessage().popInt()+1);
}
peer.unconfirmed_msgs.addLast(ev);
}
private void removeUnconfirmed(Peer peer, long last) {
while (peer.last_msg_confirmed < last) {
SendableEvent ev = (SendableEvent) peer.unconfirmed_msgs.removeFirst();
if (ev instanceof UpdateEvent)
peer.last_msg_confirmed=((UpdateEvent)ev).to;
else {
peer.last_msg_confirmed++;
// handles peer counter
int c=ev.getMessage().popInt()-1;
if (c <= 0)
ev.getMessage().discardAll();
else
ev.getMessage().pushInt(c);
}
}
}
private void resend(Peer peer, long first, long last) {
ListIterator aux=peer.unconfirmed_msgs.listIterator();
long seq=peer.last_msg_confirmed;
while (aux.hasNext() && (seq <= last)) {
SendableEvent evaux=(SendableEvent)aux.next();
if (evaux instanceof UpdateEvent) {
UpdateEvent update=(UpdateEvent)evaux;
seq=update.to;
if (((update.from >= first) && (update.from <= last)) || ((update.to >= first) && (update.to <= last))) {
try {
SendableEvent ev=(UpdateEvent)update.cloneEvent();
ev.setSource(this);
ev.init();
utils.pushSeq(ev.getMessage(),update.to);
utils.pushSeq(ev.getMessage(),update.from);
ev.dest=peer.addr;
ev.go();
peer.rounds_msg_sent=0;
} catch (AppiaEventException ex1) {
ex1.printStackTrace();
} catch (CloneNotSupportedException ex2) {
ex2.printStackTrace();
}
}
} else {
seq++;
if ((seq >= first) && (seq <= last)) {
try {
SendableEvent ev=(SendableEvent)evaux.cloneEvent();
// Removes peer counter
ev.getMessage().popInt();
ev.setSource(this);
ev.init();
utils.pushSeq(ev.getMessage(),seq);
ev.getMessage().pushByte(MessageUtils.NOFLAGS);
ev.dest=peer.addr;
ev.go();
peer.rounds_msg_sent=0;
} catch (AppiaEventException ex1) {
ex1.printStackTrace();
} catch (CloneNotSupportedException ex2) {
ex2.printStackTrace();
}
}
}
}
}
private void storeUndelivered(Peer peer, SendableEvent ev, long seq) {
if (!(ev instanceof UpdateEvent))
utils.pushSeq(ev.getMessage(),seq);
ListIterator aux=peer.undelivered_msgs.listIterator(peer.undelivered_msgs.size());
while (aux.hasPrevious()) {
SendableEvent evaux=(SendableEvent)aux.previous();
long seqaux;
if (evaux instanceof UpdateEvent) {
UpdateEvent update=(UpdateEvent)evaux;
if ((seq >= update.from) && (seq <= update.to)) {
debug("Received undelivered message already stored. Discarding new copy.");
return;
}
seqaux=update.to;
} else {
seqaux=utils.popSeq(evaux.getMessage(),peer.last_msg_delivered,true);
if (seqaux == seq) {
debug("Received undelivered message already stored. Discarding new copy.");
return;
}
}
if (seqaux < seq) {
aux.next();
aux.add(ev);
return;
}
}
peer.undelivered_msgs.addFirst(ev);
}
private long deliverUndelivered(Peer peer) {
ListIterator aux=peer.undelivered_msgs.listIterator();
while (aux.hasNext()) {
SendableEvent evaux=(SendableEvent)aux.next();
if (evaux instanceof UpdateEvent) {
UpdateEvent update=(UpdateEvent)evaux;
if (update.to <= peer.last_msg_delivered) {
debug("Discarded unwated event from "+peer.addr+" with seq "+update.from+" -> "+update.to);
aux.remove();
} else if (update.from == peer.last_msg_delivered+1) {
peer.last_msg_delivered=update.to;
aux.remove();
} else {
return update.from;
}
} else { // Not UpdateEvent interface regular SendableEvent
long seqaux=utils.popSeq(evaux.getMessage(),peer.last_msg_delivered,true);
if (seqaux <= peer.last_msg_delivered) {
debug("Discarded unwated event from "+peer.addr+" with seq "+seqaux);
aux.remove();
} else if (seqaux == peer.last_msg_delivered+1) {
if (!(evaux instanceof PingEvent)) {
try {
evaux.getMessage().discard(MessageUtils.SEQ_SIZE);
evaux.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Discarding event "+evaux+". This may lead to incoherence.");
}
}
peer.last_msg_delivered=seqaux;
aux.remove();
} else {
return seqaux;
}
}
}
return -1;
}
private Peer createPeer(Object addr, long init, Channel channel) {
Peer peer=new Peer(addr,init);
peers.put(peer.addr,peer);
ignore(peer,channel);
return peer;
}
private void sendFIFOUndelivered(SendableEvent ev, Object addr) {
if (ev instanceof PingEvent)
return;
try {
SendableEvent clone=(SendableEvent)ev.cloneEvent();
clone.dest=addr;
FIFOUndeliveredEvent e=new FIFOUndeliveredEvent(ev.getChannel(),this,clone);
e.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Unable to send Undelivered notification. Continuing but problems may happen.");
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("Unable to send Undelivered notification. Continuing but problems may happen.");
}
}
private void sendTimer(Channel channel) {
try {
NakFifoTimer timer=new NakFifoTimer(param_TIMER_PERIOD,channel,this,EventQualifier.ON);
timer.go();
timerChannel=channel;
} catch (AppiaException ex) {
//ex.printStackTrace();
debug("Unable to send timer. Correct operation of session is not guaranteed.");
}
}
/*
private int[] myHashes=new int[5];
private int myHashesLen=0;
private void registerAddr(Object addr) {
if (myHashes.length == myHashesLen) {
int[] aux=new int[myHashes.length*2];
System.arraycopy(myHashes, 0, aux, 0, myHashes.length);
myHashes=aux;
}
myHashes[myHashesLen]=addr.hashCode();
myHashesLen++;
debug("Registered "+addr+" with hash "+myHashes[myHashesLen-1]);
}
private boolean forMe(int hash) {
for (int i=0 ; i < myHashesLen ; i++) {
if (myHashes[i] == hash)
return true;
}
return false;
}
*/
// DEBUG
/** Full debug information. */
public static final boolean debugFull=false;
public static final int debugListLimit=10;
private boolean debugOn=false;
private java.io.PrintStream debug = System.err;
private void debug(String s) {
if ((debugFull || debugOn) && (debug != null))
debug.println("appia.protocols.NakFifoMulticastSession: "+s);
}
private void debugPeer(Peer peer, String s) {
if ((debugFull || debugOn) && (debug != null)) {
debug.println("@"+s+" Peer: "+peer.addr.toString());
debug.println("\t First Msg Sent: "+peer.first_msg_sent);
debug.println("\t Last Msg Sent/Confirmed: "+peer.last_msg_sent+"/"+peer.last_msg_confirmed);
debug.println("\t Last Msg Delivered: "+peer.last_msg_delivered);
debug.println("\t Rounds Appl/Sent/Recv: "+peer.rounds_appl_msg+"/"+peer.rounds_msg_sent+"/"+peer.rounds_msg_recv);
int limit=debugListLimit;
debug.println("\t Unconfirmed Msgs (size="+peer.unconfirmed_msgs.size()+"):");
ListIterator iter=peer.unconfirmed_msgs.listIterator();
long l=peer.last_msg_confirmed;
while (iter.hasNext()) {
SendableEvent ev=(SendableEvent)iter.next();
l++;
debug.println("\t\t "+l+": "+ev);
if (--limit <= 0) {
debug.println("\t\t ...");
break;
}
}
limit=debugListLimit;
debug.println("\t Undelivered Msgs (size="+peer.undelivered_msgs.size()+"):");
iter=peer.undelivered_msgs.listIterator();
while (iter.hasNext()) {
SendableEvent ev=(SendableEvent)iter.next();
if (ev instanceof UpdateEvent) {
UpdateEvent e=(UpdateEvent)ev;
debug.println("\t\t "+e.from+" -> "+e.to);
} else {
l=utils.popSeq(ev.getMessage(),peer.last_msg_delivered,true);
debug.println("\t\t "+l+": "+ev);
}
if (--limit <= 0) {
debug.println("\t\t ...");
break;
}
}
debug.print("\t Nacked First/Last/Rounds: ");
if (peer.nacked == null)
debug.println("null");
else
debug.println(""+peer.nacked.first_msg+"/"+peer.nacked.last_msg+"/"+peer.nacked.rounds);
debug.println("\t Channel: "+peer.last_channel);
}
}
/*
public static void main(String[] args) {
NakFifoMulticastSession fs=new NakFifoMulticastSession(null);
SendableEvent ev=new SendableEvent();
Peer peer=new Peer(new InetWithPort());
long l;
System.out.println("SEQ_SIZE="+SEQ_SIZE+" SEQ_MASK="+Long.toHexString(SEQ_MASK)+" INIT_SEQ_SIZE="+INIT_SEQ_SIZE+" INIT_SEQ_MASK="+Long.toHexString(INIT_SEQ_MASK));
// if (SEQ_SIZE == 4) {
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,10);
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,15);
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,16);
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,12);
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,9);
ev=new SendableEvent();
fs.storeUndelivered(peer,ev,11);
// }
fs.debugPeer(peer,"");
}
*/
}
| true | true | private void handleNakFifoTimer(NakFifoTimer ev) {
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
if (ev.getQualifierMode() != EventQualifier.NOTIFY)
return;
boolean doConfirm=false;
rounds_confirm++;
if (rounds_confirm > param_CONFIRM_ROUNDS) {
rounds_confirm=0;
doConfirm=true;
}
boolean changedSeq=false;
Iterator peers_iter=peers.values().iterator();
while (peers_iter.hasNext()) {
Peer peer=(Peer)peers_iter.next();
peer.rounds_appl_msg++;
peer.rounds_msg_recv++;
peer.rounds_msg_sent++;
if (debugFull)
debugPeer(peer,"Timer");
if (peer.nacked != null) {
peer.nacked.rounds++;
if (peer.nacked.rounds > param_RESEND_NACK_ROUNDS) {
nack(peer,peer.last_msg_delivered >= peer.nacked.first_msg ? peer.last_msg_delivered+1 : peer.nacked.first_msg, peer.nacked.last_msg, ((SendableEvent)peer.undelivered_msgs.getFirst()).getChannel());
peer.nacked.rounds=0;
}
} else {
if (peer.rounds_appl_msg > param_MAX_APPL_ROUNDS) {
peers_iter.remove();
peer=null;
}
}
if ((peer != null) && (peer.rounds_msg_recv > param_MAX_RECV_ROUNDS)) {
Iterator msgs=peer.unconfirmed_msgs.iterator();
while (msgs.hasNext()) {
sendFIFOUndelivered((SendableEvent)msgs.next(),peer.addr);
}
peers_iter.remove();
peer=null;
}
if ((peer != null) && (peer.rounds_msg_sent > param_MAX_SENT_ROUNDS)) {
try {
PingEvent e=new PingEvent(peer.last_channel,this);
if (!changedSeq) {
last_msg_sent++;
changedSeq=true;
}
sending(e,peer.addr,last_msg_sent);
utils.pushSeq(e.getMessage(), last_msg_sent);
e.getMessage().pushByte(MessageUtils.NOFLAGS);
// Confirmed
utils.pushSeq(e.getMessage(), peer.last_msg_delivered);
peer.last_confirm_sent=peer.last_msg_delivered;
e.dest=peer.addr;
e.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
}
}
if (doConfirm && (peer != null) &&
(peer.last_msg_delivered > peer.last_confirm_sent)) {
confirm(peer);
}
}
}
| private void handleNakFifoTimer(NakFifoTimer ev) {
try { ev.go(); } catch (AppiaEventException ex) { ex.printStackTrace(); }
if (ev.getQualifierMode() != EventQualifier.NOTIFY)
return;
boolean doConfirm=false;
rounds_confirm++;
if (rounds_confirm > param_CONFIRM_ROUNDS) {
rounds_confirm=0;
doConfirm=true;
}
boolean changedSeq=false;
Iterator peers_iter=peers.values().iterator();
while (peers_iter.hasNext()) {
Peer peer=(Peer)peers_iter.next();
peer.rounds_appl_msg++;
peer.rounds_msg_recv++;
peer.rounds_msg_sent++;
if (debugFull)
debugPeer(peer,"Timer");
if (peer.nacked != null) {
peer.nacked.rounds++;
if (peer.nacked.rounds > param_RESEND_NACK_ROUNDS) {
nack(peer,peer.last_msg_delivered >= peer.nacked.first_msg ? peer.last_msg_delivered+1 : peer.nacked.first_msg, peer.nacked.last_msg, ((SendableEvent)peer.undelivered_msgs.getFirst()).getChannel());
peer.nacked.rounds=0;
}
} else {
if (peer.rounds_appl_msg > param_MAX_APPL_ROUNDS) {
peers_iter.remove();
peer=null;
}
}
if ((peer != null) && (peer.rounds_msg_recv > param_MAX_RECV_ROUNDS)) {
Iterator msgs=peer.unconfirmed_msgs.iterator();
while (msgs.hasNext()) {
sendFIFOUndelivered((SendableEvent)msgs.next(),peer.addr);
}
peers_iter.remove();
peer=null;
}
if ((peer != null) && (peer.rounds_msg_sent > param_MAX_SENT_ROUNDS)) {
try {
PingEvent e=new PingEvent(peer.last_channel,this);
e.getMessage().pushInt(0);
if (!changedSeq) {
last_msg_sent++;
changedSeq=true;
}
sending(e,peer.addr,last_msg_sent);
utils.pushSeq(e.getMessage(), last_msg_sent);
e.getMessage().pushByte(MessageUtils.NOFLAGS);
// Confirmed
utils.pushSeq(e.getMessage(), peer.last_msg_delivered);
peer.last_confirm_sent=peer.last_msg_delivered;
e.dest=peer.addr;
e.go();
} catch (AppiaEventException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
} catch (CloneNotSupportedException ex) {
ex.printStackTrace();
debug("Impossible to send ping.");
}
}
if (doConfirm && (peer != null) &&
(peer.last_msg_delivered > peer.last_confirm_sent)) {
confirm(peer);
}
}
}
|
diff --git a/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java b/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
index 311bc89fc..f89b146b5 100644
--- a/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
+++ b/geogebra/geogebra3D/euclidian3D/DrawAxis3D.java
@@ -1,204 +1,208 @@
package geogebra3D.euclidian3D;
import geogebra.Matrix.GgbVector;
import geogebra.main.Application;
import geogebra3D.euclidian3D.opengl.PlotterBrush;
import geogebra3D.euclidian3D.opengl.Renderer;
import geogebra3D.kernel3D.GeoAxis3D;
import geogebra3D.kernel3D.GeoCoordSys1D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.TreeMap;
/**
* Class for drawing axis (Ox), (Oy), ...
*
* @author matthieu
*
*/
public class DrawAxis3D extends DrawLine3D {
private TreeMap<String, DrawLabel3D> labels;
/**
* common constructor
* @param view3D
* @param axis3D
*/
public DrawAxis3D(EuclidianView3D view3D, GeoAxis3D axis3D){
super(view3D, axis3D);
labels = new TreeMap<String, DrawLabel3D>();
}
/**
* drawLabel is used here for ticks
*/
public void drawLabel(Renderer renderer){
//if (!getView3D().isStarted()) return;
if(!getGeoElement().isEuclidianVisible())
return;
if (!getGeoElement().isLabelVisible())
return;
for(DrawLabel3D label : labels.values())
label.draw(renderer);
super.drawLabel(renderer);
}
protected void updateLabel(){
//draw numbers
GeoAxis3D axis = (GeoAxis3D) getGeoElement();
NumberFormat numberFormat = axis.getNumberFormat();
double distance = axis.getNumbersDistance();
int iMin = (int) (getDrawMin()/distance);
int iMax = (int) (getDrawMax()/distance);
int nb = iMax-iMin+1;
if (nb<1){
Application.debug("nb="+nb);
//labels = null;
return;
}
//sets all already existing labels not visible
for(DrawLabel3D label : labels.values())
label.setIsVisible(false);
for(int i=iMin;i<=iMax;i++){
double val = i*distance;
GgbVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
//check if the label already exists
DrawLabel3D label = labels.get(strNum);
if (label!=null){
//sets the label visible
label.setIsVisible(true);
- label.updateTexture(); //TODO remove this
+ label.update(strNum, 10,
+ getGeoElement().getObjectColor(),
+ origin.copyVector(),
+ axis.getNumbersXOffset()-4,axis.getNumbersYOffset()-6);
+ //TODO optimize this
}else{
//creates new label
label = new DrawLabel3D(getView3D());
label.update(strNum, 10,
getGeoElement().getObjectColor(),
origin.copyVector(),
axis.getNumbersXOffset()-4,axis.getNumbersYOffset()-6);
labels.put(strNum, label);
}
//TODO 4 and 6 depends to police size -> anchor
}
// update end of axis label
label.update(((GeoAxis3D) getGeoElement()).getAxisLabel(), 10,
getGeoElement().getObjectColor(),
((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()),
axis.labelOffsetX-4,axis.labelOffsetY-6
);
}
protected void updateForItSelf(){
updateDrawMinMax();
updateDecorations();
updateLabel();
PlotterBrush brush = getView3D().getRenderer().getGeometryManager().getBrush();
brush.setArrowType(PlotterBrush.ARROW_TYPE_SIMPLE);
brush.setTicks(PlotterBrush.TICKS_ON);
brush.setTicksDistance( (float) ((GeoAxis3D) getGeoElement()).getNumbersDistance());
brush.setTicksOffset((float) (-getDrawMin()/(getDrawMax()-getDrawMin())));
super.updateForItSelf(false);
brush.setArrowType(PlotterBrush.ARROW_TYPE_NONE);
brush.setTicks(PlotterBrush.TICKS_OFF);
}
private void updateDecorations(){
//update decorations
GeoAxis3D axis = (GeoAxis3D) getGeoElement();
//gets the direction vector of the axis as it is drawn on screen
GgbVector v = axis.getCoordSys().getVx().copyVector();
getView3D().toScreenCoords3D(v);
v.set(3, 0); //set z-coord to 0
double vScale = v.norm(); //axis scale, used for ticks distance
//calc orthogonal offsets
int vx = (int) (v.get(1)*3*axis.getTickSize()/vScale);
int vy = (int) (v.get(2)*3*axis.getTickSize()/vScale);
int xOffset = -vy;
int yOffset = vx;
if (yOffset>0){
xOffset = -xOffset;
yOffset = -yOffset;
}
//interval between two ticks
//TODO merge with EuclidianView.setAxesIntervals(double scale, int axis)
//Application.debug("vscale : "+vScale);
double maxPix = 100; // only one tick is allowed per maxPix pixels
double units = maxPix / vScale;
DecimalFormat numberFormat = new DecimalFormat();
double distance = getView3D().getKernel().axisNumberDistance(units, numberFormat);
axis.updateDecorations(distance, numberFormat,
xOffset, yOffset,
-vx-xOffset,-vy-yOffset);
}
protected void updateForView(){
updateForItSelf();
}
}
| true | true | protected void updateLabel(){
//draw numbers
GeoAxis3D axis = (GeoAxis3D) getGeoElement();
NumberFormat numberFormat = axis.getNumberFormat();
double distance = axis.getNumbersDistance();
int iMin = (int) (getDrawMin()/distance);
int iMax = (int) (getDrawMax()/distance);
int nb = iMax-iMin+1;
if (nb<1){
Application.debug("nb="+nb);
//labels = null;
return;
}
//sets all already existing labels not visible
for(DrawLabel3D label : labels.values())
label.setIsVisible(false);
for(int i=iMin;i<=iMax;i++){
double val = i*distance;
GgbVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
//check if the label already exists
DrawLabel3D label = labels.get(strNum);
if (label!=null){
//sets the label visible
label.setIsVisible(true);
label.updateTexture(); //TODO remove this
}else{
//creates new label
label = new DrawLabel3D(getView3D());
label.update(strNum, 10,
getGeoElement().getObjectColor(),
origin.copyVector(),
axis.getNumbersXOffset()-4,axis.getNumbersYOffset()-6);
labels.put(strNum, label);
}
//TODO 4 and 6 depends to police size -> anchor
}
// update end of axis label
label.update(((GeoAxis3D) getGeoElement()).getAxisLabel(), 10,
getGeoElement().getObjectColor(),
((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()),
axis.labelOffsetX-4,axis.labelOffsetY-6
);
}
| protected void updateLabel(){
//draw numbers
GeoAxis3D axis = (GeoAxis3D) getGeoElement();
NumberFormat numberFormat = axis.getNumberFormat();
double distance = axis.getNumbersDistance();
int iMin = (int) (getDrawMin()/distance);
int iMax = (int) (getDrawMax()/distance);
int nb = iMax-iMin+1;
if (nb<1){
Application.debug("nb="+nb);
//labels = null;
return;
}
//sets all already existing labels not visible
for(DrawLabel3D label : labels.values())
label.setIsVisible(false);
for(int i=iMin;i<=iMax;i++){
double val = i*distance;
GgbVector origin = ((GeoCoordSys1D) getGeoElement()).getPoint(val);
//draw numbers
String strNum = getView3D().getKernel().formatPiE(val,numberFormat);
//check if the label already exists
DrawLabel3D label = labels.get(strNum);
if (label!=null){
//sets the label visible
label.setIsVisible(true);
label.update(strNum, 10,
getGeoElement().getObjectColor(),
origin.copyVector(),
axis.getNumbersXOffset()-4,axis.getNumbersYOffset()-6);
//TODO optimize this
}else{
//creates new label
label = new DrawLabel3D(getView3D());
label.update(strNum, 10,
getGeoElement().getObjectColor(),
origin.copyVector(),
axis.getNumbersXOffset()-4,axis.getNumbersYOffset()-6);
labels.put(strNum, label);
}
//TODO 4 and 6 depends to police size -> anchor
}
// update end of axis label
label.update(((GeoAxis3D) getGeoElement()).getAxisLabel(), 10,
getGeoElement().getObjectColor(),
((GeoCoordSys1D) getGeoElement()).getPoint(getDrawMax()),
axis.labelOffsetX-4,axis.labelOffsetY-6
);
}
|
diff --git a/src/net/sujee/hadoop/CheckDNS.java b/src/net/sujee/hadoop/CheckDNS.java
index 33db483..92e226b 100644
--- a/src/net/sujee/hadoop/CheckDNS.java
+++ b/src/net/sujee/hadoop/CheckDNS.java
@@ -1,117 +1,116 @@
package net.sujee.hadoop;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
/**
* check dns and reverse dns of hosts in a given file
*
* @author [email protected]
*
*/
public class CheckDNS {
public static void main(String[] args) throws Exception {
System.out.println("# self check...");
InetAddress inet = checkHost(null);
System.out.println("# end self check\n");
if (args.length > 0)
{
if (inet != null)
System.out.println("==== Running on : " + inet + " =====");
else
System.out.println("==== Running on : unknown host =====");
}
for (String s : args) {
String[] hosts = readLinesFromFile(s, true);
for (String host : hosts) {
checkHost(host);
System.out.println("");
}
}
}
public static InetAddress checkHost(String host) {
if (host != null)
System.out.println("-- host : " + host);
- else
- System.out.println("-- host : localhost (myself)");
InetAddress inet = null;
try {
if (host != null)
inet = InetAddress.getByName(host);
else
{
inet = InetAddress.getLocalHost();
host = inet.getHostName();
+ System.out.println("-- host : " + host);
}
String ip = inet.getHostAddress();
System.out.println(" host lookup : success (" + ip + ")");
} catch (UnknownHostException e) {
System.out.println(" host lookup : *** failed ***");
e.printStackTrace();
}
// reverse
if (inet != null) {
try {
InetAddress revHost = InetAddress.getByAddress(inet
.getAddress());
String revHostName = revHost.getHostName();
if (host.equals(revHostName))
System.out.println(" reverse lookup : success ("
+ revHostName + ")");
else
System.out.println(" reverse lookup : ***failed*** ("
+ revHostName + " != " + host + " (expected) )");
} catch (UnknownHostException e) {
System.out.println(" reverse lookup : ***failed***");
}
try {
if (inet.isReachable(10))
System.out.println(" is reachable : yes");
else
System.out.println(" is reachable : *** failed ***");
} catch (IOException e) {
System.out.println(" is reachable : *** failed ***");
e.printStackTrace();
}
}
return inet;
}
public static String[] readLinesFromFile(String fileName,
boolean skipCommentsAndBlanks) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
if (skipCommentsAndBlanks) {
line = line.trim();
if (line.length() == 0)
continue;
if (line.startsWith("#"))
continue;
}
lines.add(line);
}
String[] arrLines = new String[lines.size()];
lines.toArray(arrLines);
return arrLines;
}
}
| false | true | public static InetAddress checkHost(String host) {
if (host != null)
System.out.println("-- host : " + host);
else
System.out.println("-- host : localhost (myself)");
InetAddress inet = null;
try {
if (host != null)
inet = InetAddress.getByName(host);
else
{
inet = InetAddress.getLocalHost();
host = inet.getHostName();
}
String ip = inet.getHostAddress();
System.out.println(" host lookup : success (" + ip + ")");
} catch (UnknownHostException e) {
System.out.println(" host lookup : *** failed ***");
e.printStackTrace();
}
// reverse
if (inet != null) {
try {
InetAddress revHost = InetAddress.getByAddress(inet
.getAddress());
String revHostName = revHost.getHostName();
if (host.equals(revHostName))
System.out.println(" reverse lookup : success ("
+ revHostName + ")");
else
System.out.println(" reverse lookup : ***failed*** ("
+ revHostName + " != " + host + " (expected) )");
} catch (UnknownHostException e) {
System.out.println(" reverse lookup : ***failed***");
}
try {
if (inet.isReachable(10))
System.out.println(" is reachable : yes");
else
System.out.println(" is reachable : *** failed ***");
} catch (IOException e) {
System.out.println(" is reachable : *** failed ***");
e.printStackTrace();
}
}
return inet;
}
| public static InetAddress checkHost(String host) {
if (host != null)
System.out.println("-- host : " + host);
InetAddress inet = null;
try {
if (host != null)
inet = InetAddress.getByName(host);
else
{
inet = InetAddress.getLocalHost();
host = inet.getHostName();
System.out.println("-- host : " + host);
}
String ip = inet.getHostAddress();
System.out.println(" host lookup : success (" + ip + ")");
} catch (UnknownHostException e) {
System.out.println(" host lookup : *** failed ***");
e.printStackTrace();
}
// reverse
if (inet != null) {
try {
InetAddress revHost = InetAddress.getByAddress(inet
.getAddress());
String revHostName = revHost.getHostName();
if (host.equals(revHostName))
System.out.println(" reverse lookup : success ("
+ revHostName + ")");
else
System.out.println(" reverse lookup : ***failed*** ("
+ revHostName + " != " + host + " (expected) )");
} catch (UnknownHostException e) {
System.out.println(" reverse lookup : ***failed***");
}
try {
if (inet.isReachable(10))
System.out.println(" is reachable : yes");
else
System.out.println(" is reachable : *** failed ***");
} catch (IOException e) {
System.out.println(" is reachable : *** failed ***");
e.printStackTrace();
}
}
return inet;
}
|
diff --git a/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/CellSetFormatter.java b/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/CellSetFormatter.java
index ca6f26a4..5ddc048c 100644
--- a/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/CellSetFormatter.java
+++ b/saiku-core/saiku-service/src/main/java/org/saiku/olap/util/formatter/CellSetFormatter.java
@@ -1,497 +1,506 @@
/*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.saiku.olap.util.formatter;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.CellSetAxis;
import org.olap4j.Position;
import org.olap4j.impl.CoordinateIterator;
import org.olap4j.impl.Olap4jUtil;
import org.olap4j.metadata.Dimension;
import org.olap4j.metadata.Level;
import org.olap4j.metadata.Member;
import org.olap4j.metadata.Property;
import org.saiku.olap.dto.resultset.DataCell;
import org.saiku.olap.dto.resultset.Matrix;
import org.saiku.olap.dto.resultset.MemberCell;
import org.saiku.olap.util.SaikuProperties;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
public class CellSetFormatter implements ICellSetFormatter {
/**
* Description of an axis.
*/
private static class AxisInfo {
final List<AxisOrdinalInfo> ordinalInfos;
/**
* Creates an AxisInfo.
*
* @param ordinalCount
* Number of hierarchies on this axis
*/
AxisInfo(final int ordinalCount) {
ordinalInfos = new ArrayList<AxisOrdinalInfo>(ordinalCount);
for (int i = 0; i < ordinalCount; i++) {
ordinalInfos.add(new AxisOrdinalInfo());
}
}
/**
* Returns the number of matrix columns required by this axis. The sum of the width of the hierarchies on this
* axis.
*
* @return Width of axis
*/
public int getWidth() {
int width = 0;
for (final AxisOrdinalInfo info : ordinalInfos) {
width += info.getWidth();
}
return width;
}
}
/**
* Description of a particular hierarchy mapped to an axis.
*/
private static class AxisOrdinalInfo {
private List<Integer> depths = new ArrayList<Integer>();
private Map<Integer,Level> depthLevel = new HashMap<Integer,Level>();
public int getWidth() {
return depths.size();
}
public List<Integer> getDepths() {
return depths;
}
public Level getLevel(Integer depth) {
return depthLevel.get(depth);
}
public void addLevel(Integer depth, Level level) {
depthLevel.put(depth, level);
}
}
/**
* Returns an iterator over cells in a result.
*/
private static Iterable<Cell> cellIter(final int[] pageCoords, final CellSet cellSet) {
return new Iterable<Cell>() {
public Iterator<Cell> iterator() {
final int[] axisDimensions = new int[cellSet.getAxes().size() - pageCoords.length];
assert pageCoords.length <= axisDimensions.length;
for (int i = 0; i < axisDimensions.length; i++) {
final CellSetAxis axis = cellSet.getAxes().get(i);
axisDimensions[i] = axis.getPositions().size();
}
final CoordinateIterator coordIter = new CoordinateIterator(axisDimensions, true);
return new Iterator<Cell>() {
public boolean hasNext() {
return coordIter.hasNext();
}
public Cell next() {
final int[] ints = coordIter.next();
final AbstractList<Integer> intList = new AbstractList<Integer>() {
@Override
public Integer get(final int index) {
return index < ints.length ? ints[index] : pageCoords[index - ints.length];
}
@Override
public int size() {
return pageCoords.length + ints.length;
}
};
return cellSet.getCell(intList);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
private Matrix matrix;
public Matrix format(final CellSet cellSet) {
// Compute how many rows are required to display the columns axis.
final CellSetAxis columnsAxis;
if (cellSet.getAxes().size() > 0) {
columnsAxis = cellSet.getAxes().get(0);
} else {
columnsAxis = null;
}
final AxisInfo columnsAxisInfo = computeAxisInfo(columnsAxis);
// Compute how many columns are required to display the rows axis.
final CellSetAxis rowsAxis;
if (cellSet.getAxes().size() > 1) {
rowsAxis = cellSet.getAxes().get(1);
} else {
rowsAxis = null;
}
final AxisInfo rowsAxisInfo = computeAxisInfo(rowsAxis);
if (cellSet.getAxes().size() > 2) {
final int[] dimensions = new int[cellSet.getAxes().size() - 2];
for (int i = 2; i < cellSet.getAxes().size(); i++) {
final CellSetAxis cellSetAxis = cellSet.getAxes().get(i);
dimensions[i - 2] = cellSetAxis.getPositions().size();
}
for (final int[] pageCoords : CoordinateIterator.iterate(dimensions)) {
matrix = formatPage(cellSet, pageCoords, columnsAxis, columnsAxisInfo, rowsAxis, rowsAxisInfo);
}
} else {
matrix = formatPage(cellSet, new int[] {}, columnsAxis, columnsAxisInfo, rowsAxis, rowsAxisInfo);
}
return matrix;
}
/**
* Computes a description of an axis.
*
* @param axis
* Axis
* @return Description of axis
*/
private AxisInfo computeAxisInfo(final CellSetAxis axis) {
if (axis == null) {
return new AxisInfo(0);
}
final AxisInfo axisInfo = new AxisInfo(axis.getAxisMetaData().getHierarchies().size());
int p = -1;
for (final Position position : axis.getPositions()) {
++p;
int k = -1;
for (final Member member : position.getMembers()) {
++k;
final AxisOrdinalInfo axisOrdinalInfo = axisInfo.ordinalInfos.get(k);
if (!axisOrdinalInfo.getDepths().contains(member.getDepth())) {
axisOrdinalInfo.getDepths().add(member.getDepth());
axisOrdinalInfo.addLevel(member.getDepth(), member.getLevel());
Collections.sort(axisOrdinalInfo.depths);
}
}
}
return axisInfo;
}
/**
* Formats a two-dimensional page.
*
* @param cellSet
* Cell set
* @param pw
* Print writer
* @param pageCoords
* Coordinates of page [page, chapter, section, ...]
* @param columnsAxis
* Columns axis
* @param columnsAxisInfo
* Description of columns axis
* @param rowsAxis
* Rows axis
* @param rowsAxisInfo
* Description of rows axis
*/
private Matrix formatPage(final CellSet cellSet, final int[] pageCoords, final CellSetAxis columnsAxis,
final AxisInfo columnsAxisInfo, final CellSetAxis rowsAxis, final AxisInfo rowsAxisInfo) {
// Figure out the dimensions of the blank rectangle in the top left
// corner.
final int yOffset = columnsAxisInfo.getWidth();
final int xOffsset = rowsAxisInfo.getWidth();
// Populate a string matrix
final Matrix matrix = new Matrix(xOffsset + (columnsAxis == null ? 1 : columnsAxis.getPositions().size()),
yOffset + (rowsAxis == null ? 1 : rowsAxis.getPositions().size()));
// Populate corner
List<Level> levels = new ArrayList<Level>();
if (rowsAxis != null && rowsAxis.getPositions().size() > 0) {
Position p = rowsAxis.getPositions().get(0);
for (int m = 0; m < p.getMembers().size(); m++) {
AxisOrdinalInfo a = rowsAxisInfo.ordinalInfos.get(m);
for (Integer depth : a.getDepths()) {
levels.add(a.getLevel(depth));
}
}
for (int x = 0; x < xOffsset; x++) {
Level xLevel = levels.get(x);
String s = xLevel.getCaption();
for (int y = 0; y < yOffset; y++) {
final MemberCell memberInfo = new MemberCell(false, x > 0);
if (y == yOffset-1) {
memberInfo.setRawValue(s);
memberInfo.setFormattedValue(s);
memberInfo.setProperty("__headertype", "row_header_header");
memberInfo.setProperty("levelindex", "" + levels.indexOf(xLevel));
memberInfo.setHierarchy(xLevel.getHierarchy().getUniqueName());
memberInfo.setParentDimension(xLevel.getDimension().getName());
memberInfo.setLevel(xLevel.getUniqueName());
}
matrix.set(x, y, memberInfo);
}
}
}
// Populate matrix with cells representing axes
// noinspection SuspiciousNameCombination
populateAxis(matrix, columnsAxis, columnsAxisInfo, true, xOffsset);
populateAxis(matrix, rowsAxis, rowsAxisInfo, false, yOffset);
// Populate cell values
for (final Cell cell : cellIter(pageCoords, cellSet)) {
final List<Integer> coordList = cell.getCoordinateList();
int x = xOffsset;
if (coordList.size() > 0)
x += coordList.get(0);
int y = yOffset;
if (coordList.size() > 1)
y += coordList.get(1);
final DataCell cellInfo = new DataCell(true, false, coordList);
cellInfo.setCoordinates(cell.getCoordinateList());
if (cell.getValue() != null) {
try {
cellInfo.setRawNumber(cell.getDoubleValue());
} catch (Exception e1) {
}
}
String cellValue = cell.getFormattedValue(); // First try to get a
// formatted value
if (cellValue == null || cellValue.equals("null")) { //$NON-NLS-1$
cellValue =""; //$NON-NLS-1$
}
if ( cellValue.length() < 1) {
final Object value = cell.getValue();
if (value == null || value.equals("null")) //$NON-NLS-1$
cellValue = ""; //$NON-NLS-1$
else {
try {
// TODO this needs to become query / execution specific
DecimalFormat myFormatter = new DecimalFormat(SaikuProperties.formatDefautNumberFormat); //$NON-NLS-1$
DecimalFormatSymbols dfs = new DecimalFormatSymbols(SaikuProperties.locale);
myFormatter.setDecimalFormatSymbols(dfs);
String output = myFormatter.format(cell.getValue());
cellValue = output;
}
catch (Exception e) {
// TODO: handle exception
}
}
// the raw value
}
// Format string is relevant for Excel export
// xmla cells can throw an error on this
try {
String formatString = (String) cell.getPropertyValue(Property.StandardCellProperty.FORMAT_STRING);
if (formatString != null && !formatString.startsWith("|")) {
cellInfo.setFormatString(formatString);
} else {
formatString = formatString.substring(1, formatString.length());
cellInfo.setFormatString(formatString.substring(0, formatString.indexOf("|")));
}
} catch (Exception e) {
// we tried
}
Map<String, String> cellProperties = new HashMap<String, String>();
String val = Olap4jUtil.parseFormattedCellValue(cellValue, cellProperties);
if (!cellProperties.isEmpty()) {
cellInfo.setProperties(cellProperties);
}
cellInfo.setFormattedValue(val);
matrix.set(x, y, cellInfo);
}
return matrix;
}
/**
* Populates cells in the matrix corresponding to a particular axis.
*
* @param matrix
* Matrix to populate
* @param axis
* Axis
* @param axisInfo
* Description of axis
* @param isColumns
* True if columns, false if rows
* @param offset
* Ordinal of first cell to populate in matrix
*/
private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo,
final boolean isColumns, final int offset) {
if (axis == null)
return;
final Member[] prevMembers = new Member[axisInfo.getWidth()];
final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()];
final Member[] members = new Member[axisInfo.getWidth()];
for (int i = 0; i < axis.getPositions().size(); i++) {
final int x = offset + i;
final Position position = axis.getPositions().get(i);
int yOffset = 0;
final List<Member> memberList = position.getMembers();
final Map<Dimension,List<Integer>> lvls = new HashMap<Dimension, List<Integer>>();
for (int j = 0; j < memberList.size(); j++) {
Member member = memberList.get(j);
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j);
List<Integer> depths = ordinalInfo.depths;
Collections.sort(depths);
lvls.put(member.getDimension(), depths);
if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0))
break;
final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth());
members[y] = member;
yOffset += ordinalInfo.getWidth();
}
boolean expanded = false;
boolean same = true;
for (int y = 0; y < members.length; y++) {
final MemberCell memberInfo = new MemberCell();
final Member member = members[y];
expanded = false;
int index = memberList.indexOf(member);
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
if (depth_i > 0) {
expanded = true;
}
}
memberInfo.setExpanded(expanded);
same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member);
if (member != null) {
if (lvls != null && lvls.get(member.getDimension()) != null) {
memberInfo.setProperty("levelindex", "" + lvls.get(member.getDimension()).indexOf(member.getLevel().getDepth()));
}
if (x - 1 == offset)
memberInfo.setLastRow(true);
matrix.setOffset(offset);
memberInfo.setRawValue(member.getCaption());
memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value
memberInfo.setParentDimension(member.getDimension().getName());
memberInfo.setHierarchy(member.getHierarchy().getUniqueName());
memberInfo.setLevel(member.getLevel().getUniqueName());
memberInfo.setUniquename(member.getUniqueName());
// try {
// memberInfo.setChildMemberCount(member.getChildMemberCount());
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// NamedList<Property> values = member.getLevel().getProperties();
// for(int j=0; j<values.size();j++){
// String val;
// try {
// val = member.getPropertyFormattedValue(values.get(j));
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// memberInfo.setProperty(values.get(j).getCaption(), val);
// }
// if (y > 0) {
// for (int previ = y-1; previ >= 0;previ--) {
// if(prevMembers[previ] != null) {
// memberInfo.setRightOf(prevMemberInfo[previ]);
// memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName());
// previ = -1;
// }
// }
// }
//
//
// if (member.getParentMember() != null)
// memberInfo.setParentMember(member.getParentMember().getUniqueName());
} else {
memberInfo.setRawValue(null);
memberInfo.setFormattedValue(null);
memberInfo.setParentDimension(null);
}
if (isColumns) {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(same);
if (member != null)
memberInfo.setParentDimension(member.getDimension().getName());
matrix.set(x, y, memberInfo);
} else {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(false);
matrix.set(y, x, memberInfo);
}
int x_parent = isColumns ? x : y-1;
int y_parent = isColumns ? y-1 : x;
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
while (depth_i > 0) {
depth_i--;
int parentDepth = (ordinalInfo.getDepths().get(depth_i));
Member parent = member.getParentMember();
while (parent != null && parent.getDepth() > parentDepth) {
parent = parent.getParentMember();
}
final MemberCell pInfo = new MemberCell();
- pInfo.setRawValue(parent.getCaption());
- pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value
- pInfo.setParentDimension(parent.getDimension().getName());
- pInfo.setHierarchy(parent.getHierarchy().getUniqueName());
- pInfo.setLevel(parent.getLevel().getUniqueName());
- pInfo.setUniquename(parent.getUniqueName());
+ if (parent != null) {
+ pInfo.setRawValue(parent.getCaption());
+ pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value
+ pInfo.setParentDimension(parent.getDimension().getName());
+ pInfo.setHierarchy(parent.getHierarchy().getUniqueName());
+ pInfo.setUniquename(parent.getUniqueName());
+ pInfo.setLevel(parent.getLevel().getUniqueName());
+ } else {
+ pInfo.setRawValue("");
+ pInfo.setFormattedValue(""); // First try to get a formatted value
+ pInfo.setParentDimension(member.getDimension().getName());
+ pInfo.setHierarchy(member.getHierarchy().getUniqueName());
+ pInfo.setLevel(member.getLevel().getUniqueName());
+ pInfo.setUniquename("");
+ }
matrix.set(x_parent, y_parent, pInfo);
if (isColumns) {
y_parent--;
} else {
x_parent--;
}
}
}
prevMembers[y] = member;
prevMemberInfo[y] = memberInfo;
members[y] = null;
}
}
}
}
| true | true | private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo,
final boolean isColumns, final int offset) {
if (axis == null)
return;
final Member[] prevMembers = new Member[axisInfo.getWidth()];
final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()];
final Member[] members = new Member[axisInfo.getWidth()];
for (int i = 0; i < axis.getPositions().size(); i++) {
final int x = offset + i;
final Position position = axis.getPositions().get(i);
int yOffset = 0;
final List<Member> memberList = position.getMembers();
final Map<Dimension,List<Integer>> lvls = new HashMap<Dimension, List<Integer>>();
for (int j = 0; j < memberList.size(); j++) {
Member member = memberList.get(j);
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j);
List<Integer> depths = ordinalInfo.depths;
Collections.sort(depths);
lvls.put(member.getDimension(), depths);
if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0))
break;
final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth());
members[y] = member;
yOffset += ordinalInfo.getWidth();
}
boolean expanded = false;
boolean same = true;
for (int y = 0; y < members.length; y++) {
final MemberCell memberInfo = new MemberCell();
final Member member = members[y];
expanded = false;
int index = memberList.indexOf(member);
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
if (depth_i > 0) {
expanded = true;
}
}
memberInfo.setExpanded(expanded);
same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member);
if (member != null) {
if (lvls != null && lvls.get(member.getDimension()) != null) {
memberInfo.setProperty("levelindex", "" + lvls.get(member.getDimension()).indexOf(member.getLevel().getDepth()));
}
if (x - 1 == offset)
memberInfo.setLastRow(true);
matrix.setOffset(offset);
memberInfo.setRawValue(member.getCaption());
memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value
memberInfo.setParentDimension(member.getDimension().getName());
memberInfo.setHierarchy(member.getHierarchy().getUniqueName());
memberInfo.setLevel(member.getLevel().getUniqueName());
memberInfo.setUniquename(member.getUniqueName());
// try {
// memberInfo.setChildMemberCount(member.getChildMemberCount());
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// NamedList<Property> values = member.getLevel().getProperties();
// for(int j=0; j<values.size();j++){
// String val;
// try {
// val = member.getPropertyFormattedValue(values.get(j));
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// memberInfo.setProperty(values.get(j).getCaption(), val);
// }
// if (y > 0) {
// for (int previ = y-1; previ >= 0;previ--) {
// if(prevMembers[previ] != null) {
// memberInfo.setRightOf(prevMemberInfo[previ]);
// memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName());
// previ = -1;
// }
// }
// }
//
//
// if (member.getParentMember() != null)
// memberInfo.setParentMember(member.getParentMember().getUniqueName());
} else {
memberInfo.setRawValue(null);
memberInfo.setFormattedValue(null);
memberInfo.setParentDimension(null);
}
if (isColumns) {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(same);
if (member != null)
memberInfo.setParentDimension(member.getDimension().getName());
matrix.set(x, y, memberInfo);
} else {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(false);
matrix.set(y, x, memberInfo);
}
int x_parent = isColumns ? x : y-1;
int y_parent = isColumns ? y-1 : x;
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
while (depth_i > 0) {
depth_i--;
int parentDepth = (ordinalInfo.getDepths().get(depth_i));
Member parent = member.getParentMember();
while (parent != null && parent.getDepth() > parentDepth) {
parent = parent.getParentMember();
}
final MemberCell pInfo = new MemberCell();
pInfo.setRawValue(parent.getCaption());
pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value
pInfo.setParentDimension(parent.getDimension().getName());
pInfo.setHierarchy(parent.getHierarchy().getUniqueName());
pInfo.setLevel(parent.getLevel().getUniqueName());
pInfo.setUniquename(parent.getUniqueName());
matrix.set(x_parent, y_parent, pInfo);
if (isColumns) {
y_parent--;
} else {
x_parent--;
}
}
}
prevMembers[y] = member;
prevMemberInfo[y] = memberInfo;
members[y] = null;
}
}
}
| private void populateAxis(final Matrix matrix, final CellSetAxis axis, final AxisInfo axisInfo,
final boolean isColumns, final int offset) {
if (axis == null)
return;
final Member[] prevMembers = new Member[axisInfo.getWidth()];
final MemberCell[] prevMemberInfo = new MemberCell[axisInfo.getWidth()];
final Member[] members = new Member[axisInfo.getWidth()];
for (int i = 0; i < axis.getPositions().size(); i++) {
final int x = offset + i;
final Position position = axis.getPositions().get(i);
int yOffset = 0;
final List<Member> memberList = position.getMembers();
final Map<Dimension,List<Integer>> lvls = new HashMap<Dimension, List<Integer>>();
for (int j = 0; j < memberList.size(); j++) {
Member member = memberList.get(j);
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(j);
List<Integer> depths = ordinalInfo.depths;
Collections.sort(depths);
lvls.put(member.getDimension(), depths);
if (ordinalInfo.getDepths().size() > 0 && member.getDepth() < ordinalInfo.getDepths().get(0))
break;
final int y = yOffset + ordinalInfo.depths.indexOf(member.getDepth());
members[y] = member;
yOffset += ordinalInfo.getWidth();
}
boolean expanded = false;
boolean same = true;
for (int y = 0; y < members.length; y++) {
final MemberCell memberInfo = new MemberCell();
final Member member = members[y];
expanded = false;
int index = memberList.indexOf(member);
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
if (depth_i > 0) {
expanded = true;
}
}
memberInfo.setExpanded(expanded);
same = same && i > 0 && Olap4jUtil.equal(prevMembers[y], member);
if (member != null) {
if (lvls != null && lvls.get(member.getDimension()) != null) {
memberInfo.setProperty("levelindex", "" + lvls.get(member.getDimension()).indexOf(member.getLevel().getDepth()));
}
if (x - 1 == offset)
memberInfo.setLastRow(true);
matrix.setOffset(offset);
memberInfo.setRawValue(member.getCaption());
memberInfo.setFormattedValue(member.getCaption()); // First try to get a formatted value
memberInfo.setParentDimension(member.getDimension().getName());
memberInfo.setHierarchy(member.getHierarchy().getUniqueName());
memberInfo.setLevel(member.getLevel().getUniqueName());
memberInfo.setUniquename(member.getUniqueName());
// try {
// memberInfo.setChildMemberCount(member.getChildMemberCount());
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// NamedList<Property> values = member.getLevel().getProperties();
// for(int j=0; j<values.size();j++){
// String val;
// try {
// val = member.getPropertyFormattedValue(values.get(j));
// } catch (OlapException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// memberInfo.setProperty(values.get(j).getCaption(), val);
// }
// if (y > 0) {
// for (int previ = y-1; previ >= 0;previ--) {
// if(prevMembers[previ] != null) {
// memberInfo.setRightOf(prevMemberInfo[previ]);
// memberInfo.setRightOfDimension(prevMembers[previ].getDimension().getName());
// previ = -1;
// }
// }
// }
//
//
// if (member.getParentMember() != null)
// memberInfo.setParentMember(member.getParentMember().getUniqueName());
} else {
memberInfo.setRawValue(null);
memberInfo.setFormattedValue(null);
memberInfo.setParentDimension(null);
}
if (isColumns) {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(same);
if (member != null)
memberInfo.setParentDimension(member.getDimension().getName());
matrix.set(x, y, memberInfo);
} else {
memberInfo.setRight(false);
memberInfo.setSameAsPrev(false);
matrix.set(y, x, memberInfo);
}
int x_parent = isColumns ? x : y-1;
int y_parent = isColumns ? y-1 : x;
if (index >= 0) {
final AxisOrdinalInfo ordinalInfo = axisInfo.ordinalInfos.get(index);
int depth_i = ordinalInfo.getDepths().indexOf(member.getDepth());
while (depth_i > 0) {
depth_i--;
int parentDepth = (ordinalInfo.getDepths().get(depth_i));
Member parent = member.getParentMember();
while (parent != null && parent.getDepth() > parentDepth) {
parent = parent.getParentMember();
}
final MemberCell pInfo = new MemberCell();
if (parent != null) {
pInfo.setRawValue(parent.getCaption());
pInfo.setFormattedValue(parent.getCaption()); // First try to get a formatted value
pInfo.setParentDimension(parent.getDimension().getName());
pInfo.setHierarchy(parent.getHierarchy().getUniqueName());
pInfo.setUniquename(parent.getUniqueName());
pInfo.setLevel(parent.getLevel().getUniqueName());
} else {
pInfo.setRawValue("");
pInfo.setFormattedValue(""); // First try to get a formatted value
pInfo.setParentDimension(member.getDimension().getName());
pInfo.setHierarchy(member.getHierarchy().getUniqueName());
pInfo.setLevel(member.getLevel().getUniqueName());
pInfo.setUniquename("");
}
matrix.set(x_parent, y_parent, pInfo);
if (isColumns) {
y_parent--;
} else {
x_parent--;
}
}
}
prevMembers[y] = member;
prevMemberInfo[y] = memberInfo;
members[y] = null;
}
}
}
|
diff --git a/src/main/java/com/mojang/minecraft/gui/HUDScreen.java b/src/main/java/com/mojang/minecraft/gui/HUDScreen.java
index fa515e7..143a394 100644
--- a/src/main/java/com/mojang/minecraft/gui/HUDScreen.java
+++ b/src/main/java/com/mojang/minecraft/gui/HUDScreen.java
@@ -1,351 +1,351 @@
package com.mojang.minecraft.gui;
import com.mojang.minecraft.ChatLine;
import com.mojang.minecraft.Minecraft;
import com.mojang.minecraft.PlayerListNameData;
import com.mojang.minecraft.gamemode.SurvivalGameMode;
import com.mojang.minecraft.level.tile.Block;
import com.mojang.minecraft.player.Inventory;
import com.mojang.minecraft.render.ShapeRenderer;
import com.mojang.minecraft.render.TextureManager;
import com.mojang.util.MathHelper;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public final class HUDScreen extends Screen {
public List<ChatLine> chat = new ArrayList<ChatLine>();
private Random random = new Random();
private Minecraft mc;
public int width;
public int height;
public String hoveredPlayer = null;
public int ticks = 0;
public static String Compass = "";
public static String ServerName = "";
public static String UserDetail = "";
public List<ChatScreenData> chatsOnScreen = new ArrayList<ChatScreenData>();
public static void drawCenteredString(FontRenderer var0, String var1, int var2, int var3,
int var4) {
var0.render(var1, var2 - var0.getWidth(var1) / 2, var3, var4);
}
int Page = 0;
public HUDScreen(Minecraft var1, int var2, int var3) {
this.mc = var1;
this.width = var2 * 240 / var3;
this.height = var3 * 240 / var3;
}
public final void addChat(String var1) {
if (var1.contains("^detail.user=")) {
Compass = var1.replace("^detail.user=", "");
return;
}
this.chat.add(0, new ChatLine(var1));
while (this.chat.size() > 50) {
this.chat.remove(this.chat.size() - 1);
}
}
public int FindGroupChanges(int Page, List<PlayerListNameData> playerListNames) {
int groupChanges = 0;
String lastGroupName = "";
int rangeA = 28 * Page;
int rangeB = rangeA + 28;
rangeB = Math.min(rangeB, playerListNames.size());
List<PlayerListNameData> namesToPrint = new ArrayList<PlayerListNameData>();
for (int k = rangeA; k < rangeB; k++) {
namesToPrint.add(playerListNames.get(k));
}
for (int var11 = 0; var11 < namesToPrint.size(); ++var11) {
PlayerListNameData pi = (PlayerListNameData) namesToPrint.get(var11);
if (!lastGroupName.equals(pi.groupName)) {
lastGroupName = pi.groupName;
groupChanges++;
}
}
return groupChanges;
}
public final void render(float var1, boolean var2, int var3, int var4) {
FontRenderer var5 = this.mc.fontRenderer;
this.mc.renderer.enableGuiMode();
TextureManager var6 = this.mc.textureManager;
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png"));
ShapeRenderer var7 = ShapeRenderer.instance;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3042);
Inventory var8 = this.mc.player.inventory;
this.imgZ = -90.0F;
this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22);
this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22,
24, 22);
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png"));
this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16);
boolean var9 = (this.mc.player.invulnerableTime / 3 & 1) == 1;
if (this.mc.player.invulnerableTime < 10) {
var9 = false;
}
int var10 = this.mc.player.health;
int var11 = this.mc.player.lastHealth;
this.random.setSeed((long) (this.ticks * 312871));
int var12;
int i;
int var15;
int var26;
if (this.mc.gamemode.isSurvival()) {
for (var12 = 0; var12 < 10; ++var12) {
byte var13 = 0;
if (var9) {
var13 = 1;
}
i = this.width / 2 - 91 + (var12 << 3);
var15 = this.height - 32;
if (var10 <= 4) {
var15 += this.random.nextInt(2);
}
this.drawImage(i, var15, 16 + var13 * 9, 0, 9, 9);
if (var9) {
if ((var12 << 1) + 1 < var11) {
this.drawImage(i, var15, 70, 0, 9, 9);
}
if ((var12 << 1) + 1 == var11) {
this.drawImage(i, var15, 79, 0, 9, 9);
}
}
if ((var12 << 1) + 1 < var10) {
this.drawImage(i, var15, 52, 0, 9, 9);
}
if ((var12 << 1) + 1 == var10) {
this.drawImage(i, var15, 61, 0, 9, 9);
}
}
if (this.mc.player.isUnderWater()) {
var12 = (int) Math.ceil((double) (this.mc.player.airSupply - 2) * 10.0D / 300.0D);
var26 = (int) Math.ceil((double) this.mc.player.airSupply * 10.0D / 300.0D) - var12;
for (i = 0; i < var12 + var26; ++i) {
if (i < var12) {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 16,
18, 9, 9);
} else {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 25,
18, 9, 9);
}
}
}
}
GL11.glDisable(3042);
String var23;
for (var12 = 0; var12 < var8.slots.length; ++var12) {
var26 = this.width / 2 - 90 + var12 * 20;
i = this.height - 16;
if ((var15 = var8.slots[var12]) > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float) var26, (float) i, -50.0F);
if (var8.popTime[var12] > 0) {
float var18;
float var21 = -MathHelper
.sin((var18 = ((float) var8.popTime[var12] - var1) / 5.0F) * var18
* 3.1415927F) * 8.0F;
float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F;
float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F;
GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F);
GL11.glScalef(var19, var16, 1.0F);
GL11.glTranslatef(-10.0F, -10.0F, 0.0F);
}
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 0.0F);
GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-1.5F, 0.5F, 0.5F);
GL11.glScalef(-1.0F, -1.0F, -1.0F);
int var20 = var6.load("/terrain.png");
GL11.glBindTexture(3553, var20);
var7.begin();
Block.blocks[var15].renderFullbright(var7);
var7.end();
GL11.glPopMatrix();
if (var8.count[var12] > 1) {
var23 = "" + var8.count[var12];
var5.render(var23, var26 + 19 - var5.getWidth(var23), i + 6, 16777215);
}
}
}
//if (Minecraft.isSinglePlayer)
//var5.render("Development Build", 2, 32, 16777215);
if (this.mc.settings.showDebug) {
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
var5.render("ClassiCube", 2, 2, 16777215); // lol fuck that.
var5.render(this.mc.debug, 2, 12, 16777215);
var5.render("Position: (" + (int) this.mc.player.x + ", " + (int) this.mc.player.y
+ ", " + (int) this.mc.player.z + ")", 2, 22, 16777215);
GL11.glPopMatrix();
var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215);
var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215);
var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215);
}
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& !(this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON.", 2, 32, 16777215);
else if (!(this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("NoClip: ON.", 2, 32, 16777215);
else if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON. NoClip: ON", 2, 32, 16777215);
GL11.glPopMatrix();
if (this.mc.gamemode instanceof SurvivalGameMode) {
String var24 = "Score: &e" + this.mc.player.getScore();
var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215);
var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33,
16777215);
}
byte var25 = 10;
boolean var27 = false;
if (this.mc.currentScreen instanceof ChatInputScreenExtension) {
var25 = 20;
var27 = true;
}
this.chatsOnScreen.clear();
for (i = 0; i < this.chat.size() && i < var25; ++i) {
if (((ChatLine) this.chat.get(i)).time < 200 || var27) {
var5.render(((ChatLine) this.chat.get(i)).message, 2, this.height - 8 - i * 9 - 20,
16777215);
this.chatsOnScreen.add(new ChatScreenData(1, 8, 2, this.height - 8 - i * 9 - 20,
this.chat.get(i).message, var5));
}
}
i = this.width / 2;
var15 = this.height / 2;
this.hoveredPlayer = null;
if (Keyboard.isCreated()) {
if (Keyboard.isKeyDown(15) && this.mc.networkManager != null
&& this.mc.networkManager.isConnected()) {
for (int l = 2; l < 11; l++)
if (Keyboard.isKeyDown(l)) {
Page = l - 2;
}
List<String> playersOnWorld = this.mc.networkManager.getPlayers();
GL11.glEnable(3042);
GL11.glDisable(3553);
GL11.glBlendFunc(770, 771);
GL11.glBegin(7);
GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F);
GL11.glVertex2f((float) (i + 132), (float) (var15 - 72 - 12));
GL11.glVertex2f((float) (i - 132), (float) (var15 - 72 - 12));
GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F);
GL11.glVertex2f((float) (i - 132), (float) (var15 + 72));
GL11.glVertex2f((float) (i + 132), (float) (var15 + 72));
GL11.glEnd();
GL11.glDisable(3042);
GL11.glEnable(3553);
boolean drawDefault = false;
List<PlayerListNameData> playerListNames = this.mc.playerListNameData;
if (playerListNames.isEmpty()) {
drawDefault = true;
}
int maxStringsPerColumn = 14;
int maxStringsPerScreen = 28;
var23 = !drawDefault ? "Players online: (Page " + (Page + 1) + ")" : "Players online:";
var5.render(var23, i - var5.getWidth(var23) / 2, var15 - 64 - 12, 25855);
if (drawDefault) {
for (var11 = 0; var11 < playersOnWorld.size(); ++var11) {
int var28 = i + var11 % 2 * 120 - 120;
int var17 = var15 - 64 + (var11 / 2 << 3);
if (var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120
&& var4 < var17 + 8) {
this.hoveredPlayer = (String) playersOnWorld.get(var11);
var5.renderNoShadow((String) playersOnWorld.get(var11), var28 + 2,
var17, 16777215);
} else {
var5.renderNoShadow((String) playersOnWorld.get(var11), var28, var17,
15658734);
}
}
} else { //draw the new screen
String lastGroupName = "";
int x = i + 8;
int y = var15 - 73;
int groupChanges = 0;
boolean hasStartedNewColumn = false;
List<PlayerListNameData> namesToPrint = new ArrayList<PlayerListNameData>();
for (int m = 0; m < Page; m++) {
groupChanges += FindGroupChanges(m, playerListNames);
}
int rangeA = (maxStringsPerScreen * Page) - groupChanges;
int rangeB = rangeA + (maxStringsPerScreen)
- FindGroupChanges(Page, playerListNames);
rangeB = Math.min(rangeB, playerListNames.size());
for (int k = rangeA; k < rangeB; k++) {
namesToPrint.add(playerListNames.get(k));
}
int groupsOnThisPage = 0;
for (var11 = 0; var11 < namesToPrint.size(); ++var11) {
if (var11 < maxStringsPerColumn - groupsOnThisPage) {
x = (i - 128) + 8;
} else {
if ((var11 >= maxStringsPerColumn - groupsOnThisPage)
&& !hasStartedNewColumn) {
y = var15 - 73;
hasStartedNewColumn = true;
}
x = i + 8;
}
y += 9;
PlayerListNameData pi = namesToPrint.get(var11);
if (!lastGroupName.equals(pi.groupName)) {
lastGroupName = pi.groupName;
var5.render(lastGroupName, x + 2, y, 51455);
groupsOnThisPage++;
y += 9;
}
String playerName = FontRenderer.stripColor(pi.playerName);
- String listName = FontRenderer.stripColor(pi.listName);
+ String listName = (pi.listName);
if (var2 && var3 >= x && var4 >= y && var3 < x + 120 && var4 < y + 8) {
// if your mouse is hovered over this name
this.hoveredPlayer = playerName;
var5.renderNoShadow(listName, x + 8, y, 16777215);
} else { // else render a normal name
var5.renderNoShadow(listName, x + 6, y, 15658734);
}
}
}
}
}
}
}
| true | true | public final void render(float var1, boolean var2, int var3, int var4) {
FontRenderer var5 = this.mc.fontRenderer;
this.mc.renderer.enableGuiMode();
TextureManager var6 = this.mc.textureManager;
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png"));
ShapeRenderer var7 = ShapeRenderer.instance;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3042);
Inventory var8 = this.mc.player.inventory;
this.imgZ = -90.0F;
this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22);
this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22,
24, 22);
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png"));
this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16);
boolean var9 = (this.mc.player.invulnerableTime / 3 & 1) == 1;
if (this.mc.player.invulnerableTime < 10) {
var9 = false;
}
int var10 = this.mc.player.health;
int var11 = this.mc.player.lastHealth;
this.random.setSeed((long) (this.ticks * 312871));
int var12;
int i;
int var15;
int var26;
if (this.mc.gamemode.isSurvival()) {
for (var12 = 0; var12 < 10; ++var12) {
byte var13 = 0;
if (var9) {
var13 = 1;
}
i = this.width / 2 - 91 + (var12 << 3);
var15 = this.height - 32;
if (var10 <= 4) {
var15 += this.random.nextInt(2);
}
this.drawImage(i, var15, 16 + var13 * 9, 0, 9, 9);
if (var9) {
if ((var12 << 1) + 1 < var11) {
this.drawImage(i, var15, 70, 0, 9, 9);
}
if ((var12 << 1) + 1 == var11) {
this.drawImage(i, var15, 79, 0, 9, 9);
}
}
if ((var12 << 1) + 1 < var10) {
this.drawImage(i, var15, 52, 0, 9, 9);
}
if ((var12 << 1) + 1 == var10) {
this.drawImage(i, var15, 61, 0, 9, 9);
}
}
if (this.mc.player.isUnderWater()) {
var12 = (int) Math.ceil((double) (this.mc.player.airSupply - 2) * 10.0D / 300.0D);
var26 = (int) Math.ceil((double) this.mc.player.airSupply * 10.0D / 300.0D) - var12;
for (i = 0; i < var12 + var26; ++i) {
if (i < var12) {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 16,
18, 9, 9);
} else {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 25,
18, 9, 9);
}
}
}
}
GL11.glDisable(3042);
String var23;
for (var12 = 0; var12 < var8.slots.length; ++var12) {
var26 = this.width / 2 - 90 + var12 * 20;
i = this.height - 16;
if ((var15 = var8.slots[var12]) > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float) var26, (float) i, -50.0F);
if (var8.popTime[var12] > 0) {
float var18;
float var21 = -MathHelper
.sin((var18 = ((float) var8.popTime[var12] - var1) / 5.0F) * var18
* 3.1415927F) * 8.0F;
float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F;
float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F;
GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F);
GL11.glScalef(var19, var16, 1.0F);
GL11.glTranslatef(-10.0F, -10.0F, 0.0F);
}
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 0.0F);
GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-1.5F, 0.5F, 0.5F);
GL11.glScalef(-1.0F, -1.0F, -1.0F);
int var20 = var6.load("/terrain.png");
GL11.glBindTexture(3553, var20);
var7.begin();
Block.blocks[var15].renderFullbright(var7);
var7.end();
GL11.glPopMatrix();
if (var8.count[var12] > 1) {
var23 = "" + var8.count[var12];
var5.render(var23, var26 + 19 - var5.getWidth(var23), i + 6, 16777215);
}
}
}
//if (Minecraft.isSinglePlayer)
//var5.render("Development Build", 2, 32, 16777215);
if (this.mc.settings.showDebug) {
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
var5.render("ClassiCube", 2, 2, 16777215); // lol fuck that.
var5.render(this.mc.debug, 2, 12, 16777215);
var5.render("Position: (" + (int) this.mc.player.x + ", " + (int) this.mc.player.y
+ ", " + (int) this.mc.player.z + ")", 2, 22, 16777215);
GL11.glPopMatrix();
var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215);
var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215);
var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215);
}
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& !(this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON.", 2, 32, 16777215);
else if (!(this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("NoClip: ON.", 2, 32, 16777215);
else if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON. NoClip: ON", 2, 32, 16777215);
GL11.glPopMatrix();
if (this.mc.gamemode instanceof SurvivalGameMode) {
String var24 = "Score: &e" + this.mc.player.getScore();
var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215);
var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33,
16777215);
}
byte var25 = 10;
boolean var27 = false;
if (this.mc.currentScreen instanceof ChatInputScreenExtension) {
var25 = 20;
var27 = true;
}
this.chatsOnScreen.clear();
for (i = 0; i < this.chat.size() && i < var25; ++i) {
if (((ChatLine) this.chat.get(i)).time < 200 || var27) {
var5.render(((ChatLine) this.chat.get(i)).message, 2, this.height - 8 - i * 9 - 20,
16777215);
this.chatsOnScreen.add(new ChatScreenData(1, 8, 2, this.height - 8 - i * 9 - 20,
this.chat.get(i).message, var5));
}
}
i = this.width / 2;
var15 = this.height / 2;
this.hoveredPlayer = null;
if (Keyboard.isCreated()) {
if (Keyboard.isKeyDown(15) && this.mc.networkManager != null
&& this.mc.networkManager.isConnected()) {
for (int l = 2; l < 11; l++)
if (Keyboard.isKeyDown(l)) {
Page = l - 2;
}
List<String> playersOnWorld = this.mc.networkManager.getPlayers();
GL11.glEnable(3042);
GL11.glDisable(3553);
GL11.glBlendFunc(770, 771);
GL11.glBegin(7);
GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F);
GL11.glVertex2f((float) (i + 132), (float) (var15 - 72 - 12));
GL11.glVertex2f((float) (i - 132), (float) (var15 - 72 - 12));
GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F);
GL11.glVertex2f((float) (i - 132), (float) (var15 + 72));
GL11.glVertex2f((float) (i + 132), (float) (var15 + 72));
GL11.glEnd();
GL11.glDisable(3042);
GL11.glEnable(3553);
boolean drawDefault = false;
List<PlayerListNameData> playerListNames = this.mc.playerListNameData;
if (playerListNames.isEmpty()) {
drawDefault = true;
}
int maxStringsPerColumn = 14;
int maxStringsPerScreen = 28;
var23 = !drawDefault ? "Players online: (Page " + (Page + 1) + ")" : "Players online:";
var5.render(var23, i - var5.getWidth(var23) / 2, var15 - 64 - 12, 25855);
if (drawDefault) {
for (var11 = 0; var11 < playersOnWorld.size(); ++var11) {
int var28 = i + var11 % 2 * 120 - 120;
int var17 = var15 - 64 + (var11 / 2 << 3);
if (var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120
&& var4 < var17 + 8) {
this.hoveredPlayer = (String) playersOnWorld.get(var11);
var5.renderNoShadow((String) playersOnWorld.get(var11), var28 + 2,
var17, 16777215);
} else {
var5.renderNoShadow((String) playersOnWorld.get(var11), var28, var17,
15658734);
}
}
} else { //draw the new screen
String lastGroupName = "";
int x = i + 8;
int y = var15 - 73;
int groupChanges = 0;
boolean hasStartedNewColumn = false;
List<PlayerListNameData> namesToPrint = new ArrayList<PlayerListNameData>();
for (int m = 0; m < Page; m++) {
groupChanges += FindGroupChanges(m, playerListNames);
}
int rangeA = (maxStringsPerScreen * Page) - groupChanges;
int rangeB = rangeA + (maxStringsPerScreen)
- FindGroupChanges(Page, playerListNames);
rangeB = Math.min(rangeB, playerListNames.size());
for (int k = rangeA; k < rangeB; k++) {
namesToPrint.add(playerListNames.get(k));
}
int groupsOnThisPage = 0;
for (var11 = 0; var11 < namesToPrint.size(); ++var11) {
if (var11 < maxStringsPerColumn - groupsOnThisPage) {
x = (i - 128) + 8;
} else {
if ((var11 >= maxStringsPerColumn - groupsOnThisPage)
&& !hasStartedNewColumn) {
y = var15 - 73;
hasStartedNewColumn = true;
}
x = i + 8;
}
y += 9;
PlayerListNameData pi = namesToPrint.get(var11);
if (!lastGroupName.equals(pi.groupName)) {
lastGroupName = pi.groupName;
var5.render(lastGroupName, x + 2, y, 51455);
groupsOnThisPage++;
y += 9;
}
String playerName = FontRenderer.stripColor(pi.playerName);
String listName = FontRenderer.stripColor(pi.listName);
if (var2 && var3 >= x && var4 >= y && var3 < x + 120 && var4 < y + 8) {
// if your mouse is hovered over this name
this.hoveredPlayer = playerName;
var5.renderNoShadow(listName, x + 8, y, 16777215);
} else { // else render a normal name
var5.renderNoShadow(listName, x + 6, y, 15658734);
}
}
}
}
}
}
| public final void render(float var1, boolean var2, int var3, int var4) {
FontRenderer var5 = this.mc.fontRenderer;
this.mc.renderer.enableGuiMode();
TextureManager var6 = this.mc.textureManager;
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png"));
ShapeRenderer var7 = ShapeRenderer.instance;
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(3042);
Inventory var8 = this.mc.player.inventory;
this.imgZ = -90.0F;
this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22);
this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22,
24, 22);
GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png"));
this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16);
boolean var9 = (this.mc.player.invulnerableTime / 3 & 1) == 1;
if (this.mc.player.invulnerableTime < 10) {
var9 = false;
}
int var10 = this.mc.player.health;
int var11 = this.mc.player.lastHealth;
this.random.setSeed((long) (this.ticks * 312871));
int var12;
int i;
int var15;
int var26;
if (this.mc.gamemode.isSurvival()) {
for (var12 = 0; var12 < 10; ++var12) {
byte var13 = 0;
if (var9) {
var13 = 1;
}
i = this.width / 2 - 91 + (var12 << 3);
var15 = this.height - 32;
if (var10 <= 4) {
var15 += this.random.nextInt(2);
}
this.drawImage(i, var15, 16 + var13 * 9, 0, 9, 9);
if (var9) {
if ((var12 << 1) + 1 < var11) {
this.drawImage(i, var15, 70, 0, 9, 9);
}
if ((var12 << 1) + 1 == var11) {
this.drawImage(i, var15, 79, 0, 9, 9);
}
}
if ((var12 << 1) + 1 < var10) {
this.drawImage(i, var15, 52, 0, 9, 9);
}
if ((var12 << 1) + 1 == var10) {
this.drawImage(i, var15, 61, 0, 9, 9);
}
}
if (this.mc.player.isUnderWater()) {
var12 = (int) Math.ceil((double) (this.mc.player.airSupply - 2) * 10.0D / 300.0D);
var26 = (int) Math.ceil((double) this.mc.player.airSupply * 10.0D / 300.0D) - var12;
for (i = 0; i < var12 + var26; ++i) {
if (i < var12) {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 16,
18, 9, 9);
} else {
this.drawImage(this.width / 2 - 91 + (i << 3), this.height - 32 - 9, 25,
18, 9, 9);
}
}
}
}
GL11.glDisable(3042);
String var23;
for (var12 = 0; var12 < var8.slots.length; ++var12) {
var26 = this.width / 2 - 90 + var12 * 20;
i = this.height - 16;
if ((var15 = var8.slots[var12]) > 0) {
GL11.glPushMatrix();
GL11.glTranslatef((float) var26, (float) i, -50.0F);
if (var8.popTime[var12] > 0) {
float var18;
float var21 = -MathHelper
.sin((var18 = ((float) var8.popTime[var12] - var1) / 5.0F) * var18
* 3.1415927F) * 8.0F;
float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F;
float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F;
GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F);
GL11.glScalef(var19, var16, 1.0F);
GL11.glTranslatef(-10.0F, -10.0F, 0.0F);
}
GL11.glScalef(10.0F, 10.0F, 10.0F);
GL11.glTranslatef(1.0F, 0.5F, 0.0F);
GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-1.5F, 0.5F, 0.5F);
GL11.glScalef(-1.0F, -1.0F, -1.0F);
int var20 = var6.load("/terrain.png");
GL11.glBindTexture(3553, var20);
var7.begin();
Block.blocks[var15].renderFullbright(var7);
var7.end();
GL11.glPopMatrix();
if (var8.count[var12] > 1) {
var23 = "" + var8.count[var12];
var5.render(var23, var26 + 19 - var5.getWidth(var23), i + 6, 16777215);
}
}
}
//if (Minecraft.isSinglePlayer)
//var5.render("Development Build", 2, 32, 16777215);
if (this.mc.settings.showDebug) {
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
var5.render("ClassiCube", 2, 2, 16777215); // lol fuck that.
var5.render(this.mc.debug, 2, 12, 16777215);
var5.render("Position: (" + (int) this.mc.player.x + ", " + (int) this.mc.player.y
+ ", " + (int) this.mc.player.z + ")", 2, 22, 16777215);
GL11.glPopMatrix();
var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215);
var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215);
var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215);
}
GL11.glPushMatrix();
GL11.glScalef(0.7F, 0.7F, 1.0F);
if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& !(this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON.", 2, 32, 16777215);
else if (!(this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("NoClip: ON.", 2, 32, 16777215);
else if ((this.mc.player.flyingMode || this.mc.player.input.fly)
&& (this.mc.player.noPhysics || this.mc.player.input.noclip))
var5.render("Fly: ON. NoClip: ON", 2, 32, 16777215);
GL11.glPopMatrix();
if (this.mc.gamemode instanceof SurvivalGameMode) {
String var24 = "Score: &e" + this.mc.player.getScore();
var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215);
var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33,
16777215);
}
byte var25 = 10;
boolean var27 = false;
if (this.mc.currentScreen instanceof ChatInputScreenExtension) {
var25 = 20;
var27 = true;
}
this.chatsOnScreen.clear();
for (i = 0; i < this.chat.size() && i < var25; ++i) {
if (((ChatLine) this.chat.get(i)).time < 200 || var27) {
var5.render(((ChatLine) this.chat.get(i)).message, 2, this.height - 8 - i * 9 - 20,
16777215);
this.chatsOnScreen.add(new ChatScreenData(1, 8, 2, this.height - 8 - i * 9 - 20,
this.chat.get(i).message, var5));
}
}
i = this.width / 2;
var15 = this.height / 2;
this.hoveredPlayer = null;
if (Keyboard.isCreated()) {
if (Keyboard.isKeyDown(15) && this.mc.networkManager != null
&& this.mc.networkManager.isConnected()) {
for (int l = 2; l < 11; l++)
if (Keyboard.isKeyDown(l)) {
Page = l - 2;
}
List<String> playersOnWorld = this.mc.networkManager.getPlayers();
GL11.glEnable(3042);
GL11.glDisable(3553);
GL11.glBlendFunc(770, 771);
GL11.glBegin(7);
GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F);
GL11.glVertex2f((float) (i + 132), (float) (var15 - 72 - 12));
GL11.glVertex2f((float) (i - 132), (float) (var15 - 72 - 12));
GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F);
GL11.glVertex2f((float) (i - 132), (float) (var15 + 72));
GL11.glVertex2f((float) (i + 132), (float) (var15 + 72));
GL11.glEnd();
GL11.glDisable(3042);
GL11.glEnable(3553);
boolean drawDefault = false;
List<PlayerListNameData> playerListNames = this.mc.playerListNameData;
if (playerListNames.isEmpty()) {
drawDefault = true;
}
int maxStringsPerColumn = 14;
int maxStringsPerScreen = 28;
var23 = !drawDefault ? "Players online: (Page " + (Page + 1) + ")" : "Players online:";
var5.render(var23, i - var5.getWidth(var23) / 2, var15 - 64 - 12, 25855);
if (drawDefault) {
for (var11 = 0; var11 < playersOnWorld.size(); ++var11) {
int var28 = i + var11 % 2 * 120 - 120;
int var17 = var15 - 64 + (var11 / 2 << 3);
if (var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120
&& var4 < var17 + 8) {
this.hoveredPlayer = (String) playersOnWorld.get(var11);
var5.renderNoShadow((String) playersOnWorld.get(var11), var28 + 2,
var17, 16777215);
} else {
var5.renderNoShadow((String) playersOnWorld.get(var11), var28, var17,
15658734);
}
}
} else { //draw the new screen
String lastGroupName = "";
int x = i + 8;
int y = var15 - 73;
int groupChanges = 0;
boolean hasStartedNewColumn = false;
List<PlayerListNameData> namesToPrint = new ArrayList<PlayerListNameData>();
for (int m = 0; m < Page; m++) {
groupChanges += FindGroupChanges(m, playerListNames);
}
int rangeA = (maxStringsPerScreen * Page) - groupChanges;
int rangeB = rangeA + (maxStringsPerScreen)
- FindGroupChanges(Page, playerListNames);
rangeB = Math.min(rangeB, playerListNames.size());
for (int k = rangeA; k < rangeB; k++) {
namesToPrint.add(playerListNames.get(k));
}
int groupsOnThisPage = 0;
for (var11 = 0; var11 < namesToPrint.size(); ++var11) {
if (var11 < maxStringsPerColumn - groupsOnThisPage) {
x = (i - 128) + 8;
} else {
if ((var11 >= maxStringsPerColumn - groupsOnThisPage)
&& !hasStartedNewColumn) {
y = var15 - 73;
hasStartedNewColumn = true;
}
x = i + 8;
}
y += 9;
PlayerListNameData pi = namesToPrint.get(var11);
if (!lastGroupName.equals(pi.groupName)) {
lastGroupName = pi.groupName;
var5.render(lastGroupName, x + 2, y, 51455);
groupsOnThisPage++;
y += 9;
}
String playerName = FontRenderer.stripColor(pi.playerName);
String listName = (pi.listName);
if (var2 && var3 >= x && var4 >= y && var3 < x + 120 && var4 < y + 8) {
// if your mouse is hovered over this name
this.hoveredPlayer = playerName;
var5.renderNoShadow(listName, x + 8, y, 16777215);
} else { // else render a normal name
var5.renderNoShadow(listName, x + 6, y, 15658734);
}
}
}
}
}
}
|
diff --git a/dev/katari-core/src/main/java/com/globant/katari/core/web/BaseStaticContentServlet.java b/dev/katari-core/src/main/java/com/globant/katari/core/web/BaseStaticContentServlet.java
index 095c0203..e86723d2 100644
--- a/dev/katari-core/src/main/java/com/globant/katari/core/web/BaseStaticContentServlet.java
+++ b/dev/katari-core/src/main/java/com/globant/katari/core/web/BaseStaticContentServlet.java
@@ -1,423 +1,426 @@
/* vim: set ts=2 et sw=2 cindent fo=qroca: */
package com.globant.katari.core.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A base servlet used to serve static content (gif, png, css, etc) from the
* classpath.
*
* This class handles all the process related to sending the content to the
* client. The location of the content is delegated to the subclasses.
*
* Subclasses must implement findInputStream and getContentType.
*
* You must call this class init(ServletConfig) if you override it.
*
* This accepts the following configuration parameters:<br>
*
* requestCacheContent: whether to send the cache headers to the client with an
* expiration date in the future, or the headers that state that the content
* should not be cached (true / false). It is false by default.<br>
*
* debug: whether to enable debug mode or not. In debug mode, the servlet
* attempts to load the requested content directly from the file system. This
* makes it possible to edit the resources directly from disk and see the
* results inmediately without a redeploy. It is false by default.<br>
*
* All other initialization parameters are ignored, so subclasses can define
* adittional config parameters.
*/
public abstract class BaseStaticContentServlet extends HttpServlet {
/** The serialization version number.
*
* This number must change every time a new serialization incompatible change
* is introduced in the class.
*/
private static final long serialVersionUID = 1;
/** The buffer size used to transfer bytes to the client.
*/
private static final int BUFFER_SIZE = 4096;
/** The class logger.
*/
private static Logger log = LoggerFactory.getLogger(
BaseStaticContentServlet.class);
/** Provide a formatted date for setting heading information when caching
* static content.
*/
private final Calendar lastModified = Calendar.getInstance();
/** Whether to send the client the cache header asking to cache the content
* served by this servlet or not.
*/
private boolean requestCacheContent = false;
/** Whether debug mode is enabled.
*
* Initialized from the debug servlet parameter.
*/
private boolean debug = false;
/** Initializes the servlet.
*
* It sets the default packages for static resources.
*
* @param config The servlet configuration. It cannot be null.
*/
public void init(final ServletConfig config) throws ServletException {
log.trace("Entering init");
Validate.notNull(config, "The servlet config cannot be null.");
String applyCacheInfo = config.getInitParameter("requestCacheContent");
requestCacheContent = Boolean.valueOf(applyCacheInfo);
String debugValue = config.getInitParameter("debug");
debug = Boolean.valueOf(debugValue);
log.trace("Leaving init");
}
/** Serves a get request.
*
* @param request The request object.
*
* @param response The response object.
*
* @throws IOException in case of an io error.
*
* @throws ServletException in case of error.
*/
@Override
protected void doGet(final HttpServletRequest request, final
HttpServletResponse response) throws ServletException, IOException {
serveStaticContent(request, response);
}
/** Serves a post request.
*
* @param request The request object.
*
* @param response The response object.
*
* @throws IOException in case of an io error.
*
* @throws ServletException in case of error.
*/
@Override
protected void doPost(final HttpServletRequest request, final
HttpServletResponse response) throws ServletException, IOException {
serveStaticContent(request, response);
}
/** Serves some static content.
*
* @param request The request object.
*
* @param response The response object.
*
* @throws IOException in case of an io error.
*
* @throws ServletException in case of error.
*
* TODO See if it shuold use pathInfo instead of servletPath.
*/
private void serveStaticContent(final HttpServletRequest request, final
HttpServletResponse response) throws ServletException, IOException {
log.trace("Entering serveStaticContent");
String resourcePath = getServletPath(request);
findStaticResource(resourcePath, request, response);
log.trace("Leaving serveStaticContent");
}
/** Locate a static resource and copy directly to the response, setting the
* appropriate caching headers.
*
* A URL decoder is run on the resource path and it is configured to use the
* UTF-8 encoding because according to the World Wide Web Consortium
* Recommendation UTF-8 should be used and not doing so may introduce
* incompatibilites.
*
* @param theName The resource name
*
* @param request The request
*
* @param response The response
*
* @throws IOException If anything goes wrong
*/
private void findStaticResource(final String theName, final
HttpServletRequest request, final HttpServletResponse response) throws
IOException {
log.trace("Entering findStaticResource('{}', ...)", theName);
String name = URLDecoder.decode(theName, "UTF-8");
// Checks if the requested resource matches a recognized content type.
String contentType = getContentType(name);
if (contentType == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
- response.getWriter().write("<html><head><title>404</title></head>"
+ response.getWriter().write(
+ "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'"
+ + " 'http://www.w3.org/TR/html4/strict.dtd'>"
+ + "<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
// Looks for the resource.
InputStream is = findInputStream(name);
if (is == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.getWriter().write(
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'"
+ " 'http://www.w3.org/TR/html4/strict.dtd'> "
+ "<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
Calendar cal = Calendar.getInstance();
// check for if-modified-since, prior to any other headers
long requestedOn = 0;
try {
requestedOn = request.getDateHeader("If-Modified-Since");
} catch (Exception e) {
log.warn("Invalid If-Modified-Since header value: '"
+ request.getHeader("If-Modified-Since") + "', ignoring");
}
long lastModifiedMillis = lastModified.getTimeInMillis();
long now = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, 1);
long expires = cal.getTimeInMillis();
boolean notModified;
notModified = 0 < requestedOn && requestedOn <= lastModifiedMillis;
if (!debug && notModified) {
// not modified, content is not sent - only basic headers and status
// SC_NOT_MODIFIED
response.setDateHeader("Expires", expires);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
is.close();
log.trace("Leaving findStaticResource with SC_NOT_MODIFIED");
return;
}
// set the content-type header
response.setContentType(contentType);
if (!debug && requestCacheContent) {
// set heading information for caching static content
response.setDateHeader("Date", now);
response.setDateHeader("Expires", expires);
response.setDateHeader("Retry-After", expires);
response.setHeader("Cache-Control", "public");
response.setDateHeader("Last-Modified", lastModifiedMillis);
} else {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
}
try {
copy(is, response.getOutputStream());
} finally {
is.close();
}
log.trace("Leaving findStaticResource");
}
/**
* Determine the content type for the resource name.
*
* @param name The resource name. It cannot be null.
*
* @return The mime type, null if the resource name is not recognized.
*/
protected abstract String getContentType(final String name);
/**
* Copy bytes from the input stream to the output stream.
*
* @param input The input stream
* @param output The output stream
* @throws IOException If anytSrtringhing goes wrong
*/
private void copy(final InputStream input, final OutputStream output) throws
IOException {
final byte[] buffer = new byte[BUFFER_SIZE];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.flush();
}
/** Look for a static resource in the classpath.
*
* In debug mode, it looks for the resource in the file system, using
* debugPrefix as the base file name.
*
* @param name The resource name. It cannot be null.
*
* @return the inputstream of the resource, null if the resource could not be
* found.
*
* @throws IOException If there is a problem locating the resource.
*/
protected abstract InputStream findInputStream(final String name)
throws IOException;
/** Concatenates two path names.
*
* This is protected as an aid for subclasses.
*
* @param prefix The first component of the file name. It cannot be null.
*
* @param name The second component of the file name. It cannot be null.
*
* @return A file name of the form prefix/name with the correct number of /.
*/
protected String buildPath(final String prefix, final String name) {
Validate.notNull(prefix, "The file component prefix cannot be null.");
Validate.notNull(name, "The second file component cannot be null.");
if (prefix.endsWith("/") && name.startsWith("/")) {
return prefix + name.substring(1);
} else if (prefix.endsWith("/") || name.startsWith("/")) {
return prefix + name;
}
return prefix + "/" + name;
}
/** This is a convenience method to load a resource as a stream.
*
* The algorithm used to find the resource is given in getResource().
*
* @param resourceName The name of the resource to load. It cannot be null
* nor start with '/'.
*
* @return Returns an input stream representing the resource, null if not
* found.
*/
protected InputStream getResourceAsStream(final String resourceName) {
Validate.notNull(resourceName, "The resource name cannot be null.");
Validate.isTrue(!resourceName.startsWith("/"),
"The resource cannot start with /");
URL url = getResource(resourceName);
if (url == null) {
return null;
}
try {
return url.openStream();
} catch (IOException e) {
log.debug("Exception opening resource: " + resourceName, e);
return null;
}
}
/**
* Load a given resource.
* <p/>
* This method will try to load the resource using the following methods (in
* order):
*
* <ul>
*
* <li>From {@link Thread#getContextClassLoader()
* Thread.currentThread().getContextClassLoader()}
*
* <li>From the {@link Class#getClassLoader() getClass().getClassLoader() }
*
* </ul>
*
* @param resourceName The name of the resource to load
*
* @return Returns the url of the reesource, null if not found.
*/
protected URL getResource(final String resourceName) {
URL url = null;
// Try the context class loader.
ClassLoader contextClassLoader;
contextClassLoader = Thread.currentThread().getContextClassLoader();
if (null != contextClassLoader) {
url = contextClassLoader.getResource(resourceName);
}
// Try the current class class loader if the context class loader failed.
if (url == null) {
url = getClass().getClassLoader().getResource(resourceName);
}
return url;
}
/**
* Retrieves the current request servlet path.
* Deals with differences between servlet specs (2.2 vs 2.3+)
*
* @param request the request
* @return the servlet path
*/
private String getServletPath(final HttpServletRequest request) {
String servletPath = request.getServletPath();
if (null != servletPath && !"".equals(servletPath)) {
return servletPath;
}
String requestUri = request.getRequestURI();
int startIndex = request.getContextPath().length();
int endIndex = 0;
if (request.getPathInfo() == null) {
endIndex = requestUri.length();
} else {
endIndex = requestUri.lastIndexOf(request.getPathInfo());
}
if (startIndex > endIndex) { // this should not happen
endIndex = startIndex;
}
return requestUri.substring(startIndex, endIndex);
}
/** True if in debug mode.
*
* @return true in debug mode.
*/
public boolean isInDebugMode() {
return debug;
}
}
| true | true | private void findStaticResource(final String theName, final
HttpServletRequest request, final HttpServletResponse response) throws
IOException {
log.trace("Entering findStaticResource('{}', ...)", theName);
String name = URLDecoder.decode(theName, "UTF-8");
// Checks if the requested resource matches a recognized content type.
String contentType = getContentType(name);
if (contentType == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().write("<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
// Looks for the resource.
InputStream is = findInputStream(name);
if (is == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.getWriter().write(
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'"
+ " 'http://www.w3.org/TR/html4/strict.dtd'> "
+ "<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
Calendar cal = Calendar.getInstance();
// check for if-modified-since, prior to any other headers
long requestedOn = 0;
try {
requestedOn = request.getDateHeader("If-Modified-Since");
} catch (Exception e) {
log.warn("Invalid If-Modified-Since header value: '"
+ request.getHeader("If-Modified-Since") + "', ignoring");
}
long lastModifiedMillis = lastModified.getTimeInMillis();
long now = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, 1);
long expires = cal.getTimeInMillis();
boolean notModified;
notModified = 0 < requestedOn && requestedOn <= lastModifiedMillis;
if (!debug && notModified) {
// not modified, content is not sent - only basic headers and status
// SC_NOT_MODIFIED
response.setDateHeader("Expires", expires);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
is.close();
log.trace("Leaving findStaticResource with SC_NOT_MODIFIED");
return;
}
// set the content-type header
response.setContentType(contentType);
if (!debug && requestCacheContent) {
// set heading information for caching static content
response.setDateHeader("Date", now);
response.setDateHeader("Expires", expires);
response.setDateHeader("Retry-After", expires);
response.setHeader("Cache-Control", "public");
response.setDateHeader("Last-Modified", lastModifiedMillis);
} else {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
}
try {
copy(is, response.getOutputStream());
} finally {
is.close();
}
log.trace("Leaving findStaticResource");
}
| private void findStaticResource(final String theName, final
HttpServletRequest request, final HttpServletResponse response) throws
IOException {
log.trace("Entering findStaticResource('{}', ...)", theName);
String name = URLDecoder.decode(theName, "UTF-8");
// Checks if the requested resource matches a recognized content type.
String contentType = getContentType(name);
if (contentType == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().write(
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'"
+ " 'http://www.w3.org/TR/html4/strict.dtd'>"
+ "<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
// Looks for the resource.
InputStream is = findInputStream(name);
if (is == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.getWriter().write(
"<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN'"
+ " 'http://www.w3.org/TR/html4/strict.dtd'> "
+ "<html><head><title>404</title></head>"
+ "<body>Resource not found</body></html>");
log.trace("Leaving findStaticResource with SC_NOT_FOUND");
response.flushBuffer();
return;
}
Calendar cal = Calendar.getInstance();
// check for if-modified-since, prior to any other headers
long requestedOn = 0;
try {
requestedOn = request.getDateHeader("If-Modified-Since");
} catch (Exception e) {
log.warn("Invalid If-Modified-Since header value: '"
+ request.getHeader("If-Modified-Since") + "', ignoring");
}
long lastModifiedMillis = lastModified.getTimeInMillis();
long now = cal.getTimeInMillis();
cal.add(Calendar.DAY_OF_MONTH, 1);
long expires = cal.getTimeInMillis();
boolean notModified;
notModified = 0 < requestedOn && requestedOn <= lastModifiedMillis;
if (!debug && notModified) {
// not modified, content is not sent - only basic headers and status
// SC_NOT_MODIFIED
response.setDateHeader("Expires", expires);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
is.close();
log.trace("Leaving findStaticResource with SC_NOT_MODIFIED");
return;
}
// set the content-type header
response.setContentType(contentType);
if (!debug && requestCacheContent) {
// set heading information for caching static content
response.setDateHeader("Date", now);
response.setDateHeader("Expires", expires);
response.setDateHeader("Retry-After", expires);
response.setHeader("Cache-Control", "public");
response.setDateHeader("Last-Modified", lastModifiedMillis);
} else {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
}
try {
copy(is, response.getOutputStream());
} finally {
is.close();
}
log.trace("Leaving findStaticResource");
}
|
diff --git a/src/main/java/com/yanchuanli/games/pokr/server/ClientHandler.java b/src/main/java/com/yanchuanli/games/pokr/server/ClientHandler.java
index f0ed66d..d1a5d6d 100644
--- a/src/main/java/com/yanchuanli/games/pokr/server/ClientHandler.java
+++ b/src/main/java/com/yanchuanli/games/pokr/server/ClientHandler.java
@@ -1,89 +1,90 @@
package com.yanchuanli.games.pokr.server;
import com.yanchuanli.games.pokr.basic.Card;
import com.yanchuanli.games.pokr.util.Config;
import com.yanchuanli.games.pokr.util.Memory;
import com.yanchuanli.games.pokr.util.Util;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import java.util.List;
import java.util.Map;
/**
* Author: Yanchuan Li
* Date: 5/27/12
* Email: [email protected]
*/
public class ClientHandler extends IoHandlerAdapter {
private static Logger log = Logger.getLogger(ClientHandler.class);
public ClientHandler() {
}
@Override
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
Memory.sessionsOnClient.put(String.valueOf(session.getId()), session);
// log.info("sessionCreated ...");
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
List<Map<Integer, String>> list = Util.ioBufferToString(buffer);
for (Map<Integer, String> map : list) {
for (Integer key : map.keySet()) {
String info = map.get(key);
log.debug("[messageReceived] status code: [" + key + "] " + info);
switch (key) {
case Config.TYPE_ACTION_INGAME:
String[] infos = info.split(",");
String username = infos[1];
log.debug(username + ":" + infos[2]);
break;
case Config.TYPE_HOLE_INGAME:
infos = info.split(",");
username = infos[1];
String[] pokers = infos[2].split("_");
String debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug(username + ":" + debuginfo);
break;
case Config.TYPE_USER_INGAME:
break;
case Config.TYPE_CARD_INGAME:
infos = info.split(",");
pokers = infos[0].split("_");
debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug("ontable" + ":" + debuginfo);
+ break;
}
}
}
} else {
log.info("[messageReceived]illegal");
}
}
@Override
public void sessionClosed(IoSession session) throws Exception {
// log.info("sessionClosed");
super.sessionClosed(session);
Memory.sessionsOnClient.remove(String.valueOf(session.getId()));
}
}
| true | true | public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
List<Map<Integer, String>> list = Util.ioBufferToString(buffer);
for (Map<Integer, String> map : list) {
for (Integer key : map.keySet()) {
String info = map.get(key);
log.debug("[messageReceived] status code: [" + key + "] " + info);
switch (key) {
case Config.TYPE_ACTION_INGAME:
String[] infos = info.split(",");
String username = infos[1];
log.debug(username + ":" + infos[2]);
break;
case Config.TYPE_HOLE_INGAME:
infos = info.split(",");
username = infos[1];
String[] pokers = infos[2].split("_");
String debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug(username + ":" + debuginfo);
break;
case Config.TYPE_USER_INGAME:
break;
case Config.TYPE_CARD_INGAME:
infos = info.split(",");
pokers = infos[0].split("_");
debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug("ontable" + ":" + debuginfo);
}
}
}
} else {
log.info("[messageReceived]illegal");
}
}
| public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
if (message instanceof IoBuffer) {
IoBuffer buffer = (IoBuffer) message;
List<Map<Integer, String>> list = Util.ioBufferToString(buffer);
for (Map<Integer, String> map : list) {
for (Integer key : map.keySet()) {
String info = map.get(key);
log.debug("[messageReceived] status code: [" + key + "] " + info);
switch (key) {
case Config.TYPE_ACTION_INGAME:
String[] infos = info.split(",");
String username = infos[1];
log.debug(username + ":" + infos[2]);
break;
case Config.TYPE_HOLE_INGAME:
infos = info.split(",");
username = infos[1];
String[] pokers = infos[2].split("_");
String debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug(username + ":" + debuginfo);
break;
case Config.TYPE_USER_INGAME:
break;
case Config.TYPE_CARD_INGAME:
infos = info.split(",");
pokers = infos[0].split("_");
debuginfo = "";
for (String s : pokers) {
Card c = new Card(Integer.parseInt(s));
debuginfo = debuginfo + " " + c.toChineseString();
}
log.debug("ontable" + ":" + debuginfo);
break;
}
}
}
} else {
log.info("[messageReceived]illegal");
}
}
|
diff --git a/src/main/java/org/bukkit/permissions/PermissibleBase.java b/src/main/java/org/bukkit/permissions/PermissibleBase.java
index 88fa82e9..6da5663b 100644
--- a/src/main/java/org/bukkit/permissions/PermissibleBase.java
+++ b/src/main/java/org/bukkit/permissions/PermissibleBase.java
@@ -1,249 +1,249 @@
package org.bukkit.permissions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
/**
* Base Permissible for use in any Permissible object via proxy or extension
*/
public class PermissibleBase implements Permissible {
private ServerOperator opable = null;
private Permissible parent = this;
private final List<PermissionAttachment> attachments = new LinkedList<PermissionAttachment>();
private final Map<String, PermissionAttachmentInfo> permissions = new HashMap<String, PermissionAttachmentInfo>();
public PermissibleBase(ServerOperator opable) {
this.opable = opable;
if (opable instanceof Permissible) {
this.parent = (Permissible)opable;
}
recalculatePermissions();
}
public boolean isOp() {
if (opable == null) {
return false;
} else {
return opable.isOp();
}
}
public void setOp(boolean value) {
if (opable == null) {
throw new UnsupportedOperationException("Cannot change op value as no ServerOperator is set");
} else {
opable.setOp(value);
}
}
public boolean isPermissionSet(String name) {
if (name == null) {
throw new IllegalArgumentException("Permission name cannot be null");
}
return permissions.containsKey(name.toLowerCase());
}
public boolean isPermissionSet(Permission perm) {
if (perm == null) {
throw new IllegalArgumentException("Permission cannot be null");
}
return isPermissionSet(perm.getName());
}
public boolean hasPermission(String inName) {
if (inName == null) {
throw new IllegalArgumentException("Permission name cannot be null");
}
String name = inName.toLowerCase();
if (isPermissionSet(name)) {
return permissions.get(name).getValue();
} else {
Permission perm = Bukkit.getServer().getPluginManager().getPermission(name);
if (perm != null) {
return perm.getDefault().getValue(isOp());
} else {
- return false;
+ return Permission.DEFAULT_PERMISSION.getValue(isOp());
}
}
}
public boolean hasPermission(Permission perm) {
if (perm == null) {
throw new IllegalArgumentException("Permission cannot be null");
}
String name = perm.getName().toLowerCase();
if (isPermissionSet(name)) {
return permissions.get(name).getValue();
} else if (perm != null) {
return perm.getDefault().getValue(isOp());
} else {
return Permission.DEFAULT_PERMISSION.getValue(isOp());
}
}
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) {
if (name == null) {
throw new IllegalArgumentException("Permission name cannot be null");
} else if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
} else if (!plugin.isEnabled()) {
throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled");
}
PermissionAttachment result = addAttachment(plugin);
result.setPermission(name, value);
recalculatePermissions();
return result;
}
public PermissionAttachment addAttachment(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
} else if (!plugin.isEnabled()) {
throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled");
}
PermissionAttachment result = new PermissionAttachment(plugin, parent);
attachments.add(result);
recalculatePermissions();
return result;
}
public void removeAttachment(PermissionAttachment attachment) {
if (attachment == null) {
throw new IllegalArgumentException("Attachment cannot be null");
}
if (attachments.contains(attachment)) {
attachments.remove(attachment);
PermissionRemovedExecutor ex = attachment.getRemovalCallback();
if (ex != null) {
ex.attachmentRemoved(attachment);
}
recalculatePermissions();
} else {
throw new IllegalArgumentException("Given attachment is not part of Permissible object " + parent);
}
}
public void recalculatePermissions() {
clearPermissions();
Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp());
Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent);
for (Permission perm : defaults) {
String name = perm.getName().toLowerCase();
permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true));
Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent);
calculateChildPermissions(perm.getChildren(), false, null);
}
for (PermissionAttachment attachment : attachments) {
calculateChildPermissions(attachment.getPermissions(), false, attachment);
}
}
private synchronized void clearPermissions() {
Set<String> perms = permissions.keySet();
for (String name : perms) {
Bukkit.getServer().getPluginManager().unsubscribeFromPermission(name, parent);
}
Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(false, parent);
Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(true, parent);
permissions.clear();
}
private void calculateChildPermissions(Map<String, Boolean> children, boolean invert, PermissionAttachment attachment) {
Set<String> keys = children.keySet();
for (String name : keys) {
Permission perm = Bukkit.getServer().getPluginManager().getPermission(name);
boolean value = children.get(name) ^ invert;
String lname = name.toLowerCase();
permissions.put(lname, new PermissionAttachmentInfo(parent, lname, attachment, value));
Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent);
if (perm != null) {
calculateChildPermissions(perm.getChildren(), !value, attachment);
}
}
}
public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) {
if (name == null) {
throw new IllegalArgumentException("Permission name cannot be null");
} else if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
} else if (!plugin.isEnabled()) {
throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled");
}
PermissionAttachment result = addAttachment(plugin, ticks);
if (result != null) {
result.setPermission(name, value);
}
return result;
}
public PermissionAttachment addAttachment(Plugin plugin, int ticks) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
} else if (!plugin.isEnabled()) {
throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled");
}
PermissionAttachment result = addAttachment(plugin);
if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RemoveAttachmentRunnable(result), ticks) == -1) {
Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1");
result.remove();
return null;
} else {
return result;
}
}
public Set<PermissionAttachmentInfo> getEffectivePermissions() {
return new HashSet<PermissionAttachmentInfo>(permissions.values());
}
private class RemoveAttachmentRunnable implements Runnable {
private PermissionAttachment attachment;
public RemoveAttachmentRunnable(PermissionAttachment attachment) {
this.attachment = attachment;
}
public void run() {
attachment.remove();
}
}
}
| true | true | public boolean hasPermission(String inName) {
if (inName == null) {
throw new IllegalArgumentException("Permission name cannot be null");
}
String name = inName.toLowerCase();
if (isPermissionSet(name)) {
return permissions.get(name).getValue();
} else {
Permission perm = Bukkit.getServer().getPluginManager().getPermission(name);
if (perm != null) {
return perm.getDefault().getValue(isOp());
} else {
return false;
}
}
}
| public boolean hasPermission(String inName) {
if (inName == null) {
throw new IllegalArgumentException("Permission name cannot be null");
}
String name = inName.toLowerCase();
if (isPermissionSet(name)) {
return permissions.get(name).getValue();
} else {
Permission perm = Bukkit.getServer().getPluginManager().getPermission(name);
if (perm != null) {
return perm.getDefault().getValue(isOp());
} else {
return Permission.DEFAULT_PERMISSION.getValue(isOp());
}
}
}
|
diff --git a/Responder.java b/Responder.java
index f09ee1b..db66ab2 100644
--- a/Responder.java
+++ b/Responder.java
@@ -1,218 +1,218 @@
/* Ahmet Aktay and Nathan Griffith
* DarkChat
* CS435: Final Project
*/
import java.io.*;
import java.net.*;
import java.util.*;
class Responder implements Runnable {
private Queue<Socket> q;
private BufferedInputStream bin;
private Socket socket;
private UserList knownUsers;
private String name;
private Message pm;
User toUser;
User fromUser;
User ofUser;
public Responder(Queue<Socket> q, UserList knownUsers, Message pm, String name){
this.q = q;
this.knownUsers = knownUsers;
this.name = name;
this.pm = pm;
}
public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is online", fromUser.name));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
}
else if (ln.equals("OFL")) {
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is offline", fromUser.name));
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
if (!toUser.name.equals(pm.localUser.name)) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else if (ln.equals("REQ")) // someone is requesting known users
{
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
Boolean friends = false;
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
// do not respond
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
- else if (!friends)
+ else if (!fromUser.knowUser(ofUser))
{
MyUtils.dPrintLine("Recieved REQuest where users haven't met.");
- MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list"));
+ MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list",fromUser.name,ofUser.name));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
else
{
MyUtils.dPrintLine("Received valid REQuest where users have met.");
MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser));
pm.deliverKnownList(ofUser, fromUser);
}
}
else if (ln.equals("BUD")) // someone is delivering known users
// TODO: check if we requested one
{
// String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName);
// String fromUserName = inFromClient.readLine();
// String ofUserName = inFromClient.readLine();
// port = Integer.parseInt(inFromClient.readLine());
// Boolean friends = false;
// synchronized (knownUsers) {
// fromUser = knownUsers.get(fromUserName,true);
// ofUser = knownUsers.get(ofUserName,true);
// }
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved BUDs from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved BUDs of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
}
else
{
MyUtils.dPrintLine("Received valid BUDs");
MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser));
synchronized(ofUser)
{
synchronized(knownUsers)
{
String budName = inFromClient.readLine();
while(budName != "")
{
User budUser = knownUsers.get(budName);
synchronized (budUser) {
ofUser.meetUser(budUser);
}
}
budName = inFromClient.readLine();
}
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
}
| false | true | public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is online", fromUser.name));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
}
else if (ln.equals("OFL")) {
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is offline", fromUser.name));
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
if (!toUser.name.equals(pm.localUser.name)) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else if (ln.equals("REQ")) // someone is requesting known users
{
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
Boolean friends = false;
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
// do not respond
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
else if (!friends)
{
MyUtils.dPrintLine("Recieved REQuest where users haven't met.");
MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list"));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
else
{
MyUtils.dPrintLine("Received valid REQuest where users have met.");
MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser));
pm.deliverKnownList(ofUser, fromUser);
}
}
else if (ln.equals("BUD")) // someone is delivering known users
// TODO: check if we requested one
{
// String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName);
// String fromUserName = inFromClient.readLine();
// String ofUserName = inFromClient.readLine();
// port = Integer.parseInt(inFromClient.readLine());
// Boolean friends = false;
// synchronized (knownUsers) {
// fromUser = knownUsers.get(fromUserName,true);
// ofUser = knownUsers.get(ofUserName,true);
// }
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved BUDs from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved BUDs of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
}
else
{
MyUtils.dPrintLine("Received valid BUDs");
MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser));
synchronized(ofUser)
{
synchronized(knownUsers)
{
String budName = inFromClient.readLine();
while(budName != "")
{
User budUser = knownUsers.get(budName);
synchronized (budUser) {
ofUser.meetUser(budUser);
}
}
budName = inFromClient.readLine();
}
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
| public void run() {
try {
MyUtils.dPrintLine(String.format("Launching thread %s", name));
//Wait for an item to enter the socket queue
while(true) {
socket = null;
while (socket==null) {
synchronized(q) {
while (q.isEmpty()) {
try {
q.wait(500);
}
catch (InterruptedException e) {
MyUtils.dPrintLine("Connection interrupted");
}
}
socket = q.poll();
}
}
MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort()));
// create read stream to get input
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ln = inFromClient.readLine();
int port = socket.getPort();
if (ln.equals("ONL")) //fromUser is online
{
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String state = inFromClient.readLine();
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is online", fromUser.name));
if (state.equals("INIT")) {
synchronized (pm) {
pm.declareOnline(fromUser, false);
}
}
}
}
}
}
else if (ln.equals("OFL")) {
ln = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
//DEAL WITH USER
synchronized (knownUsers) {
fromUser = knownUsers.get(ln,true); //only get if exists
}
synchronized (fromUser) {
if (fromUser != null) {
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
if (!fromUser.name.equals(pm.localUser.name)) {
System.out.println(String.format("'%s' is offline", fromUser.name));
}
}
}
}
else if (ln.equals("CHT")) //fromUser is chatting with you!
{
String fromUsername = inFromClient.readLine();
String toUsername = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
ln = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUsername,true); //only get if exists
toUser = knownUsers.get(toUsername, true);
}
synchronized (fromUser) {
if (!toUser.name.equals(pm.localUser.name)) {
MyUtils.dPrintLine("Recieved chat with incorrect user fields:");
MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln));
}
else if (fromUser != null) {
System.out.println(String.format("%s: %s", fromUser.name,ln));
fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port));
}
else {
MyUtils.dPrintLine("Recieved chat from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
}
}
else if (ln.equals("REQ")) // someone is requesting known users
{
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
Boolean friends = false;
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
// do not respond
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
else if (!fromUser.knowUser(ofUser))
{
MyUtils.dPrintLine("Recieved REQuest where users haven't met.");
MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list",fromUser.name,ofUser.name));
pm.deliverFakeKnownList(ofUserName, fromUser);
}
else
{
MyUtils.dPrintLine("Received valid REQuest where users have met.");
MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser));
pm.deliverKnownList(ofUser, fromUser);
}
}
else if (ln.equals("BUD")) // someone is delivering known users
// TODO: check if we requested one
{
// String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName);
// String fromUserName = inFromClient.readLine();
// String ofUserName = inFromClient.readLine();
// port = Integer.parseInt(inFromClient.readLine());
// Boolean friends = false;
// synchronized (knownUsers) {
// fromUser = knownUsers.get(fromUserName,true);
// ofUser = knownUsers.get(ofUserName,true);
// }
String fromUserName = inFromClient.readLine();
port = Integer.parseInt(inFromClient.readLine());
String ofUserName = inFromClient.readLine();
synchronized (knownUsers) {
fromUser = knownUsers.get(fromUserName,true);
ofUser = knownUsers.get(ofUserName,true);
}
if (fromUser == null)
{
MyUtils.dPrintLine("Recieved BUDs from unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln));
}
else if (ofUser == null)
{
MyUtils.dPrintLine("Recieved BUDs of unknown user:");
MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln));
}
else
{
MyUtils.dPrintLine("Received valid BUDs");
MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser));
synchronized(ofUser)
{
synchronized(knownUsers)
{
String budName = inFromClient.readLine();
while(budName != "")
{
User budUser = knownUsers.get(budName);
synchronized (budUser) {
ofUser.meetUser(budUser);
}
}
budName = inFromClient.readLine();
}
}
}
}
else
MyUtils.dPrintLine("Unrecognized message format");
socket.close();
}
}
catch (Exception e) {
MyUtils.dPrintLine(String.format("%s",e));
//some sort of exception
}
}
|
diff --git a/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java b/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java
index b45747d5..5ce54af2 100644
--- a/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java
+++ b/editor/server/src/org/oryxeditor/server/WSDL2XFormsServlet.java
@@ -1,175 +1,185 @@
package org.oryxeditor.server;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import de.hpi.xforms.XForm;
import de.hpi.xforms.generation.WSDL2XFormsTransformation;
import de.hpi.xforms.rdf.XFormsERDFExporter;
import de.hpi.xforms.serialization.XFormsXHTMLImporter;
/**
*
* @author [email protected]
*
*/
public class WSDL2XFormsServlet extends HttpServlet {
private static final long serialVersionUID = 6084194342174761234L;
/*private static List<String> portTypes;
private static Map<String, String> operations; // operation name -> port type
private static Map<String, String> forms; // form url -> operation*/
private static Map<String, Map<String, String>> forms; // port type -> ( operation name -> form url )
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
Writer resWriter = res.getWriter();
String wsdlUrl = req.getParameter("wsdlUrl");
boolean outputXHTML = false;
- String repesentation = req.getParameter("repesentation");
- if (repesentation.equals("xhtml")) {
+ String representation = req.getParameter("representation");
+ if (representation != null && representation.equals("xhtml")) {
outputXHTML = true;
}
forms = new HashMap<String, Map<String, String>>();
try {
// get WSDL document
URL url = new URL(wsdlUrl);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document wsdlDoc = builder.parse(url.openStream());
// transform to XForms documents
String wsdlId = generateWsdlId(wsdlUrl);
List<Document> xformsDocs = WSDL2XFormsTransformation.transform(
getServletContext(), wsdlDoc.getDocumentElement(), wsdlId);
int i=0;
for(Document xformsDoc : xformsDocs) {
XFormsXHTMLImporter importer = new XFormsXHTMLImporter(xformsDoc);
XForm form = importer.getXForm();
// import XForms document for Oryx
XFormsERDFExporter exporter = new XFormsERDFExporter(form, getServletContext().getRealPath("/stencilsets/xforms/xforms.json"));
StringWriter erdfWriter = new StringWriter();
exporter.exportERDF(erdfWriter);
// save to backend
Repository repo = new Repository(Repository.getBaseUrl(req));
String modelName = wsdlId + " " + i;
String modelUrl = Repository.getBaseUrl(req) + repo.saveNewModel(
erdfWriter.toString(),
modelName,
modelName,
"http://b3mn.org/stencilset/xforms#",
"/stencilsets/xforms/xforms.json");
addResponseParams(xformsDoc.getDocumentElement(), modelUrl.substring(modelUrl.lastIndexOf("http://")));
i++;
}
if (outputXHTML) {
//TODO: examination of the HTTP Accept header (see http://www.w3.org/TR/xhtml-media-types/#media-types)
res.setContentType("application/xhtml+xml");
resWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<body style=\"font-size: 75%; font-family: sans-serif;\">"
+ "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>"
+ "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>"
+ + "<p>To execute the forms below, you will need an XForms-capable browser, e.g., "
+ + "<a href=\"http://www.x-smiles.org/\">X-Smiles</a>, "
+ + "<br />"
+ + "or a suitable browser plugin, e.g., "
+ + "<a href=\"https://addons.mozilla.org/en-US/firefox/addon/824\">the XForms extension for Firefox 2.x and 3.x</a> "
+ + "or <a href=\"http://www.formsplayer.com/\">formsPlayer for Internet Explorer</a>."
+ + "<br />"
+ + "See also <a href=\"http://www.xml.com/pub/a/2003/09/10/xforms.html\">Ten Favorite XForms Engines</a> "
+ + "and <a href=\"http://en.wikipedia.org/wiki/Xforms#Software_support\">XForms Software Support</a>."
+ + "</p>"
);
for(String portType : forms.keySet()) {
resWriter.write("<h2>PortType: " + portType + "</h2>");
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("<h3>Operation: " + operationName + "</h3>");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>");
}
}
resWriter.write("</body></html>");
} else {
resWriter.write("svc0=" + wsdlUrl);
int ptId=0;
for(String portType : forms.keySet()) {
resWriter.write("&svc0_pt" + ptId + "=" + portType);
int opId=0;
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName);
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName));
opId++;
}
ptId++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String generateWsdlId(String url) {
UUID uuid = UUID.nameUUIDFromBytes(url.getBytes());
return uuid.toString();
}
private static void addResponseParams(Node formNode, String formUrl) {
Node instanceNode = getChild(getChild(getChild(formNode, "xhtml:head"), "xforms:model"), "xforms:instance");
if(instanceNode!=null) {
String[] splitted = getAttributeValue(instanceNode, "id").split("\\.");
Map<String, String> operations = new HashMap<String, String>();
if(!forms.containsKey(splitted[1]))
forms.put(splitted[1], operations);
else
operations = forms.get(splitted[1]);
operations.put(splitted[2], formUrl);
}
}
private static Node getChild(Node n, String name) {
if (n == null)
return null;
for (Node node=n.getFirstChild(); node != null; node=node.getNextSibling())
if (node.getNodeName().equals(name))
return node;
return null;
}
private static String getAttributeValue(Node node, String attribute) {
Node item = node.getAttributes().getNamedItem(attribute);
if (item != null)
return item.getNodeValue();
else
return null;
}
}
| false | true | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
Writer resWriter = res.getWriter();
String wsdlUrl = req.getParameter("wsdlUrl");
boolean outputXHTML = false;
String repesentation = req.getParameter("repesentation");
if (repesentation.equals("xhtml")) {
outputXHTML = true;
}
forms = new HashMap<String, Map<String, String>>();
try {
// get WSDL document
URL url = new URL(wsdlUrl);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document wsdlDoc = builder.parse(url.openStream());
// transform to XForms documents
String wsdlId = generateWsdlId(wsdlUrl);
List<Document> xformsDocs = WSDL2XFormsTransformation.transform(
getServletContext(), wsdlDoc.getDocumentElement(), wsdlId);
int i=0;
for(Document xformsDoc : xformsDocs) {
XFormsXHTMLImporter importer = new XFormsXHTMLImporter(xformsDoc);
XForm form = importer.getXForm();
// import XForms document for Oryx
XFormsERDFExporter exporter = new XFormsERDFExporter(form, getServletContext().getRealPath("/stencilsets/xforms/xforms.json"));
StringWriter erdfWriter = new StringWriter();
exporter.exportERDF(erdfWriter);
// save to backend
Repository repo = new Repository(Repository.getBaseUrl(req));
String modelName = wsdlId + " " + i;
String modelUrl = Repository.getBaseUrl(req) + repo.saveNewModel(
erdfWriter.toString(),
modelName,
modelName,
"http://b3mn.org/stencilset/xforms#",
"/stencilsets/xforms/xforms.json");
addResponseParams(xformsDoc.getDocumentElement(), modelUrl.substring(modelUrl.lastIndexOf("http://")));
i++;
}
if (outputXHTML) {
//TODO: examination of the HTTP Accept header (see http://www.w3.org/TR/xhtml-media-types/#media-types)
res.setContentType("application/xhtml+xml");
resWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<body style=\"font-size: 75%; font-family: sans-serif;\">"
+ "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>"
+ "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>"
);
for(String portType : forms.keySet()) {
resWriter.write("<h2>PortType: " + portType + "</h2>");
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("<h3>Operation: " + operationName + "</h3>");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>");
}
}
resWriter.write("</body></html>");
} else {
resWriter.write("svc0=" + wsdlUrl);
int ptId=0;
for(String portType : forms.keySet()) {
resWriter.write("&svc0_pt" + ptId + "=" + portType);
int opId=0;
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName);
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName));
opId++;
}
ptId++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/plain");
Writer resWriter = res.getWriter();
String wsdlUrl = req.getParameter("wsdlUrl");
boolean outputXHTML = false;
String representation = req.getParameter("representation");
if (representation != null && representation.equals("xhtml")) {
outputXHTML = true;
}
forms = new HashMap<String, Map<String, String>>();
try {
// get WSDL document
URL url = new URL(wsdlUrl);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document wsdlDoc = builder.parse(url.openStream());
// transform to XForms documents
String wsdlId = generateWsdlId(wsdlUrl);
List<Document> xformsDocs = WSDL2XFormsTransformation.transform(
getServletContext(), wsdlDoc.getDocumentElement(), wsdlId);
int i=0;
for(Document xformsDoc : xformsDocs) {
XFormsXHTMLImporter importer = new XFormsXHTMLImporter(xformsDoc);
XForm form = importer.getXForm();
// import XForms document for Oryx
XFormsERDFExporter exporter = new XFormsERDFExporter(form, getServletContext().getRealPath("/stencilsets/xforms/xforms.json"));
StringWriter erdfWriter = new StringWriter();
exporter.exportERDF(erdfWriter);
// save to backend
Repository repo = new Repository(Repository.getBaseUrl(req));
String modelName = wsdlId + " " + i;
String modelUrl = Repository.getBaseUrl(req) + repo.saveNewModel(
erdfWriter.toString(),
modelName,
modelName,
"http://b3mn.org/stencilset/xforms#",
"/stencilsets/xforms/xforms.json");
addResponseParams(xformsDoc.getDocumentElement(), modelUrl.substring(modelUrl.lastIndexOf("http://")));
i++;
}
if (outputXHTML) {
//TODO: examination of the HTTP Accept header (see http://www.w3.org/TR/xhtml-media-types/#media-types)
res.setContentType("application/xhtml+xml");
resWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
+ "<body style=\"font-size: 75%; font-family: sans-serif;\">"
+ "<h1>Generated User Interfaces for Service: " + wsdlUrl + "</h1>"
+ "<a href=\"" + wsdlUrl + "\">View WSDL Definition of the Service</a>"
+ "<p>To execute the forms below, you will need an XForms-capable browser, e.g., "
+ "<a href=\"http://www.x-smiles.org/\">X-Smiles</a>, "
+ "<br />"
+ "or a suitable browser plugin, e.g., "
+ "<a href=\"https://addons.mozilla.org/en-US/firefox/addon/824\">the XForms extension for Firefox 2.x and 3.x</a> "
+ "or <a href=\"http://www.formsplayer.com/\">formsPlayer for Internet Explorer</a>."
+ "<br />"
+ "See also <a href=\"http://www.xml.com/pub/a/2003/09/10/xforms.html\">Ten Favorite XForms Engines</a> "
+ "and <a href=\"http://en.wikipedia.org/wiki/Xforms#Software_support\">XForms Software Support</a>."
+ "</p>"
);
for(String portType : forms.keySet()) {
resWriter.write("<h2>PortType: " + portType + "</h2>");
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("<h3>Operation: " + operationName + "</h3>");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport?path=/backend") + "\">Run in XForms-capable Client</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName).replace("/backend", "/oryx/xformsexport-orbeon?path=/backend") + "\">Run on Server</a> | ");
resWriter.write("<a href=\"" + forms.get(portType).get(operationName) + "\">Open in Editor</a>");
}
}
resWriter.write("</body></html>");
} else {
resWriter.write("svc0=" + wsdlUrl);
int ptId=0;
for(String portType : forms.keySet()) {
resWriter.write("&svc0_pt" + ptId + "=" + portType);
int opId=0;
for(String operationName : forms.get(portType).keySet()) {
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "=" + operationName);
resWriter.write("&svc0_pt" + ptId + "_op" + opId + "_ui0=" + forms.get(portType).get(operationName));
opId++;
}
ptId++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/modules/rampart-core/src/main/java/org/apache/rampart/util/Axis2Util.java b/modules/rampart-core/src/main/java/org/apache/rampart/util/Axis2Util.java
index df8313de2..c76875b3c 100644
--- a/modules/rampart-core/src/main/java/org/apache/rampart/util/Axis2Util.java
+++ b/modules/rampart-core/src/main/java/org/apache/rampart/util/Axis2Util.java
@@ -1,346 +1,346 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rampart.util;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMMetaFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axiom.soap.SOAP12Constants;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPHeader;
import org.apache.axiom.soap.SOAPHeaderBlock;
import org.apache.axiom.soap.SOAPModelBuilder;
import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
import org.apache.rampart.handler.WSSHandlerConstants;
import org.apache.ws.security.WSSecurityException;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Utility class for the Axis2-WSS4J Module
*/
public class Axis2Util {
private static ThreadLocal doomTacker = new ThreadLocal();
public static boolean isUseDOOM() {
Object value = doomTacker.get();
return (value != null);
}
public static void useDOOM(boolean isDOOMRequired) {
//TODO Enable this when we have DOOM fixed to be able to flow in and out of Axis2
// if(isDOOMRequired) {
// if(!isUseDOOM()) {
// System.setProperty(OMAbstractFactory.SOAP11_FACTORY_NAME_PROPERTY, SOAP11Factory.class.getName());
// System.setProperty(OMAbstractFactory.SOAP12_FACTORY_NAME_PROPERTY, SOAP12Factory.class.getName());
// System.setProperty(OMAbstractFactory.OM_FACTORY_NAME_PROPERTY, OMDOMFactory.class.getName());
// doomTacker.set(new Object());
// }
// } else {
// System.getProperties().remove(OMAbstractFactory.SOAP11_FACTORY_NAME_PROPERTY);
// System.getProperties().remove(OMAbstractFactory.SOAP12_FACTORY_NAME_PROPERTY);
// System.getProperties().remove(OMAbstractFactory.OM_FACTORY_NAME_PROPERTY);
// doomTacker.set(null);
// }
}
/**
* Creates a DOM Document using the SOAP Envelope.
* @param env An org.apache.axiom.soap.SOAPEnvelope instance
* @return Returns the DOM Document of the given SOAP Envelope.
* @throws Exception
*/
public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom)
throws WSSecurityException {
try {
if(env instanceof Element) {
Element element = (Element)env;
Document document = element.getOwnerDocument();
// For outgoing messages, Axis2 only creates the SOAPEnvelope, but no document. If
// the Axiom implementation also supports DOM, then the envelope (seen as a DOM
// element) will have an owner document, but the document and the envelope have no
// parent-child relationship. On the other hand, the input expected by WSS4J is
// a document with the envelope as document element. Therefore we need to set the
// envelope as document element on the owner document.
if (element.getParentNode() != document) {
document.appendChild(element);
}
// If the Axiom implementation supports DOM, then it is possible/likely that the
// DOM API was used to create the object model (or parts of it). In this case, the
// object model is not necessarily well formed with respect to namespaces because
// DOM doesn't generate namespace declarations automatically. This is an issue
// because WSS4J/Santuario expects that all namespace declarations are present.
// If this is not the case, then signature values or encryptions will be incorrect.
// To avoid this, we normalize the document. Note that if we disable the other
// normalizations supported by DOM, this is generally not a heavy operation.
// In particular, the Axiom implementation is not required to expand the object
// model (including OMSourcedElements) because the Axiom builder is required to
// perform namespace repairing, so that no modifications to unexpanded parts of
// the message are required.
DOMConfiguration domConfig = document.getDomConfig();
domConfig.setParameter("split-cdata-sections", Boolean.FALSE);
domConfig.setParameter("well-formed", Boolean.FALSE);
domConfig.setParameter("namespaces", Boolean.TRUE);
document.normalizeDocument();
return document;
}
if (useDoom) {
env.build();
// Workaround to prevent a bug in AXIOM where
// there can be an incomplete OMElement as the first child body
OMElement firstElement = env.getBody().getFirstElement();
if (firstElement != null) {
firstElement.build();
}
//Get processed headers
SOAPHeader soapHeader = env.getHeader();
ArrayList processedHeaderQNames = new ArrayList();
if(soapHeader != null) {
Iterator headerBlocs = soapHeader.getChildElements();
while (headerBlocs.hasNext()) {
SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next();
if(element.isProcessed()) {
processedHeaderQNames.add(element.getQName());
}
}
}
// Check the namespace and find SOAP version and factory
String nsURI = null;
OMMetaFactory metaFactory = OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM);
SOAPFactory factory;
if (env.getNamespace().getNamespaceURI().equals(
SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
nsURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
factory = metaFactory.getSOAP11Factory();
} else {
nsURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
factory = metaFactory.getSOAP12Factory();
}
StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(
env.getXMLStreamReader(), factory, nsURI);
SOAPEnvelope envelope = (stAXSOAPModelBuilder)
.getSOAPEnvelope();
envelope.getParent().build();
//Set the processed flag of the processed headers
SOAPHeader header = envelope.getHeader();
for (Iterator iter = processedHeaderQNames.iterator(); iter
.hasNext();) {
QName name = (QName) iter.next();
Iterator omKids = header.getChildrenWithName(name);
if(omKids.hasNext()) {
((SOAPHeaderBlock)omKids.next()).setProcessed();
}
}
Element envElem = (Element) envelope;
return envElem.getOwnerDocument();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
env.build();
env.serialize(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos
.toByteArray());
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(bais);
}
} catch (Exception e) {
throw new WSSecurityException(
"Error in converting SOAP Envelope to Document", e);
}
}
/**
* Builds a SOAPEnvelope from DOM Document.
* @param doc - The dom document that contains a SOAP message
* @param useDoom
* @return
* @throws WSSecurityException
*/
public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
throws WSSecurityException {
Element documentElement = doc.getDocumentElement();
if (documentElement instanceof SOAPEnvelope) {
SOAPEnvelope env = (SOAPEnvelope)documentElement;
// If the DOM tree already implements the Axiom API and the corresponding
// Axiom implementation is also used as default implementation, then just return
// the SOAPEnvelope directly. Note that this will never be the case for DOOM,
// but may be the case for a non standard Axiom implementation.
if (env.getOMFactory().getMetaFactory() == OMAbstractFactory.getMetaFactory()) {
return env;
}
}
if(useDoom) {
try {
//Get processed headers
SOAPEnvelope env = (SOAPEnvelope)doc.getDocumentElement();
ArrayList processedHeaderQNames = new ArrayList();
SOAPHeader soapHeader = env.getHeader();
if(soapHeader != null) {
Iterator headerBlocs = soapHeader.getChildElements();
while (headerBlocs.hasNext()) {
OMElement element = (OMElement)headerBlocs.next();
SOAPHeaderBlock header = null;
if (element instanceof SOAPHeaderBlock) {
header = (SOAPHeaderBlock) element;
// If a header block is not an instance of SOAPHeaderBlock, it means that
// it is a header we have added in rampart eg. EncryptedHeader and should
// be converted to SOAPHeaderBlock for processing
} else {
header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
Iterator attrIter = element.getAllAttributes();
while (attrIter.hasNext()) {
OMAttribute attr = (OMAttribute)attrIter.next();
header.addAttribute(attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
}
Iterator nsIter = element.getAllDeclaredNamespaces();
while (nsIter.hasNext()) {
OMNamespace ns = (OMNamespace) nsIter.next();
header.declareNamespace(ns);
}
// retrieve all child nodes (including any text nodes)
// and re-attach to header block
Iterator children = element.getChildren();
while (children.hasNext()) {
OMNode child = (OMNode)children.next();
children.remove();
header.addChild(child);
}
- element.detach();
+ headerBlocs.remove();
soapHeader.build();
header.setProcessed();
}
if(header.isProcessed()) {
processedHeaderQNames.add(element.getQName());
}
}
}
XMLStreamReader reader = ((OMElement) doc.getDocumentElement())
.getXMLStreamReader();
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
reader);
SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();
//Set the processed flag of the processed headers
SOAPHeader header = envelope.getHeader();
for (Iterator iter = processedHeaderQNames.iterator(); iter
.hasNext();) {
QName name = (QName) iter.next();
Iterator omKids = header.getChildrenWithName(name);
if(omKids.hasNext()) {
((SOAPHeaderBlock)omKids.next()).setProcessed();
}
}
envelope.build();
return envelope;
} catch (FactoryConfigurationError e) {
throw new WSSecurityException(e.getMessage());
}
} else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createSOAPModelBuilder(bais, null);
return stAXSOAPModelBuilder.getSOAPEnvelope();
} catch (Exception e) {
throw new WSSecurityException(e.getMessage());
}
}
}
/**
* Provides the appropriate key to pickup config params from the message context.
* This is acutally used when the outflow handler (WSDoAllSender)
* is repeated n number of times.
* @param originalKey The default key
* @param inHandler Whether the handler is the inflow handler or not
* @param repetition The current repetition number
* @return Returns the key to be used internally in the security module to pick
* up the config params.
*/
public static String getKey(String originalKey, boolean inHandler, int repetition) {
if(repetition > 0 && !inHandler &&
!originalKey.equals(WSSHandlerConstants.OUTFLOW_SECURITY)&&
!originalKey.equals(WSSHandlerConstants.SENDER_REPEAT_COUNT)) {
return originalKey + repetition;
}
return originalKey;
}
/**
* This will build a DOOM Element that is of the same <code>Document</code>
* @param factory
* @param element
* @return
*/
public static OMElement toDOOM(OMFactory factory, OMElement element){
StAXOMBuilder builder = new StAXOMBuilder(factory, element.getXMLStreamReader());
OMElement elem = builder.getDocumentElement();
elem.build();
return elem;
}
}
| true | true | public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
throws WSSecurityException {
Element documentElement = doc.getDocumentElement();
if (documentElement instanceof SOAPEnvelope) {
SOAPEnvelope env = (SOAPEnvelope)documentElement;
// If the DOM tree already implements the Axiom API and the corresponding
// Axiom implementation is also used as default implementation, then just return
// the SOAPEnvelope directly. Note that this will never be the case for DOOM,
// but may be the case for a non standard Axiom implementation.
if (env.getOMFactory().getMetaFactory() == OMAbstractFactory.getMetaFactory()) {
return env;
}
}
if(useDoom) {
try {
//Get processed headers
SOAPEnvelope env = (SOAPEnvelope)doc.getDocumentElement();
ArrayList processedHeaderQNames = new ArrayList();
SOAPHeader soapHeader = env.getHeader();
if(soapHeader != null) {
Iterator headerBlocs = soapHeader.getChildElements();
while (headerBlocs.hasNext()) {
OMElement element = (OMElement)headerBlocs.next();
SOAPHeaderBlock header = null;
if (element instanceof SOAPHeaderBlock) {
header = (SOAPHeaderBlock) element;
// If a header block is not an instance of SOAPHeaderBlock, it means that
// it is a header we have added in rampart eg. EncryptedHeader and should
// be converted to SOAPHeaderBlock for processing
} else {
header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
Iterator attrIter = element.getAllAttributes();
while (attrIter.hasNext()) {
OMAttribute attr = (OMAttribute)attrIter.next();
header.addAttribute(attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
}
Iterator nsIter = element.getAllDeclaredNamespaces();
while (nsIter.hasNext()) {
OMNamespace ns = (OMNamespace) nsIter.next();
header.declareNamespace(ns);
}
// retrieve all child nodes (including any text nodes)
// and re-attach to header block
Iterator children = element.getChildren();
while (children.hasNext()) {
OMNode child = (OMNode)children.next();
children.remove();
header.addChild(child);
}
element.detach();
soapHeader.build();
header.setProcessed();
}
if(header.isProcessed()) {
processedHeaderQNames.add(element.getQName());
}
}
}
XMLStreamReader reader = ((OMElement) doc.getDocumentElement())
.getXMLStreamReader();
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
reader);
SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();
//Set the processed flag of the processed headers
SOAPHeader header = envelope.getHeader();
for (Iterator iter = processedHeaderQNames.iterator(); iter
.hasNext();) {
QName name = (QName) iter.next();
Iterator omKids = header.getChildrenWithName(name);
if(omKids.hasNext()) {
((SOAPHeaderBlock)omKids.next()).setProcessed();
}
}
envelope.build();
return envelope;
} catch (FactoryConfigurationError e) {
throw new WSSecurityException(e.getMessage());
}
} else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createSOAPModelBuilder(bais, null);
return stAXSOAPModelBuilder.getSOAPEnvelope();
} catch (Exception e) {
throw new WSSecurityException(e.getMessage());
}
}
}
| public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
throws WSSecurityException {
Element documentElement = doc.getDocumentElement();
if (documentElement instanceof SOAPEnvelope) {
SOAPEnvelope env = (SOAPEnvelope)documentElement;
// If the DOM tree already implements the Axiom API and the corresponding
// Axiom implementation is also used as default implementation, then just return
// the SOAPEnvelope directly. Note that this will never be the case for DOOM,
// but may be the case for a non standard Axiom implementation.
if (env.getOMFactory().getMetaFactory() == OMAbstractFactory.getMetaFactory()) {
return env;
}
}
if(useDoom) {
try {
//Get processed headers
SOAPEnvelope env = (SOAPEnvelope)doc.getDocumentElement();
ArrayList processedHeaderQNames = new ArrayList();
SOAPHeader soapHeader = env.getHeader();
if(soapHeader != null) {
Iterator headerBlocs = soapHeader.getChildElements();
while (headerBlocs.hasNext()) {
OMElement element = (OMElement)headerBlocs.next();
SOAPHeaderBlock header = null;
if (element instanceof SOAPHeaderBlock) {
header = (SOAPHeaderBlock) element;
// If a header block is not an instance of SOAPHeaderBlock, it means that
// it is a header we have added in rampart eg. EncryptedHeader and should
// be converted to SOAPHeaderBlock for processing
} else {
header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
Iterator attrIter = element.getAllAttributes();
while (attrIter.hasNext()) {
OMAttribute attr = (OMAttribute)attrIter.next();
header.addAttribute(attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
}
Iterator nsIter = element.getAllDeclaredNamespaces();
while (nsIter.hasNext()) {
OMNamespace ns = (OMNamespace) nsIter.next();
header.declareNamespace(ns);
}
// retrieve all child nodes (including any text nodes)
// and re-attach to header block
Iterator children = element.getChildren();
while (children.hasNext()) {
OMNode child = (OMNode)children.next();
children.remove();
header.addChild(child);
}
headerBlocs.remove();
soapHeader.build();
header.setProcessed();
}
if(header.isProcessed()) {
processedHeaderQNames.add(element.getQName());
}
}
}
XMLStreamReader reader = ((OMElement) doc.getDocumentElement())
.getXMLStreamReader();
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
reader);
SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();
//Set the processed flag of the processed headers
SOAPHeader header = envelope.getHeader();
for (Iterator iter = processedHeaderQNames.iterator(); iter
.hasNext();) {
QName name = (QName) iter.next();
Iterator omKids = header.getChildrenWithName(name);
if(omKids.hasNext()) {
((SOAPHeaderBlock)omKids.next()).setProcessed();
}
}
envelope.build();
return envelope;
} catch (FactoryConfigurationError e) {
throw new WSSecurityException(e.getMessage());
}
} else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createSOAPModelBuilder(bais, null);
return stAXSOAPModelBuilder.getSOAPEnvelope();
} catch (Exception e) {
throw new WSSecurityException(e.getMessage());
}
}
}
|
diff --git a/src/main/java/InlineCacheExample.java b/src/main/java/InlineCacheExample.java
index a2b5cb6..5b9b7bc 100644
--- a/src/main/java/InlineCacheExample.java
+++ b/src/main/java/InlineCacheExample.java
@@ -1,64 +1,63 @@
public class InlineCacheExample {
static class ClassWithColor {
protected final int color;
ClassWithColor(final int color) {
this.color = color;
}
public int getColor() {
return color;
}
}
static class SubClassWithColor extends ClassWithColor {
SubClassWithColor(final int color) {
super(color);
}
public int getColor() {
return color + 1;
}
}
static long playWithColorA(ClassWithColor thingWithColor) {
long sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += thingWithColor.getColor() & 0xffff;
}
return sum;
}
static long playWithColorB(ClassWithColor thingWithColor) {
long sum = 0;
for (int i = 0; i < 1000000; i++) {
sum += thingWithColor.getColor() & 0xffff;
}
return sum;
}
public static long doIt(int color) {
long sum = 0;
ClassWithColor thingOneWithColor = new ClassWithColor(color);
ClassWithColor thingTwoWithColor = new SubClassWithColor(color);
// playWithColorA is monomorphic:
sum += playWithColorA(thingOneWithColor);
- // playWithColorA is megamorphic:
- sum += playWithColorB(thingOneWithColor);
- sum += playWithColorB(thingTwoWithColor);
+ // playWithColorB is megamorphic:
+ sum += playWithColorB(((color & 1) == 1) ? thingOneWithColor : thingTwoWithColor);
return sum;
}
public static void main(String [] args) {
long sum = 0;
for (int i = 0; i < 100000; i++) {
sum += doIt(i);
}
System.out.println("sum = " + sum);
}
}
| true | true | public static long doIt(int color) {
long sum = 0;
ClassWithColor thingOneWithColor = new ClassWithColor(color);
ClassWithColor thingTwoWithColor = new SubClassWithColor(color);
// playWithColorA is monomorphic:
sum += playWithColorA(thingOneWithColor);
// playWithColorA is megamorphic:
sum += playWithColorB(thingOneWithColor);
sum += playWithColorB(thingTwoWithColor);
return sum;
}
| public static long doIt(int color) {
long sum = 0;
ClassWithColor thingOneWithColor = new ClassWithColor(color);
ClassWithColor thingTwoWithColor = new SubClassWithColor(color);
// playWithColorA is monomorphic:
sum += playWithColorA(thingOneWithColor);
// playWithColorB is megamorphic:
sum += playWithColorB(((color & 1) == 1) ? thingOneWithColor : thingTwoWithColor);
return sum;
}
|
diff --git a/psd-parser/src/psd/parser/imageresource/ImageResourceSectionParser.java b/psd-parser/src/psd/parser/imageresource/ImageResourceSectionParser.java
index cb06a6f..e8e4aba 100644
--- a/psd-parser/src/psd/parser/imageresource/ImageResourceSectionParser.java
+++ b/psd-parser/src/psd/parser/imageresource/ImageResourceSectionParser.java
@@ -1,56 +1,57 @@
package psd.parser.imageresource;
import java.io.IOException;
import psd.parser.PsdInputStream;
import psd.parser.object.PsdDescriptor;
public class ImageResourceSectionParser {
private static final String PSD_TAG = "8BIM";
private ImageResourceSectionHandler handler;
public void setHandler(ImageResourceSectionHandler handler) {
this.handler = handler;
}
public void parse(PsdInputStream stream) throws IOException {
int length = stream.readInt();
int pos = stream.getPos();
while (length > 0) {
String tag = stream.readString(4);
if (!tag.equals(PSD_TAG) && !tag.equals("MeSa")) {
throw new IOException("Format error: Invalid image resources section.: " + tag);
}
length -= 4;
int id = stream.readShort();
length -= 2;
int sizeOfName = stream.readByte() & 0xFF;
if ((sizeOfName & 0x01) == 0)
sizeOfName++;
+ @SuppressWarnings("unused")
String name = stream.readString(sizeOfName);
length -= sizeOfName + 1;
int sizeOfData = stream.readInt();
length -= 4;
if ((sizeOfData & 0x01) == 1)
sizeOfData++;
length -= sizeOfData;
int storePos = stream.getPos();
// TODO FIXME Is id correct?
if (sizeOfData > 0 && tag.equals(PSD_TAG) && id >= 4000 && id < 5000) {
String key = stream.readString(4);
if (key.equals("mani")) {
stream.skipBytes(12 + 12); // unknown data
PsdDescriptor descriptor = new PsdDescriptor(stream);
if (handler != null) {
handler.imageResourceManiSectionParsed(descriptor);
}
}
}
stream.skipBytes(sizeOfData - (stream.getPos() - storePos));
}
stream.skipBytes(length - (stream.getPos() - pos));
}
}
| true | true | public void parse(PsdInputStream stream) throws IOException {
int length = stream.readInt();
int pos = stream.getPos();
while (length > 0) {
String tag = stream.readString(4);
if (!tag.equals(PSD_TAG) && !tag.equals("MeSa")) {
throw new IOException("Format error: Invalid image resources section.: " + tag);
}
length -= 4;
int id = stream.readShort();
length -= 2;
int sizeOfName = stream.readByte() & 0xFF;
if ((sizeOfName & 0x01) == 0)
sizeOfName++;
String name = stream.readString(sizeOfName);
length -= sizeOfName + 1;
int sizeOfData = stream.readInt();
length -= 4;
if ((sizeOfData & 0x01) == 1)
sizeOfData++;
length -= sizeOfData;
int storePos = stream.getPos();
// TODO FIXME Is id correct?
if (sizeOfData > 0 && tag.equals(PSD_TAG) && id >= 4000 && id < 5000) {
String key = stream.readString(4);
if (key.equals("mani")) {
stream.skipBytes(12 + 12); // unknown data
PsdDescriptor descriptor = new PsdDescriptor(stream);
if (handler != null) {
handler.imageResourceManiSectionParsed(descriptor);
}
}
}
stream.skipBytes(sizeOfData - (stream.getPos() - storePos));
}
stream.skipBytes(length - (stream.getPos() - pos));
}
| public void parse(PsdInputStream stream) throws IOException {
int length = stream.readInt();
int pos = stream.getPos();
while (length > 0) {
String tag = stream.readString(4);
if (!tag.equals(PSD_TAG) && !tag.equals("MeSa")) {
throw new IOException("Format error: Invalid image resources section.: " + tag);
}
length -= 4;
int id = stream.readShort();
length -= 2;
int sizeOfName = stream.readByte() & 0xFF;
if ((sizeOfName & 0x01) == 0)
sizeOfName++;
@SuppressWarnings("unused")
String name = stream.readString(sizeOfName);
length -= sizeOfName + 1;
int sizeOfData = stream.readInt();
length -= 4;
if ((sizeOfData & 0x01) == 1)
sizeOfData++;
length -= sizeOfData;
int storePos = stream.getPos();
// TODO FIXME Is id correct?
if (sizeOfData > 0 && tag.equals(PSD_TAG) && id >= 4000 && id < 5000) {
String key = stream.readString(4);
if (key.equals("mani")) {
stream.skipBytes(12 + 12); // unknown data
PsdDescriptor descriptor = new PsdDescriptor(stream);
if (handler != null) {
handler.imageResourceManiSectionParsed(descriptor);
}
}
}
stream.skipBytes(sizeOfData - (stream.getPos() - storePos));
}
stream.skipBytes(length - (stream.getPos() - pos));
}
|
diff --git a/src/main/java/org/codinjutsu/tools/jenkins/JenkinsControlComponent.java b/src/main/java/org/codinjutsu/tools/jenkins/JenkinsControlComponent.java
index ea9a05f..0c7d7b3 100644
--- a/src/main/java/org/codinjutsu/tools/jenkins/JenkinsControlComponent.java
+++ b/src/main/java/org/codinjutsu/tools/jenkins/JenkinsControlComponent.java
@@ -1,246 +1,246 @@
/*
* Copyright (c) 2012 David Boissier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codinjutsu.tools.jenkins;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.*;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.codinjutsu.tools.jenkins.logic.BuildStatusAggregator;
import org.codinjutsu.tools.jenkins.logic.JenkinsBrowserLogic;
import org.codinjutsu.tools.jenkins.logic.JenkinsRequestManager;
import org.codinjutsu.tools.jenkins.model.Build;
import org.codinjutsu.tools.jenkins.model.View;
import org.codinjutsu.tools.jenkins.util.GuiUtil;
import org.codinjutsu.tools.jenkins.view.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.concurrent.TimeUnit;
import static org.codinjutsu.tools.jenkins.view.action.RunBuildAction.RUN_ICON;
@State(
name = JenkinsControlComponent.JENKINS_CONTROL_COMPONENT_NAME,
storages = {@Storage(id = "JenkinsControlSettings", file = "$PROJECT_FILE$")}
)
public class JenkinsControlComponent
implements ProjectComponent, Configurable, PersistentStateComponent<JenkinsConfiguration> {
static final String JENKINS_CONTROL_COMPONENT_NAME = "JenkinsControlComponent";
private static final String JENKINS_CONTROL_PLUGIN_NAME = "Jenkins Control Plugin";
private static final String JENKINS_BROWSER = "jenkinsBrowser";
private static final String JENKINS_BROWSER_TITLE = "Jenkins Browser";
private static final String JENKINS_BROWSER_ICON = "jenkins_logo.png";
private final JenkinsConfiguration configuration;
private JenkinsConfigurationPanel configurationPanel;
private final Project project;
private JenkinsBrowserLogic jenkinsBrowserLogic;
private JenkinsRequestManager jenkinsRequestManager;
private JenkinsWidget jenkinsWidget;
public JenkinsControlComponent(Project project) {
this.project = project;
this.configuration = new JenkinsConfiguration();
}
public void projectOpened() {
installJenkinsPanel();
}
public void projectClosed() {
jenkinsBrowserLogic.dispose();
ToolWindowManager.getInstance(project).unregisterToolWindow(JENKINS_BROWSER);
}
public JComponent createComponent() {
if (configurationPanel == null) {
configurationPanel = new JenkinsConfigurationPanel(jenkinsRequestManager);
}
return configurationPanel.getRootPanel();
}
public boolean isModified() {
return configurationPanel != null && configurationPanel.isModified(configuration);
}
public void disposeUIResources() {
configurationPanel = null;
}
public JenkinsConfiguration getState() {
return configuration;
}
public void loadState(JenkinsConfiguration jenkinsConfiguration) {
XmlSerializerUtil.copyBean(jenkinsConfiguration, configuration);
}
public String getHelpTopic() {
return null;
}
public void apply() throws ConfigurationException {
if (configurationPanel != null) {
try {
configurationPanel.applyConfigurationData(configuration);
jenkinsBrowserLogic.reloadConfiguration();
} catch (org.codinjutsu.tools.jenkins.exception.ConfigurationException ex) {
throw new ConfigurationException(ex.getMessage());
}
}
}
public void notifyInfoJenkinsToolWindow(final String message) {
ToolWindowManager.getInstance(project).notifyByBalloon(
JENKINS_BROWSER,
MessageType.INFO,
message,
RUN_ICON,
new BrowserHyperlinkListener());
}
public void notifyErrorJenkinsToolWindow(final String message) {
ToolWindowManager.getInstance(project).notifyByBalloon(JENKINS_BROWSER, MessageType.ERROR, message);
}
private void installJenkinsPanel() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
- ToolWindow toolWindow = toolWindowManager.registerToolWindow(JENKINS_BROWSER, true, ToolWindowAnchor.RIGHT);
+ ToolWindow toolWindow = toolWindowManager.registerToolWindow(JENKINS_BROWSER, false, ToolWindowAnchor.RIGHT);
jenkinsRequestManager = new JenkinsRequestManager(configuration.getCrumbFile());
JenkinsBrowserPanel browserPanel = new JenkinsBrowserPanel();
RssLatestBuildPanel rssLatestJobPanel = new RssLatestBuildPanel();
jenkinsWidget = new JenkinsWidget();
JenkinsBrowserLogic.BuildStatusListener buildStatusListener = new JenkinsBrowserLogic.BuildStatusListener() {
public void onBuildFailure(final String jobName, final Build build) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(jobName + "#" + build.getNumber() + ": FAILED", MessageType.ERROR, null);
Balloon balloon = balloonBuilder.setFadeoutTime(TimeUnit.SECONDS.toMillis(1)).createBalloon();
balloon.show(new RelativePoint(jenkinsWidget.getComponent(), new Point(0, 0)), Balloon.Position.above);
}
};
JenkinsBrowserLogic.JobLoadListener jobLoadListener = new JenkinsBrowserLogic.JobLoadListener() {
@Override
public void afterLoadingJobs(BuildStatusAggregator buildStatusAggregator) {
jenkinsWidget.updateInformation(buildStatusAggregator);
}
};
configuration.getBrowserPreferences().setLastSelectedView(PropertiesComponent.getInstance(project).getValue("last_selected_view"));
jenkinsBrowserLogic = new JenkinsBrowserLogic(configuration, jenkinsRequestManager, browserPanel, rssLatestJobPanel, buildStatusListener, jobLoadListener);
jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
View selectedView = (View) jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().getSelectedItem();
PropertiesComponent.getInstance(project).setValue("last_selected_view", selectedView.getName());
}
});
StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
@Override
public void run() {
jenkinsBrowserLogic.init();
}
});
final StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
statusBar.addWidget(jenkinsWidget);
jenkinsWidget.install(statusBar);
Content content = ContentFactory.SERVICE.getInstance()
.createContent(JenkinsPanel.onePanel(browserPanel, rssLatestJobPanel), JENKINS_BROWSER_TITLE, false);
toolWindow.getContentManager().
addContent(content);
toolWindow.setIcon(GuiUtil.loadIcon(JENKINS_BROWSER_ICON));
}
@NotNull
public String getComponentName() {
return JENKINS_CONTROL_COMPONENT_NAME;
}
@Nls
public String getDisplayName() {
return JENKINS_CONTROL_PLUGIN_NAME;
}
public Icon getIcon() {
return null;
}
public void reset() {
configurationPanel.loadConfigurationData(configuration);
}
public void initComponent() {
}
public void disposeComponent() {
jenkinsWidget.dispose();
}
}
| true | true | private void installJenkinsPanel() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
ToolWindow toolWindow = toolWindowManager.registerToolWindow(JENKINS_BROWSER, true, ToolWindowAnchor.RIGHT);
jenkinsRequestManager = new JenkinsRequestManager(configuration.getCrumbFile());
JenkinsBrowserPanel browserPanel = new JenkinsBrowserPanel();
RssLatestBuildPanel rssLatestJobPanel = new RssLatestBuildPanel();
jenkinsWidget = new JenkinsWidget();
JenkinsBrowserLogic.BuildStatusListener buildStatusListener = new JenkinsBrowserLogic.BuildStatusListener() {
public void onBuildFailure(final String jobName, final Build build) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(jobName + "#" + build.getNumber() + ": FAILED", MessageType.ERROR, null);
Balloon balloon = balloonBuilder.setFadeoutTime(TimeUnit.SECONDS.toMillis(1)).createBalloon();
balloon.show(new RelativePoint(jenkinsWidget.getComponent(), new Point(0, 0)), Balloon.Position.above);
}
};
JenkinsBrowserLogic.JobLoadListener jobLoadListener = new JenkinsBrowserLogic.JobLoadListener() {
@Override
public void afterLoadingJobs(BuildStatusAggregator buildStatusAggregator) {
jenkinsWidget.updateInformation(buildStatusAggregator);
}
};
configuration.getBrowserPreferences().setLastSelectedView(PropertiesComponent.getInstance(project).getValue("last_selected_view"));
jenkinsBrowserLogic = new JenkinsBrowserLogic(configuration, jenkinsRequestManager, browserPanel, rssLatestJobPanel, buildStatusListener, jobLoadListener);
jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
View selectedView = (View) jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().getSelectedItem();
PropertiesComponent.getInstance(project).setValue("last_selected_view", selectedView.getName());
}
});
StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
@Override
public void run() {
jenkinsBrowserLogic.init();
}
});
final StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
statusBar.addWidget(jenkinsWidget);
jenkinsWidget.install(statusBar);
Content content = ContentFactory.SERVICE.getInstance()
.createContent(JenkinsPanel.onePanel(browserPanel, rssLatestJobPanel), JENKINS_BROWSER_TITLE, false);
toolWindow.getContentManager().
addContent(content);
toolWindow.setIcon(GuiUtil.loadIcon(JENKINS_BROWSER_ICON));
}
| private void installJenkinsPanel() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
ToolWindow toolWindow = toolWindowManager.registerToolWindow(JENKINS_BROWSER, false, ToolWindowAnchor.RIGHT);
jenkinsRequestManager = new JenkinsRequestManager(configuration.getCrumbFile());
JenkinsBrowserPanel browserPanel = new JenkinsBrowserPanel();
RssLatestBuildPanel rssLatestJobPanel = new RssLatestBuildPanel();
jenkinsWidget = new JenkinsWidget();
JenkinsBrowserLogic.BuildStatusListener buildStatusListener = new JenkinsBrowserLogic.BuildStatusListener() {
public void onBuildFailure(final String jobName, final Build build) {
BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(jobName + "#" + build.getNumber() + ": FAILED", MessageType.ERROR, null);
Balloon balloon = balloonBuilder.setFadeoutTime(TimeUnit.SECONDS.toMillis(1)).createBalloon();
balloon.show(new RelativePoint(jenkinsWidget.getComponent(), new Point(0, 0)), Balloon.Position.above);
}
};
JenkinsBrowserLogic.JobLoadListener jobLoadListener = new JenkinsBrowserLogic.JobLoadListener() {
@Override
public void afterLoadingJobs(BuildStatusAggregator buildStatusAggregator) {
jenkinsWidget.updateInformation(buildStatusAggregator);
}
};
configuration.getBrowserPreferences().setLastSelectedView(PropertiesComponent.getInstance(project).getValue("last_selected_view"));
jenkinsBrowserLogic = new JenkinsBrowserLogic(configuration, jenkinsRequestManager, browserPanel, rssLatestJobPanel, buildStatusListener, jobLoadListener);
jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
View selectedView = (View) jenkinsBrowserLogic.getJenkinsBrowserPanel().getViewCombo().getSelectedItem();
PropertiesComponent.getInstance(project).setValue("last_selected_view", selectedView.getName());
}
});
StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
@Override
public void run() {
jenkinsBrowserLogic.init();
}
});
final StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
statusBar.addWidget(jenkinsWidget);
jenkinsWidget.install(statusBar);
Content content = ContentFactory.SERVICE.getInstance()
.createContent(JenkinsPanel.onePanel(browserPanel, rssLatestJobPanel), JENKINS_BROWSER_TITLE, false);
toolWindow.getContentManager().
addContent(content);
toolWindow.setIcon(GuiUtil.loadIcon(JENKINS_BROWSER_ICON));
}
|
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/services/AbyssService.java b/AE-go_GameServer/src/com/aionemu/gameserver/services/AbyssService.java
index 011d1bd1..a434683a 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/services/AbyssService.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/services/AbyssService.java
@@ -1,149 +1,149 @@
/*
* This file is part of aion-unique <aion-unique.org>.
*
* aion-unique is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* aion-unique is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aion-unique. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.services;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_ABYSS_RANK;
import com.aionemu.gameserver.network.aion.serverpackets.SM_ABYSS_RANK_UPDATE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.stats.StatFunctions;
import com.google.inject.Inject;
/**
* @author ATracer
*
*/
public class AbyssService
{
@Inject
private LegionService legionService;
/**
* Very basic method for now
*
* @param victim
* @param winner
*/
public void doReward(Player defeated, Player winner)
{
- int pointsGained = Math.round(winner.getAbyssRank().getRank().getPointsGained() * winner.getRates().getApPlayerRate());
+ int pointsGained = Math.round(defeated.getAbyssRank().getRank().getPointsGained() * winner.getRates().getApPlayerRate());
int pointsLost = Math.round(defeated.getAbyssRank().getRank().getPointsLost() * defeated.getRates().getApPlayerRate());
// Level penalty calc
int difference = winner.getLevel() - defeated.getLevel();
switch(difference)
{
case 3:
pointsGained = Math.round(pointsGained * 0.85f);
pointsLost = Math.round(pointsLost * 0.85f);
break;
case 4:
pointsGained = Math.round(pointsGained * 0.65f);
pointsLost = Math.round(pointsLost * 0.65f);
break;
case -2:
pointsGained = Math.round(pointsGained * 1.1f);
break;
case -3:
pointsGained = Math.round(pointsGained * 1.2f);
break;
}
if(difference > 4)
{
pointsGained = Math.round(pointsGained * 0.1f);
pointsLost = Math.round(pointsLost * 0.1f);
}
if(difference < -3)
{
pointsGained = Math.round(pointsGained * 1.3f);
}
// Abyss rank penalty calc
int winnerAbyssRank = winner.getAbyssRank().getRank().getId();
int defeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
int abyssRankDifference = winnerAbyssRank - defeatedAbyssRank;
if(winnerAbyssRank <= 7 && abyssRankDifference > 0)
{
float penaltyPercent = abyssRankDifference * 0.05f;
pointsGained -= Math.round(pointsGained * penaltyPercent);
}
// AP farm protection
if(defeated.getAbyssRank().getAp() < pointsGained)
pointsGained = StatFunctions.calculateSoloAPReward(winner, defeated);
int oldWinnerAbyssRank = winner.getAbyssRank().getRank().getId();
int oldDefeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
defeated.getAbyssRank().addAp(-pointsLost);
if(defeated.getAbyssRank().getRank().getId() != oldDefeatedAbyssRank)
PacketSendUtility.broadcastPacket(defeated, new SM_ABYSS_RANK_UPDATE(defeated));
winner.getAbyssRank().addAp(pointsGained);
if(winner.isLegionMember())
legionService.addContributionPoints(winner.getLegion(), pointsGained);
if(winner.getAbyssRank().getRank().getId() != oldWinnerAbyssRank)
PacketSendUtility.broadcastPacket(winner, new SM_ABYSS_RANK_UPDATE(winner));
winner.getAbyssRank().setAllKill();
PacketSendUtility.sendPacket(defeated, new SM_ABYSS_RANK(defeated.getAbyssRank()));
PacketSendUtility.sendPacket(winner, new SM_ABYSS_RANK(winner.getAbyssRank()));
PacketSendUtility.sendPacket(winner, SM_SYSTEM_MESSAGE.EARNED_ABYSS_POINT(String.valueOf(pointsGained)));
PacketSendUtility.sendPacket(defeated, new SM_SYSTEM_MESSAGE(1340002, winner.getName()));
}
/**
*
* @param victim
* @param winner
*/
public void doReward(Creature victim, Player winner)
{
int apReward = StatFunctions.calculateSoloAPReward(winner, victim);
int oldWinnerAbyssRank = winner.getAbyssRank().getRank().getId();
winner.getAbyssRank().addAp(apReward);
if(winner.isLegionMember())
legionService.addContributionPoints(winner.getLegion(), apReward);
if(winner.getAbyssRank().getRank().getId() != oldWinnerAbyssRank)
PacketSendUtility.broadcastPacket(winner, new SM_ABYSS_RANK_UPDATE(winner));
PacketSendUtility.sendPacket(winner, new SM_ABYSS_RANK(winner.getAbyssRank()));
PacketSendUtility.sendPacket(winner, SM_SYSTEM_MESSAGE.EARNED_ABYSS_POINT(String.valueOf(apReward)));
}
public void doReward(Player winner, int apReward)
{
winner.getAbyssRank().addAp(apReward);
if(winner.isLegionMember())
legionService.addContributionPoints(winner.getLegion(), apReward);
PacketSendUtility.broadcastPacket(winner, new SM_ABYSS_RANK_UPDATE(winner));
winner.getAbyssRank().setAllKill();
PacketSendUtility.sendPacket(winner, new SM_ABYSS_RANK(winner.getAbyssRank()));
PacketSendUtility.sendPacket(winner, SM_SYSTEM_MESSAGE.EARNED_ABYSS_POINT(String.valueOf(apReward)));
}
}
| true | true | public void doReward(Player defeated, Player winner)
{
int pointsGained = Math.round(winner.getAbyssRank().getRank().getPointsGained() * winner.getRates().getApPlayerRate());
int pointsLost = Math.round(defeated.getAbyssRank().getRank().getPointsLost() * defeated.getRates().getApPlayerRate());
// Level penalty calc
int difference = winner.getLevel() - defeated.getLevel();
switch(difference)
{
case 3:
pointsGained = Math.round(pointsGained * 0.85f);
pointsLost = Math.round(pointsLost * 0.85f);
break;
case 4:
pointsGained = Math.round(pointsGained * 0.65f);
pointsLost = Math.round(pointsLost * 0.65f);
break;
case -2:
pointsGained = Math.round(pointsGained * 1.1f);
break;
case -3:
pointsGained = Math.round(pointsGained * 1.2f);
break;
}
if(difference > 4)
{
pointsGained = Math.round(pointsGained * 0.1f);
pointsLost = Math.round(pointsLost * 0.1f);
}
if(difference < -3)
{
pointsGained = Math.round(pointsGained * 1.3f);
}
// Abyss rank penalty calc
int winnerAbyssRank = winner.getAbyssRank().getRank().getId();
int defeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
int abyssRankDifference = winnerAbyssRank - defeatedAbyssRank;
if(winnerAbyssRank <= 7 && abyssRankDifference > 0)
{
float penaltyPercent = abyssRankDifference * 0.05f;
pointsGained -= Math.round(pointsGained * penaltyPercent);
}
// AP farm protection
if(defeated.getAbyssRank().getAp() < pointsGained)
pointsGained = StatFunctions.calculateSoloAPReward(winner, defeated);
int oldWinnerAbyssRank = winner.getAbyssRank().getRank().getId();
int oldDefeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
defeated.getAbyssRank().addAp(-pointsLost);
if(defeated.getAbyssRank().getRank().getId() != oldDefeatedAbyssRank)
PacketSendUtility.broadcastPacket(defeated, new SM_ABYSS_RANK_UPDATE(defeated));
winner.getAbyssRank().addAp(pointsGained);
if(winner.isLegionMember())
legionService.addContributionPoints(winner.getLegion(), pointsGained);
if(winner.getAbyssRank().getRank().getId() != oldWinnerAbyssRank)
PacketSendUtility.broadcastPacket(winner, new SM_ABYSS_RANK_UPDATE(winner));
winner.getAbyssRank().setAllKill();
PacketSendUtility.sendPacket(defeated, new SM_ABYSS_RANK(defeated.getAbyssRank()));
PacketSendUtility.sendPacket(winner, new SM_ABYSS_RANK(winner.getAbyssRank()));
PacketSendUtility.sendPacket(winner, SM_SYSTEM_MESSAGE.EARNED_ABYSS_POINT(String.valueOf(pointsGained)));
PacketSendUtility.sendPacket(defeated, new SM_SYSTEM_MESSAGE(1340002, winner.getName()));
}
| public void doReward(Player defeated, Player winner)
{
int pointsGained = Math.round(defeated.getAbyssRank().getRank().getPointsGained() * winner.getRates().getApPlayerRate());
int pointsLost = Math.round(defeated.getAbyssRank().getRank().getPointsLost() * defeated.getRates().getApPlayerRate());
// Level penalty calc
int difference = winner.getLevel() - defeated.getLevel();
switch(difference)
{
case 3:
pointsGained = Math.round(pointsGained * 0.85f);
pointsLost = Math.round(pointsLost * 0.85f);
break;
case 4:
pointsGained = Math.round(pointsGained * 0.65f);
pointsLost = Math.round(pointsLost * 0.65f);
break;
case -2:
pointsGained = Math.round(pointsGained * 1.1f);
break;
case -3:
pointsGained = Math.round(pointsGained * 1.2f);
break;
}
if(difference > 4)
{
pointsGained = Math.round(pointsGained * 0.1f);
pointsLost = Math.round(pointsLost * 0.1f);
}
if(difference < -3)
{
pointsGained = Math.round(pointsGained * 1.3f);
}
// Abyss rank penalty calc
int winnerAbyssRank = winner.getAbyssRank().getRank().getId();
int defeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
int abyssRankDifference = winnerAbyssRank - defeatedAbyssRank;
if(winnerAbyssRank <= 7 && abyssRankDifference > 0)
{
float penaltyPercent = abyssRankDifference * 0.05f;
pointsGained -= Math.round(pointsGained * penaltyPercent);
}
// AP farm protection
if(defeated.getAbyssRank().getAp() < pointsGained)
pointsGained = StatFunctions.calculateSoloAPReward(winner, defeated);
int oldWinnerAbyssRank = winner.getAbyssRank().getRank().getId();
int oldDefeatedAbyssRank = defeated.getAbyssRank().getRank().getId();
defeated.getAbyssRank().addAp(-pointsLost);
if(defeated.getAbyssRank().getRank().getId() != oldDefeatedAbyssRank)
PacketSendUtility.broadcastPacket(defeated, new SM_ABYSS_RANK_UPDATE(defeated));
winner.getAbyssRank().addAp(pointsGained);
if(winner.isLegionMember())
legionService.addContributionPoints(winner.getLegion(), pointsGained);
if(winner.getAbyssRank().getRank().getId() != oldWinnerAbyssRank)
PacketSendUtility.broadcastPacket(winner, new SM_ABYSS_RANK_UPDATE(winner));
winner.getAbyssRank().setAllKill();
PacketSendUtility.sendPacket(defeated, new SM_ABYSS_RANK(defeated.getAbyssRank()));
PacketSendUtility.sendPacket(winner, new SM_ABYSS_RANK(winner.getAbyssRank()));
PacketSendUtility.sendPacket(winner, SM_SYSTEM_MESSAGE.EARNED_ABYSS_POINT(String.valueOf(pointsGained)));
PacketSendUtility.sendPacket(defeated, new SM_SYSTEM_MESSAGE(1340002, winner.getName()));
}
|
diff --git a/modules/kernel/src/com/caucho/env/health/AbstractHealthService.java b/modules/kernel/src/com/caucho/env/health/AbstractHealthService.java
index c9ae9d7ec..64f57bc1a 100644
--- a/modules/kernel/src/com/caucho/env/health/AbstractHealthService.java
+++ b/modules/kernel/src/com/caucho/env/health/AbstractHealthService.java
@@ -1,123 +1,123 @@
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.env.health;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.caucho.env.service.AbstractResinService;
import com.caucho.env.service.ResinSystem;
abstract public class AbstractHealthService extends AbstractResinService {
private static final Logger log
= Logger.getLogger(AbstractHealthService.class.getName());
private static final Class<? extends AbstractHealthService> _healthServiceClass;
private static AbstractHealthService create()
{
if (_healthServiceClass == null)
return null;
ResinSystem system = ResinSystem.getCurrent();
AbstractHealthService healthService = null;
if (system != null) {
healthService = system.getService(_healthServiceClass);
if (healthService == null) {
try {
- healthService = (AbstractHealthService) _healthServiceClass.newInstance();
+ healthService = (AbstractHealthService) _healthServiceClass.getConstructor(ResinSystem.class).newInstance(system);
system.addService(healthService);
healthService = system.getService(_healthServiceClass);
} catch (Exception e) {
// exception might be thrown for License failure
log.log(Level.FINER, e.toString(), e);
}
}
}
return healthService;
}
public static <T extends HealthCheck> T
getCurrentHealthCheck(Class<T> healthCheck)
{
AbstractHealthService healthService = create();
if (healthService != null)
return healthService.getHealthCheck(healthCheck);
else
return null;
}
public static <T extends HealthCheck>
T addCurrentHealthCheck(T healthCheck)
{
AbstractHealthService healthService = create();
if (healthService != null)
return healthService.addHealthCheck(healthCheck);
else
return healthCheck;
}
abstract protected <T extends HealthCheck>
T getHealthCheck(Class<T> healthCheckClass);
abstract protected <T extends HealthCheck>
T addHealthCheck(T healthCheck);
static {
_healthServiceClass = loadHealthServiceClass();
}
@SuppressWarnings("unchecked")
private static Class<? extends AbstractHealthService>
loadHealthServiceClass()
{
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return (Class) Class.forName("com.caucho.env.health.HealthService",
false,
loader);
} catch (Exception e) {
log.log(Level.ALL, e.toString(), e);
}
return null;
}
}
| true | true | private static AbstractHealthService create()
{
if (_healthServiceClass == null)
return null;
ResinSystem system = ResinSystem.getCurrent();
AbstractHealthService healthService = null;
if (system != null) {
healthService = system.getService(_healthServiceClass);
if (healthService == null) {
try {
healthService = (AbstractHealthService) _healthServiceClass.newInstance();
system.addService(healthService);
healthService = system.getService(_healthServiceClass);
} catch (Exception e) {
// exception might be thrown for License failure
log.log(Level.FINER, e.toString(), e);
}
}
}
return healthService;
}
| private static AbstractHealthService create()
{
if (_healthServiceClass == null)
return null;
ResinSystem system = ResinSystem.getCurrent();
AbstractHealthService healthService = null;
if (system != null) {
healthService = system.getService(_healthServiceClass);
if (healthService == null) {
try {
healthService = (AbstractHealthService) _healthServiceClass.getConstructor(ResinSystem.class).newInstance(system);
system.addService(healthService);
healthService = system.getService(_healthServiceClass);
} catch (Exception e) {
// exception might be thrown for License failure
log.log(Level.FINER, e.toString(), e);
}
}
}
return healthService;
}
|
diff --git a/test/regression/src/org/jacorb/test/AllTest.java b/test/regression/src/org/jacorb/test/AllTest.java
index 65d2e32f..c473dee8 100644
--- a/test/regression/src/org/jacorb/test/AllTest.java
+++ b/test/regression/src/org/jacorb/test/AllTest.java
@@ -1,43 +1,44 @@
package org.jacorb.test;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2001 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import junit.framework.*;
public class AllTest extends TestCase
{
public AllTest (String name)
{
super (name);
}
public static Test suite ()
{
TestSuite suite = new TestSuite ("All jacorb");
suite.addTest (org.jacorb.test.idl.AllTest.suite ());
suite.addTest (org.jacorb.test.orb.AllTest.suite ());
suite.addTest (org.jacorb.test.poa.AllTest.suite ());
suite.addTest (org.jacorb.test.naming.AllTest.suite ());
+ suite.addTest (org.jacorb.test.bugs.AllTest.suite());
return suite;
}
}
| true | true | public static Test suite ()
{
TestSuite suite = new TestSuite ("All jacorb");
suite.addTest (org.jacorb.test.idl.AllTest.suite ());
suite.addTest (org.jacorb.test.orb.AllTest.suite ());
suite.addTest (org.jacorb.test.poa.AllTest.suite ());
suite.addTest (org.jacorb.test.naming.AllTest.suite ());
return suite;
}
| public static Test suite ()
{
TestSuite suite = new TestSuite ("All jacorb");
suite.addTest (org.jacorb.test.idl.AllTest.suite ());
suite.addTest (org.jacorb.test.orb.AllTest.suite ());
suite.addTest (org.jacorb.test.poa.AllTest.suite ());
suite.addTest (org.jacorb.test.naming.AllTest.suite ());
suite.addTest (org.jacorb.test.bugs.AllTest.suite());
return suite;
}
|
diff --git a/DTBD-Webproject/src/main/java/no/nith/User.java b/DTBD-Webproject/src/main/java/no/nith/User.java
index b890b1b..2b2fbc5 100644
--- a/DTBD-Webproject/src/main/java/no/nith/User.java
+++ b/DTBD-Webproject/src/main/java/no/nith/User.java
@@ -1,70 +1,71 @@
package no.nith;
public class User {
private String fullName;
private String dateOfBirth;
private String sex;
private String email;
private String phoneNumber;
private String occupation;
public User() {
}
public User(String fullName, String dateOfBirth, String sex, String email, String phoneNumber, String occupation) {
this.setName(fullName);
this.setDateOfBirth(dateOfBirth);
this.setSex(sex);
this.setEmail(email);
this.setPhoneNumber(phoneNumber);
+ this.setOccupation(occupation);
}
public String getName() {
return fullName;
}
public void setName(String fullName) {
this.fullName = fullName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex = sex;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber){
this.phoneNumber = phoneNumber;
}
public String getOccupation(){
return occupation;
}
public void setOccupation(String occupation){
this.occupation = occupation;
}
}
| true | true | public User(String fullName, String dateOfBirth, String sex, String email, String phoneNumber, String occupation) {
this.setName(fullName);
this.setDateOfBirth(dateOfBirth);
this.setSex(sex);
this.setEmail(email);
this.setPhoneNumber(phoneNumber);
}
| public User(String fullName, String dateOfBirth, String sex, String email, String phoneNumber, String occupation) {
this.setName(fullName);
this.setDateOfBirth(dateOfBirth);
this.setSex(sex);
this.setEmail(email);
this.setPhoneNumber(phoneNumber);
this.setOccupation(occupation);
}
|
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SybaseDictionary.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SybaseDictionary.java
index 5ebba5111..1d118ec4f 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SybaseDictionary.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SybaseDictionary.java
@@ -1,454 +1,455 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.jdbc.sql;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.apache.openjpa.jdbc.identifier.DBIdentifier.DBIdentifierType;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.ForeignKey;
import org.apache.openjpa.jdbc.schema.Index;
import org.apache.openjpa.jdbc.schema.PrimaryKey;
import org.apache.openjpa.jdbc.schema.Table;
import org.apache.openjpa.jdbc.schema.Unique;
import org.apache.openjpa.lib.jdbc.DelegatingConnection;
import org.apache.openjpa.lib.util.ConcreteClassGenerator;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.meta.JavaTypes;
/**
* Dictionary for Sybase.
* The main point of interest is that by default, every table
* that is created will have a unique column named "UNQ_INDEX" of
* the "IDENTITY" type. OpenJPA will not ever utilize this column. However,
* due to internal Sybase restrictions, this column is required
* in order to support pessimistic (datastore) locking, since Sybase
* requires that any tables in a "SELECT ... FOR UPDATE" clause have
* a unique index that is <strong>not</strong> included in the list
* of columns, as described in the
* <a href="http://www.sybase.com/detail/1,6904,1023075,00.html"
* >Sybase documentation</a>. This behavior can be surpressed by setting the
* dictionary property <code>CreateIdentityColumn=false</code>. The
* name of the unique column can be changed by setting the property
* <code>IdentityColumnName=COLUMN_NAME</code>.
* A good Sybase type reference is can be found <a
* href="http://www.ispirer.com/doc/sqlways36/sybase/syb_dtypes.html">here</a>.
*/
public class SybaseDictionary
extends AbstractSQLServerDictionary {
private static Localizer _loc = Localizer.forPackage
(SybaseDictionary.class);
private static Constructor<SybaseConnection> sybaseConnectionImpl;
public static String RIGHT_TRUNCATION_ON_SQL = "set string_rtruncation on";
public static String NUMERIC_TRUNCATION_OFF_SQL = "set arithabort numeric_truncation off";
static {
try {
sybaseConnectionImpl = ConcreteClassGenerator.getConcreteConstructor(SybaseConnection.class,
Connection.class);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* If true, then whenever the <code>schematool</code> creates a
* table, it will append an additional IDENTITY column to the
* table's creation SQL. This is so Sybase will be able to
* perform <code>SELECT...FOR UPDATE</code> statements.
*/
public boolean createIdentityColumn = true;
/**
* If {@link #createIdentityColumn} is true, then the
* <code>identityColumnName</code> will be the name of the
* additional unique column that will be created.
*/
public String identityColumnName = "UNQ_INDEX";
/**
* If true, Sybase will ignore numeric truncation on insert or
* update operations. Otherwise, the operation will fail. The default
* value, false is in accordance with SQL92.
*/
public boolean ignoreNumericTruncation = false;
public SybaseDictionary() {
platform = "Sybase";
schemaCase = SCHEMA_CASE_PRESERVE;
forUpdateClause = "FOR UPDATE AT ISOLATION SERIALIZABLE";
supportsLockingWithDistinctClause = false;
supportsNullTableForGetColumns = false;
requiresAliasForSubselect = true;
requiresAutoCommitForMetaData = true;
maxTableNameLength = 30;
maxColumnNameLength = 30;
maxIndexNameLength = 30;
maxConstraintNameLength = 30;
bigintTypeName = "NUMERIC(38)";
bitTypeName = "TINYINT";
// Sybase doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
// these tables should not be reflected on
systemTableSet.addAll(Arrays.asList(new String[]{
"IJDBC_FUNCTION_ESCAPES", "JDBC_FUNCTION_ESCAPES",
"SPT_IJDBC_CONVERSION", "SPT_IJDBC_MDA", "SPT_IJDBC_TABLE_TYPES",
"SPT_JDBC_CONVERSION", "SPT_JDBC_TABLE_TYPES", "SPT_JTEXT",
"SPT_LIMIT_TYPES", "SPT_MDA", "SPT_MONITOR", "SPT_VALUES",
"SYBLICENSESLOG",
}));
// reserved words specified at:
// http://manuals.sybase.com/onlinebooks/group-as/asg1250e/
// refman/@Generic__BookTextView/26603
reservedWordSet.addAll(Arrays.asList(new String[]{
"ARITH_OVERFLOW", "BREAK", "BROWSE", "BULK", "CHAR_CONVERT",
"CHECKPOINT", "CLUSTERED", "COMPUTE", "CONFIRM", "CONTROLROW",
"DATABASE", "DBCC", "DETERMINISTIC", "DISK DISTINCT", "DUMMY",
"DUMP", "ENDTRAN", "ERRLVL", "ERRORDATA", "ERROREXIT", "EXCLUSIVE",
"EXIT", "EXP_ROW_SIZE", "FILLFACTOR", "FUNC", "FUNCTION",
"HOLDLOCK", "IDENTITY_GAP", "IDENTITY_INSERT", "IDENTITY_START",
"IF", "INDEX", "INOUT", "INSTALL", "INTERSECT", "JAR", "KILL",
"LINENO", "LOAD", "LOCK", "MAX_ROWS_PER_PAGE", "MIRROR",
"MIRROREXIT", "MODIFY", "NEW", "NOHOLDLOCK", "NONCLUSTERED",
"NUMERIC_TRUNCATION", "OFF", "OFFSETS", "ONCE", "ONLINE", "OUT",
"OVER", "PARTITION", "PERM", "PERMANENT", "PLAN", "PRINT", "PROC",
"PROCESSEXIT", "PROXY_TABLE", "QUIESCE", "RAISERROR", "READ",
"READPAST", "READTEXT", "RECONFIGURE", "REFERENCES REMOVE", "REORG",
"REPLACE", "REPLICATION", "RESERVEPAGEGAP", "RETURN", "RETURNS",
"ROLE", "ROWCOUNT", "RULE", "SAVE", "SETUSER", "SHARED",
"SHUTDOWN", "SOME", "STATISTICS", "STRINGSIZE", "STRIPE",
"SYB_IDENTITY", "SYB_RESTREE", "SYB_TERMINATE", "TEMP", "TEXTSIZE",
"TRAN", "TRIGGER", "TRUNCATE", "TSEQUAL", "UNPARTITION", "USE",
"USER_OPTION", "WAITFOR", "WHILE", "WRITETEXT",
}));
// Sybase does not support foreign key delete/update action NULL,
// DEFAULT, CASCADE
supportsNullDeleteAction = false;
supportsDefaultDeleteAction = false;
supportsCascadeDeleteAction = false;
supportsNullUpdateAction = false;
supportsDefaultUpdateAction = false;
supportsCascadeUpdateAction = false;
+ fixedSizeTypeNameSet.remove("NUMERIC");
}
@Override
public int getJDBCType(int metaTypeCode, boolean lob) {
switch (metaTypeCode) {
// the default mapping for BYTE is a TINYINT, but Sybase's TINYINT
// type can't handle the complete range for a Java byte
case JavaTypes.BYTE:
case JavaTypes.BYTE_OBJ:
return getPreferredType(Types.SMALLINT);
default:
return super.getJDBCType(metaTypeCode, lob);
}
}
@Override
public void setBigInteger(PreparedStatement stmnt, int idx, BigInteger val,
Column col)
throws SQLException {
// setBigDecimal doesn't work here: in one case, a stored value
// of 7799438514924349440 turns into 7799438514924349400
// setObject gets around this in the Sybase JDBC drivers
setObject(stmnt, idx, new BigDecimal(val), Types.BIGINT, col);
}
@Override
public String[] getAddForeignKeySQL(ForeignKey fk) {
// Sybase has problems with adding foriegn keys via ALTER TABLE command
return new String[0];
}
@Override
public String[] getCreateTableSQL(Table table) {
if (!createIdentityColumn)
return super.getCreateTableSQL(table);
StringBuilder buf = new StringBuilder();
buf.append("CREATE TABLE ").append(getFullName(table, false)).
append(" (");
Column[] cols = table.getColumns();
boolean hasIdentity = false;
for (int i = 0; i < cols.length; i++) {
// can only have one identity column
if (cols[i].isAutoAssigned()) {
hasIdentity = true;
}
// The column may exist if dropping and recreating a table.
if(cols[i].getIdentifier().getName().equals(identityColumnName)) {
hasIdentity=true;
// column type may be lost when recreating - reset to NUMERIC
if(cols[i].getType() != Types.NUMERIC) { // should check if compatible
cols[i].setType(Types.NUMERIC);
}
}
buf.append(i == 0 ? "" : ", ");
buf.append(getDeclareColumnSQL(cols[i], false));
}
// add an identity column if we do not already have one
if (!hasIdentity)
buf.append(", ").append(identityColumnName).
append(" NUMERIC IDENTITY UNIQUE");
PrimaryKey pk = table.getPrimaryKey();
if (pk != null)
buf.append(", ").append(getPrimaryKeyConstraintSQL(pk));
Unique[] unqs = table.getUniques();
String unqStr;
for (int i = 0; i < unqs.length; i++) {
unqStr = getUniqueConstraintSQL(unqs[i]);
if (unqStr != null)
buf.append(", ").append(unqStr);
}
buf.append(")");
return new String[]{ buf.toString() };
}
@Override
protected String getDeclareColumnSQL(Column col, boolean alter) {
StringBuilder buf = new StringBuilder();
buf.append(getColumnDBName(col)).append(" ");
buf.append(getTypeName(col));
// can't add constraints to a column we're adding after table
// creation, cause some data might already be inserted
if (!alter) {
if (col.getDefaultString() != null && !col.isAutoAssigned())
buf.append(" DEFAULT ").append(col.getDefaultString());
if (col.isAutoAssigned())
buf.append(" IDENTITY");
}
if (col.isNotNull())
buf.append(" NOT NULL");
else if (!col.isPrimaryKey()) {
// sybase forces you to explicitly specify that
// you will allow NULL values
buf.append(" NULL");
}
return buf.toString();
}
@Override
public String[] getDropColumnSQL(Column column) {
// Sybase uses "ALTER TABLE DROP <COLUMN_NAME>" rather than the
// usual "ALTER TABLE DROP COLUMN <COLUMN_NAME>"
return new String[]{ "ALTER TABLE "
+ getFullName(column.getTable(), false) + " DROP " + getColumnDBName(column) };
}
@Override
public void refSchemaComponents(Table table) {
// note that we use getColumns() rather than getting the column by name
// because under some circumstances this method is called under the
// dynamic schema factory, where getting a column by name creates
// that column
Column[] cols = table.getColumns();
for (int i = 0; i < cols.length; i++)
if (identityColumnName.equalsIgnoreCase(cols[i].getIdentifier().getName()))
cols[i].ref();
}
@Override
public void endConfiguration() {
super.endConfiguration();
// warn about jdbc compliant flag
String url = conf.getConnectionURL();
if (!StringUtils.isEmpty(url)
&& url.toLowerCase().indexOf("jdbc:sybase:tds") != -1
&& url.toLowerCase().indexOf("be_as_jdbc_compliant_as_possible=")
== -1) {
log.warn(_loc.get("sybase-compliance", url));
}
}
@Override
public Connection decorate(Connection conn)
throws SQLException {
conn = super.decorate(conn);
Connection savedConn = conn;
// if(ignoreConnectionSetup) {
// if(conn instanceof DelegatingConnection) {
// conn = ((DelegatingConnection)conn).getInnermostDelegate();
// }
// }
// In order for Sybase to raise the truncation exception when the
// string length is greater than the column length for Char, VarChar,
// Binary, VarBinary, the "set string_rtruncation on" must be executed.
// This setting is effective for the duration of current connection.
if (setStringRightTruncationOn) {
PreparedStatement stmnt = prepareStatement(conn, RIGHT_TRUNCATION_ON_SQL);
stmnt.execute();
stmnt.close();
}
// By default, Sybase will fail to insert or update if a numeric
// truncation occurs as a result of, for example, loss of decimal
// precision. This setting specifies that the operation should not
// fail if a numeric truncation occurs.
if (ignoreNumericTruncation) {
PreparedStatement stmnt = prepareStatement(conn, NUMERIC_TRUNCATION_OFF_SQL);
stmnt.execute();
stmnt.close();
}
return ConcreteClassGenerator.newInstance(sybaseConnectionImpl, savedConn);
}
/**
* Helper method obtains a string value from a given column in a ResultSet. Strings provided are column names,
* jdbcName will be tried first if an SQLException occurs we'll try the sybase name.
*/
protected String getStringFromResultSet(ResultSet rs, String jdbcName, String sybaseName) throws SQLException {
try {
return rs.getString(jdbcName);
}
catch(SQLException sqle) {
// if the generic JDBC identifier isn't found an SQLException will be thrown
// try the Sybase specific id
return rs.getString(sybaseName);
}
}
/**
* Helper method obtains a boolean value from a given column in a ResultSet. Strings provided are column names,
* jdbcName will be tried first if an SQLException occurs we'll try the sybase name.
*/
protected boolean getBooleanFromResultSet(ResultSet rs, String jdbcName, String sybaseName) throws SQLException {
try {
return rs.getBoolean(jdbcName);
}
catch(SQLException sqle) {
// if the generic JDBC identifier isn't found an SQLException will be thrown
// try the Sybase specific id
return rs.getBoolean(sybaseName);
}
}
/**
* Create a new primary key from the information in the schema metadata.
*/
protected PrimaryKey newPrimaryKey(ResultSet pkMeta)
throws SQLException {
PrimaryKey pk = new PrimaryKey();
pk.setSchemaIdentifier(fromDBName(getStringFromResultSet(pkMeta, "TABLE_SCHEM", "table_owner"),
DBIdentifierType.SCHEMA));
pk.setTableIdentifier(fromDBName(getStringFromResultSet(pkMeta, "TABLE_NAME", "table_name"),
DBIdentifierType.TABLE));
pk.setColumnIdentifier(fromDBName(getStringFromResultSet(pkMeta, "COLUMN_NAME", "column_name"),
DBIdentifierType.COLUMN));
pk.setIdentifier(fromDBName(getStringFromResultSet(pkMeta, "PK_NAME", "index_name"),
DBIdentifierType.CONSTRAINT));
return pk;
}
/**
* Create a new index from the information in the index metadata.
*/
protected Index newIndex(ResultSet idxMeta)
throws SQLException {
Index idx = new Index();
idx.setSchemaIdentifier(fromDBName(getStringFromResultSet(idxMeta, "TABLE_SCHEM", "table_owner"),
DBIdentifierType.SCHEMA));
idx.setTableIdentifier(fromDBName(getStringFromResultSet(idxMeta, "TABLE_NAME", "table_name"),
DBIdentifierType.TABLE));
idx.setColumnIdentifier(fromDBName(getStringFromResultSet(idxMeta, "COLUMN_NAME", "column_name"),
DBIdentifierType.COLUMN));
idx.setIdentifier(fromDBName(getStringFromResultSet(idxMeta, "INDEX_NAME", "index_name"),
DBIdentifierType.INDEX));
idx.setUnique(!getBooleanFromResultSet(idxMeta, "NON_UNIQUE", "non_unique"));
return idx;
}
/**
* Connection wrapper to cache the {@link Connection#getCatalog} result,
* which takes a very long time with the Sybase Connection (and
* which we frequently invoke).
*/
protected abstract static class SybaseConnection
extends DelegatingConnection {
private String _catalog = null;
public SybaseConnection(Connection conn) {
super(conn);
}
public String getCatalog()
throws SQLException {
if (_catalog == null)
_catalog = super.getCatalog();
return _catalog;
}
public void setAutoCommit(boolean autocommit)
throws SQLException {
// the sybase jdbc driver demands that the Connection always
// be rolled back before autocommit status changes. Failure to
// do so will yield "SET CHAINED command not allowed within
// multi-statement transaction." exceptions
try {
super.setAutoCommit(autocommit);
} catch (SQLException e) {
// failed for some reason: try rolling back and then
// setting autocommit again.
if (autocommit)
super.commit();
else
super.rollback();
super.setAutoCommit(autocommit);
}
}
}
}
| true | true | public SybaseDictionary() {
platform = "Sybase";
schemaCase = SCHEMA_CASE_PRESERVE;
forUpdateClause = "FOR UPDATE AT ISOLATION SERIALIZABLE";
supportsLockingWithDistinctClause = false;
supportsNullTableForGetColumns = false;
requiresAliasForSubselect = true;
requiresAutoCommitForMetaData = true;
maxTableNameLength = 30;
maxColumnNameLength = 30;
maxIndexNameLength = 30;
maxConstraintNameLength = 30;
bigintTypeName = "NUMERIC(38)";
bitTypeName = "TINYINT";
// Sybase doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
// these tables should not be reflected on
systemTableSet.addAll(Arrays.asList(new String[]{
"IJDBC_FUNCTION_ESCAPES", "JDBC_FUNCTION_ESCAPES",
"SPT_IJDBC_CONVERSION", "SPT_IJDBC_MDA", "SPT_IJDBC_TABLE_TYPES",
"SPT_JDBC_CONVERSION", "SPT_JDBC_TABLE_TYPES", "SPT_JTEXT",
"SPT_LIMIT_TYPES", "SPT_MDA", "SPT_MONITOR", "SPT_VALUES",
"SYBLICENSESLOG",
}));
// reserved words specified at:
// http://manuals.sybase.com/onlinebooks/group-as/asg1250e/
// refman/@Generic__BookTextView/26603
reservedWordSet.addAll(Arrays.asList(new String[]{
"ARITH_OVERFLOW", "BREAK", "BROWSE", "BULK", "CHAR_CONVERT",
"CHECKPOINT", "CLUSTERED", "COMPUTE", "CONFIRM", "CONTROLROW",
"DATABASE", "DBCC", "DETERMINISTIC", "DISK DISTINCT", "DUMMY",
"DUMP", "ENDTRAN", "ERRLVL", "ERRORDATA", "ERROREXIT", "EXCLUSIVE",
"EXIT", "EXP_ROW_SIZE", "FILLFACTOR", "FUNC", "FUNCTION",
"HOLDLOCK", "IDENTITY_GAP", "IDENTITY_INSERT", "IDENTITY_START",
"IF", "INDEX", "INOUT", "INSTALL", "INTERSECT", "JAR", "KILL",
"LINENO", "LOAD", "LOCK", "MAX_ROWS_PER_PAGE", "MIRROR",
"MIRROREXIT", "MODIFY", "NEW", "NOHOLDLOCK", "NONCLUSTERED",
"NUMERIC_TRUNCATION", "OFF", "OFFSETS", "ONCE", "ONLINE", "OUT",
"OVER", "PARTITION", "PERM", "PERMANENT", "PLAN", "PRINT", "PROC",
"PROCESSEXIT", "PROXY_TABLE", "QUIESCE", "RAISERROR", "READ",
"READPAST", "READTEXT", "RECONFIGURE", "REFERENCES REMOVE", "REORG",
"REPLACE", "REPLICATION", "RESERVEPAGEGAP", "RETURN", "RETURNS",
"ROLE", "ROWCOUNT", "RULE", "SAVE", "SETUSER", "SHARED",
"SHUTDOWN", "SOME", "STATISTICS", "STRINGSIZE", "STRIPE",
"SYB_IDENTITY", "SYB_RESTREE", "SYB_TERMINATE", "TEMP", "TEXTSIZE",
"TRAN", "TRIGGER", "TRUNCATE", "TSEQUAL", "UNPARTITION", "USE",
"USER_OPTION", "WAITFOR", "WHILE", "WRITETEXT",
}));
// Sybase does not support foreign key delete/update action NULL,
// DEFAULT, CASCADE
supportsNullDeleteAction = false;
supportsDefaultDeleteAction = false;
supportsCascadeDeleteAction = false;
supportsNullUpdateAction = false;
supportsDefaultUpdateAction = false;
supportsCascadeUpdateAction = false;
}
| public SybaseDictionary() {
platform = "Sybase";
schemaCase = SCHEMA_CASE_PRESERVE;
forUpdateClause = "FOR UPDATE AT ISOLATION SERIALIZABLE";
supportsLockingWithDistinctClause = false;
supportsNullTableForGetColumns = false;
requiresAliasForSubselect = true;
requiresAutoCommitForMetaData = true;
maxTableNameLength = 30;
maxColumnNameLength = 30;
maxIndexNameLength = 30;
maxConstraintNameLength = 30;
bigintTypeName = "NUMERIC(38)";
bitTypeName = "TINYINT";
// Sybase doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
// these tables should not be reflected on
systemTableSet.addAll(Arrays.asList(new String[]{
"IJDBC_FUNCTION_ESCAPES", "JDBC_FUNCTION_ESCAPES",
"SPT_IJDBC_CONVERSION", "SPT_IJDBC_MDA", "SPT_IJDBC_TABLE_TYPES",
"SPT_JDBC_CONVERSION", "SPT_JDBC_TABLE_TYPES", "SPT_JTEXT",
"SPT_LIMIT_TYPES", "SPT_MDA", "SPT_MONITOR", "SPT_VALUES",
"SYBLICENSESLOG",
}));
// reserved words specified at:
// http://manuals.sybase.com/onlinebooks/group-as/asg1250e/
// refman/@Generic__BookTextView/26603
reservedWordSet.addAll(Arrays.asList(new String[]{
"ARITH_OVERFLOW", "BREAK", "BROWSE", "BULK", "CHAR_CONVERT",
"CHECKPOINT", "CLUSTERED", "COMPUTE", "CONFIRM", "CONTROLROW",
"DATABASE", "DBCC", "DETERMINISTIC", "DISK DISTINCT", "DUMMY",
"DUMP", "ENDTRAN", "ERRLVL", "ERRORDATA", "ERROREXIT", "EXCLUSIVE",
"EXIT", "EXP_ROW_SIZE", "FILLFACTOR", "FUNC", "FUNCTION",
"HOLDLOCK", "IDENTITY_GAP", "IDENTITY_INSERT", "IDENTITY_START",
"IF", "INDEX", "INOUT", "INSTALL", "INTERSECT", "JAR", "KILL",
"LINENO", "LOAD", "LOCK", "MAX_ROWS_PER_PAGE", "MIRROR",
"MIRROREXIT", "MODIFY", "NEW", "NOHOLDLOCK", "NONCLUSTERED",
"NUMERIC_TRUNCATION", "OFF", "OFFSETS", "ONCE", "ONLINE", "OUT",
"OVER", "PARTITION", "PERM", "PERMANENT", "PLAN", "PRINT", "PROC",
"PROCESSEXIT", "PROXY_TABLE", "QUIESCE", "RAISERROR", "READ",
"READPAST", "READTEXT", "RECONFIGURE", "REFERENCES REMOVE", "REORG",
"REPLACE", "REPLICATION", "RESERVEPAGEGAP", "RETURN", "RETURNS",
"ROLE", "ROWCOUNT", "RULE", "SAVE", "SETUSER", "SHARED",
"SHUTDOWN", "SOME", "STATISTICS", "STRINGSIZE", "STRIPE",
"SYB_IDENTITY", "SYB_RESTREE", "SYB_TERMINATE", "TEMP", "TEXTSIZE",
"TRAN", "TRIGGER", "TRUNCATE", "TSEQUAL", "UNPARTITION", "USE",
"USER_OPTION", "WAITFOR", "WHILE", "WRITETEXT",
}));
// Sybase does not support foreign key delete/update action NULL,
// DEFAULT, CASCADE
supportsNullDeleteAction = false;
supportsDefaultDeleteAction = false;
supportsCascadeDeleteAction = false;
supportsNullUpdateAction = false;
supportsDefaultUpdateAction = false;
supportsCascadeUpdateAction = false;
fixedSizeTypeNameSet.remove("NUMERIC");
}
|
diff --git a/src/com/pilot51/voicenotify/Service.java b/src/com/pilot51/voicenotify/Service.java
index ac4b935..22fbe50 100644
--- a/src/com/pilot51/voicenotify/Service.java
+++ b/src/com/pilot51/voicenotify/Service.java
@@ -1,267 +1,267 @@
package com.pilot51.voicenotify;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.IllegalFormatException;
import java.util.Timer;
import java.util.TimerTask;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.speech.tts.TextToSpeech;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
public class Service extends AccessibilityService {
private Common common;
private String lastMsg = "";
private static final int
SPEAK = 1,
STOP_SPEAK = 2,
START_TTS = 3,
STOP_TTS = 4;
private long lastMsgTime;
private TextToSpeech mTts;
private AudioManager audioMan;
private TelephonyManager telephony;
private HeadsetReceiver headsetReceiver = new HeadsetReceiver();
private boolean isInitialized, isScreenOn, isHeadsetPlugged, isBluetoothConnected;
private HashMap<String, String> ttsParams = new HashMap<String, String>();
private ArrayList<String> ignoredApps, ignoreReasons = new ArrayList<String>();
private Handler ttsHandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case SPEAK:
boolean isNotificationStream = Common.prefs.getString("ttsStream", null).contentEquals("notification");
if (isNotificationStream)
ttsParams.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
mTts.speak((String)message.obj, TextToSpeech.QUEUE_ADD, ttsParams);
if (isNotificationStream) {
ttsParams.clear();
mTts.speak(" ", TextToSpeech.QUEUE_ADD, null);
}
break;
case STOP_SPEAK:
mTts.stop();
break;
case START_TTS:
mTts = new TextToSpeech(Service.this, null);
break;
case STOP_TTS:
mTts.shutdown();
break;
}
}
};
private void setServiceInfo(int feedbackType) {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = feedbackType;
setServiceInfo(info);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
long newMsgTime = System.currentTimeMillis();
PackageManager packMan = getPackageManager();
ApplicationInfo appInfo = new ApplicationInfo();
String pkgName = String.valueOf(event.getPackageName());
try {
appInfo = packMan.getApplicationInfo(pkgName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
ignoredApps = common.readList();
StringBuilder notifyMsg = new StringBuilder();
if (!event.getText().isEmpty())
for (CharSequence subText : event.getText())
notifyMsg.append(subText);
final String label = String.valueOf(appInfo.loadLabel(packMan)),
ttsStringPref = Common.prefs.getString("ttsString", null);
String newMsg;
try {
newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " "));
} catch(IllegalFormatException e) {
Log.w(Common.TAG, "Error formatting custom TTS string!");
e.printStackTrace();
newMsg = ttsStringPref;
}
final String[] ignoreStrings = Common.prefs.getString("ignore_strings", null).split("\n");
boolean stringIgnored = false;
if (ignoreStrings != null) {
for (int i = 0; i < ignoreStrings.length; i++) {
- if (!ignoreStrings[i].isEmpty() && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) {
+ if (ignoreStrings[i].length() != 0 && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) {
stringIgnored = true;
break;
}
}
}
if (ignoredApps.contains(pkgName))
ignoreReasons.add("ignored app (pref.)");
if (stringIgnored)
ignoreReasons.add("ignored string (pref.)");
if (event.getText().isEmpty())
ignoreReasons.add("empty message");
int ignoreRepeat;
try {
ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null));
} catch (NumberFormatException e) {
ignoreRepeat = -1;
}
if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000))
ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)");
if (ignoreReasons.isEmpty()) {
int delay = 0;
try {
delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null));
} catch (NumberFormatException e) {}
if (delay > 0) {
final String msg = newMsg;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
speak(msg);
}
}, delay * 1000);
} else speak(newMsg);
} else {
Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + ignoreReasons.toString().replaceAll("\\[|\\]", ""));
ignoreReasons.clear();
}
lastMsg = newMsg;
lastMsgTime = newMsgTime;
}
/**
* Sends msg to TTS if ignore condition is not met.
* @param msg The string to be spoken.
*/
private void speak(String msg) {
if (ignore()) return;
ttsHandler.obtainMessage(SPEAK, msg).sendToTarget();
}
/**
* Checks for any notification-independent ignore states.
* @returns True if an ignore condition is met, false otherwise.
*/
private boolean ignore() {
Calendar c = Calendar.getInstance();
int calTime = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE),
quietStart = Common.prefs.getInt("quietStart", 0),
quietEnd = Common.prefs.getInt("quietEnd", 0);
if ((quietStart < quietEnd & quietStart <= calTime & calTime < quietEnd)
| (quietEnd < quietStart & (quietStart <= calTime | calTime < quietEnd))) {
ignoreReasons.add("quiet time (pref.)");
}
if (audioMan.getRingerMode() == AudioManager.RINGER_MODE_SILENT
| audioMan.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
ignoreReasons.add("silent or vibrate mode");
}
if (telephony.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK
| telephony.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
ignoreReasons.add("active or ringing call");
}
if (!isScreenOn() & !Common.prefs.getBoolean("speakScreenOff", true)) {
ignoreReasons.add("screen off (pref.)");
}
if (isScreenOn() & !Common.prefs.getBoolean("speakScreenOn", true)) {
ignoreReasons.add("screen on (pref.)");
}
if (!(isHeadsetPlugged | isBluetoothConnected) & !Common.prefs.getBoolean("speakHeadsetOff", true)) {
ignoreReasons.add("headset off (pref.)");
}
if ((isHeadsetPlugged | isBluetoothConnected) & !Common.prefs.getBoolean("speakHeadsetOn", true)) {
ignoreReasons.add("headset on (pref.)");
}
if (!ignoreReasons.isEmpty()) {
Log.i(Common.TAG, "Notification ignored for reason(s): " + ignoreReasons.toString().replaceAll("\\[|\\]", ""));
ignoreReasons.clear();
return true;
}
return false;
}
@Override
public void onInterrupt() {
ttsHandler.sendEmptyMessage(STOP_SPEAK);
}
@Override
public void onServiceConnected() {
if (isInitialized) return;
common = new Common(this);
ttsHandler.sendEmptyMessage(START_TTS);
setServiceInfo(AccessibilityServiceInfo.FEEDBACK_SPOKEN);
audioMan = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
telephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(headsetReceiver, filter);
isInitialized = true;
}
@Override
public boolean onUnbind(Intent intent) {
if (isInitialized) {
ttsHandler.sendEmptyMessage(STOP_TTS);
unregisterReceiver(headsetReceiver);
isInitialized = false;
}
return false;
}
private boolean isScreenOn() {
if (android.os.Build.VERSION.SDK_INT >= 7)
isScreenOn = CheckScreen.isScreenOn(this);
return isScreenOn;
}
private static class CheckScreen {
private static PowerManager powerMan;
private static boolean isScreenOn(Context c) {
if (powerMan == null)
powerMan = (PowerManager)c.getSystemService(Context.POWER_SERVICE);
return powerMan.isScreenOn();
}
}
private class HeadsetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG))
isHeadsetPlugged = intent.getIntExtra("state", 0) == 1;
else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED))
isBluetoothConnected = true;
else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED))
isBluetoothConnected = false;
else if (action.equals(Intent.ACTION_SCREEN_ON))
isScreenOn = true;
else if (action.equals(Intent.ACTION_SCREEN_OFF))
isScreenOn = false;
if (mTts.isSpeaking() && ignore())
ttsHandler.sendEmptyMessage(STOP_SPEAK);
}
}
}
| true | true | public void onAccessibilityEvent(AccessibilityEvent event) {
long newMsgTime = System.currentTimeMillis();
PackageManager packMan = getPackageManager();
ApplicationInfo appInfo = new ApplicationInfo();
String pkgName = String.valueOf(event.getPackageName());
try {
appInfo = packMan.getApplicationInfo(pkgName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
ignoredApps = common.readList();
StringBuilder notifyMsg = new StringBuilder();
if (!event.getText().isEmpty())
for (CharSequence subText : event.getText())
notifyMsg.append(subText);
final String label = String.valueOf(appInfo.loadLabel(packMan)),
ttsStringPref = Common.prefs.getString("ttsString", null);
String newMsg;
try {
newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " "));
} catch(IllegalFormatException e) {
Log.w(Common.TAG, "Error formatting custom TTS string!");
e.printStackTrace();
newMsg = ttsStringPref;
}
final String[] ignoreStrings = Common.prefs.getString("ignore_strings", null).split("\n");
boolean stringIgnored = false;
if (ignoreStrings != null) {
for (int i = 0; i < ignoreStrings.length; i++) {
if (!ignoreStrings[i].isEmpty() && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) {
stringIgnored = true;
break;
}
}
}
if (ignoredApps.contains(pkgName))
ignoreReasons.add("ignored app (pref.)");
if (stringIgnored)
ignoreReasons.add("ignored string (pref.)");
if (event.getText().isEmpty())
ignoreReasons.add("empty message");
int ignoreRepeat;
try {
ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null));
} catch (NumberFormatException e) {
ignoreRepeat = -1;
}
if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000))
ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)");
if (ignoreReasons.isEmpty()) {
int delay = 0;
try {
delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null));
} catch (NumberFormatException e) {}
if (delay > 0) {
final String msg = newMsg;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
speak(msg);
}
}, delay * 1000);
} else speak(newMsg);
} else {
Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + ignoreReasons.toString().replaceAll("\\[|\\]", ""));
ignoreReasons.clear();
}
lastMsg = newMsg;
lastMsgTime = newMsgTime;
}
| public void onAccessibilityEvent(AccessibilityEvent event) {
long newMsgTime = System.currentTimeMillis();
PackageManager packMan = getPackageManager();
ApplicationInfo appInfo = new ApplicationInfo();
String pkgName = String.valueOf(event.getPackageName());
try {
appInfo = packMan.getApplicationInfo(pkgName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
ignoredApps = common.readList();
StringBuilder notifyMsg = new StringBuilder();
if (!event.getText().isEmpty())
for (CharSequence subText : event.getText())
notifyMsg.append(subText);
final String label = String.valueOf(appInfo.loadLabel(packMan)),
ttsStringPref = Common.prefs.getString("ttsString", null);
String newMsg;
try {
newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " "));
} catch(IllegalFormatException e) {
Log.w(Common.TAG, "Error formatting custom TTS string!");
e.printStackTrace();
newMsg = ttsStringPref;
}
final String[] ignoreStrings = Common.prefs.getString("ignore_strings", null).split("\n");
boolean stringIgnored = false;
if (ignoreStrings != null) {
for (int i = 0; i < ignoreStrings.length; i++) {
if (ignoreStrings[i].length() != 0 && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) {
stringIgnored = true;
break;
}
}
}
if (ignoredApps.contains(pkgName))
ignoreReasons.add("ignored app (pref.)");
if (stringIgnored)
ignoreReasons.add("ignored string (pref.)");
if (event.getText().isEmpty())
ignoreReasons.add("empty message");
int ignoreRepeat;
try {
ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null));
} catch (NumberFormatException e) {
ignoreRepeat = -1;
}
if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000))
ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)");
if (ignoreReasons.isEmpty()) {
int delay = 0;
try {
delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null));
} catch (NumberFormatException e) {}
if (delay > 0) {
final String msg = newMsg;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
speak(msg);
}
}, delay * 1000);
} else speak(newMsg);
} else {
Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + ignoreReasons.toString().replaceAll("\\[|\\]", ""));
ignoreReasons.clear();
}
lastMsg = newMsg;
lastMsgTime = newMsgTime;
}
|
diff --git a/src/GameServerGUI.java b/src/GameServerGUI.java
index 959a070..a19942a 100644
--- a/src/GameServerGUI.java
+++ b/src/GameServerGUI.java
@@ -1,355 +1,355 @@
/* CS3283/CS3284 Project
*
* Game Server GUI: simple graphical user interface for the game server
*
*/
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import javax.swing.JTextArea;
import java.awt.Insets;
import java.awt.Color;
import javax.swing.JScrollPane;
import javax.swing.text.DefaultCaret;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import java.awt.Font;
import javax.swing.JTextField;
public class GameServerGUI {
private JFrame frame;
private GameServer gameServer;
private GameServerThread gameServerThread;
JButton startButton = new JButton("Start Server");
JButton closeButton = new JButton("Close Server");
JTextArea JConsole = new JTextArea();
JTextArea JKeyCode = new JTextArea();
JTextArea JPlayer = new JTextArea();
JTextArea JTreasure = new JTextArea();
JTextArea JControlHelp = new JTextArea();
JPanel panelKeyCodePairingList = new JPanel();
JPanel panelTreasureList = new JPanel();
JPanel panelPlayerInfo = new JPanel();
JPanel panelControls = new JPanel();
JButton btnMoveUp = new JButton("^");
JButton btnMoveDown = new JButton("v");
JButton btnMoveLeft = new JButton("<");
JButton btnMoveRight = new JButton(">");
private JTextField textFieldPlayerID;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Starting ProjectKim Server GUI");
GameServerGUI window = new GameServerGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws Exception
*/
public GameServerGUI() throws Exception {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Project Kim Server");
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setResizable(false);
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane JConsoleScrollPane = new JScrollPane();
JConsoleScrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Console", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JConsoleScrollPane.setBounds(10, 253, 429, 305);
DefaultCaret caret = (DefaultCaret)JConsole.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JConsoleScrollPane.setBackground(Color.LIGHT_GRAY);
frame.getContentPane().add(JConsoleScrollPane);
JConsoleScrollPane.setViewportView(JConsole);
JConsole.setMargin(new Insets(5, 5, 5, 5));
JConsole.setRows(5);
JConsole.setEditable(false);
JConsole.setText("Press Start to continue...");
panelKeyCodePairingList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelKeyCodePairingList.setBounds(10, 11, 574, 100);
frame.getContentPane().add(panelKeyCodePairingList);
panelKeyCodePairingList.setLayout(new BorderLayout(0, 0));
JKeyCode.setLineWrap(true);
JKeyCode.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Key Code pairing list", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JKeyCode.setEditable(false);
JKeyCode.setMargin(new Insets(5, 5, 5, 5));
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
panelKeyCodePairingList.add(JKeyCode, BorderLayout.CENTER);
panelTreasureList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelTreasureList.setBounds(10, 132, 170, 100);
frame.getContentPane().add(panelTreasureList);
panelTreasureList.setLayout(new BorderLayout(0, 0));
JTreasure.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Treasure List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelTreasureList.add(JTreasure, BorderLayout.CENTER);
JTreasure.setEditable(false);
JTreasure.setMargin(new Insets(5, 5, 5, 5));
- JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\nhas treasure chest");
+ JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\n1: has treasure chest");
panelPlayerInfo.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelPlayerInfo.setBounds(200, 132, 384, 100);
frame.getContentPane().add(panelPlayerInfo);
panelPlayerInfo.setLayout(new BorderLayout(0, 0));
JPlayer.setBorder(new TitledBorder(null, "Player Infomation", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelPlayerInfo.add(JPlayer, BorderLayout.CENTER);
JPlayer.setEditable(false);
JPlayer.setMargin(new Insets(5, 5, 5, 5));
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
panelControls.setBackground(Color.LIGHT_GRAY);
panelControls.setBorder(new TitledBorder(null, "Controls", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelControls.setBounds(449, 253, 135, 305);
frame.getContentPane().add(panelControls);
btnMoveUp.setFont(new Font("Tahoma", Font.BOLD, 11));
btnMoveUp.setBounds(52, 89, 30, 30);
btnMoveUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,0);
}
});
panelControls.setLayout(null);
panelControls.add(btnMoveUp);
btnMoveUp.setMargin(new Insets(2, 2, 2, 2));
btnMoveUp.setEnabled(false);
btnMoveDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,1);
}
});
btnMoveDown.setBounds(52, 171, 30, 30);
panelControls.add(btnMoveDown);
btnMoveDown.setMargin(new Insets(2, 2, 2, 2));
btnMoveDown.setEnabled(false);
btnMoveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,2);
}
});
btnMoveLeft.setBounds(10, 130, 30, 30);
panelControls.add(btnMoveLeft);
btnMoveLeft.setMargin(new Insets(2, 2, 2, 2));
btnMoveLeft.setEnabled(false);
btnMoveRight.setBounds(95, 130, 30, 30);
panelControls.add(btnMoveRight);
btnMoveRight.setMargin(new Insets(2, 2, 2, 2));
btnMoveRight.setEnabled(false);
closeButton.setBounds(10, 55, 115, 23);
panelControls.add(closeButton);
closeButton.setMargin(new Insets(2, 5, 2, 5));
closeButton.setEnabled(false);
startButton.setBounds(10, 21, 115, 23);
panelControls.add(startButton);
startButton.setMargin(new Insets(2, 5, 2, 5));
textFieldPlayerID = new JTextField();
textFieldPlayerID.setText("1");
textFieldPlayerID.setEnabled(false);
textFieldPlayerID.setMargin(new Insets(5, 9, 5, 9));
textFieldPlayerID.setBounds(52, 130, 30, 30);
panelControls.add(textFieldPlayerID);
textFieldPlayerID.setColumns(10);
JTextArea JControlHelp = new JTextArea();
JControlHelp.setMargin(new Insets(2, 5, 2, 5));
JControlHelp.setEditable(false);
JControlHelp.setText("Remote controls:\r\nEnter playerID\r\nPress the buttons \r\nto move around ");
JControlHelp.setBounds(10, 212, 115, 82);
panelControls.add(JControlHelp);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
startButton.setEnabled(false);
closeButton.setEnabled(true);
btnMoveUp.setEnabled(true);
btnMoveDown.setEnabled(true);
btnMoveLeft.setEnabled(true);
btnMoveRight.setEnabled(true);
textFieldPlayerID.setEnabled(true);
gameServerThread = new GameServerThread();
gameServerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//connectThread.stop();
startButton.setEnabled(true);
closeButton.setEnabled(false);
btnMoveUp.setEnabled(false);
btnMoveDown.setEnabled(false);
btnMoveLeft.setEnabled(false);
btnMoveRight.setEnabled(false);
textFieldPlayerID.setEnabled(false);
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
- JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\nhas treasure chest");
+ JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\n1: has treasure chest");
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
gameServer.disconnect();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnMoveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,3);
}
});
}
class GameServerThread extends Thread {
public void run() {
System.out.println("GUI initiatised!");
try {
gameServer = new GameServer();
gameServer.connect();
} catch (Exception e) {
//
e.printStackTrace();
}
}
}
// Game Server: feedback to client's requests through UDP connections
class GameServer {
private EventHandler eventHandler;
private DatagramSocket socket ;
public void connect() throws Exception {
System.out.println("Game Server starting up... ");
JConsole.setText("Press Start to continue...\nGame Server starting up... ");
/* *** Initialization *** */
String reply = ""; // stores the reply info
eventHandler = new EventHandler();
JPlayer.setText(eventHandler.getPlayerInfoString());
JKeyCode.setText(eventHandler.getKeyCodeString());
JTreasure.setText(eventHandler.getTreasureInfoString());
//use DatagramSocket for UDP connection
//@SuppressWarnings("resource")
socket = new DatagramSocket(9001);
byte[] incomingBuffer = new byte[1000];
// Constantly receiving incoming packets
while (true)
{
JConsole.setText(JConsole.getText() + "\nWaiting for incoming packet from game client... ");
DatagramPacket incomingPacket = new DatagramPacket(incomingBuffer, incomingBuffer.length);
socket.receive(incomingPacket);
// convert content of packet into a string
String request = new String(incomingPacket.getData(), 0, incomingPacket.getLength() );
/* ----------------------------------------------------- */
// pass client request to event handler to compute results
reply = eventHandler.computeEventsReply(request);
/* ----------------------------------------------------- */
// convert reply into array of bytes (output buffer)
byte[] outputBuffer = new byte[1000];
outputBuffer = reply.getBytes();
// create reply packet using output buffer.
// Note: destination address/port is retrieved from incomingPacket
DatagramPacket outPacket = new DatagramPacket(outputBuffer, outputBuffer.length, incomingPacket.getAddress(), incomingPacket.getPort());
// finally, send the packet
socket.send(outPacket);
System.out.println("Sent reply: " + reply + " [GamerServer.java]");
JConsole.setText(JConsole.getText() + "\nSent reply: " + reply);
JPlayer.setText(eventHandler.getPlayerInfoString());
JTreasure.setText(eventHandler.getTreasureInfoString());
}
}
public void movePlayer(int playerID, int direction) {
eventHandler.movePlayer(playerID, direction);
JPlayer.setText(eventHandler.getPlayerInfoString());
}
String getPlayerInfoString(){
return eventHandler.getPlayerInfoString();
}
String getTreasureInfoString(){
return eventHandler.getTreasureInfoString();
}
public void disconnect() throws Exception {
JConsole.setText(JConsole.getText() + "\nClosing server\nPress Start to continue...");
//socket.disconnect();
socket.close();
//connectThread.destroy();
}
}
}
| false | true | private void initialize() {
frame = new JFrame("Project Kim Server");
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setResizable(false);
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane JConsoleScrollPane = new JScrollPane();
JConsoleScrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Console", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JConsoleScrollPane.setBounds(10, 253, 429, 305);
DefaultCaret caret = (DefaultCaret)JConsole.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JConsoleScrollPane.setBackground(Color.LIGHT_GRAY);
frame.getContentPane().add(JConsoleScrollPane);
JConsoleScrollPane.setViewportView(JConsole);
JConsole.setMargin(new Insets(5, 5, 5, 5));
JConsole.setRows(5);
JConsole.setEditable(false);
JConsole.setText("Press Start to continue...");
panelKeyCodePairingList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelKeyCodePairingList.setBounds(10, 11, 574, 100);
frame.getContentPane().add(panelKeyCodePairingList);
panelKeyCodePairingList.setLayout(new BorderLayout(0, 0));
JKeyCode.setLineWrap(true);
JKeyCode.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Key Code pairing list", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JKeyCode.setEditable(false);
JKeyCode.setMargin(new Insets(5, 5, 5, 5));
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
panelKeyCodePairingList.add(JKeyCode, BorderLayout.CENTER);
panelTreasureList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelTreasureList.setBounds(10, 132, 170, 100);
frame.getContentPane().add(panelTreasureList);
panelTreasureList.setLayout(new BorderLayout(0, 0));
JTreasure.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Treasure List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelTreasureList.add(JTreasure, BorderLayout.CENTER);
JTreasure.setEditable(false);
JTreasure.setMargin(new Insets(5, 5, 5, 5));
JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\nhas treasure chest");
panelPlayerInfo.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelPlayerInfo.setBounds(200, 132, 384, 100);
frame.getContentPane().add(panelPlayerInfo);
panelPlayerInfo.setLayout(new BorderLayout(0, 0));
JPlayer.setBorder(new TitledBorder(null, "Player Infomation", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelPlayerInfo.add(JPlayer, BorderLayout.CENTER);
JPlayer.setEditable(false);
JPlayer.setMargin(new Insets(5, 5, 5, 5));
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
panelControls.setBackground(Color.LIGHT_GRAY);
panelControls.setBorder(new TitledBorder(null, "Controls", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelControls.setBounds(449, 253, 135, 305);
frame.getContentPane().add(panelControls);
btnMoveUp.setFont(new Font("Tahoma", Font.BOLD, 11));
btnMoveUp.setBounds(52, 89, 30, 30);
btnMoveUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,0);
}
});
panelControls.setLayout(null);
panelControls.add(btnMoveUp);
btnMoveUp.setMargin(new Insets(2, 2, 2, 2));
btnMoveUp.setEnabled(false);
btnMoveDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,1);
}
});
btnMoveDown.setBounds(52, 171, 30, 30);
panelControls.add(btnMoveDown);
btnMoveDown.setMargin(new Insets(2, 2, 2, 2));
btnMoveDown.setEnabled(false);
btnMoveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,2);
}
});
btnMoveLeft.setBounds(10, 130, 30, 30);
panelControls.add(btnMoveLeft);
btnMoveLeft.setMargin(new Insets(2, 2, 2, 2));
btnMoveLeft.setEnabled(false);
btnMoveRight.setBounds(95, 130, 30, 30);
panelControls.add(btnMoveRight);
btnMoveRight.setMargin(new Insets(2, 2, 2, 2));
btnMoveRight.setEnabled(false);
closeButton.setBounds(10, 55, 115, 23);
panelControls.add(closeButton);
closeButton.setMargin(new Insets(2, 5, 2, 5));
closeButton.setEnabled(false);
startButton.setBounds(10, 21, 115, 23);
panelControls.add(startButton);
startButton.setMargin(new Insets(2, 5, 2, 5));
textFieldPlayerID = new JTextField();
textFieldPlayerID.setText("1");
textFieldPlayerID.setEnabled(false);
textFieldPlayerID.setMargin(new Insets(5, 9, 5, 9));
textFieldPlayerID.setBounds(52, 130, 30, 30);
panelControls.add(textFieldPlayerID);
textFieldPlayerID.setColumns(10);
JTextArea JControlHelp = new JTextArea();
JControlHelp.setMargin(new Insets(2, 5, 2, 5));
JControlHelp.setEditable(false);
JControlHelp.setText("Remote controls:\r\nEnter playerID\r\nPress the buttons \r\nto move around ");
JControlHelp.setBounds(10, 212, 115, 82);
panelControls.add(JControlHelp);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
startButton.setEnabled(false);
closeButton.setEnabled(true);
btnMoveUp.setEnabled(true);
btnMoveDown.setEnabled(true);
btnMoveLeft.setEnabled(true);
btnMoveRight.setEnabled(true);
textFieldPlayerID.setEnabled(true);
gameServerThread = new GameServerThread();
gameServerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//connectThread.stop();
startButton.setEnabled(true);
closeButton.setEnabled(false);
btnMoveUp.setEnabled(false);
btnMoveDown.setEnabled(false);
btnMoveLeft.setEnabled(false);
btnMoveRight.setEnabled(false);
textFieldPlayerID.setEnabled(false);
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\nhas treasure chest");
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
gameServer.disconnect();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnMoveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,3);
}
});
}
| private void initialize() {
frame = new JFrame("Project Kim Server");
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setResizable(false);
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane JConsoleScrollPane = new JScrollPane();
JConsoleScrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Console", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JConsoleScrollPane.setBounds(10, 253, 429, 305);
DefaultCaret caret = (DefaultCaret)JConsole.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JConsoleScrollPane.setBackground(Color.LIGHT_GRAY);
frame.getContentPane().add(JConsoleScrollPane);
JConsoleScrollPane.setViewportView(JConsole);
JConsole.setMargin(new Insets(5, 5, 5, 5));
JConsole.setRows(5);
JConsole.setEditable(false);
JConsole.setText("Press Start to continue...");
panelKeyCodePairingList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelKeyCodePairingList.setBounds(10, 11, 574, 100);
frame.getContentPane().add(panelKeyCodePairingList);
panelKeyCodePairingList.setLayout(new BorderLayout(0, 0));
JKeyCode.setLineWrap(true);
JKeyCode.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Key Code pairing list", TitledBorder.LEADING, TitledBorder.TOP, null, null));
JKeyCode.setEditable(false);
JKeyCode.setMargin(new Insets(5, 5, 5, 5));
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
panelKeyCodePairingList.add(JKeyCode, BorderLayout.CENTER);
panelTreasureList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelTreasureList.setBounds(10, 132, 170, 100);
frame.getContentPane().add(panelTreasureList);
panelTreasureList.setLayout(new BorderLayout(0, 0));
JTreasure.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Treasure List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelTreasureList.add(JTreasure, BorderLayout.CENTER);
JTreasure.setEditable(false);
JTreasure.setMargin(new Insets(5, 5, 5, 5));
JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\n1: has treasure chest");
panelPlayerInfo.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panelPlayerInfo.setBounds(200, 132, 384, 100);
frame.getContentPane().add(panelPlayerInfo);
panelPlayerInfo.setLayout(new BorderLayout(0, 0));
JPlayer.setBorder(new TitledBorder(null, "Player Infomation", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelPlayerInfo.add(JPlayer, BorderLayout.CENTER);
JPlayer.setEditable(false);
JPlayer.setMargin(new Insets(5, 5, 5, 5));
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
panelControls.setBackground(Color.LIGHT_GRAY);
panelControls.setBorder(new TitledBorder(null, "Controls", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelControls.setBounds(449, 253, 135, 305);
frame.getContentPane().add(panelControls);
btnMoveUp.setFont(new Font("Tahoma", Font.BOLD, 11));
btnMoveUp.setBounds(52, 89, 30, 30);
btnMoveUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,0);
}
});
panelControls.setLayout(null);
panelControls.add(btnMoveUp);
btnMoveUp.setMargin(new Insets(2, 2, 2, 2));
btnMoveUp.setEnabled(false);
btnMoveDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,1);
}
});
btnMoveDown.setBounds(52, 171, 30, 30);
panelControls.add(btnMoveDown);
btnMoveDown.setMargin(new Insets(2, 2, 2, 2));
btnMoveDown.setEnabled(false);
btnMoveLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,2);
}
});
btnMoveLeft.setBounds(10, 130, 30, 30);
panelControls.add(btnMoveLeft);
btnMoveLeft.setMargin(new Insets(2, 2, 2, 2));
btnMoveLeft.setEnabled(false);
btnMoveRight.setBounds(95, 130, 30, 30);
panelControls.add(btnMoveRight);
btnMoveRight.setMargin(new Insets(2, 2, 2, 2));
btnMoveRight.setEnabled(false);
closeButton.setBounds(10, 55, 115, 23);
panelControls.add(closeButton);
closeButton.setMargin(new Insets(2, 5, 2, 5));
closeButton.setEnabled(false);
startButton.setBounds(10, 21, 115, 23);
panelControls.add(startButton);
startButton.setMargin(new Insets(2, 5, 2, 5));
textFieldPlayerID = new JTextField();
textFieldPlayerID.setText("1");
textFieldPlayerID.setEnabled(false);
textFieldPlayerID.setMargin(new Insets(5, 9, 5, 9));
textFieldPlayerID.setBounds(52, 130, 30, 30);
panelControls.add(textFieldPlayerID);
textFieldPlayerID.setColumns(10);
JTextArea JControlHelp = new JTextArea();
JControlHelp.setMargin(new Insets(2, 5, 2, 5));
JControlHelp.setEditable(false);
JControlHelp.setText("Remote controls:\r\nEnter playerID\r\nPress the buttons \r\nto move around ");
JControlHelp.setBounds(10, 212, 115, 82);
panelControls.add(JControlHelp);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
startButton.setEnabled(false);
closeButton.setEnabled(true);
btnMoveUp.setEnabled(true);
btnMoveDown.setEnabled(true);
btnMoveLeft.setEnabled(true);
btnMoveRight.setEnabled(true);
textFieldPlayerID.setEnabled(true);
gameServerThread = new GameServerThread();
gameServerThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//connectThread.stop();
startButton.setEnabled(true);
closeButton.setEnabled(false);
btnMoveUp.setEnabled(false);
btnMoveDown.setEnabled(false);
btnMoveLeft.setEnabled(false);
btnMoveRight.setEnabled(false);
textFieldPlayerID.setEnabled(false);
JKeyCode.setText("Displays all KeyCodes paired with their respective Node\n"
+ "KeyCode: 1234 Node: 16\nKeyCode pair: 1234[16]\n"
+"Each KeyCode can only be use once by each player");
JTreasure.setText("Displays treasure chests\nlocated at each Node\n0: no treasure chest\n1: has treasure chest");
JPlayer.setText("Display infomation of all players in the game\n" +"Example:\n"
+"Player 0: logon: ? Score: ? keysHeld: ? Location: ?\n");
gameServer.disconnect();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnMoveRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int playerID = Integer.parseInt(textFieldPlayerID.getText());
if(playerID >= 0 && playerID <=3 )
gameServer.movePlayer(playerID,3);
}
});
}
|
diff --git a/libraries/javalib/gnu/xml/transform/StreamSerializer.java b/libraries/javalib/gnu/xml/transform/StreamSerializer.java
index bc018b796..46bded37c 100644
--- a/libraries/javalib/gnu/xml/transform/StreamSerializer.java
+++ b/libraries/javalib/gnu/xml/transform/StreamSerializer.java
@@ -1,634 +1,635 @@
/* StreamSerializer.java --
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.transform;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Serializes a DOM node to an output stream.
*
* @author <a href='mailto:[email protected]'>Chris Burdess</a>
*/
public class StreamSerializer
{
static final int SPACE = 0x20;
static final int BANG = 0x21; // !
static final int APOS = 0x27; // '
static final int SLASH = 0x2f; // /
static final int BRA = 0x3c; // <
static final int KET = 0x3e; // >
static final int EQ = 0x3d; // =
protected final String encoding;
final Charset charset;
final CharsetEncoder encoder;
final int mode;
final Map namespaces;
protected String eol;
Collection cdataSectionElements = Collections.EMPTY_SET;
protected boolean discardDefaultContent;
protected boolean xmlDeclaration = true;
public StreamSerializer()
{
this(Stylesheet.OUTPUT_XML, null, null);
}
public StreamSerializer(String encoding)
{
this(Stylesheet.OUTPUT_XML, encoding, null);
}
public StreamSerializer(int mode, String encoding, String eol)
{
this.mode = mode;
if (encoding == null)
{
encoding = "UTF-8";
}
this.encoding = encoding.intern();
charset = Charset.forName(this.encoding);
encoder = charset.newEncoder();
this.eol = (eol != null) ? eol : System.getProperty("line.separator");
namespaces = new HashMap();
}
void setCdataSectionElements(Collection c)
{
cdataSectionElements = c;
}
public void serialize(final Node node, final OutputStream out)
throws IOException
{
serialize(node, out, false);
}
void serialize(final Node node, final OutputStream out,
boolean convertToCdata)
throws IOException
{
if (out == null)
{
throw new NullPointerException("no output stream");
}
String value, prefix;
Node children;
Node next = node.getNextSibling();
String uri = node.getNamespaceURI();
boolean defined = false;
short nt = node.getNodeType();
if (convertToCdata && nt == Node.TEXT_NODE)
{
nt = Node.CDATA_SECTION_NODE;
}
switch (nt)
{
case Node.ATTRIBUTE_NODE:
prefix = node.getPrefix();
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) ||
(prefix != null && prefix.startsWith("xmlns:")))
{
String nsuri = node.getNodeValue();
if (isDefined(nsuri))
{
break;
}
define(nsuri, node.getLocalName());
}
else if (uri != null && !isDefined(uri))
{
prefix = define(uri, prefix);
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(nsvalue.getBytes(encoding));
defined = true;
}
out.write(SPACE);
String a_nodeName = node.getNodeName();
out.write(encodeText(a_nodeName));
String a_nodeValue = node.getNodeValue();
if (mode == Stylesheet.OUTPUT_HTML &&
a_nodeName.equals(a_nodeValue))
{
break;
}
out.write(EQ);
value = "'" + encode(a_nodeValue, true, true) + "'";
out.write(encodeText(value));
break;
case Node.ELEMENT_NODE:
value = node.getNodeName();
out.write(BRA);
out.write(encodeText(value));
if (uri != null && !isDefined(uri))
{
prefix = define(uri, node.getPrefix());
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(encodeText(nsvalue));
defined = true;
}
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
int len = attrs.getLength();
for (int i = 0; i < len; i++)
{
Attr attr = (Attr) attrs.item(i);
if (discardDefaultContent && !attr.getSpecified())
{
// NOOP
}
else
{
serialize(attr, out, false);
}
}
}
convertToCdata = cdataSectionElements.contains(value);
children = node.getFirstChild();
if (children == null)
{
out.write(SLASH);
out.write(KET);
}
else
{
out.write(KET);
serialize(children, out, convertToCdata);
out.write(BRA);
out.write(SLASH);
out.write(encodeText(value));
out.write(KET);
}
break;
case Node.TEXT_NODE:
value = node.getNodeValue();
if (!"yes".equals(node.getUserData("disable-output-escaping")))
{
value = encode(value, false, false);
}
out.write(encodeText(value));
break;
case Node.CDATA_SECTION_NODE:
value = "<![CDATA[" + node.getNodeValue() + "]]>";
out.write(encodeText(value));
break;
case Node.COMMENT_NODE:
value = "<!--" + node.getNodeValue() + "-->";
out.write(encodeText(value));
Node cp = node.getParentNode();
if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
if (mode == Stylesheet.OUTPUT_XML)
{
if ("UTF-16".equalsIgnoreCase(encoding))
{
out.write(0xfe);
out.write(0xff);
}
if (!"yes".equals(node.getUserData("omit-xml-declaration")) &&
xmlDeclaration)
{
Document doc = (node instanceof Document) ?
(Document) node : null;
String version = (doc != null) ? doc.getXmlVersion() : null;
if (version == null)
{
version = (String) node.getUserData("version");
}
if (version == null)
{
version = "1.0";
}
out.write(BRA);
out.write(0x3f);
out.write("xml version='".getBytes("US-ASCII"));
out.write(version.getBytes("US-ASCII"));
out.write(APOS);
if (!("UTF-8".equalsIgnoreCase(encoding)))
{
out.write(" encoding='".getBytes("US-ASCII"));
out.write(encoding.getBytes("US-ASCII"));
out.write(APOS);
}
if ((doc != null && doc.getXmlStandalone()) ||
"yes".equals(node.getUserData("standalone")))
{
out.write(" standalone='yes'".getBytes("US-ASCII"));
}
out.write(0x3f);
out.write(KET);
out.write(encodeText(eol));
}
// TODO warn if not outputting the declaration would be a
// problem
}
else if (mode == Stylesheet.OUTPUT_HTML)
{
// Ensure that encoding is accessible
String mediaType = (String) node.getUserData("media-type");
if (mediaType == null)
{
mediaType = "text/html";
}
String contentType = mediaType + "; charset=" +
((encoding.indexOf(' ') != -1) ?
"\"" + encoding + "\"" :
encoding);
Document doc = (node instanceof Document) ? (Document) node :
node.getOwnerDocument();
Node html = null;
for (Node ctx = node.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
html = ctx;
break;
}
}
if (html == null)
{
html = doc.createElement("html");
node.appendChild(html);
}
Node head = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"head".equalsIgnoreCase(ctx.getLocalName()))
{
head = ctx;
break;
}
}
if (head == null)
{
head = doc.createElement("head");
Node c1 = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
c1 = ctx;
break;
}
}
if (c1 != null)
{
html.insertBefore(head, c1);
}
else
{
html.appendChild(head);
}
}
Node meta = null;
Node metaContent = null;
for (Node ctx = head.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"meta".equalsIgnoreCase(ctx.getLocalName()))
{
NamedNodeMap metaAttrs = ctx.getAttributes();
int len = metaAttrs.getLength();
String httpEquiv = null;
Node content = null;
for (int i = 0; i < len; i++)
{
Node attr = metaAttrs.item(i);
String attrName = attr.getNodeName();
if ("http-equiv".equalsIgnoreCase(attrName))
{
httpEquiv = attr.getNodeValue();
}
else if ("content".equalsIgnoreCase(attrName))
{
content = attr;
}
}
if ("Content-Type".equalsIgnoreCase(httpEquiv))
{
meta = ctx;
metaContent = content;
break;
}
}
}
if (meta == null)
{
meta = doc.createElement("meta");
// Insert first
Node first = head.getFirstChild();
if (first == null)
{
head.appendChild(meta);
}
else
{
head.insertBefore(meta, first);
}
Node metaHttpEquiv = doc.createAttribute("http-equiv");
meta.getAttributes().setNamedItem(metaHttpEquiv);
metaHttpEquiv.setNodeValue("Content-Type");
}
if (metaContent == null)
{
metaContent = doc.createAttribute("content");
meta.getAttributes().setNamedItem(metaContent);
}
metaContent.setNodeValue(contentType);
// phew
}
children = node.getFirstChild();
if (children != null)
{
serialize(children, out, convertToCdata);
}
break;
case Node.DOCUMENT_TYPE_NODE:
DocumentType doctype = (DocumentType) node;
out.write(BRA);
out.write(BANG);
+ out.write(encodeText("DOCTYPE "));
value = doctype.getNodeName();
out.write(encodeText(value));
String publicId = doctype.getPublicId();
if (publicId != null)
{
out.write(encodeText(" PUBLIC "));
out.write(APOS);
out.write(encodeText(publicId));
out.write(APOS);
}
String systemId = doctype.getSystemId();
if (systemId != null)
{
out.write(encodeText(" SYSTEM "));
out.write(APOS);
out.write(encodeText(systemId));
out.write(APOS);
}
String internalSubset = doctype.getInternalSubset();
if (internalSubset != null)
{
out.write(encodeText(internalSubset));
}
out.write(KET);
out.write(eol.getBytes(encoding));
break;
case Node.ENTITY_REFERENCE_NODE:
value = "&" + node.getNodeValue() + ";";
out.write(encodeText(value));
break;
case Node.PROCESSING_INSTRUCTION_NODE:
value = "<?" + node.getNodeName() + " " + node.getNodeValue() + "?>";
out.write(encodeText(value));
Node pp = node.getParentNode();
if (pp != null && pp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
}
if (defined)
{
undefine(uri);
}
if (next != null)
{
serialize(next, out, convertToCdata);
}
}
boolean isDefined(String uri)
{
return XMLConstants.XML_NS_URI.equals(uri) ||
XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
namespaces.containsKey(uri);
}
String define(String uri, String prefix)
{
while (namespaces.containsValue(prefix))
{
// Fabricate new prefix
prefix = prefix + "_";
}
namespaces.put(uri, prefix);
return prefix;
}
void undefine(String uri)
{
namespaces.remove(uri);
}
final byte[] encodeText(String text)
throws IOException
{
encoder.reset();
if (!encoder.canEncode(text))
{
// Check each character
StringBuffer buf = new StringBuffer();
int len = text.length();
for (int i = 0; i < len; i++)
{
char c = text.charAt(i);
if (encoder.canEncode(c))
{
buf.append(c);
}
else
{
// Replace with character entity reference
String hex = Integer.toHexString((int) c);
buf.append("&#x");
buf.append(hex);
buf.append(';');
}
}
text = buf.toString();
}
ByteBuffer encoded = encoder.encode(CharBuffer.wrap(text));
if (encoded.hasArray())
{
return encoded.array();
}
encoded.flip();
int len = encoded.limit() - encoded.position();
byte[] ret = new byte[len];
encoded.get(ret, 0, len);
return ret;
}
String encode(String text, boolean encodeCtl, boolean inAttr)
{
int len = text.length();
StringBuffer buf = null;
for (int i = 0; i < len; i++)
{
char c = text.charAt(i);
if (c == '<')
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append("<");
}
else if (c == '>')
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append(">");
}
else if (c == '&')
{
if (mode == Stylesheet.OUTPUT_HTML && (i + 1) < len &&
text.charAt(i + 1) == '{')
{
if (buf != null)
{
buf.append(c);
}
}
else
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append("&");
}
}
else if (c == '\'' && inAttr)
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append("'");
}
else if (c == '"' && inAttr)
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append(""");
}
else if (encodeCtl)
{
if (c < 0x20)
{
if (buf == null)
{
buf = new StringBuffer(text.substring(0, i));
}
buf.append('&');
buf.append('#');
buf.append((int) c);
buf.append(';');
}
else if (buf != null)
{
buf.append(c);
}
}
else if (buf != null)
{
buf.append(c);
}
}
return (buf == null) ? text : buf.toString();
}
String toString(Node node)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
serialize(node, out);
return new String(out.toByteArray(), encoding);
}
catch (IOException e)
{
throw new RuntimeException(e.getMessage());
}
}
}
| true | true | void serialize(final Node node, final OutputStream out,
boolean convertToCdata)
throws IOException
{
if (out == null)
{
throw new NullPointerException("no output stream");
}
String value, prefix;
Node children;
Node next = node.getNextSibling();
String uri = node.getNamespaceURI();
boolean defined = false;
short nt = node.getNodeType();
if (convertToCdata && nt == Node.TEXT_NODE)
{
nt = Node.CDATA_SECTION_NODE;
}
switch (nt)
{
case Node.ATTRIBUTE_NODE:
prefix = node.getPrefix();
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) ||
(prefix != null && prefix.startsWith("xmlns:")))
{
String nsuri = node.getNodeValue();
if (isDefined(nsuri))
{
break;
}
define(nsuri, node.getLocalName());
}
else if (uri != null && !isDefined(uri))
{
prefix = define(uri, prefix);
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(nsvalue.getBytes(encoding));
defined = true;
}
out.write(SPACE);
String a_nodeName = node.getNodeName();
out.write(encodeText(a_nodeName));
String a_nodeValue = node.getNodeValue();
if (mode == Stylesheet.OUTPUT_HTML &&
a_nodeName.equals(a_nodeValue))
{
break;
}
out.write(EQ);
value = "'" + encode(a_nodeValue, true, true) + "'";
out.write(encodeText(value));
break;
case Node.ELEMENT_NODE:
value = node.getNodeName();
out.write(BRA);
out.write(encodeText(value));
if (uri != null && !isDefined(uri))
{
prefix = define(uri, node.getPrefix());
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(encodeText(nsvalue));
defined = true;
}
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
int len = attrs.getLength();
for (int i = 0; i < len; i++)
{
Attr attr = (Attr) attrs.item(i);
if (discardDefaultContent && !attr.getSpecified())
{
// NOOP
}
else
{
serialize(attr, out, false);
}
}
}
convertToCdata = cdataSectionElements.contains(value);
children = node.getFirstChild();
if (children == null)
{
out.write(SLASH);
out.write(KET);
}
else
{
out.write(KET);
serialize(children, out, convertToCdata);
out.write(BRA);
out.write(SLASH);
out.write(encodeText(value));
out.write(KET);
}
break;
case Node.TEXT_NODE:
value = node.getNodeValue();
if (!"yes".equals(node.getUserData("disable-output-escaping")))
{
value = encode(value, false, false);
}
out.write(encodeText(value));
break;
case Node.CDATA_SECTION_NODE:
value = "<![CDATA[" + node.getNodeValue() + "]]>";
out.write(encodeText(value));
break;
case Node.COMMENT_NODE:
value = "<!--" + node.getNodeValue() + "-->";
out.write(encodeText(value));
Node cp = node.getParentNode();
if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
if (mode == Stylesheet.OUTPUT_XML)
{
if ("UTF-16".equalsIgnoreCase(encoding))
{
out.write(0xfe);
out.write(0xff);
}
if (!"yes".equals(node.getUserData("omit-xml-declaration")) &&
xmlDeclaration)
{
Document doc = (node instanceof Document) ?
(Document) node : null;
String version = (doc != null) ? doc.getXmlVersion() : null;
if (version == null)
{
version = (String) node.getUserData("version");
}
if (version == null)
{
version = "1.0";
}
out.write(BRA);
out.write(0x3f);
out.write("xml version='".getBytes("US-ASCII"));
out.write(version.getBytes("US-ASCII"));
out.write(APOS);
if (!("UTF-8".equalsIgnoreCase(encoding)))
{
out.write(" encoding='".getBytes("US-ASCII"));
out.write(encoding.getBytes("US-ASCII"));
out.write(APOS);
}
if ((doc != null && doc.getXmlStandalone()) ||
"yes".equals(node.getUserData("standalone")))
{
out.write(" standalone='yes'".getBytes("US-ASCII"));
}
out.write(0x3f);
out.write(KET);
out.write(encodeText(eol));
}
// TODO warn if not outputting the declaration would be a
// problem
}
else if (mode == Stylesheet.OUTPUT_HTML)
{
// Ensure that encoding is accessible
String mediaType = (String) node.getUserData("media-type");
if (mediaType == null)
{
mediaType = "text/html";
}
String contentType = mediaType + "; charset=" +
((encoding.indexOf(' ') != -1) ?
"\"" + encoding + "\"" :
encoding);
Document doc = (node instanceof Document) ? (Document) node :
node.getOwnerDocument();
Node html = null;
for (Node ctx = node.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
html = ctx;
break;
}
}
if (html == null)
{
html = doc.createElement("html");
node.appendChild(html);
}
Node head = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"head".equalsIgnoreCase(ctx.getLocalName()))
{
head = ctx;
break;
}
}
if (head == null)
{
head = doc.createElement("head");
Node c1 = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
c1 = ctx;
break;
}
}
if (c1 != null)
{
html.insertBefore(head, c1);
}
else
{
html.appendChild(head);
}
}
Node meta = null;
Node metaContent = null;
for (Node ctx = head.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"meta".equalsIgnoreCase(ctx.getLocalName()))
{
NamedNodeMap metaAttrs = ctx.getAttributes();
int len = metaAttrs.getLength();
String httpEquiv = null;
Node content = null;
for (int i = 0; i < len; i++)
{
Node attr = metaAttrs.item(i);
String attrName = attr.getNodeName();
if ("http-equiv".equalsIgnoreCase(attrName))
{
httpEquiv = attr.getNodeValue();
}
else if ("content".equalsIgnoreCase(attrName))
{
content = attr;
}
}
if ("Content-Type".equalsIgnoreCase(httpEquiv))
{
meta = ctx;
metaContent = content;
break;
}
}
}
if (meta == null)
{
meta = doc.createElement("meta");
// Insert first
Node first = head.getFirstChild();
if (first == null)
{
head.appendChild(meta);
}
else
{
head.insertBefore(meta, first);
}
Node metaHttpEquiv = doc.createAttribute("http-equiv");
meta.getAttributes().setNamedItem(metaHttpEquiv);
metaHttpEquiv.setNodeValue("Content-Type");
}
if (metaContent == null)
{
metaContent = doc.createAttribute("content");
meta.getAttributes().setNamedItem(metaContent);
}
metaContent.setNodeValue(contentType);
// phew
}
children = node.getFirstChild();
if (children != null)
{
serialize(children, out, convertToCdata);
}
break;
case Node.DOCUMENT_TYPE_NODE:
DocumentType doctype = (DocumentType) node;
out.write(BRA);
out.write(BANG);
value = doctype.getNodeName();
out.write(encodeText(value));
String publicId = doctype.getPublicId();
if (publicId != null)
{
out.write(encodeText(" PUBLIC "));
out.write(APOS);
out.write(encodeText(publicId));
out.write(APOS);
}
String systemId = doctype.getSystemId();
if (systemId != null)
{
out.write(encodeText(" SYSTEM "));
out.write(APOS);
out.write(encodeText(systemId));
out.write(APOS);
}
String internalSubset = doctype.getInternalSubset();
if (internalSubset != null)
{
out.write(encodeText(internalSubset));
}
out.write(KET);
out.write(eol.getBytes(encoding));
break;
case Node.ENTITY_REFERENCE_NODE:
value = "&" + node.getNodeValue() + ";";
out.write(encodeText(value));
break;
case Node.PROCESSING_INSTRUCTION_NODE:
value = "<?" + node.getNodeName() + " " + node.getNodeValue() + "?>";
out.write(encodeText(value));
Node pp = node.getParentNode();
if (pp != null && pp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
}
if (defined)
{
undefine(uri);
}
if (next != null)
{
serialize(next, out, convertToCdata);
}
}
| void serialize(final Node node, final OutputStream out,
boolean convertToCdata)
throws IOException
{
if (out == null)
{
throw new NullPointerException("no output stream");
}
String value, prefix;
Node children;
Node next = node.getNextSibling();
String uri = node.getNamespaceURI();
boolean defined = false;
short nt = node.getNodeType();
if (convertToCdata && nt == Node.TEXT_NODE)
{
nt = Node.CDATA_SECTION_NODE;
}
switch (nt)
{
case Node.ATTRIBUTE_NODE:
prefix = node.getPrefix();
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri) ||
XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) ||
(prefix != null && prefix.startsWith("xmlns:")))
{
String nsuri = node.getNodeValue();
if (isDefined(nsuri))
{
break;
}
define(nsuri, node.getLocalName());
}
else if (uri != null && !isDefined(uri))
{
prefix = define(uri, prefix);
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(nsvalue.getBytes(encoding));
defined = true;
}
out.write(SPACE);
String a_nodeName = node.getNodeName();
out.write(encodeText(a_nodeName));
String a_nodeValue = node.getNodeValue();
if (mode == Stylesheet.OUTPUT_HTML &&
a_nodeName.equals(a_nodeValue))
{
break;
}
out.write(EQ);
value = "'" + encode(a_nodeValue, true, true) + "'";
out.write(encodeText(value));
break;
case Node.ELEMENT_NODE:
value = node.getNodeName();
out.write(BRA);
out.write(encodeText(value));
if (uri != null && !isDefined(uri))
{
prefix = define(uri, node.getPrefix());
String nsname = (prefix == null) ? "xmlns" : "xmlns:" + prefix;
out.write(SPACE);
out.write(encodeText(nsname));
out.write(EQ);
String nsvalue = "'" + encode(uri, true, true) + "'";
out.write(encodeText(nsvalue));
defined = true;
}
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
{
int len = attrs.getLength();
for (int i = 0; i < len; i++)
{
Attr attr = (Attr) attrs.item(i);
if (discardDefaultContent && !attr.getSpecified())
{
// NOOP
}
else
{
serialize(attr, out, false);
}
}
}
convertToCdata = cdataSectionElements.contains(value);
children = node.getFirstChild();
if (children == null)
{
out.write(SLASH);
out.write(KET);
}
else
{
out.write(KET);
serialize(children, out, convertToCdata);
out.write(BRA);
out.write(SLASH);
out.write(encodeText(value));
out.write(KET);
}
break;
case Node.TEXT_NODE:
value = node.getNodeValue();
if (!"yes".equals(node.getUserData("disable-output-escaping")))
{
value = encode(value, false, false);
}
out.write(encodeText(value));
break;
case Node.CDATA_SECTION_NODE:
value = "<![CDATA[" + node.getNodeValue() + "]]>";
out.write(encodeText(value));
break;
case Node.COMMENT_NODE:
value = "<!--" + node.getNodeValue() + "-->";
out.write(encodeText(value));
Node cp = node.getParentNode();
if (cp != null && cp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
if (mode == Stylesheet.OUTPUT_XML)
{
if ("UTF-16".equalsIgnoreCase(encoding))
{
out.write(0xfe);
out.write(0xff);
}
if (!"yes".equals(node.getUserData("omit-xml-declaration")) &&
xmlDeclaration)
{
Document doc = (node instanceof Document) ?
(Document) node : null;
String version = (doc != null) ? doc.getXmlVersion() : null;
if (version == null)
{
version = (String) node.getUserData("version");
}
if (version == null)
{
version = "1.0";
}
out.write(BRA);
out.write(0x3f);
out.write("xml version='".getBytes("US-ASCII"));
out.write(version.getBytes("US-ASCII"));
out.write(APOS);
if (!("UTF-8".equalsIgnoreCase(encoding)))
{
out.write(" encoding='".getBytes("US-ASCII"));
out.write(encoding.getBytes("US-ASCII"));
out.write(APOS);
}
if ((doc != null && doc.getXmlStandalone()) ||
"yes".equals(node.getUserData("standalone")))
{
out.write(" standalone='yes'".getBytes("US-ASCII"));
}
out.write(0x3f);
out.write(KET);
out.write(encodeText(eol));
}
// TODO warn if not outputting the declaration would be a
// problem
}
else if (mode == Stylesheet.OUTPUT_HTML)
{
// Ensure that encoding is accessible
String mediaType = (String) node.getUserData("media-type");
if (mediaType == null)
{
mediaType = "text/html";
}
String contentType = mediaType + "; charset=" +
((encoding.indexOf(' ') != -1) ?
"\"" + encoding + "\"" :
encoding);
Document doc = (node instanceof Document) ? (Document) node :
node.getOwnerDocument();
Node html = null;
for (Node ctx = node.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
html = ctx;
break;
}
}
if (html == null)
{
html = doc.createElement("html");
node.appendChild(html);
}
Node head = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"head".equalsIgnoreCase(ctx.getLocalName()))
{
head = ctx;
break;
}
}
if (head == null)
{
head = doc.createElement("head");
Node c1 = null;
for (Node ctx = html.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE)
{
c1 = ctx;
break;
}
}
if (c1 != null)
{
html.insertBefore(head, c1);
}
else
{
html.appendChild(head);
}
}
Node meta = null;
Node metaContent = null;
for (Node ctx = head.getFirstChild(); ctx != null;
ctx = ctx.getNextSibling())
{
if (ctx.getNodeType() == Node.ELEMENT_NODE &&
"meta".equalsIgnoreCase(ctx.getLocalName()))
{
NamedNodeMap metaAttrs = ctx.getAttributes();
int len = metaAttrs.getLength();
String httpEquiv = null;
Node content = null;
for (int i = 0; i < len; i++)
{
Node attr = metaAttrs.item(i);
String attrName = attr.getNodeName();
if ("http-equiv".equalsIgnoreCase(attrName))
{
httpEquiv = attr.getNodeValue();
}
else if ("content".equalsIgnoreCase(attrName))
{
content = attr;
}
}
if ("Content-Type".equalsIgnoreCase(httpEquiv))
{
meta = ctx;
metaContent = content;
break;
}
}
}
if (meta == null)
{
meta = doc.createElement("meta");
// Insert first
Node first = head.getFirstChild();
if (first == null)
{
head.appendChild(meta);
}
else
{
head.insertBefore(meta, first);
}
Node metaHttpEquiv = doc.createAttribute("http-equiv");
meta.getAttributes().setNamedItem(metaHttpEquiv);
metaHttpEquiv.setNodeValue("Content-Type");
}
if (metaContent == null)
{
metaContent = doc.createAttribute("content");
meta.getAttributes().setNamedItem(metaContent);
}
metaContent.setNodeValue(contentType);
// phew
}
children = node.getFirstChild();
if (children != null)
{
serialize(children, out, convertToCdata);
}
break;
case Node.DOCUMENT_TYPE_NODE:
DocumentType doctype = (DocumentType) node;
out.write(BRA);
out.write(BANG);
out.write(encodeText("DOCTYPE "));
value = doctype.getNodeName();
out.write(encodeText(value));
String publicId = doctype.getPublicId();
if (publicId != null)
{
out.write(encodeText(" PUBLIC "));
out.write(APOS);
out.write(encodeText(publicId));
out.write(APOS);
}
String systemId = doctype.getSystemId();
if (systemId != null)
{
out.write(encodeText(" SYSTEM "));
out.write(APOS);
out.write(encodeText(systemId));
out.write(APOS);
}
String internalSubset = doctype.getInternalSubset();
if (internalSubset != null)
{
out.write(encodeText(internalSubset));
}
out.write(KET);
out.write(eol.getBytes(encoding));
break;
case Node.ENTITY_REFERENCE_NODE:
value = "&" + node.getNodeValue() + ";";
out.write(encodeText(value));
break;
case Node.PROCESSING_INSTRUCTION_NODE:
value = "<?" + node.getNodeName() + " " + node.getNodeValue() + "?>";
out.write(encodeText(value));
Node pp = node.getParentNode();
if (pp != null && pp.getNodeType() == Node.DOCUMENT_NODE)
{
out.write(encodeText(eol));
}
break;
}
if (defined)
{
undefine(uri);
}
if (next != null)
{
serialize(next, out, convertToCdata);
}
}
|
diff --git a/cache2-dist/src/main/java/com/cache2/intercepter/Cache2Intercepter.java b/cache2-dist/src/main/java/com/cache2/intercepter/Cache2Intercepter.java
index 87e3f6e..dac2343 100644
--- a/cache2-dist/src/main/java/com/cache2/intercepter/Cache2Intercepter.java
+++ b/cache2-dist/src/main/java/com/cache2/intercepter/Cache2Intercepter.java
@@ -1,409 +1,409 @@
package com.cache2.intercepter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cache2.annotation.Cache2Element;
import com.cache2.annotation.CachedMethod;
import com.cache2.domain.CacheCommand;
import com.cache2.domain.CacheStrategy;
import com.cache2.domain.CachedValue;
import com.cache2.domain.Identifiable;
import com.cache2.helper.Cache1Helper;
import com.cache2.helper.Cache2Helper;
import com.cache2.key.Cache1Key;
import com.cache2.key.Cache2Key;
import com.cache2.util.CacheUtil;
/**
* Intercepts methods marked with {@link CachedMethod} and caches them according
* to the diagram.
*
* <p>
* Primary cache (cache1):<br>
* ( ) => O
* </p>
*
* <p>
* Secondary cache (cache2):<br>
* E => ( )
* </p>
*
* <p>
* Key:<br>
* ( ) denotes a method signature<br>
* O denotes an object<br>
* E denotes an element signature (class and id)
* </p>
*
* <p>
* Methods marked with {@link CachedMethod} and their returned objects get put
* into cache1 using {@link Cache1Key} as the key. When a method gets cached,
* the returned object and its arguments are evaluated for
* {@link Cached2Element} annotations and if present creates entries in cache2
* using {@link Cache2Key} as a key, and {@link Cache1Key} as a value. This
* creates a link between the elements and the methods, which lets us invalidate
* the cached methods when we intercept updates on the elements.
* </p>
*
* <p>
* Support the following situations:
* <ol>
* <li>1. A method gets cached and changes to the returned object invalidate it.
* This is handled by invalidations on update or delete to the returned object,
* as we create a cache2 relating that element back to the method.</li>
* <li>2. A method gets cached and the returned entity contains a list of child
* entities. If that list is added to or removed from we invalidate the method
* cache. Basically the child elements need to invalidate methods linked to the
* parent element. This is handled by invalidations on the child element update
* or delete, as they normally contain a field of the parent element or its id.
* As long as that field is annotated, it will find the method to invalidate.
* <li>
* </ol>
* </p>
*
* @author matthew
*
*/
@Component
@Aspect
public class Cache2Intercepter {
@Autowired
private Cache1Helper cache1Helper;
@Autowired
private Cache2Helper cache2Helper;
/**
* Command for putting elements into the cache.
*/
private final CacheCommand putCommand = new CacheCommand() {
@Override
public void execute(Cache2Key cache2Key, Cache1Key cache1Key) {
cache2Helper.put(cache2Key, cache1Key);
}
};
/**
* Command for invalidating elements from the cache.
*/
private final CacheCommand invalidateCommand = new CacheCommand() {
@Override
public void execute(Cache2Key cache2Key, Cache1Key cache1Key) {
// get cache1 keys from cache2
Set<Cache1Key> keys = cache2Helper.get(cache2Key);
if (keys != null) {
for (Cache1Key key : keys) {
// remove the cache1
cache1Helper.remove(key);
// remove the link
cache2Helper.remove(cache2Key, key);
}
}
}
};
@Around("@annotation(cachedMethod)")
public Object around(ProceedingJoinPoint pjp, CachedMethod cachedMethod)
throws Throwable {
Object retVal = null;
switch (cachedMethod.value()) {
case GET:
retVal = this.get(pjp, cachedMethod);
break;
case INSERT:
case UPDATE:
case DELETE:
case INVALIDATE:
retVal = this.invalidate(pjp);
break;
default:
retVal = pjp.proceed();
break;
}
return retVal;
}
/**
* Handles the {@link CacheStrategy#GET} strategy by intercepting a method
* call with a cache lookup and caching it if it was not found.
*
* @param pjp
* @return cached value or retVal
* @throws Throwable
*/
@SuppressWarnings("unchecked")
protected Object get(ProceedingJoinPoint pjp, CachedMethod annotation)
throws Throwable {
Object retVal = null;
final Method method = ((MethodSignature) pjp.getSignature())
.getMethod();
// the declaring class
final Class<?> declaringClass = pjp.getTarget().getClass();
// cache 1 key
final Cache1Key cache1Key = CacheUtil.createCache1Key(declaringClass,
method.getName(), method.getParameterTypes(), pjp.getArgs());
// return type of method
final Class<?> returnType = method.getReturnType();
// if the return type is a list
if (List.class.isAssignableFrom(returnType)
- && annotation.clazz().isAnnotationPresent(CachedMethod.class)) {
+ && annotation.clazz().isAnnotationPresent(Cache2Element.class)) {
CachedValue<List<Identifiable>> cachedValue = (CachedValue<List<Identifiable>>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<List<Identifiable>>(
(List<Identifiable>) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is a normal cache2 element or the method is
// annotated
else if (returnType.isAnnotationPresent(Cache2Element.class)
|| method.isAnnotationPresent(Cache2Element.class)) {
// check the cache
CachedValue<Identifiable> cachedValue = (CachedValue<Identifiable>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<Identifiable>(
(Identifiable) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is not an entity
else {
retVal = pjp.proceed();
}
return retVal;
}
/**
* Handles the {@link CacheStrategy#INVALIDATE} strategy by intercepting a
* method call and invalidating any cached methods linked to method argument
* elements.
*
* @param pjp
* @return retVal
* @throws Throwable
*/
protected Object invalidate(ProceedingJoinPoint pjp) throws Throwable {
final Method method = ((MethodSignature) pjp.getSignature())
.getMethod();
final Object retVal = pjp.proceed();
// handle the arguments with the command
this.handleArguments(pjp.getArgs(), method.getParameterAnnotations(),
null, this.invalidateCommand);
return retVal;
}
/**
* Check each argument for the {@link Cache2Element} annotation and execute
* the cache command for it.
*
* @param args
* @param cache1Key
* @param command
* @throws Exception
*/
@SuppressWarnings("unchecked")
private void handleArguments(Object[] args, Annotation[][] annotations,
Cache1Key cache1Key, CacheCommand command) throws Exception {
if (args != null) {
for (int i = 0; i < args.length; i++) {
Cache2Element cache2Element = null;
final Object arg = args[i];
if (arg != null) {
// first see if the argument is an annotated class
cache2Element = arg.getClass().getAnnotation(
Cache2Element.class);
// if its not, check if it is an annotated argument
if (cache2Element == null) {
for (Annotation annotation : annotations[i]) {
if (annotation instanceof Cache2Element) {
cache2Element = (Cache2Element) annotation;
break;
}
}
}
if (cache2Element == null) {
continue;
}
// if its a list
if (List.class.isAssignableFrom(arg.getClass())) {
this.handleFields((List<Identifiable>) arg, cache1Key,
command);
}
// if its an integer
else if (int.class.isAssignableFrom(arg.getClass())
|| Integer.class.isAssignableFrom(arg.getClass())) {
command.execute(CacheUtil.createCache2Key(
cache2Element.value(), (int) arg), cache1Key);
}
// if its a normal element
else if (Identifiable.class
.isAssignableFrom(arg.getClass())) {
this.handleFields((Identifiable) arg, cache1Key,
command);
}
}
}
}
}
/**
* Delegates to {@link #handleFields(Identifiable, Cache1Key, CacheCommand)}
* for each element in the list.
*
* @param elements
* @param cache1Key
* @param command
* @throws Exception
*/
private void handleFields(List<Identifiable> elements, Cache1Key cache1Key,
CacheCommand command) throws Exception {
if (elements != null) {
for (Identifiable element : elements) {
this.handleFields(element, cache1Key, command);
}
}
}
/**
* Recurses down the element's fields for {@link Cache2Element} annotations
* and executes the command for each.
*
* @param element
* @param cache1Key
* @param command
* @throws Exception
*/
@SuppressWarnings("unchecked")
private void handleFields(Identifiable element, Cache1Key cache1Key,
CacheCommand command) throws Exception {
if (element != null
&& element.getClass().isAnnotationPresent(Cache2Element.class)) {
// execute command
command.execute(
CacheUtil.createCache2Key(element.getClass(),
element.getId()), cache1Key);
// recurse for fields
final Field[] fields = element.getClass().getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
field.setAccessible(true);
// if the field is annotated
if (field.isAnnotationPresent(Cache2Element.class)) {
// if its a list
if (List.class.isAssignableFrom(field.getType())) {
this.handleFields(
(List<Identifiable>) field.get(element),
cache1Key, command);
}
// if its an integer
else if (int.class.isAssignableFrom(field.getType())
|| Integer.class.isAssignableFrom(field
.getType())) {
// execute the command
command.execute(
CacheUtil.createCache2Key(field
.getAnnotation(Cache2Element.class)
.value(), (int) field.get(element)),
cache1Key);
}
// if its a normal element
else if (Identifiable.class.isAssignableFrom(field
.getType())) {
this.handleFields((Identifiable) field.get(field),
cache1Key, command);
}
}
}
}
}
}
}
| true | true | protected Object get(ProceedingJoinPoint pjp, CachedMethod annotation)
throws Throwable {
Object retVal = null;
final Method method = ((MethodSignature) pjp.getSignature())
.getMethod();
// the declaring class
final Class<?> declaringClass = pjp.getTarget().getClass();
// cache 1 key
final Cache1Key cache1Key = CacheUtil.createCache1Key(declaringClass,
method.getName(), method.getParameterTypes(), pjp.getArgs());
// return type of method
final Class<?> returnType = method.getReturnType();
// if the return type is a list
if (List.class.isAssignableFrom(returnType)
&& annotation.clazz().isAnnotationPresent(CachedMethod.class)) {
CachedValue<List<Identifiable>> cachedValue = (CachedValue<List<Identifiable>>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<List<Identifiable>>(
(List<Identifiable>) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is a normal cache2 element or the method is
// annotated
else if (returnType.isAnnotationPresent(Cache2Element.class)
|| method.isAnnotationPresent(Cache2Element.class)) {
// check the cache
CachedValue<Identifiable> cachedValue = (CachedValue<Identifiable>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<Identifiable>(
(Identifiable) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is not an entity
else {
retVal = pjp.proceed();
}
return retVal;
}
| protected Object get(ProceedingJoinPoint pjp, CachedMethod annotation)
throws Throwable {
Object retVal = null;
final Method method = ((MethodSignature) pjp.getSignature())
.getMethod();
// the declaring class
final Class<?> declaringClass = pjp.getTarget().getClass();
// cache 1 key
final Cache1Key cache1Key = CacheUtil.createCache1Key(declaringClass,
method.getName(), method.getParameterTypes(), pjp.getArgs());
// return type of method
final Class<?> returnType = method.getReturnType();
// if the return type is a list
if (List.class.isAssignableFrom(returnType)
&& annotation.clazz().isAnnotationPresent(Cache2Element.class)) {
CachedValue<List<Identifiable>> cachedValue = (CachedValue<List<Identifiable>>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<List<Identifiable>>(
(List<Identifiable>) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is a normal cache2 element or the method is
// annotated
else if (returnType.isAnnotationPresent(Cache2Element.class)
|| method.isAnnotationPresent(Cache2Element.class)) {
// check the cache
CachedValue<Identifiable> cachedValue = (CachedValue<Identifiable>) cache1Helper
.get(cache1Key);
if (cachedValue != null) {
retVal = cachedValue.getValue();
} else {
// proceed
retVal = pjp.proceed();
// create new cached value
cachedValue = new CachedValue<Identifiable>(
(Identifiable) retVal);
// cache the value
cache1Helper.put(cache1Key, cachedValue);
// create links in cache2
this.handleFields(cachedValue.getValue(), cache1Key,
this.putCommand);
}
}
// if the return type is not an entity
else {
retVal = pjp.proceed();
}
return retVal;
}
|
diff --git a/java/com/delcyon/capo/resourcemanager/types/FileResourceContentMetaData.java b/java/com/delcyon/capo/resourcemanager/types/FileResourceContentMetaData.java
index bb31d32..515bcd4 100644
--- a/java/com/delcyon/capo/resourcemanager/types/FileResourceContentMetaData.java
+++ b/java/com/delcyon/capo/resourcemanager/types/FileResourceContentMetaData.java
@@ -1,167 +1,169 @@
/**
Copyright (C) 2012 Delcyon, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.delcyon.capo.resourcemanager.types;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.net.URI;
import com.delcyon.capo.datastream.stream_attribute_filter.MD5FilterInputStream;
import com.delcyon.capo.resourcemanager.ResourceManager;
import com.delcyon.capo.resourcemanager.ResourceParameter;
import com.delcyon.capo.resourcemanager.ResourceParameterBuilder;
/**
* @author jeremiah
*
*/
public class FileResourceContentMetaData extends AbstractContentMetaData
{
@SuppressWarnings("unused")
private FileResourceContentMetaData() //serialization only
{
}
public FileResourceContentMetaData(String uri, ResourceParameter... resourceParameters) throws Exception
{
init(uri,0,resourceParameters);
}
public FileResourceContentMetaData(String uri, int currentDepth, ResourceParameter... resourceParameters) throws Exception
{
init(uri,currentDepth,resourceParameters);
}
@Override
public Attributes[] getAdditionalSupportedAttributes()
{
return new Attributes[]{Attributes.exists,Attributes.executable,Attributes.readable,Attributes.writeable,Attributes.container,Attributes.lastModified};
}
public void refresh(String uri) throws Exception
{
init(uri,0);
}
private void init(String uri,int currentDepth, ResourceParameter... resourceParameters) throws Exception
{
if (getBoolean(Parameters.USE_RELATIVE_PATHS,false,resourceParameters))
{
if (getString(Attributes.path,null,resourceParameters) == null)
{
ResourceParameterBuilder resourceParameterBuilder = new ResourceParameterBuilder();
resourceParameterBuilder.addAll(resourceParameters);
resourceParameterBuilder.addParameter(Attributes.path, uri.toString());
resourceParameters = resourceParameterBuilder.getParameters();
}
else
{
String uriString = uri.toString();
uriString = uriString.replaceFirst(getString(Attributes.path,null,resourceParameters),"");
setResourceURI(ResourceManager.removeURN(uriString));
}
}
else
{
setResourceURI(uri);
}
File file = new File(new URI(uri));
getAttributeMap().put(Attributes.exists.toString(), file.exists()+"");
getAttributeMap().put(Attributes.executable.toString(), file.canExecute()+"");
getAttributeMap().put(Attributes.readable.toString(), file.canRead()+"");
getAttributeMap().put(Attributes.writeable.toString(), file.canWrite()+"");
getAttributeMap().put(Attributes.container.toString(), file.isDirectory()+"");
getAttributeMap().put(Attributes.lastModified.toString(), file.lastModified()+"");
if (file.exists() == true && file.canRead() == true && file.isDirectory() == false)
{
- readInputStream(new FileInputStream(file));
+ FileInputStream fileInputStream = new FileInputStream(file);
+ readInputStream(fileInputStream);
+ fileInputStream.close();
}
else if (file.isDirectory() == true && getIntValue(com.delcyon.capo.controller.elements.ResourceMetaDataElement.Attributes.depth,1,resourceParameters) > currentDepth)
{
BigInteger contentMD5 = new BigInteger(new byte[]{0});
for (String childURI : file.list())
{
File childFile = new File(file,childURI);
String tempChildURI = childFile.toURI().toString();
if (tempChildURI.endsWith(File.separator))
{
tempChildURI = tempChildURI.substring(0, tempChildURI.length()-File.separator.length());
}
FileResourceContentMetaData contentMetaData = new FileResourceContentMetaData(tempChildURI, currentDepth+1,resourceParameters);
if (contentMetaData.getMD5() != null)
{
contentMD5 = contentMD5.add(new BigInteger(contentMetaData.getMD5(), 16));
}
addContainedResource(contentMetaData);
}
getAttributeMap().put(MD5FilterInputStream.ATTRIBUTE_NAME, contentMD5.abs().toString(16));
}
setInitialized(true);
}
@Override
public Boolean exists()
{
return Boolean.parseBoolean(getAttributeMap().get(Attributes.exists.toString()));
}
@Override
public Long getLastModified()
{
return Long.parseLong(getAttributeMap().get(Attributes.lastModified.toString()));
}
@Override
public Boolean isContainer()
{
return Boolean.parseBoolean(getAttributeMap().get(Attributes.container.toString()));
}
@Override
public Boolean isReadable()
{
return Boolean.parseBoolean(getAttributeMap().get(Attributes.readable.toString()));
}
@Override
public Boolean isWriteable()
{
return Boolean.parseBoolean(getAttributeMap().get(Attributes.writeable.toString()));
}
}
| true | true | private void init(String uri,int currentDepth, ResourceParameter... resourceParameters) throws Exception
{
if (getBoolean(Parameters.USE_RELATIVE_PATHS,false,resourceParameters))
{
if (getString(Attributes.path,null,resourceParameters) == null)
{
ResourceParameterBuilder resourceParameterBuilder = new ResourceParameterBuilder();
resourceParameterBuilder.addAll(resourceParameters);
resourceParameterBuilder.addParameter(Attributes.path, uri.toString());
resourceParameters = resourceParameterBuilder.getParameters();
}
else
{
String uriString = uri.toString();
uriString = uriString.replaceFirst(getString(Attributes.path,null,resourceParameters),"");
setResourceURI(ResourceManager.removeURN(uriString));
}
}
else
{
setResourceURI(uri);
}
File file = new File(new URI(uri));
getAttributeMap().put(Attributes.exists.toString(), file.exists()+"");
getAttributeMap().put(Attributes.executable.toString(), file.canExecute()+"");
getAttributeMap().put(Attributes.readable.toString(), file.canRead()+"");
getAttributeMap().put(Attributes.writeable.toString(), file.canWrite()+"");
getAttributeMap().put(Attributes.container.toString(), file.isDirectory()+"");
getAttributeMap().put(Attributes.lastModified.toString(), file.lastModified()+"");
if (file.exists() == true && file.canRead() == true && file.isDirectory() == false)
{
readInputStream(new FileInputStream(file));
}
else if (file.isDirectory() == true && getIntValue(com.delcyon.capo.controller.elements.ResourceMetaDataElement.Attributes.depth,1,resourceParameters) > currentDepth)
{
BigInteger contentMD5 = new BigInteger(new byte[]{0});
for (String childURI : file.list())
{
File childFile = new File(file,childURI);
String tempChildURI = childFile.toURI().toString();
if (tempChildURI.endsWith(File.separator))
{
tempChildURI = tempChildURI.substring(0, tempChildURI.length()-File.separator.length());
}
FileResourceContentMetaData contentMetaData = new FileResourceContentMetaData(tempChildURI, currentDepth+1,resourceParameters);
if (contentMetaData.getMD5() != null)
{
contentMD5 = contentMD5.add(new BigInteger(contentMetaData.getMD5(), 16));
}
addContainedResource(contentMetaData);
}
getAttributeMap().put(MD5FilterInputStream.ATTRIBUTE_NAME, contentMD5.abs().toString(16));
}
setInitialized(true);
}
| private void init(String uri,int currentDepth, ResourceParameter... resourceParameters) throws Exception
{
if (getBoolean(Parameters.USE_RELATIVE_PATHS,false,resourceParameters))
{
if (getString(Attributes.path,null,resourceParameters) == null)
{
ResourceParameterBuilder resourceParameterBuilder = new ResourceParameterBuilder();
resourceParameterBuilder.addAll(resourceParameters);
resourceParameterBuilder.addParameter(Attributes.path, uri.toString());
resourceParameters = resourceParameterBuilder.getParameters();
}
else
{
String uriString = uri.toString();
uriString = uriString.replaceFirst(getString(Attributes.path,null,resourceParameters),"");
setResourceURI(ResourceManager.removeURN(uriString));
}
}
else
{
setResourceURI(uri);
}
File file = new File(new URI(uri));
getAttributeMap().put(Attributes.exists.toString(), file.exists()+"");
getAttributeMap().put(Attributes.executable.toString(), file.canExecute()+"");
getAttributeMap().put(Attributes.readable.toString(), file.canRead()+"");
getAttributeMap().put(Attributes.writeable.toString(), file.canWrite()+"");
getAttributeMap().put(Attributes.container.toString(), file.isDirectory()+"");
getAttributeMap().put(Attributes.lastModified.toString(), file.lastModified()+"");
if (file.exists() == true && file.canRead() == true && file.isDirectory() == false)
{
FileInputStream fileInputStream = new FileInputStream(file);
readInputStream(fileInputStream);
fileInputStream.close();
}
else if (file.isDirectory() == true && getIntValue(com.delcyon.capo.controller.elements.ResourceMetaDataElement.Attributes.depth,1,resourceParameters) > currentDepth)
{
BigInteger contentMD5 = new BigInteger(new byte[]{0});
for (String childURI : file.list())
{
File childFile = new File(file,childURI);
String tempChildURI = childFile.toURI().toString();
if (tempChildURI.endsWith(File.separator))
{
tempChildURI = tempChildURI.substring(0, tempChildURI.length()-File.separator.length());
}
FileResourceContentMetaData contentMetaData = new FileResourceContentMetaData(tempChildURI, currentDepth+1,resourceParameters);
if (contentMetaData.getMD5() != null)
{
contentMD5 = contentMD5.add(new BigInteger(contentMetaData.getMD5(), 16));
}
addContainedResource(contentMetaData);
}
getAttributeMap().put(MD5FilterInputStream.ATTRIBUTE_NAME, contentMD5.abs().toString(16));
}
setInitialized(true);
}
|
diff --git a/src/main/java/org/waarp/openr66/client/SpooledDirectoryTransfer.java b/src/main/java/org/waarp/openr66/client/SpooledDirectoryTransfer.java
index c8c2b462..402551f4 100644
--- a/src/main/java/org/waarp/openr66/client/SpooledDirectoryTransfer.java
+++ b/src/main/java/org/waarp/openr66/client/SpooledDirectoryTransfer.java
@@ -1,499 +1,503 @@
/**
* This file is part of Waarp Project.
*
* Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the
* COPYRIGHT.txt in the distribution for a full listing of individual contributors.
*
* All Waarp Project is free software: you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Waarp . If not, see
* <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.client;
import java.io.File;
import java.io.FileFilter;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.waarp.common.database.exception.WaarpDatabaseException;
import org.waarp.common.filemonitor.FileMonitor;
import org.waarp.common.filemonitor.FileMonitorCommand;
import org.waarp.common.filemonitor.RegexFileFilter;
import org.waarp.common.logging.WaarpInternalLogger;
import org.waarp.common.logging.WaarpInternalLoggerFactory;
import org.waarp.common.logging.WaarpSlf4JLoggerFactory;
import org.waarp.openr66.configuration.FileBasedConfiguration;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66Result;
import org.waarp.openr66.context.task.SpooledInformTask;
import org.waarp.openr66.database.DbConstant;
import org.waarp.openr66.database.data.DbRule;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.configuration.Messages;
import org.waarp.openr66.protocol.localhandler.packet.BusinessRequestPacket;
import org.waarp.openr66.protocol.networkhandler.NetworkTransaction;
import org.waarp.openr66.protocol.utils.ChannelUtils;
import org.waarp.openr66.protocol.utils.R66Future;
/**
* Direct Transfer from a client with or without database connection
* or Submit Transfer from a client with database connection
* to transfer files from a spooled directory to possibly multiple hosts at once.<br>
* -to Hosts will have to be separated by ','.<br>
* <br>
* Mandatory additional elements:<br>
* -directory source (directory to spooled on ; many directories can be specified using a comma separated list as "directory1,directory2,directory3")<br>
* -statusfile file (file to use as permanent status (if process is killed or aborts))<br>
* -stopfile file (file when created will stop the dameon)<br>
* Other options:<br>
* -regex regex (regular expression to filter file names from directory source)<br>
* -elapse elapse (elapse time between 2 checks of the directory)<br>
* -submit (to submit only: default)<br>
* -direct (to directly transfer only)<br>
* -recursive (to scan recursively from the root)<br>
* -waarp WaarpHosts (seperated by ',') to inform of running spooled directory (information stays in memory of Waarp servers, not in database)<br>
*
* @author Frederic Bregier
*
*/
public class SpooledDirectoryTransfer implements Runnable {
/**
* Internal Logger
*/
static protected volatile WaarpInternalLogger logger;
protected static String _INFO_ARGS =
Messages.getString("SpooledDirectoryTransfer.0"); //$NON-NLS-1$
protected static final String NO_INFO_ARGS = "noinfo";
protected final R66Future future;
protected final String name;
protected final String directory;
protected final String statusFile;
protected final String stopFile;
protected final String rulename;
protected final String fileinfo;
protected final boolean isMD5;
protected final String remoteHosts;
protected final String regexFilter;
protected final String waarpHosts;
protected final int blocksize;
protected final long elapseTime;
protected final boolean submit;
protected final boolean nolog;
protected final boolean recurs;
protected final NetworkTransaction networkTransaction;
public long sent = 0;
public long error = 0;
/**
* @param future
* @param directory
* @param statusfile
* @param stopfile
* @param rulename
* @param fileinfo
* @param isMD5
* @param remoteHosts
* @param blocksize
* @param regex
* @param elapse
* @param submit
* @param nolog
* @param networkTransaction
*/
public SpooledDirectoryTransfer(R66Future future, String name, String directory,
String statusfile, String stopfile, String rulename,
String fileinfo, boolean isMD5,
String remoteHosts, int blocksize, String regex,
long elapse, boolean submit, boolean nolog, boolean recursive,
String waarphost, NetworkTransaction networkTransaction) {
if (logger == null) {
logger = WaarpInternalLoggerFactory.getLogger(SpooledDirectoryTransfer.class);
}
this.future = future;
this.name = name;
this.directory = directory;
this.statusFile = statusfile;
this.stopFile = stopfile;
this.rulename = rulename;
this.fileinfo = fileinfo;
this.isMD5 = isMD5;
this.remoteHosts = remoteHosts;
this.blocksize = blocksize;
this.regexFilter = regex;
this.elapseTime = elapse;
this.submit = submit;
this.nolog = nolog && (!submit);
AbstractTransfer.nolog = this.nolog;
this.recurs = recursive;
this.waarpHosts = waarphost;
this.networkTransaction = networkTransaction;
}
@Override
public void run() {
if (submit && ! DbConstant.admin.isConnected) {
logger.error(Messages.getString("SpooledDirectoryTransfer.2")); //$NON-NLS-1$
this.future.cancel();
return;
}
sent = 0;
error = 0;
final String [] allrhosts = remoteHosts.split(",");
// first check if rule is for SEND
DbRule dbrule = null;
try {
dbrule = new DbRule(DbConstant.admin.session, rulename);
} catch (WaarpDatabaseException e1) {
logger.error(Messages.getString("Transfer.18"), e1); //$NON-NLS-1$
this.future.setFailure(e1);
return;
}
if (dbrule.isRecvMode()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.5")); //$NON-NLS-1$
this.future.cancel();
return;
}
File status = new File(statusFile);
if (status.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.6")); //$NON-NLS-1$
this.future.cancel();
return;
}
File stop = new File(stopFile);
if (stop.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.7")); //$NON-NLS-1$
this.future.cancel();
return;
} else if (stop.exists()) {
logger.warn(Messages.getString("SpooledDirectoryTransfer.8")); //$NON-NLS-1$
this.future.setSuccess();
return;
}
String [] directories = directory.split(",");
for (String dirname : directories) {
File dir = new File(dirname);
if (!dir.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.9")+" : "+dir); //$NON-NLS-1$
this.future.cancel();
return;
}
}
FileFilter filter = null;
if (regexFilter != null) {
filter = new RegexFileFilter(regexFilter);
}
FileMonitorCommand commandValidFile = new FileMonitorCommand() {
- public void run(File file) {
+ public boolean run(File file) {
+ boolean finalStatus = false;
for (String host : allrhosts) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
String filename = file.getAbsolutePath();
logger.info("Launch transfer to "+host+" with file "+filename);
R66Future future = new R66Future(true);
String text = null;
if (submit) {
text = "Submit Transfer";
SubmitTransfer transaction = new SubmitTransfer(future,
host, filename, rulename, fileinfo, isMD5, blocksize,
DbConstant.ILLEGALVALUE, null);
transaction.run();
} else {
text = "Direct Transfer";
DirectTransfer transaction = new DirectTransfer(future,
host, filename, rule, fileInfo, ismd5, block,
DbConstant.ILLEGALVALUE, networkTransaction);
logger.debug("rhost: "+host+":"+transaction.remoteHost);
transaction.run();
}
future.awaitUninterruptibly();
R66Result result = future.getResult();
if (future.isSuccess()) {
+ finalStatus = true;
sent++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
String status = Messages.getString("RequestInformation.Success"); //$NON-NLS-1$
if (runner.getErrorInfo() == ErrorCode.Warning) {
status = Messages.getString("RequestInformation.Warned"); //$NON-NLS-1$
}
logger.warn(text+" in status: "+status+" "
+ runner.toShortString()
+" <REMOTE>"+ host+ "</REMOTE>"
+" <FILEFINAL>"+
(result.file != null ?
result.file.toString() + "</FILEFINAL>"
: "no file"));
if (nolog && !submit) {
// In case of success, delete the runner
try {
runner.delete();
} catch (WaarpDatabaseException e) {
logger.warn("Cannot apply nolog to " +
runner.toShortString(),
e);
}
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
error++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
logger.error(text+Messages.getString("RequestInformation.Failure") + //$NON-NLS-1$
runner.toShortString() +
"<REMOTE>" + host + "</REMOTE>", future.getCause());
} else {
logger.error(text+Messages.getString("RequestInformation.Failure"), //$NON-NLS-1$
future.getCause());
}
} else {
logger.error(text+Messages.getString("RequestInformation.Failure") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>",
future.getCause());
}
}
}
}
+ return finalStatus;
}
};
FileMonitorCommand waarpHostCommand = null;
File dir = new File(directories[0]);
final FileMonitor monitor = new FileMonitor(name, status, stop, dir, null, elapsed, filter,
recurs, commandValidFile, null, null);
if (waarpHosts != null && ! waarpHosts.isEmpty()) {
final String [] allwaarps = waarpHosts.split(",");
waarpHostCommand = new FileMonitorCommand() {
- public void run(File notused) {
+ public boolean run(File notused) {
String status = monitor.getStatus();
for (String host : allwaarps) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
R66Future future = new R66Future(true);
BusinessRequestPacket packet =
new BusinessRequestPacket(SpooledInformTask.class.getName() + " " + status, 0);
BusinessRequest transaction = new BusinessRequest(
networkTransaction, future, host, packet);
transaction.run();
future.awaitUninterruptibly();
if (! future.isSuccess()) {
logger.info("Can't inform Waarp server: "+host + " since " + future.getCause());
}
}
}
+ return true;
}
};
monitor.setCommandCheckIteration(waarpHostCommand);
}
for (int i = 1; i < directories.length; i++) {
dir = new File(directories[i]);
monitor.addDirectory(dir);
}
monitor.start();
monitor.waitForStopFile();
this.future.setSuccess();
}
static protected String sname = null;
static protected String rhosts = null;
static protected String localDirectory = null;
static protected String rule = null;
static protected String fileInfo = null;
static protected boolean ismd5 = false;
static protected int block = 0x10000; // 64K
// as
// default
static protected String statusfile = null;
static protected String stopfile = null;
static protected String regex = null;
static protected long elapsed = 1000;
static protected boolean tosubmit = true;
static protected boolean noLog = false;
static protected boolean recursive = false;
static protected String waarphosts = null;
/**
* Parse the parameter and set current values
*
* @param args
* @return True if all parameters were found and correct
*/
protected static boolean getParams(String[] args) {
_INFO_ARGS = Messages.getString("SpooledDirectoryTransfer.0"); //$NON-NLS-1$
if (args.length < 11) {
logger
.error(_INFO_ARGS);
return false;
}
if (!FileBasedConfiguration
.setClientConfigurationFromXml(Configuration.configuration, args[0])) {
logger
.error(Messages.getString("Configuration.NeedCorrectConfig")); //$NON-NLS-1$
return false;
}
// Now set default values from configuration
block = Configuration.configuration.BLOCKSIZE;
int i = 1;
try {
for (i = 1; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-to")) {
i++;
rhosts = args[i];
} else if (args[i].equalsIgnoreCase("-name")) {
i++;
sname = args[i];
} else if (args[i].equalsIgnoreCase("-directory")) {
i++;
localDirectory = args[i];
} else if (args[i].equalsIgnoreCase("-rule")) {
i++;
rule = args[i];
} else if (args[i].equalsIgnoreCase("-statusfile")) {
i++;
statusfile = args[i];
} else if (args[i].equalsIgnoreCase("-stopfile")) {
i++;
stopfile = args[i];
} else if (args[i].equalsIgnoreCase("-info")) {
i++;
fileInfo = args[i];
} else if (args[i].equalsIgnoreCase("-md5")) {
ismd5 = true;
} else if (args[i].equalsIgnoreCase("-block")) {
i++;
block = Integer.parseInt(args[i]);
if (block < 100) {
logger.error(Messages.getString("AbstractTransfer.1") + block); //$NON-NLS-1$
return false;
}
} else if (args[i].equalsIgnoreCase("-nolog")) {
noLog = true;
} else if (args[i].equalsIgnoreCase("-submit")) {
tosubmit = true;
} else if (args[i].equalsIgnoreCase("-direct")) {
tosubmit = false;
} else if (args[i].equalsIgnoreCase("-recursive")) {
recursive = true;
} else if (args[i].equalsIgnoreCase("-regex")) {
i++;
regex = args[i];
} else if (args[i].equalsIgnoreCase("-waarp")) {
i++;
waarphosts = args[i];
} else if (args[i].equalsIgnoreCase("-elapse")) {
i++;
elapsed = Long.parseLong(args[i]);
}
}
} catch (NumberFormatException e) {
logger.error(Messages.getString("AbstractTransfer.20")+i); //$NON-NLS-1$
return false;
}
if (fileInfo == null) {
fileInfo = NO_INFO_ARGS;
}
if (sname == null) {
sname = localDirectory;
}
if (tosubmit && ! DbConstant.admin.isConnected) {
logger.error(Messages.getString("SpooledDirectoryTransfer.2")); //$NON-NLS-1$
return false;
}
if (rhosts != null && rule != null && localDirectory != null && statusfile != null && stopfile != null) {
return true;
}
logger.error(Messages.getString("SpooledDirectoryTransfer.56")+ //$NON-NLS-1$
_INFO_ARGS);
return false;
}
public static void main(String[] args) {
InternalLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null));
if (logger == null) {
logger = WaarpInternalLoggerFactory.getLogger(SpooledDirectoryTransfer.class);
}
initialize(args, true);
}
/**
* @param args
*/
public static boolean initialize(String[] args, boolean normalStart) {
if (logger == null) {
logger = WaarpInternalLoggerFactory.getLogger(SpooledDirectoryTransfer.class);
}
if (!getParams(args)) {
logger.error(Messages.getString("Configuration.WrongInit")); //$NON-NLS-1$
if (DbConstant.admin != null && DbConstant.admin.isConnected) {
DbConstant.admin.close();
}
if (normalStart) {
ChannelUtils.stopLogger();
System.exit(2);
}
return false;
}
Configuration.configuration.pipelineInit();
NetworkTransaction networkTransaction = new NetworkTransaction();
try {
R66Future future = new R66Future(true);
SpooledDirectoryTransfer spooled =
new SpooledDirectoryTransfer(future, sname, localDirectory, statusfile, stopfile,
rule, fileInfo, ismd5, rhosts, block, regex, elapsed, tosubmit, noLog, recursive,
waarphosts, networkTransaction);
spooled.run();
if (normalStart) {
future.awaitUninterruptibly();
logger.warn(Messages.getString("SpooledDirectoryTransfer.58")+spooled.sent+" sent and "+spooled.error+Messages.getString("SpooledDirectoryTransfer.60")); //$NON-NLS-1$
}
return true;
} catch (Exception e) {
logger.warn("exc", e);
return false;
} finally {
if (normalStart) {
networkTransaction.closeAll();
System.exit(0);
}
}
}
}
| false | true | public void run() {
if (submit && ! DbConstant.admin.isConnected) {
logger.error(Messages.getString("SpooledDirectoryTransfer.2")); //$NON-NLS-1$
this.future.cancel();
return;
}
sent = 0;
error = 0;
final String [] allrhosts = remoteHosts.split(",");
// first check if rule is for SEND
DbRule dbrule = null;
try {
dbrule = new DbRule(DbConstant.admin.session, rulename);
} catch (WaarpDatabaseException e1) {
logger.error(Messages.getString("Transfer.18"), e1); //$NON-NLS-1$
this.future.setFailure(e1);
return;
}
if (dbrule.isRecvMode()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.5")); //$NON-NLS-1$
this.future.cancel();
return;
}
File status = new File(statusFile);
if (status.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.6")); //$NON-NLS-1$
this.future.cancel();
return;
}
File stop = new File(stopFile);
if (stop.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.7")); //$NON-NLS-1$
this.future.cancel();
return;
} else if (stop.exists()) {
logger.warn(Messages.getString("SpooledDirectoryTransfer.8")); //$NON-NLS-1$
this.future.setSuccess();
return;
}
String [] directories = directory.split(",");
for (String dirname : directories) {
File dir = new File(dirname);
if (!dir.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.9")+" : "+dir); //$NON-NLS-1$
this.future.cancel();
return;
}
}
FileFilter filter = null;
if (regexFilter != null) {
filter = new RegexFileFilter(regexFilter);
}
FileMonitorCommand commandValidFile = new FileMonitorCommand() {
public void run(File file) {
for (String host : allrhosts) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
String filename = file.getAbsolutePath();
logger.info("Launch transfer to "+host+" with file "+filename);
R66Future future = new R66Future(true);
String text = null;
if (submit) {
text = "Submit Transfer";
SubmitTransfer transaction = new SubmitTransfer(future,
host, filename, rulename, fileinfo, isMD5, blocksize,
DbConstant.ILLEGALVALUE, null);
transaction.run();
} else {
text = "Direct Transfer";
DirectTransfer transaction = new DirectTransfer(future,
host, filename, rule, fileInfo, ismd5, block,
DbConstant.ILLEGALVALUE, networkTransaction);
logger.debug("rhost: "+host+":"+transaction.remoteHost);
transaction.run();
}
future.awaitUninterruptibly();
R66Result result = future.getResult();
if (future.isSuccess()) {
sent++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
String status = Messages.getString("RequestInformation.Success"); //$NON-NLS-1$
if (runner.getErrorInfo() == ErrorCode.Warning) {
status = Messages.getString("RequestInformation.Warned"); //$NON-NLS-1$
}
logger.warn(text+" in status: "+status+" "
+ runner.toShortString()
+" <REMOTE>"+ host+ "</REMOTE>"
+" <FILEFINAL>"+
(result.file != null ?
result.file.toString() + "</FILEFINAL>"
: "no file"));
if (nolog && !submit) {
// In case of success, delete the runner
try {
runner.delete();
} catch (WaarpDatabaseException e) {
logger.warn("Cannot apply nolog to " +
runner.toShortString(),
e);
}
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
error++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
logger.error(text+Messages.getString("RequestInformation.Failure") + //$NON-NLS-1$
runner.toShortString() +
"<REMOTE>" + host + "</REMOTE>", future.getCause());
} else {
logger.error(text+Messages.getString("RequestInformation.Failure"), //$NON-NLS-1$
future.getCause());
}
} else {
logger.error(text+Messages.getString("RequestInformation.Failure") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>",
future.getCause());
}
}
}
}
}
};
FileMonitorCommand waarpHostCommand = null;
File dir = new File(directories[0]);
final FileMonitor monitor = new FileMonitor(name, status, stop, dir, null, elapsed, filter,
recurs, commandValidFile, null, null);
if (waarpHosts != null && ! waarpHosts.isEmpty()) {
final String [] allwaarps = waarpHosts.split(",");
waarpHostCommand = new FileMonitorCommand() {
public void run(File notused) {
String status = monitor.getStatus();
for (String host : allwaarps) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
R66Future future = new R66Future(true);
BusinessRequestPacket packet =
new BusinessRequestPacket(SpooledInformTask.class.getName() + " " + status, 0);
BusinessRequest transaction = new BusinessRequest(
networkTransaction, future, host, packet);
transaction.run();
future.awaitUninterruptibly();
if (! future.isSuccess()) {
logger.info("Can't inform Waarp server: "+host + " since " + future.getCause());
}
}
}
}
};
monitor.setCommandCheckIteration(waarpHostCommand);
}
for (int i = 1; i < directories.length; i++) {
dir = new File(directories[i]);
monitor.addDirectory(dir);
}
monitor.start();
monitor.waitForStopFile();
this.future.setSuccess();
}
| public void run() {
if (submit && ! DbConstant.admin.isConnected) {
logger.error(Messages.getString("SpooledDirectoryTransfer.2")); //$NON-NLS-1$
this.future.cancel();
return;
}
sent = 0;
error = 0;
final String [] allrhosts = remoteHosts.split(",");
// first check if rule is for SEND
DbRule dbrule = null;
try {
dbrule = new DbRule(DbConstant.admin.session, rulename);
} catch (WaarpDatabaseException e1) {
logger.error(Messages.getString("Transfer.18"), e1); //$NON-NLS-1$
this.future.setFailure(e1);
return;
}
if (dbrule.isRecvMode()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.5")); //$NON-NLS-1$
this.future.cancel();
return;
}
File status = new File(statusFile);
if (status.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.6")); //$NON-NLS-1$
this.future.cancel();
return;
}
File stop = new File(stopFile);
if (stop.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.7")); //$NON-NLS-1$
this.future.cancel();
return;
} else if (stop.exists()) {
logger.warn(Messages.getString("SpooledDirectoryTransfer.8")); //$NON-NLS-1$
this.future.setSuccess();
return;
}
String [] directories = directory.split(",");
for (String dirname : directories) {
File dir = new File(dirname);
if (!dir.isDirectory()) {
logger.error(Messages.getString("SpooledDirectoryTransfer.9")+" : "+dir); //$NON-NLS-1$
this.future.cancel();
return;
}
}
FileFilter filter = null;
if (regexFilter != null) {
filter = new RegexFileFilter(regexFilter);
}
FileMonitorCommand commandValidFile = new FileMonitorCommand() {
public boolean run(File file) {
boolean finalStatus = false;
for (String host : allrhosts) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
String filename = file.getAbsolutePath();
logger.info("Launch transfer to "+host+" with file "+filename);
R66Future future = new R66Future(true);
String text = null;
if (submit) {
text = "Submit Transfer";
SubmitTransfer transaction = new SubmitTransfer(future,
host, filename, rulename, fileinfo, isMD5, blocksize,
DbConstant.ILLEGALVALUE, null);
transaction.run();
} else {
text = "Direct Transfer";
DirectTransfer transaction = new DirectTransfer(future,
host, filename, rule, fileInfo, ismd5, block,
DbConstant.ILLEGALVALUE, networkTransaction);
logger.debug("rhost: "+host+":"+transaction.remoteHost);
transaction.run();
}
future.awaitUninterruptibly();
R66Result result = future.getResult();
if (future.isSuccess()) {
finalStatus = true;
sent++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
String status = Messages.getString("RequestInformation.Success"); //$NON-NLS-1$
if (runner.getErrorInfo() == ErrorCode.Warning) {
status = Messages.getString("RequestInformation.Warned"); //$NON-NLS-1$
}
logger.warn(text+" in status: "+status+" "
+ runner.toShortString()
+" <REMOTE>"+ host+ "</REMOTE>"
+" <FILEFINAL>"+
(result.file != null ?
result.file.toString() + "</FILEFINAL>"
: "no file"));
if (nolog && !submit) {
// In case of success, delete the runner
try {
runner.delete();
} catch (WaarpDatabaseException e) {
logger.warn("Cannot apply nolog to " +
runner.toShortString(),
e);
}
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
logger.warn(text+Messages.getString("RequestInformation.Success") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>");
}
} else {
error++;
DbTaskRunner runner = null;
if (result != null) {
runner = result.runner;
if (runner != null) {
logger.error(text+Messages.getString("RequestInformation.Failure") + //$NON-NLS-1$
runner.toShortString() +
"<REMOTE>" + host + "</REMOTE>", future.getCause());
} else {
logger.error(text+Messages.getString("RequestInformation.Failure"), //$NON-NLS-1$
future.getCause());
}
} else {
logger.error(text+Messages.getString("RequestInformation.Failure") //$NON-NLS-1$
+"<REMOTE>" + host + "</REMOTE>",
future.getCause());
}
}
}
}
return finalStatus;
}
};
FileMonitorCommand waarpHostCommand = null;
File dir = new File(directories[0]);
final FileMonitor monitor = new FileMonitor(name, status, stop, dir, null, elapsed, filter,
recurs, commandValidFile, null, null);
if (waarpHosts != null && ! waarpHosts.isEmpty()) {
final String [] allwaarps = waarpHosts.split(",");
waarpHostCommand = new FileMonitorCommand() {
public boolean run(File notused) {
String status = monitor.getStatus();
for (String host : allwaarps) {
host = host.trim();
if (host != null && ! host.isEmpty()) {
R66Future future = new R66Future(true);
BusinessRequestPacket packet =
new BusinessRequestPacket(SpooledInformTask.class.getName() + " " + status, 0);
BusinessRequest transaction = new BusinessRequest(
networkTransaction, future, host, packet);
transaction.run();
future.awaitUninterruptibly();
if (! future.isSuccess()) {
logger.info("Can't inform Waarp server: "+host + " since " + future.getCause());
}
}
}
return true;
}
};
monitor.setCommandCheckIteration(waarpHostCommand);
}
for (int i = 1; i < directories.length; i++) {
dir = new File(directories[i]);
monitor.addDirectory(dir);
}
monitor.start();
monitor.waitForStopFile();
this.future.setSuccess();
}
|
diff --git a/subsolr/src/main/java/com/subsolr/entityprocessors/SQLEntityProcessor.java b/subsolr/src/main/java/com/subsolr/entityprocessors/SQLEntityProcessor.java
index 7b80464..bffc8a3 100644
--- a/subsolr/src/main/java/com/subsolr/entityprocessors/SQLEntityProcessor.java
+++ b/subsolr/src/main/java/com/subsolr/entityprocessors/SQLEntityProcessor.java
@@ -1,66 +1,66 @@
package com.subsolr.entityprocessors;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.subsolr.contextprocessor.model.FieldSetDefinition;
import com.subsolr.entityprocessors.datasources.SQLDataSource;
import com.subsolr.entityprocessors.model.Record;
public class SQLEntityProcessor implements EntityProcessor {
public static final Logger logger = LoggerFactory.getLogger(SQLEntityProcessor.class);
public List<Record> getRecords(FieldSetDefinition fieldSetDefinition) {
SQLDataSource sqlDataSource = (SQLDataSource) fieldSetDefinition.getDataSource();
final List<Record> records = Lists.newArrayList();
final Map<String, String> fieldNameToEntityNameMap = fieldSetDefinition.getFieldNameToEntityNameMap();
JdbcTemplate jdbcTemplate = getJdbcTempate(sqlDataSource);
- jdbcTemplate.query(fieldSetDefinition.getFieldNameToEntityNameMap().get("SQLQuery"), new RowCallbackHandler() {
+ jdbcTemplate.query(fieldSetDefinition.getPropertiesForEntityProcessor().get("SQLQuery"), new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
logger.debug("columns received"+rs.getMetaData().getColumnCount());
Map<String, String> valueByIndexName = Maps.newHashMap();
for (String fieldName : fieldNameToEntityNameMap.keySet()) {
String fieldValue = rs.getString(fieldNameToEntityNameMap.get(fieldName));
valueByIndexName.put(fieldName, fieldValue);
}
records.add(new Record(valueByIndexName));
}
});
return records;
}
private JdbcTemplate getJdbcTempate(SQLDataSource sqlDataSource) {
JdbcTemplate jdbcTemplate = null;
try {
Class.forName(sqlDataSource.getDriver());
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(sqlDataSource.getDriver());
dataSource.setUrl(sqlDataSource.getUrl());
dataSource.setUsername(sqlDataSource.getUserId());
dataSource.setPassword(sqlDataSource.getPassword());
jdbcTemplate = new JdbcTemplate(dataSource);
} catch (ClassNotFoundException e) {
logger.error("Exception occurred while getting connection" + e);
throw new RuntimeException(e.getMessage(), e.getCause());
}
return jdbcTemplate;
}
}
| true | true | public List<Record> getRecords(FieldSetDefinition fieldSetDefinition) {
SQLDataSource sqlDataSource = (SQLDataSource) fieldSetDefinition.getDataSource();
final List<Record> records = Lists.newArrayList();
final Map<String, String> fieldNameToEntityNameMap = fieldSetDefinition.getFieldNameToEntityNameMap();
JdbcTemplate jdbcTemplate = getJdbcTempate(sqlDataSource);
jdbcTemplate.query(fieldSetDefinition.getFieldNameToEntityNameMap().get("SQLQuery"), new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
logger.debug("columns received"+rs.getMetaData().getColumnCount());
Map<String, String> valueByIndexName = Maps.newHashMap();
for (String fieldName : fieldNameToEntityNameMap.keySet()) {
String fieldValue = rs.getString(fieldNameToEntityNameMap.get(fieldName));
valueByIndexName.put(fieldName, fieldValue);
}
records.add(new Record(valueByIndexName));
}
});
return records;
}
| public List<Record> getRecords(FieldSetDefinition fieldSetDefinition) {
SQLDataSource sqlDataSource = (SQLDataSource) fieldSetDefinition.getDataSource();
final List<Record> records = Lists.newArrayList();
final Map<String, String> fieldNameToEntityNameMap = fieldSetDefinition.getFieldNameToEntityNameMap();
JdbcTemplate jdbcTemplate = getJdbcTempate(sqlDataSource);
jdbcTemplate.query(fieldSetDefinition.getPropertiesForEntityProcessor().get("SQLQuery"), new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
logger.debug("columns received"+rs.getMetaData().getColumnCount());
Map<String, String> valueByIndexName = Maps.newHashMap();
for (String fieldName : fieldNameToEntityNameMap.keySet()) {
String fieldValue = rs.getString(fieldNameToEntityNameMap.get(fieldName));
valueByIndexName.put(fieldName, fieldValue);
}
records.add(new Record(valueByIndexName));
}
});
return records;
}
|
diff --git a/androidgui/GUI/src/gogodeX/GUI/FriendsList.java b/androidgui/GUI/src/gogodeX/GUI/FriendsList.java
index 7a7fce3..7d7c70c 100644
--- a/androidgui/GUI/src/gogodeX/GUI/FriendsList.java
+++ b/androidgui/GUI/src/gogodeX/GUI/FriendsList.java
@@ -1,240 +1,240 @@
package gogodeX.GUI;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.EditText;
public class FriendsList extends ListActivity {
private ArrayAdapter<String> m_list;
int row = -1;
private FriendsList ref = this;
private Messenger mSender = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends);
m_list = new ArrayAdapter<String>(this, R.layout.friends_rows, R.id.name);
setListAdapter(m_list);
Button add = (Button) findViewById(R.id.add_friend);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = ((EditText)findViewById(R.id.friend_name_textbox)).getText().toString();
if(!name.equals("")) {
JSONStringer friendRequest = new JSONStringer();
try
{
friendRequest.object();
friendRequest.key("Friend Name").value(name);
friendRequest.key("Request Type").value("Add Friend");
friendRequest.endObject();
GUI.getClient().sendLine(friendRequest.toString());
}
catch (JSONException e1)
{
e1.printStackTrace();
}
((EditText)findViewById(R.id.friend_name_textbox)).setText("");
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Hello "+name, duration);
toast.show();
}
}
});
////////////// Setup Two Way Communication ////////////////////
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String msgType = b.getString("Message Type");
if(msgType.equals("Toast")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, b.getString("Toast Message"), duration);
toast.show();
} else if(msgType.equals("Friend List")) {
String[] farray = b.getStringArray("Friend List");
for(String s : farray) {
m_list.add(s);
}
} else if(msgType.equals("Friend Requested")) {
m_list.add(b.getString("Friend Name") + "\t\t(Pending)");
} else if(msgType.equals("Friend Accepted")) {
String name = b.getString("Friend Name");
m_list.remove(name+"\t\t(Pending)");
m_list.add(name);
} else if(msgType.equals("Friend Request")) {
String name = b.getString("From User");
m_list.add(name+"\t\t(Unaccepted)");
} else if(msgType.equals("Friend Removed")) {
String val = b.getString("Validation");
if(val.equals("Accepted"))
m_list.remove(b.getString("Friend Name"));
else
- m_list.remove(b.getString("Friend Name\t\t("+val+")"));
+ m_list.remove(b.getString("Friend Name")+"\t\t("+val+")");
}
}
};
final Messenger mReceiver = new Messenger(mHandler);
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mSender = new Messenger(service);
try {
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Pass Messenger");
b.putString("whoami", "Friends List");
b.putParcelable("messenger", mReceiver);
mess.setData(b);
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
Intent mIntent = new Intent(FriendsList.this, GPSUpdater.class);
this.getApplicationContext().bindService(mIntent, conn, 0);
//////////////Setup Two Way Communication ////////////////////
}
@Override
protected void onResume() {
super.onResume();
if(mSender != null) {
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Declare Active");
b.putString("whoami", "Friends List");
mess.setData(b);
try {
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
protected void onListItemClick(ListView l, View v, int position, long id) {
row = position;
Button remove = (Button) findViewById(R.id.remove_friend);
Button accept = (Button) findViewById(R.id.accept_friend);
String name = m_list.getItem(row);
if(name.endsWith("\t\t(Pending)"))
name = name.substring(0, name.length() - new String("\t\t(Pending)").length());
if(name.endsWith("\t\t(Unaccepted)"))
name = name.substring(0, name.length() - new String("\t\t(Unaccepted)").length());
((EditText)findViewById(R.id.friend_name_textbox)).setText(name);
remove.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (row != -1) {
String name = m_list.getItem(row);
if(name.endsWith("\t\t(Pending)"))
name = name.substring(0, name.length() - new String("\t\t(Pending)").length());
JSONStringer friendRequest = new JSONStringer();
try
{
friendRequest.object();
friendRequest.key("Friend Name").value(name);
friendRequest.key("Request Type").value("Remove Friend");
friendRequest.endObject();
GUI.getClient().sendLine(friendRequest.toString());
}
catch (JSONException e1)
{
e1.printStackTrace();
}
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Remove Friend");
b.putString("Friend Name", name);
mess.setData(b);
try {
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(context, "Good bye "+name, duration);
toast.show();
m_list.remove(m_list.getItem(row));
row = -1;
}
}
});
accept.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (row != -1) {
String name = m_list.getItem(row);
if(name.endsWith("\t\t(Unaccepted)"))
{
m_list.remove(name);
name = name.substring(0, name.length() - new String("\t\t(Unaccepted)").length());
m_list.add(name);
JSONStringer friendRequest = new JSONStringer();
try
{
friendRequest.object();
friendRequest.key("Friend Name").value(name);
friendRequest.key("Request Type").value("Accept Friend");
friendRequest.endObject();
GUI.getClient().sendLine(friendRequest.toString());
}
catch (JSONException e1)
{
e1.printStackTrace();
}
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Accept Friend");
b.putString("Friend Name", name);
mess.setData(b);
try {
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(context, "Accepting "+name, duration);
toast.show();
}
}
}
});
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends);
m_list = new ArrayAdapter<String>(this, R.layout.friends_rows, R.id.name);
setListAdapter(m_list);
Button add = (Button) findViewById(R.id.add_friend);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = ((EditText)findViewById(R.id.friend_name_textbox)).getText().toString();
if(!name.equals("")) {
JSONStringer friendRequest = new JSONStringer();
try
{
friendRequest.object();
friendRequest.key("Friend Name").value(name);
friendRequest.key("Request Type").value("Add Friend");
friendRequest.endObject();
GUI.getClient().sendLine(friendRequest.toString());
}
catch (JSONException e1)
{
e1.printStackTrace();
}
((EditText)findViewById(R.id.friend_name_textbox)).setText("");
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Hello "+name, duration);
toast.show();
}
}
});
////////////// Setup Two Way Communication ////////////////////
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String msgType = b.getString("Message Type");
if(msgType.equals("Toast")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, b.getString("Toast Message"), duration);
toast.show();
} else if(msgType.equals("Friend List")) {
String[] farray = b.getStringArray("Friend List");
for(String s : farray) {
m_list.add(s);
}
} else if(msgType.equals("Friend Requested")) {
m_list.add(b.getString("Friend Name") + "\t\t(Pending)");
} else if(msgType.equals("Friend Accepted")) {
String name = b.getString("Friend Name");
m_list.remove(name+"\t\t(Pending)");
m_list.add(name);
} else if(msgType.equals("Friend Request")) {
String name = b.getString("From User");
m_list.add(name+"\t\t(Unaccepted)");
} else if(msgType.equals("Friend Removed")) {
String val = b.getString("Validation");
if(val.equals("Accepted"))
m_list.remove(b.getString("Friend Name"));
else
m_list.remove(b.getString("Friend Name\t\t("+val+")"));
}
}
};
final Messenger mReceiver = new Messenger(mHandler);
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mSender = new Messenger(service);
try {
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Pass Messenger");
b.putString("whoami", "Friends List");
b.putParcelable("messenger", mReceiver);
mess.setData(b);
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
Intent mIntent = new Intent(FriendsList.this, GPSUpdater.class);
this.getApplicationContext().bindService(mIntent, conn, 0);
//////////////Setup Two Way Communication ////////////////////
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends);
m_list = new ArrayAdapter<String>(this, R.layout.friends_rows, R.id.name);
setListAdapter(m_list);
Button add = (Button) findViewById(R.id.add_friend);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = ((EditText)findViewById(R.id.friend_name_textbox)).getText().toString();
if(!name.equals("")) {
JSONStringer friendRequest = new JSONStringer();
try
{
friendRequest.object();
friendRequest.key("Friend Name").value(name);
friendRequest.key("Request Type").value("Add Friend");
friendRequest.endObject();
GUI.getClient().sendLine(friendRequest.toString());
}
catch (JSONException e1)
{
e1.printStackTrace();
}
((EditText)findViewById(R.id.friend_name_textbox)).setText("");
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Hello "+name, duration);
toast.show();
}
}
});
////////////// Setup Two Way Communication ////////////////////
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String msgType = b.getString("Message Type");
if(msgType.equals("Toast")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, b.getString("Toast Message"), duration);
toast.show();
} else if(msgType.equals("Friend List")) {
String[] farray = b.getStringArray("Friend List");
for(String s : farray) {
m_list.add(s);
}
} else if(msgType.equals("Friend Requested")) {
m_list.add(b.getString("Friend Name") + "\t\t(Pending)");
} else if(msgType.equals("Friend Accepted")) {
String name = b.getString("Friend Name");
m_list.remove(name+"\t\t(Pending)");
m_list.add(name);
} else if(msgType.equals("Friend Request")) {
String name = b.getString("From User");
m_list.add(name+"\t\t(Unaccepted)");
} else if(msgType.equals("Friend Removed")) {
String val = b.getString("Validation");
if(val.equals("Accepted"))
m_list.remove(b.getString("Friend Name"));
else
m_list.remove(b.getString("Friend Name")+"\t\t("+val+")");
}
}
};
final Messenger mReceiver = new Messenger(mHandler);
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mSender = new Messenger(service);
try {
Message mess = Message.obtain();
Bundle b = new Bundle();
b.putString("Message Type", "Pass Messenger");
b.putString("whoami", "Friends List");
b.putParcelable("messenger", mReceiver);
mess.setData(b);
mSender.send(mess);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
Intent mIntent = new Intent(FriendsList.this, GPSUpdater.class);
this.getApplicationContext().bindService(mIntent, conn, 0);
//////////////Setup Two Way Communication ////////////////////
}
|
diff --git a/src/chess/eval/e9/pipeline/Stage1.java b/src/chess/eval/e9/pipeline/Stage1.java
index 71575ef..4364ab6 100644
--- a/src/chess/eval/e9/pipeline/Stage1.java
+++ b/src/chess/eval/e9/pipeline/Stage1.java
@@ -1,119 +1,119 @@
package chess.eval.e9.pipeline;
import chess.eval.e9.PawnHash;
import chess.eval.e9.PawnHashEntry;
import chess.eval.e9.Weight;
import chess.eval.e9.pawnEval.PawnEval;
import chess.state4.State4;
/**
* preliminary stage evaluations, very basic but comprise large proportion of eval score
*/
public final class Stage1 implements MidStage {
/** helper stage to check for score cutoffs*/
public final static class CutoffCheck implements MidStage{
private final MidStage next;
private final int stage;
public CutoffCheck(MidStage next, int stage){
this.next = next;
this.stage = stage;
}
@Override
public EvalResult eval(Team allied, Team enemy, BasicAttributes basics, EvalContext c, State4 s, int score) {
final int stage1MarginLower; //margin for a lower cutoff
final int stage1MarginUpper; //margin for an upper cutoff
if(allied.queenCount != 0 && enemy.queenCount != 0){
//both sides have queen, apply even margin
stage1MarginLower = -82; //margin scores taken from profiled mean score diff, 1.7 std
stage1MarginUpper = 76;
} else if(allied.queenCount != 0){
//score will be higher because allied queen, no enemy queen
stage1MarginLower = -120;
stage1MarginUpper = 96;
} else if(enemy.queenCount != 0){
//score will be lower because enemy queen, no allied queen
stage1MarginLower = -92;
stage1MarginUpper = 128;
} else{
stage1MarginLower = -142;
stage1MarginUpper = 141;
}
final boolean lowerBoundCutoff = score+stage1MarginUpper <= c.lowerBound; //highest score still less than alpha
final boolean upperBoundCutoff = score+stage1MarginLower >= c.upperBound; //lowest score still greater than beta
if(lowerBoundCutoff || upperBoundCutoff){
return new EvalResult(score, stage1MarginLower, stage1MarginUpper, stage);
} else{
return next.eval(allied, enemy, basics, c, s, score);
}
}
}
private final static int tempoWeight = S(14, 5);
private final static int bishopPairWeight = S(10, 42);
/** assist stage to check for score cutoffs before continuing down eval pipeline*/
private final MidStage cutoffChecker;
private final PawnHash pawnHash;
private final PawnHashEntry filler = new PawnHashEntry();
public Stage1(PawnHash pawnHash, MidStage next, int stage){
this.pawnHash = pawnHash;
this.cutoffChecker = new CutoffCheck(next, stage);
}
@Override
public EvalResult eval(Team allied, Team enemy, BasicAttributes basics, EvalContext c, State4 s, int prevScore) {
int player = c.player;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = 0;
stage1Score += S(basics.materialScore);
stage1Score += tempoWeight;
if(allied.bishopCount == 2){ //note, case 2 bishops on same square is not caught
stage1Score += bishopPairWeight;
}
if(enemy.bishopCount == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemy.queens, basics.nonPawnMaterialScore) -
- PawnEval.scorePawns(1-player, s, loader, allied.queens, basics.nonPawnMaterialScore);
+ PawnEval.scorePawns(1-player, s, loader, allied.queens, -basics.nonPawnMaterialScore);
int score = prevScore +
Weight.interpolate(stage1Score, c.scale) +
Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), c.scale);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
//check for score cutoff then continue if necessary
return cutoffChecker.eval(allied, enemy, basics, c, s, score);
}
/** build a weight scaling from passed start,end values*/
private static int S(int start, int end){
return Weight.encode(start, end);
}
private static int S(int weight){
return Weight.encode(weight, weight);
}
}
| true | true | public EvalResult eval(Team allied, Team enemy, BasicAttributes basics, EvalContext c, State4 s, int prevScore) {
int player = c.player;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = 0;
stage1Score += S(basics.materialScore);
stage1Score += tempoWeight;
if(allied.bishopCount == 2){ //note, case 2 bishops on same square is not caught
stage1Score += bishopPairWeight;
}
if(enemy.bishopCount == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemy.queens, basics.nonPawnMaterialScore) -
PawnEval.scorePawns(1-player, s, loader, allied.queens, basics.nonPawnMaterialScore);
int score = prevScore +
Weight.interpolate(stage1Score, c.scale) +
Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), c.scale);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
//check for score cutoff then continue if necessary
return cutoffChecker.eval(allied, enemy, basics, c, s, score);
}
| public EvalResult eval(Team allied, Team enemy, BasicAttributes basics, EvalContext c, State4 s, int prevScore) {
int player = c.player;
//load hashed pawn values, if any
final long pawnZkey = s.pawnZkey();
final PawnHashEntry phEntry = pawnHash.get(pawnZkey);
final PawnHashEntry loader;
if(phEntry == null){
filler.passedPawns = 0;
filler.zkey = 0;
loader = filler;
} else{
loader = phEntry;
}
int stage1Score = 0;
stage1Score += S(basics.materialScore);
stage1Score += tempoWeight;
if(allied.bishopCount == 2){ //note, case 2 bishops on same square is not caught
stage1Score += bishopPairWeight;
}
if(enemy.bishopCount == 2){
stage1Score += -bishopPairWeight;
}
stage1Score += PawnEval.scorePawns(player, s, loader, enemy.queens, basics.nonPawnMaterialScore) -
PawnEval.scorePawns(1-player, s, loader, allied.queens, -basics.nonPawnMaterialScore);
int score = prevScore +
Weight.interpolate(stage1Score, c.scale) +
Weight.interpolate(S((int)(Weight.egScore(stage1Score)*.1), 0), c.scale);
if(phEntry == null){ //store newly calculated pawn values
loader.zkey = pawnZkey;
pawnHash.put(pawnZkey, loader);
}
//check for score cutoff then continue if necessary
return cutoffChecker.eval(allied, enemy, basics, c, s, score);
}
|
diff --git a/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/DocumentListBrowser.java b/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/DocumentListBrowser.java
index ce4ead657..c4992aa0d 100644
--- a/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/DocumentListBrowser.java
+++ b/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/DocumentListBrowser.java
@@ -1,202 +1,198 @@
package org.carrot2.workbench.core.ui;
import java.io.StringWriter;
import java.net.URL;
import java.util.Locale;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.carrot2.core.*;
import org.carrot2.core.attribute.AttributeNames;
import org.carrot2.workbench.core.CorePlugin;
import org.carrot2.workbench.core.helpers.Utils;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.*;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.*;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
public class DocumentListBrowser
{
private Browser browser;
private ISelectionListener postSelectionListener;
private IWorkbenchSite site;
public void init(IWorkbenchSite site, Composite parent)
{
this.site = site;
browser = new Browser(parent, SWT.NONE);
attachToPostSelection(site.getPage());
attachToLocationChanging();
}
private void attachToPostSelection(final IWorkbenchPage page)
{
postSelectionListener = new ISelectionListener()
{
public void selectionChanged(IWorkbenchPart part, ISelection selection)
{
if (!selection.isEmpty() && selection instanceof IStructuredSelection)
{
IStructuredSelection selected = (IStructuredSelection) selection;
if (selected.getFirstElement() instanceof Cluster)
{
if (selected.size() == 1)
{
updateBrowserText((Cluster) selected.getFirstElement());
}
else
{
clear();
}
}
}
- if (selection.isEmpty())
- {
- clear();
- }
}
};
page.addPostSelectionListener(postSelectionListener);
page.addPartListener(new IPartListener()
{
public void partActivated(IWorkbenchPart part)
{
}
public void partBroughtToTop(IWorkbenchPart part)
{
}
public void partClosed(IWorkbenchPart part)
{
if (page.getEditorReferences().length == 0)
{
if (!browser.isDisposed())
{
clear();
}
}
}
public void partDeactivated(IWorkbenchPart part)
{
}
public void partOpened(IWorkbenchPart part)
{
}
});
}
private void attachToLocationChanging()
{
browser.addLocationListener(new LocationAdapter()
{
@Override
public void changing(LocationEvent event)
{
// browser was refreshed using setText() method
if (event.location.equals("about:blank"))
{
return;
}
try
{
CorePlugin.getDefault().getWorkbench().getBrowserSupport()
.createBrowser(
IWorkbenchBrowserSupport.AS_EDITOR
| IWorkbenchBrowserSupport.LOCATION_BAR
| IWorkbenchBrowserSupport.NAVIGATION_BAR
| IWorkbenchBrowserSupport.STATUS, null, null, null)
.openURL(new URL(event.location));
}
catch (Exception e)
{
Utils.logError("Couldn't open internal browser", e, true);
}
event.doit = false;
}
});
}
public void populateToolbar(IToolBarManager manager)
{
}
public void updateBrowserText(ProcessingResult result)
{
VelocityContext context = new VelocityContext();
context.put("result", result);
if (result.getAttributes().get(AttributeNames.RESULTS_TOTAL) != null)
{
final long total =
(Long) result.getAttributes().get(AttributeNames.RESULTS_TOTAL);
context.put("results-total-formatted", String.format(Locale.ENGLISH, "%1$,d",
total));
}
final String query = (String) result.getAttributes().get("query");
context.put("queryEscaped", StringEscapeUtils.escapeHtml(query));
merge(context, "documents-list.vm");
}
public void updateBrowserText(Cluster cluster)
{
VelocityContext context = new VelocityContext();
context.put("documents", cluster.getAllDocuments(Document.BY_ID_COMPARATOR));
merge(context, "documents-list.vm");
}
private void merge(VelocityContext context, String templateName)
{
Template template = null;
StringWriter sw = new StringWriter();
try
{
template = Velocity.getTemplate(templateName);
template.merge(context, sw);
}
catch (Exception e)
{
Utils.logError("Error while loading template", e, true);
return;
}
browser.setText(sw.toString());
}
public Control getControl()
{
return browser;
}
public void dispose()
{
if (postSelectionListener != null)
{
site.getPage().removePostSelectionListener(postSelectionListener);
}
}
public void clear()
{
merge(null, "empty-list.vm");
}
public String getPartName()
{
return "Documents";
}
}
| true | true | private void attachToPostSelection(final IWorkbenchPage page)
{
postSelectionListener = new ISelectionListener()
{
public void selectionChanged(IWorkbenchPart part, ISelection selection)
{
if (!selection.isEmpty() && selection instanceof IStructuredSelection)
{
IStructuredSelection selected = (IStructuredSelection) selection;
if (selected.getFirstElement() instanceof Cluster)
{
if (selected.size() == 1)
{
updateBrowserText((Cluster) selected.getFirstElement());
}
else
{
clear();
}
}
}
if (selection.isEmpty())
{
clear();
}
}
};
page.addPostSelectionListener(postSelectionListener);
page.addPartListener(new IPartListener()
{
public void partActivated(IWorkbenchPart part)
{
}
public void partBroughtToTop(IWorkbenchPart part)
{
}
public void partClosed(IWorkbenchPart part)
{
if (page.getEditorReferences().length == 0)
{
if (!browser.isDisposed())
{
clear();
}
}
}
public void partDeactivated(IWorkbenchPart part)
{
}
public void partOpened(IWorkbenchPart part)
{
}
});
}
| private void attachToPostSelection(final IWorkbenchPage page)
{
postSelectionListener = new ISelectionListener()
{
public void selectionChanged(IWorkbenchPart part, ISelection selection)
{
if (!selection.isEmpty() && selection instanceof IStructuredSelection)
{
IStructuredSelection selected = (IStructuredSelection) selection;
if (selected.getFirstElement() instanceof Cluster)
{
if (selected.size() == 1)
{
updateBrowserText((Cluster) selected.getFirstElement());
}
else
{
clear();
}
}
}
}
};
page.addPostSelectionListener(postSelectionListener);
page.addPartListener(new IPartListener()
{
public void partActivated(IWorkbenchPart part)
{
}
public void partBroughtToTop(IWorkbenchPart part)
{
}
public void partClosed(IWorkbenchPart part)
{
if (page.getEditorReferences().length == 0)
{
if (!browser.isDisposed())
{
clear();
}
}
}
public void partDeactivated(IWorkbenchPart part)
{
}
public void partOpened(IWorkbenchPart part)
{
}
});
}
|
diff --git a/impl/src/java/org/sakaiproject/profile2/logic/ProfileWallLogicImpl.java b/impl/src/java/org/sakaiproject/profile2/logic/ProfileWallLogicImpl.java
index db786bba..066458e9 100644
--- a/impl/src/java/org/sakaiproject/profile2/logic/ProfileWallLogicImpl.java
+++ b/impl/src/java/org/sakaiproject/profile2/logic/ProfileWallLogicImpl.java
@@ -1,445 +1,446 @@
/**
* Copyright (c) 2008-2010 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.profile2.logic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.sakaiproject.profile2.dao.ProfileDao;
import org.sakaiproject.profile2.model.Person;
import org.sakaiproject.profile2.model.ProfilePrivacy;
import org.sakaiproject.profile2.model.ProfileStatus;
import org.sakaiproject.profile2.model.WallItem;
import org.sakaiproject.profile2.util.ProfileConstants;
/**
* Implementation of ProfileWallLogic API for Profile2 wall.
*
* @author [email protected]
*/
public class ProfileWallLogicImpl implements ProfileWallLogic {
private static final Logger log = Logger.getLogger(ProfileWallLogic.class);
/**
* Creates a new instance of <code>ProfileWallLogicImpl</code>.
*/
public ProfileWallLogicImpl() {
}
/**
* {@inheritDoc}
*/
public void addEventToWalls(String event, final String userUuid) {
// get the connections of the creator of this content
final List<Person> connections = connectionsLogic.getConnectionsForUser(userUuid);
if (null == connections || 0 == connections.size()) {
// there are therefore no walls to post event to
return;
}
final WallItem wallItem = new WallItem();
wallItem.setCreatorUuid(userUuid);
wallItem.setType(ProfileConstants.WALL_ITEM_TYPE_EVENT);
wallItem.setDate(new Date());
// this string is mapped to a localized resource string in GUI
wallItem.setText(event);
Thread thread = new Thread() {
public void run() {
List<String> uuidsToEmail = new ArrayList<String>();
for (Person connection : connections) {
// only send email if successful
if (dao.addNewWallItemForUser(connection.getUuid(), wallItem)) {
// only send email if user has preference set
if (true == preferencesLogic.isEmailEnabledForThisMessageType(connection.getUuid(),
ProfileConstants.EMAIL_NOTIFICATION_WALL_EVENT_NEW)) {
uuidsToEmail.add(connection.getUuid());
}
} else {
// we don't guarantee delivery
log.warn("ProfileDao.addNewWallItemForUser failed for user: " + connection.getUuid());
}
}
sendWallNotificationEmailToConnections(uuidsToEmail, userUuid,
ProfileConstants.EMAIL_NOTIFICATION_WALL_EVENT_NEW);
}
};
thread.start();
}
/**
* {@inheritDoc}
*/
public boolean postWallItemToWall(final String userUuid, final WallItem wallItem) {
// post to wall
if (false == dao.addNewWallItemForUser(userUuid, wallItem)) {
return false;
}
// don't email user if they've posted on their own wall
if (false == sakaiProxy.getCurrentUserId().equals(userUuid)) {
sendWallNotificationEmailToUser(userUuid, wallItem.getCreatorUuid(),
ProfileConstants.EMAIL_NOTIFICATION_WALL_POST_MY_NEW);
}
// and if they have posted on their own wall, let connections know
else {
// get the connections of the user associated with the wall
final List<Person> connections = connectionsLogic.getConnectionsForUser(userUuid);
if (null != connections) {
Thread thread = new Thread() {
public void run() {
List<String> uuidsToEmail = new ArrayList<String>();
for (Person connection : connections) {
// only send email if successful
if (true == dao.addNewWallItemForUser(connection.getUuid(),
wallItem)) {
// only send email if user has preference set
if (true == preferencesLogic.isEmailEnabledForThisMessageType(connection.getUuid(),
ProfileConstants.EMAIL_NOTIFICATION_WALL_POST_CONNECTION_NEW)) {
uuidsToEmail.add(connection.getUuid());
}
} else {
log.warn("ProfileDao.addNewWallItemForUser failed for user: " + connection.getUuid());
}
}
sendWallNotificationEmailToConnections(uuidsToEmail, userUuid,
ProfileConstants.EMAIL_NOTIFICATION_WALL_POST_CONNECTION_NEW);
}
};
thread.start();
}
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean removeWallItemFromWall(String userUuid, WallItem wallItem) {
return dao.removeWallItemFromWall(userUuid, wallItem);
}
/**
* {@inheritDoc}
*/
public List<WallItem> getWallItemsForUser(String userUuid, ProfilePrivacy privacy) {
if (null == userUuid) {
throw new IllegalArgumentException("must provide user id");
}
final String currentUserUuid = sakaiProxy.getCurrentUserId();
if (null == currentUserUuid) {
throw new SecurityException(
"You must be logged in to make a request for a user's wall items.");
}
if (null == privacy) {
return new ArrayList<WallItem>();
}
if (false == StringUtils.equals(userUuid, currentUserUuid)) {
if (false == privacyLogic.isUserXWallVisibleByUserY(userUuid,
privacy, currentUserUuid, connectionsLogic
.isUserXFriendOfUserY(userUuid, currentUserUuid))) {
return new ArrayList<WallItem>();
}
}
List<WallItem> wallItems = dao.getWallItemsForUser(userUuid).getWallItems();
// filter wall items
List<WallItem> filteredWallItems = new ArrayList<WallItem>();
for (WallItem wallItem : wallItems) {
// current user is always allowed to see their wall items
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
filteredWallItems.add(wallItem);
// don't allow friend-of-a-friend if not connected
} else if (privacyLogic.isUserXWallVisibleByUserY(wallItem.getCreatorUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(wallItem.getCreatorUuid(), currentUserUuid))) {
filteredWallItems.add(wallItem);
}
}
// add in any connection statuses
List<Person> connections = connectionsLogic
.getConnectionsForUser(userUuid);
if (null == connections || 0 == connections.size()) {
+ Collections.sort(filteredWallItems);
return filteredWallItems;
}
for (Person connection : connections) {
ProfileStatus connectionStatus = statusLogic
.getUserStatus(connection.getUuid());
if (null == connectionStatus) {
continue;
}
// status privacy check
final boolean allowedStatus;
// current user is always allowed to see status of connections
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
allowedStatus = true;
// don't allow friend-of-a-friend
} else {
allowedStatus = privacyLogic.isUserXStatusVisibleByUserY(
connection.getUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(connection.getUuid(),
currentUserUuid));
}
if (true == allowedStatus) {
WallItem wallItem = new WallItem();
wallItem.setType(ProfileConstants.WALL_ITEM_TYPE_STATUS);
wallItem.setCreatorUuid(connection.getUuid());
wallItem.setDate(connectionStatus.getDateAdded());
wallItem.setText(connectionStatus.getMessage());
filteredWallItems.add(wallItem);
}
}
// wall items are comparable and need to be in order
Collections.sort(filteredWallItems);
// dao limits wall items but we also need to ensure any connection
// status updates don't push the number of wall items over limit
if (filteredWallItems.size() > ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES) {
return filteredWallItems.subList(0, ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES);
} else {
return filteredWallItems;
}
}
/**
* {@inheritDoc}
*/
public List<WallItem> getWallItemsForUser(String userUuid) {
return getWallItemsForUser(userUuid, privacyLogic
.getPrivacyRecordForUser(userUuid));
}
/**
* {@inheritDoc}
*/
public int getWallItemsCount(String userUuid) {
return getWallItemsCount(userUuid, privacyLogic
.getPrivacyRecordForUser(userUuid));
}
/**
* {@inheritDoc}
*/
public int getWallItemsCount(String userUuid, ProfilePrivacy privacy) {
final String currentUserUuid = sakaiProxy.getCurrentUserId();
if (null == sakaiProxy.getCurrentUserId()) {
throw new SecurityException(
"You must be logged in to make a request for a user's wall items.");
}
if (null == privacy) {
return 0;
}
if (false == StringUtils.equals(userUuid, currentUserUuid)) {
if (false == privacyLogic.isUserXWallVisibleByUserY(userUuid,
privacy, currentUserUuid, connectionsLogic
.isUserXFriendOfUserY(userUuid, currentUserUuid))) {
return 0;
}
}
List<WallItem> wallItems = dao.getWallItemsForUser(userUuid).getWallItems();
// filter wall items
List<WallItem> filteredWallItems = new ArrayList<WallItem>();
for (WallItem wallItem : wallItems) {
// current user is always allowed to see their wall items
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
filteredWallItems.add(wallItem);
// don't allow friend-of-a-friend if not connected
} else if (privacyLogic.isUserXWallVisibleByUserY(wallItem.getCreatorUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(wallItem.getCreatorUuid(), currentUserUuid))) {
filteredWallItems.add(wallItem);
}
}
int count = filteredWallItems.size();
// connection statuses
List<Person> connections = connectionsLogic
.getConnectionsForUser(userUuid);
if (null == connections || 0 == connections.size()) {
return count;
}
for (Person connection : connections) {
if (null != statusLogic.getUserStatus(connection.getUuid())) {
// current user is always allowed to see status of connections
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
count++;
// don't allow friend-of-a-friend if not connected
} else if (true == privacyLogic.isUserXStatusVisibleByUserY(
connection.getUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(connection.getUuid(),
currentUserUuid))) {
count++;
}
}
}
if (count > ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES) {
return ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES;
} else {
return count;
}
}
private void sendWallNotificationEmailToConnections(List<String> toUuids, final String fromUuid, final int messageType) {
// create the map of replacement values for this email template
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("senderDisplayName", sakaiProxy.getUserDisplayName(fromUuid));
replacementValues.put("localSakaiName", sakaiProxy.getServiceName());
replacementValues.put("localSakaiUrl", sakaiProxy.getPortalUrl());
replacementValues.put("toolName", sakaiProxy.getCurrentToolTitle());
String emailTemplateKey = null;
if (ProfileConstants.EMAIL_NOTIFICATION_WALL_EVENT_NEW == messageType) {
emailTemplateKey = ProfileConstants.EMAIL_TEMPLATE_KEY_WALL_EVENT_NEW;
replacementValues.put("profileLink", linkLogic.getEntityLinkToProfileHome(fromUuid));
} else if (ProfileConstants.EMAIL_NOTIFICATION_WALL_POST_CONNECTION_NEW == messageType) {
emailTemplateKey = ProfileConstants.EMAIL_TEMPLATE_KEY_WALL_POST_CONNECTION_NEW;
replacementValues.put("profileLink", linkLogic.getEntityLinkToProfileHome(fromUuid));
}
if (null != emailTemplateKey) {
sakaiProxy.sendEmail(toUuids, emailTemplateKey, replacementValues);
} else {
log.warn("not sending email, unknown message type for sendWallNotificationEmailToConnections: " + messageType);
}
}
private void sendWallNotificationEmailToUser(String toUuid,
final String fromUuid, final int messageType) {
// check if email preference enabled
if (!preferencesLogic.isEmailEnabledForThisMessageType(toUuid,
messageType)) {
return;
}
// create the map of replacement values for this email template
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("senderDisplayName", sakaiProxy.getUserDisplayName(fromUuid));
replacementValues.put("localSakaiName", sakaiProxy.getServiceName());
replacementValues.put("localSakaiUrl", sakaiProxy.getPortalUrl());
replacementValues.put("toolName", sakaiProxy.getCurrentToolTitle());
String emailTemplateKey = null;
if (ProfileConstants.EMAIL_NOTIFICATION_WALL_POST_MY_NEW == messageType) {
emailTemplateKey = ProfileConstants.EMAIL_TEMPLATE_KEY_WALL_POST_MY_NEW;
replacementValues.put("profileLink", linkLogic.getEntityLinkToProfileHome(toUuid));
}
if (null != emailTemplateKey) {
sakaiProxy.sendEmail(toUuid, emailTemplateKey, replacementValues);
} else {
log.warn("not sending email, unknown message type for sendWallNotificationEmailToUser: " + messageType);
}
}
// internal components
private ProfileDao dao;
public void setDao(ProfileDao dao) {
this.dao = dao;
}
private ProfilePrivacyLogic privacyLogic;
public void setPrivacyLogic(ProfilePrivacyLogic privacyLogic) {
this.privacyLogic = privacyLogic;
}
private ProfileConnectionsLogic connectionsLogic;
public void setConnectionsLogic(
ProfileConnectionsLogic connectionsLogic) {
this.connectionsLogic = connectionsLogic;
}
private ProfileLinkLogic linkLogic;
public void setLinkLogic(ProfileLinkLogic linkLogic) {
this.linkLogic = linkLogic;
}
private ProfilePreferencesLogic preferencesLogic;
public void setPreferencesLogic(ProfilePreferencesLogic preferencesLogic) {
this.preferencesLogic = preferencesLogic;
}
private ProfileStatusLogic statusLogic;
public void setStatusLogic(ProfileStatusLogic statusLogic) {
this.statusLogic = statusLogic;
}
private SakaiProxy sakaiProxy;
public void setSakaiProxy(SakaiProxy sakaiProxy) {
this.sakaiProxy = sakaiProxy;
}
}
| true | true | public List<WallItem> getWallItemsForUser(String userUuid, ProfilePrivacy privacy) {
if (null == userUuid) {
throw new IllegalArgumentException("must provide user id");
}
final String currentUserUuid = sakaiProxy.getCurrentUserId();
if (null == currentUserUuid) {
throw new SecurityException(
"You must be logged in to make a request for a user's wall items.");
}
if (null == privacy) {
return new ArrayList<WallItem>();
}
if (false == StringUtils.equals(userUuid, currentUserUuid)) {
if (false == privacyLogic.isUserXWallVisibleByUserY(userUuid,
privacy, currentUserUuid, connectionsLogic
.isUserXFriendOfUserY(userUuid, currentUserUuid))) {
return new ArrayList<WallItem>();
}
}
List<WallItem> wallItems = dao.getWallItemsForUser(userUuid).getWallItems();
// filter wall items
List<WallItem> filteredWallItems = new ArrayList<WallItem>();
for (WallItem wallItem : wallItems) {
// current user is always allowed to see their wall items
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
filteredWallItems.add(wallItem);
// don't allow friend-of-a-friend if not connected
} else if (privacyLogic.isUserXWallVisibleByUserY(wallItem.getCreatorUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(wallItem.getCreatorUuid(), currentUserUuid))) {
filteredWallItems.add(wallItem);
}
}
// add in any connection statuses
List<Person> connections = connectionsLogic
.getConnectionsForUser(userUuid);
if (null == connections || 0 == connections.size()) {
return filteredWallItems;
}
for (Person connection : connections) {
ProfileStatus connectionStatus = statusLogic
.getUserStatus(connection.getUuid());
if (null == connectionStatus) {
continue;
}
// status privacy check
final boolean allowedStatus;
// current user is always allowed to see status of connections
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
allowedStatus = true;
// don't allow friend-of-a-friend
} else {
allowedStatus = privacyLogic.isUserXStatusVisibleByUserY(
connection.getUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(connection.getUuid(),
currentUserUuid));
}
if (true == allowedStatus) {
WallItem wallItem = new WallItem();
wallItem.setType(ProfileConstants.WALL_ITEM_TYPE_STATUS);
wallItem.setCreatorUuid(connection.getUuid());
wallItem.setDate(connectionStatus.getDateAdded());
wallItem.setText(connectionStatus.getMessage());
filteredWallItems.add(wallItem);
}
}
// wall items are comparable and need to be in order
Collections.sort(filteredWallItems);
// dao limits wall items but we also need to ensure any connection
// status updates don't push the number of wall items over limit
if (filteredWallItems.size() > ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES) {
return filteredWallItems.subList(0, ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES);
} else {
return filteredWallItems;
}
}
| public List<WallItem> getWallItemsForUser(String userUuid, ProfilePrivacy privacy) {
if (null == userUuid) {
throw new IllegalArgumentException("must provide user id");
}
final String currentUserUuid = sakaiProxy.getCurrentUserId();
if (null == currentUserUuid) {
throw new SecurityException(
"You must be logged in to make a request for a user's wall items.");
}
if (null == privacy) {
return new ArrayList<WallItem>();
}
if (false == StringUtils.equals(userUuid, currentUserUuid)) {
if (false == privacyLogic.isUserXWallVisibleByUserY(userUuid,
privacy, currentUserUuid, connectionsLogic
.isUserXFriendOfUserY(userUuid, currentUserUuid))) {
return new ArrayList<WallItem>();
}
}
List<WallItem> wallItems = dao.getWallItemsForUser(userUuid).getWallItems();
// filter wall items
List<WallItem> filteredWallItems = new ArrayList<WallItem>();
for (WallItem wallItem : wallItems) {
// current user is always allowed to see their wall items
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
filteredWallItems.add(wallItem);
// don't allow friend-of-a-friend if not connected
} else if (privacyLogic.isUserXWallVisibleByUserY(wallItem.getCreatorUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(wallItem.getCreatorUuid(), currentUserUuid))) {
filteredWallItems.add(wallItem);
}
}
// add in any connection statuses
List<Person> connections = connectionsLogic
.getConnectionsForUser(userUuid);
if (null == connections || 0 == connections.size()) {
Collections.sort(filteredWallItems);
return filteredWallItems;
}
for (Person connection : connections) {
ProfileStatus connectionStatus = statusLogic
.getUserStatus(connection.getUuid());
if (null == connectionStatus) {
continue;
}
// status privacy check
final boolean allowedStatus;
// current user is always allowed to see status of connections
if (true == StringUtils.equals(userUuid, currentUserUuid)) {
allowedStatus = true;
// don't allow friend-of-a-friend
} else {
allowedStatus = privacyLogic.isUserXStatusVisibleByUserY(
connection.getUuid(), currentUserUuid,
connectionsLogic.isUserXFriendOfUserY(connection.getUuid(),
currentUserUuid));
}
if (true == allowedStatus) {
WallItem wallItem = new WallItem();
wallItem.setType(ProfileConstants.WALL_ITEM_TYPE_STATUS);
wallItem.setCreatorUuid(connection.getUuid());
wallItem.setDate(connectionStatus.getDateAdded());
wallItem.setText(connectionStatus.getMessage());
filteredWallItems.add(wallItem);
}
}
// wall items are comparable and need to be in order
Collections.sort(filteredWallItems);
// dao limits wall items but we also need to ensure any connection
// status updates don't push the number of wall items over limit
if (filteredWallItems.size() > ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES) {
return filteredWallItems.subList(0, ProfileConstants.MAX_WALL_ITEMS_WITH_CONNECTION_STATUSES);
} else {
return filteredWallItems;
}
}
|
diff --git a/java/src/com/android/inputmethod/keyboard/KeyDetector.java b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
index 868c8cab5..f5686dcda 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyDetector.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
@@ -1,113 +1,119 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.keyboard;
import com.android.inputmethod.latin.Constants;
public class KeyDetector {
private final int mKeyHysteresisDistanceSquared;
private Keyboard mKeyboard;
private int mCorrectionX;
private int mCorrectionY;
/**
* This class handles key detection.
*
* @param keyHysteresisDistance if the pointer movement distance is smaller than this, the
* movement will not been handled as meaningful movement. The unit is pixel.
*/
public KeyDetector(float keyHysteresisDistance) {
mKeyHysteresisDistanceSquared = (int)(keyHysteresisDistance * keyHysteresisDistance);
}
public void setKeyboard(Keyboard keyboard, float correctionX, float correctionY) {
if (keyboard == null) {
throw new NullPointerException();
}
mCorrectionX = (int)correctionX;
mCorrectionY = (int)correctionY;
mKeyboard = keyboard;
}
public int getKeyHysteresisDistanceSquared() {
return mKeyHysteresisDistanceSquared;
}
public int getTouchX(int x) {
return x + mCorrectionX;
}
// TODO: Remove vertical correction.
public int getTouchY(int y) {
return y + mCorrectionY;
}
public Keyboard getKeyboard() {
if (mKeyboard == null) {
throw new IllegalStateException("keyboard isn't set");
}
return mKeyboard;
}
public boolean alwaysAllowsSlidingInput() {
return false;
}
/**
* Detect the key whose hitbox the touch point is in.
*
* @param x The x-coordinate of a touch point
* @param y The y-coordinate of a touch point
* @return the key that the touch point hits.
*/
public Key detectHitKey(int x, int y) {
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int minDistance = Integer.MAX_VALUE;
Key primaryKey = null;
for (final Key key: mKeyboard.getNearestKeys(touchX, touchY)) {
- final boolean isOnKey = key.isOnKey(touchX, touchY);
+ // An edge key always has its enlarged hitbox to respond to an event that occurred in
+ // the empty area around the key. (@see Key#markAsLeftEdge(KeyboardParams)} etc.)
+ if (!key.isOnKey(touchX, touchY)) {
+ continue;
+ }
final int distance = key.squaredDistanceToEdge(touchX, touchY);
+ if (distance > minDistance) {
+ continue;
+ }
// To take care of hitbox overlaps, we compare mCode here too.
- if (primaryKey == null || distance < minDistance
- || (distance == minDistance && isOnKey && key.mCode > primaryKey.mCode)) {
+ if (primaryKey == null || distance < minDistance || key.mCode > primaryKey.mCode) {
minDistance = distance;
primaryKey = key;
}
}
return primaryKey;
}
public static String printableCode(Key key) {
return key != null ? Keyboard.printableCode(key.mCode) : "none";
}
public static String printableCodes(int[] codes) {
final StringBuilder sb = new StringBuilder();
boolean addDelimiter = false;
for (final int code : codes) {
if (code == Constants.NOT_A_CODE) break;
if (addDelimiter) sb.append(", ");
sb.append(Keyboard.printableCode(code));
addDelimiter = true;
}
return "[" + sb + "]";
}
}
| false | true | public Key detectHitKey(int x, int y) {
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int minDistance = Integer.MAX_VALUE;
Key primaryKey = null;
for (final Key key: mKeyboard.getNearestKeys(touchX, touchY)) {
final boolean isOnKey = key.isOnKey(touchX, touchY);
final int distance = key.squaredDistanceToEdge(touchX, touchY);
// To take care of hitbox overlaps, we compare mCode here too.
if (primaryKey == null || distance < minDistance
|| (distance == minDistance && isOnKey && key.mCode > primaryKey.mCode)) {
minDistance = distance;
primaryKey = key;
}
}
return primaryKey;
}
| public Key detectHitKey(int x, int y) {
final int touchX = getTouchX(x);
final int touchY = getTouchY(y);
int minDistance = Integer.MAX_VALUE;
Key primaryKey = null;
for (final Key key: mKeyboard.getNearestKeys(touchX, touchY)) {
// An edge key always has its enlarged hitbox to respond to an event that occurred in
// the empty area around the key. (@see Key#markAsLeftEdge(KeyboardParams)} etc.)
if (!key.isOnKey(touchX, touchY)) {
continue;
}
final int distance = key.squaredDistanceToEdge(touchX, touchY);
if (distance > minDistance) {
continue;
}
// To take care of hitbox overlaps, we compare mCode here too.
if (primaryKey == null || distance < minDistance || key.mCode > primaryKey.mCode) {
minDistance = distance;
primaryKey = key;
}
}
return primaryKey;
}
|
diff --git a/test/plugins/Library/index/TermEntryTest.java b/test/plugins/Library/index/TermEntryTest.java
index 396e104..ae08346 100644
--- a/test/plugins/Library/index/TermEntryTest.java
+++ b/test/plugins/Library/index/TermEntryTest.java
@@ -1,119 +1,119 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Library.index;
import junit.framework.TestCase;
import plugins.Library.io.serial.Serialiser.*;
import plugins.Library.io.serial.FileArchiver;
import plugins.Library.util.exec.TaskAbortException;
import plugins.Library.io.serial.Packer;
import plugins.Library.io.YamlReaderWriter;
import freenet.keys.FreenetURI;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;
import java.net.MalformedURLException;
import java.io.*;
/**
** @author infinity0
*/
public class TermEntryTest extends TestCase {
final static TermTermEntry w = new TermTermEntry("test", 0.8f, "lol");
final static TermIndexEntry x;
final static TermPageEntry z;
final static TermPageEntry v;
static {
try {
x = new TermIndexEntry("test", 0.8f, new FreenetURI("CHK@MIh5-viJQrPkde5gmRZzqjBrqOuh~Wbjg02uuXJUzgM,rKDavdwyVF9Z0sf5BMRZsXj7yiWPFUuewoe0CPesvXE,AAIC--8"));
z = new TermPageEntry("lol", 0.8f, new FreenetURI("CHK@9eDo5QWLQcgSuDh1meTm96R4oE7zpoMBuV15jLiZTps,3HJaHbdW~-MtC6YsSkKn6I0DTG9Z1gKDGgtENhHx82I,AAIC--8"), null);
v = new TermPageEntry("lol", 0.8f, new FreenetURI("CHK@9eDo5QWLQcgSuDh1meTm96R4oE7zpoMBuV15jLiZTps,3HJaHbdW~-MtC6YsSkKn6I0DTG9Z1gKDGgtENhHx82I,AAIC--8"), "title", null);
} catch (MalformedURLException e) {
throw new AssertionError();
}
}
final static TermTermEntry y = new TermTermEntry("test", 0.8f, "lol2");
public void testBasic() throws TaskAbortException {
FileArchiver<Map<String, Object>> ym = new FileArchiver<Map<String, Object>>(new YamlReaderWriter(), "test", null, ".yml");
Map<String, Object> map = new HashMap<String, Object>();
List<TermEntry> l = new ArrayList<TermEntry>();
l.add(w);
l.add(w);
l.add(x);
l.add(y);
l.add(z);
map.put("test", l);
try {
- map.put("test2", new Packer.BinInfo(new FreenetURI("CHK@yeah"), 123));
+ map.put("test2", new Packer.BinInfo(new FreenetURI("http://127.0.0.1:8888/CHK@WtWIvOZXLVZkmDrY5929RxOZ-woRpRoMgE8rdZaQ0VU,rxH~D9VvOOuA7bCnVuzq~eux77i9RR3lsdwVHUgXoOY,AAIC--8/Library.jar"), 123));
} catch (java.net.MalformedURLException e) {
assert(false);
}
ym.push(new PushTask<Map<String, Object>>(map));
PullTask<Map<String, Object>> pt = new PullTask<Map<String, Object>>("");
try{
ym.pull(pt);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(pt.data instanceof Map);
Map<String, Object> m = pt.data;
assertTrue(m.get("test") instanceof List);
List ll = (List)m.get("test");
assertTrue(ll.get(0) instanceof TermTermEntry);
assertTrue(ll.get(1) == ll.get(0));
// NOTE these tests fail in snakeYAML 1.2 and below, fixed in hg
assertTrue(ll.get(2) instanceof TermIndexEntry);
assertTrue(ll.get(3) instanceof TermTermEntry);
assertTrue(m.get("test2") instanceof Packer.BinInfo);
Packer.BinInfo inf = (Packer.BinInfo)m.get("test2");
assertTrue(inf.getID() instanceof FreenetURI);
}
public void testBinaryReadWrite() throws IOException, TaskAbortException {
TermEntryReaderWriter rw = TermEntryReaderWriter.getInstance();
ByteArrayOutputStream bo = new ByteArrayOutputStream();
DataOutputStream oo = new DataOutputStream(bo);
rw.writeObject(v, oo);
rw.writeObject(w, oo);
rw.writeObject(x, oo);
rw.writeObject(y, oo);
rw.writeObject(z, oo);
oo.close();
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
DataInputStream oi = new DataInputStream(bi);
TermEntry v1 = rw.readObject(oi);
TermEntry w1 = rw.readObject(oi);
TermEntry x1 = rw.readObject(oi);
TermEntry y1 = rw.readObject(oi);
TermEntry z1 = rw.readObject(oi);
oi.close();
assertEqualButNotIdentical(v, v1);
assertEqualButNotIdentical(w, w1);
assertEqualButNotIdentical(x, x1); // this will fail before fred@a6e73dbbaa7840bd20d5e3fb95cd2c678a106e85
assertEqualButNotIdentical(y, y1);
assertEqualButNotIdentical(z, z1);
}
public static void assertEqualButNotIdentical(Object a, Object b) {
assertTrue(a != b);
assertTrue(a.equals(b));
assertTrue(a.hashCode() == b.hashCode());
}
}
| true | true | public void testBasic() throws TaskAbortException {
FileArchiver<Map<String, Object>> ym = new FileArchiver<Map<String, Object>>(new YamlReaderWriter(), "test", null, ".yml");
Map<String, Object> map = new HashMap<String, Object>();
List<TermEntry> l = new ArrayList<TermEntry>();
l.add(w);
l.add(w);
l.add(x);
l.add(y);
l.add(z);
map.put("test", l);
try {
map.put("test2", new Packer.BinInfo(new FreenetURI("CHK@yeah"), 123));
} catch (java.net.MalformedURLException e) {
assert(false);
}
ym.push(new PushTask<Map<String, Object>>(map));
PullTask<Map<String, Object>> pt = new PullTask<Map<String, Object>>("");
try{
ym.pull(pt);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(pt.data instanceof Map);
Map<String, Object> m = pt.data;
assertTrue(m.get("test") instanceof List);
List ll = (List)m.get("test");
assertTrue(ll.get(0) instanceof TermTermEntry);
assertTrue(ll.get(1) == ll.get(0));
// NOTE these tests fail in snakeYAML 1.2 and below, fixed in hg
assertTrue(ll.get(2) instanceof TermIndexEntry);
assertTrue(ll.get(3) instanceof TermTermEntry);
assertTrue(m.get("test2") instanceof Packer.BinInfo);
Packer.BinInfo inf = (Packer.BinInfo)m.get("test2");
assertTrue(inf.getID() instanceof FreenetURI);
}
| public void testBasic() throws TaskAbortException {
FileArchiver<Map<String, Object>> ym = new FileArchiver<Map<String, Object>>(new YamlReaderWriter(), "test", null, ".yml");
Map<String, Object> map = new HashMap<String, Object>();
List<TermEntry> l = new ArrayList<TermEntry>();
l.add(w);
l.add(w);
l.add(x);
l.add(y);
l.add(z);
map.put("test", l);
try {
map.put("test2", new Packer.BinInfo(new FreenetURI("http://127.0.0.1:8888/CHK@WtWIvOZXLVZkmDrY5929RxOZ-woRpRoMgE8rdZaQ0VU,rxH~D9VvOOuA7bCnVuzq~eux77i9RR3lsdwVHUgXoOY,AAIC--8/Library.jar"), 123));
} catch (java.net.MalformedURLException e) {
assert(false);
}
ym.push(new PushTask<Map<String, Object>>(map));
PullTask<Map<String, Object>> pt = new PullTask<Map<String, Object>>("");
try{
ym.pull(pt);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(pt.data instanceof Map);
Map<String, Object> m = pt.data;
assertTrue(m.get("test") instanceof List);
List ll = (List)m.get("test");
assertTrue(ll.get(0) instanceof TermTermEntry);
assertTrue(ll.get(1) == ll.get(0));
// NOTE these tests fail in snakeYAML 1.2 and below, fixed in hg
assertTrue(ll.get(2) instanceof TermIndexEntry);
assertTrue(ll.get(3) instanceof TermTermEntry);
assertTrue(m.get("test2") instanceof Packer.BinInfo);
Packer.BinInfo inf = (Packer.BinInfo)m.get("test2");
assertTrue(inf.getID() instanceof FreenetURI);
}
|
diff --git a/modules/org.restlet/src/org/restlet/engine/converter/DefaultConverter.java b/modules/org.restlet/src/org/restlet/engine/converter/DefaultConverter.java
index dc68a195d..3052bad05 100644
--- a/modules/org.restlet/src/org/restlet/engine/converter/DefaultConverter.java
+++ b/modules/org.restlet/src/org/restlet/engine/converter/DefaultConverter.java
@@ -1,343 +1,343 @@
/**
* Copyright 2005-2011 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.engine.converter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.engine.resource.VariantInfo;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.FileRepresentation;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.ObjectRepresentation;
import org.restlet.representation.ReaderRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.representation.Variant;
import org.restlet.resource.Resource;
/**
* Converter for the built-in Representation classes.
*
* @author Jerome Louvel
*/
public class DefaultConverter extends ConverterHelper {
/** Neutral variant. */
private static final VariantInfo VARIANT_ALL = new VariantInfo(
MediaType.ALL);
/** Web form variant. */
private static final VariantInfo VARIANT_FORM = new VariantInfo(
MediaType.APPLICATION_WWW_FORM);
/** Octet stream variant. */
private static final VariantInfo VARIANT_OBJECT = new VariantInfo(
MediaType.APPLICATION_JAVA_OBJECT);
/** Octet stream variant. */
private static final VariantInfo VARIANT_OBJECT_XML = new VariantInfo(
MediaType.APPLICATION_JAVA_OBJECT_XML);
@Override
public List<Class<?>> getObjectClasses(Variant source) {
List<Class<?>> result = null;
result = addObjectClass(result, String.class);
result = addObjectClass(result, InputStream.class);
result = addObjectClass(result, Reader.class);
result = addObjectClass(result, ReadableByteChannel.class);
if (source.getMediaType() != null) {
MediaType mediaType = source.getMediaType();
if (MediaType.APPLICATION_JAVA_OBJECT.equals(mediaType)
|| MediaType.APPLICATION_JAVA_OBJECT_XML.equals(mediaType)) {
result = addObjectClass(result, Object.class);
} else if (MediaType.APPLICATION_WWW_FORM.equals(mediaType)) {
result = addObjectClass(result, Form.class);
}
}
return result;
}
@Override
public List<VariantInfo> getVariants(Class<?> source) {
List<VariantInfo> result = null;
if (String.class.isAssignableFrom(source)
|| StringRepresentation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_ALL);
} else if (File.class.isAssignableFrom(source)
|| FileRepresentation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_ALL);
} else if (InputStream.class.isAssignableFrom(source)
|| InputRepresentation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_ALL);
} else if (Reader.class.isAssignableFrom(source)
|| ReaderRepresentation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_ALL);
} else if (Representation.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_ALL);
} else if (Form.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_FORM);
} else if (Serializable.class.isAssignableFrom(source)) {
result = addVariant(result, VARIANT_OBJECT);
result = addVariant(result, VARIANT_OBJECT_XML);
}
return result;
}
@Override
public float score(Object source, Variant target, Resource resource) {
float result = -1.0F;
if (source instanceof String) {
result = 1.0F;
} else if (source instanceof File) {
result = 1.0F;
} else if (source instanceof Form) {
if ((target != null)
&& MediaType.APPLICATION_WWW_FORM.isCompatible(target
.getMediaType())) {
result = 1.0F;
} else {
result = 0.6F;
}
} else if (source instanceof InputStream) {
result = 1.0F;
} else if (source instanceof Reader) {
result = 1.0F;
} else if (source instanceof Representation) {
result = 1.0F;
} else if (source instanceof Serializable) {
if (target != null) {
if (MediaType.APPLICATION_JAVA_OBJECT.equals(target
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT
.isCompatible(target.getMediaType())) {
result = 0.6F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(target
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML
.isCompatible(target.getMediaType())) {
result = 0.6F;
}
} else {
result = 0.5F;
}
}
return result;
}
@Override
public <T> float score(Representation source, Class<T> target,
Resource resource) {
float result = -1.0F;
if (target != null) {
- if (Representation.class.isAssignableFrom(target)) {
+ if (target.isAssignableFrom(source.getClass())) {
result = 1.0F;
} else if (String.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (StringRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (EmptyRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (File.class.isAssignableFrom(target)) {
if (source instanceof FileRepresentation) {
result = 1.0F;
}
} else if (Form.class.isAssignableFrom(target)) {
if (MediaType.APPLICATION_WWW_FORM.isCompatible(source
.getMediaType())) {
result = 1.0F;
} else {
result = 0.5F;
}
} else if (InputStream.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (InputRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Reader.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (ReaderRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Serializable.class.isAssignableFrom(target)
|| target.isPrimitive()) {
if (MediaType.APPLICATION_JAVA_OBJECT.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else {
result = 0.5F;
}
}
} else if (source instanceof ObjectRepresentation<?>) {
result = 1.0F;
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public <T> T toObject(Representation source, Class<T> target,
Resource resource) throws IOException {
Object result = null;
if (target != null) {
if (target.isAssignableFrom(source.getClass())) {
result = source;
} else if (String.class.isAssignableFrom(target)) {
result = source.getText();
} else if (StringRepresentation.class.isAssignableFrom(target)) {
result = new StringRepresentation(source.getText(),
source.getMediaType());
} else if (EmptyRepresentation.class.isAssignableFrom(target)) {
result = null;
} else if (File.class.isAssignableFrom(target)) {
if (source instanceof FileRepresentation) {
result = ((FileRepresentation) source).getFile();
} else {
result = null;
}
} else if (Form.class.isAssignableFrom(target)) {
result = new Form(source);
} else if (InputStream.class.isAssignableFrom(target)) {
result = source.getStream();
} else if (InputRepresentation.class.isAssignableFrom(target)) {
result = new InputRepresentation(source.getStream());
} else if (Reader.class.isAssignableFrom(target)) {
result = source.getReader();
} else if (ReaderRepresentation.class.isAssignableFrom(target)) {
result = new ReaderRepresentation(source.getReader());
} else if (Serializable.class.isAssignableFrom(target)
|| target.isPrimitive()) {
if (source instanceof ObjectRepresentation<?>) {
result = ((ObjectRepresentation<?>) source).getObject();
} else {
try {
result = new ObjectRepresentation<Serializable>(source)
.getObject();
} catch (Exception e) {
IOException ioe = new IOException(
"Unable to create the Object representation");
ioe.initCause(e);
result = null;
}
}
}
} else if (source instanceof ObjectRepresentation<?>) {
result = ((ObjectRepresentation<?>) source).getObject();
}
return (T) result;
}
@Override
public Representation toRepresentation(Object source, Variant target,
Resource resource) throws IOException {
Representation result = null;
if (source instanceof String) {
result = new StringRepresentation((String) source,
MediaType.getMostSpecific(target.getMediaType(),
MediaType.TEXT_PLAIN));
} else if (source instanceof File) {
result = new FileRepresentation((File) source,
MediaType.getMostSpecific(target.getMediaType(),
MediaType.APPLICATION_OCTET_STREAM));
} else if (source instanceof Form) {
result = ((Form) source).getWebRepresentation();
} else if (source instanceof InputStream) {
result = new InputRepresentation((InputStream) source,
MediaType.getMostSpecific(target.getMediaType(),
MediaType.APPLICATION_OCTET_STREAM));
} else if (source instanceof Reader) {
result = new ReaderRepresentation((Reader) source,
MediaType.getMostSpecific(target.getMediaType(),
MediaType.TEXT_PLAIN));
} else if (source instanceof Representation) {
result = (Representation) source;
} else if (source instanceof Serializable) {
result = new ObjectRepresentation<Serializable>(
(Serializable) source, MediaType.getMostSpecific(
target.getMediaType(),
MediaType.APPLICATION_OCTET_STREAM));
}
return result;
}
@Override
public <T> void updatePreferences(List<Preference<MediaType>> preferences,
Class<T> entity) {
if (Form.class.isAssignableFrom(entity)) {
updatePreferences(preferences, MediaType.APPLICATION_WWW_FORM, 1.0F);
} else if (Serializable.class.isAssignableFrom(entity)) {
updatePreferences(preferences, MediaType.APPLICATION_JAVA_OBJECT,
1.0F);
updatePreferences(preferences,
MediaType.APPLICATION_JAVA_OBJECT_XML, 1.0F);
} else if (String.class.isAssignableFrom(entity)
|| Reader.class.isAssignableFrom(entity)) {
updatePreferences(preferences, MediaType.TEXT_PLAIN, 1.0F);
updatePreferences(preferences, MediaType.TEXT_ALL, 0.5F);
} else if (InputStream.class.isAssignableFrom(entity)
|| ReadableByteChannel.class.isAssignableFrom(entity)) {
updatePreferences(preferences, MediaType.APPLICATION_OCTET_STREAM,
1.0F);
updatePreferences(preferences, MediaType.APPLICATION_ALL, 0.5F);
}
}
}
| true | true | public <T> float score(Representation source, Class<T> target,
Resource resource) {
float result = -1.0F;
if (target != null) {
if (Representation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (String.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (StringRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (EmptyRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (File.class.isAssignableFrom(target)) {
if (source instanceof FileRepresentation) {
result = 1.0F;
}
} else if (Form.class.isAssignableFrom(target)) {
if (MediaType.APPLICATION_WWW_FORM.isCompatible(source
.getMediaType())) {
result = 1.0F;
} else {
result = 0.5F;
}
} else if (InputStream.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (InputRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Reader.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (ReaderRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Serializable.class.isAssignableFrom(target)
|| target.isPrimitive()) {
if (MediaType.APPLICATION_JAVA_OBJECT.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else {
result = 0.5F;
}
}
} else if (source instanceof ObjectRepresentation<?>) {
result = 1.0F;
}
return result;
}
| public <T> float score(Representation source, Class<T> target,
Resource resource) {
float result = -1.0F;
if (target != null) {
if (target.isAssignableFrom(source.getClass())) {
result = 1.0F;
} else if (String.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (StringRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (EmptyRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (File.class.isAssignableFrom(target)) {
if (source instanceof FileRepresentation) {
result = 1.0F;
}
} else if (Form.class.isAssignableFrom(target)) {
if (MediaType.APPLICATION_WWW_FORM.isCompatible(source
.getMediaType())) {
result = 1.0F;
} else {
result = 0.5F;
}
} else if (InputStream.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (InputRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Reader.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (ReaderRepresentation.class.isAssignableFrom(target)) {
result = 1.0F;
} else if (Serializable.class.isAssignableFrom(target)
|| target.isPrimitive()) {
if (MediaType.APPLICATION_JAVA_OBJECT.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML.equals(source
.getMediaType())) {
result = 1.0F;
} else if (MediaType.APPLICATION_JAVA_OBJECT_XML
.isCompatible(source.getMediaType())) {
result = 0.6F;
} else {
result = 0.5F;
}
}
} else if (source instanceof ObjectRepresentation<?>) {
result = 1.0F;
}
return result;
}
|
diff --git a/src/main/java/org/uncertweb/et/learning/Learning.java b/src/main/java/org/uncertweb/et/learning/Learning.java
index db91785..b44ffb8 100644
--- a/src/main/java/org/uncertweb/et/learning/Learning.java
+++ b/src/main/java/org/uncertweb/et/learning/Learning.java
@@ -1,169 +1,169 @@
package org.uncertweb.et.learning;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uncertweb.et.Config;
import org.uncertweb.et.ConfigException;
import org.uncertweb.et.MATLAB;
import org.uncertweb.et.design.Design;
import org.uncertweb.et.design.NormalisedDesign;
import org.uncertweb.et.process.NormalisedProcessEvaluationResult;
import org.uncertweb.et.process.ProcessEvaluationResult;
import org.uncertweb.matlab.MLException;
import org.uncertweb.matlab.MLRequest;
import org.uncertweb.matlab.MLResult;
import org.uncertweb.matlab.value.MLArray;
import org.uncertweb.matlab.value.MLCell;
import org.uncertweb.matlab.value.MLMatrix;
import org.uncertweb.matlab.value.MLScalar;
import org.uncertweb.matlab.value.MLString;
import org.uncertweb.matlab.value.MLValue;
public class Learning {
private static final Logger logger = LoggerFactory.getLogger(Learning.class);
public static LearningResult learn(Design design, ProcessEvaluationResult evaluationResult, String selectedOutputIdentifier, int trainingSetSize, String covarianceFunction, double lengthScale, double processVariance, Double nuggetVariance, String meanFunction, boolean normalisation) throws LearningException {
// setup x
Design x = design;
// setup y
ProcessEvaluationResult y = evaluationResult;
// normalise?
if (normalisation) {
logger.info("Normalising inputs and outputs...");
x = NormalisedDesign.fromDesign(x);
y = NormalisedProcessEvaluationResult.fromProcessEvaluationResult(y);
}
// setup request
MLRequest request = new MLRequest("learn_emulator", 5);
request.addParameter(new MLString((String)Config.getInstance().get("matlab", "gpml_path")));
// add x
request.addParameter(new MLMatrix(x.getPoints()));
// add y
// select output and transpose
Double[] results = y.getResults(selectedOutputIdentifier);
double[][] yt = new double[results.length][];
for (int i = 0; i < results.length; i++) {
yt[i] = new double[] { results[i] };
}
request.addParameter(new MLMatrix(yt));
// add training size
request.addParameter(new MLScalar(trainingSetSize));
// setup covariance function
MLValue covfname;
double[] covfpar;
if (covarianceFunction.equals("squared_exponential")) {
covfname = new MLString("covSEiso");
}
else {
covfname = new MLString("covMatern3iso");
}
if (nuggetVariance != null) {
covfname = new MLCell(new MLValue[] {
new MLString("covSum"),
new MLCell(new MLValue[] { covfname, new MLString("covNoise") }) });
covfpar = new double[] { lengthScale, Math.sqrt(processVariance), nuggetVariance };
}
else {
covfpar = new double[] { lengthScale, Math.sqrt(processVariance) };
}
request.addParameter(covfname);
request.addParameter(new MLArray(covfpar));
// setup mean function
String meanfname;
double[] meanfpar;
if (meanFunction.equals("zero")) {
meanfname = "";
meanfpar = new double[] {};
}
else {
meanfname = "mean_poly";
meanfpar = new double[1];
if (meanFunction.equals("constant")) {
meanfpar[0] = 0;
}
else if (meanFunction.equals("linear")) {
meanfpar[0] = 1;
}
else {
meanfpar[0] = 2;
}
}
request.addParameter(new MLString(meanfname));
request.addParameter(new MLArray(meanfpar));
// call matlab to: create training set, setup gp, predict, optimise
logger.info("Learning emulator...");
for (String identifier : design.getInputIdentifiers()) {
DescriptiveStatistics stats = new DescriptiveStatistics(ArrayUtils.toPrimitive(design.getPoints(identifier)));
logger.debug("identifier='" + identifier + "', min=" + stats.getMin() + ", max=" + stats.getMax());
}
logger.debug("meanfname=" + meanfname + ", meanfpar=" + Arrays.toString(meanfpar) + ", covfname=" + covfname + ", covfpar=" + Arrays.toString(covfpar));
// send
try {
MLResult result = MATLAB.sendRequest(request);
double[] predictedMean = result.getResult(0).getAsArray().getArray();
double[] predictedCovariance = result.getResult(1).getAsArray().getArray();
double[][] xtrn = result.getResult(2).getAsMatrix().getMatrix();
double[][] ytrn = result.getResult(3).getAsMatrix().getMatrix();
double[] optCovParams = result.getResult(4).getAsArray().getArray();
Design trainingDesign = new Design(xtrn.length);
ProcessEvaluationResult trainingEvaluationResult = new ProcessEvaluationResult();
for (int i = 0; i < design.getInputIdentifiers().size(); i++) {
// i is our row
Double[] trn = new Double[xtrn.length];
// j is the realisation
for (int j = 0; j < xtrn.length; j++) {
trn[j] = xtrn[j][i];
}
trainingDesign.addPoints(design.getInputIdentifiers().get(i), trn);
}
double[] ytrnArr = new double[ytrn.length];
for (int i = 0; i < ytrn.length; i++) {
ytrnArr[i] = ytrn[i][0]; // as we are only looking at one output
}
trainingEvaluationResult.addResults(selectedOutputIdentifier, ytrnArr);
if (normalisation) {
NormalisedDesign nd = (NormalisedDesign)x;
NormalisedProcessEvaluationResult nper = (NormalisedProcessEvaluationResult)y;
- return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1], nd.getMeans(), nd.getStdDevs(), nper.getMeans(), nper.getStdDevs());
+ return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1], nd.getMeans(), nd.getStdDevs(), nper.getMean(selectedOutputIdentifier), nper.getStdDev(selectedOutputIdentifier));
}
else {
return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1]);
}
}
catch (MLException e) {
throw new LearningException("Couldn't perform learning: " + e.getMessage());
}
catch (IOException e) {
throw new LearningException("Couldn't connect to MATLAB.");
}
catch (ConfigException e) {
throw new LearningException("Couldn't load MATLAB config details.");
}
}
}
| true | true | public static LearningResult learn(Design design, ProcessEvaluationResult evaluationResult, String selectedOutputIdentifier, int trainingSetSize, String covarianceFunction, double lengthScale, double processVariance, Double nuggetVariance, String meanFunction, boolean normalisation) throws LearningException {
// setup x
Design x = design;
// setup y
ProcessEvaluationResult y = evaluationResult;
// normalise?
if (normalisation) {
logger.info("Normalising inputs and outputs...");
x = NormalisedDesign.fromDesign(x);
y = NormalisedProcessEvaluationResult.fromProcessEvaluationResult(y);
}
// setup request
MLRequest request = new MLRequest("learn_emulator", 5);
request.addParameter(new MLString((String)Config.getInstance().get("matlab", "gpml_path")));
// add x
request.addParameter(new MLMatrix(x.getPoints()));
// add y
// select output and transpose
Double[] results = y.getResults(selectedOutputIdentifier);
double[][] yt = new double[results.length][];
for (int i = 0; i < results.length; i++) {
yt[i] = new double[] { results[i] };
}
request.addParameter(new MLMatrix(yt));
// add training size
request.addParameter(new MLScalar(trainingSetSize));
// setup covariance function
MLValue covfname;
double[] covfpar;
if (covarianceFunction.equals("squared_exponential")) {
covfname = new MLString("covSEiso");
}
else {
covfname = new MLString("covMatern3iso");
}
if (nuggetVariance != null) {
covfname = new MLCell(new MLValue[] {
new MLString("covSum"),
new MLCell(new MLValue[] { covfname, new MLString("covNoise") }) });
covfpar = new double[] { lengthScale, Math.sqrt(processVariance), nuggetVariance };
}
else {
covfpar = new double[] { lengthScale, Math.sqrt(processVariance) };
}
request.addParameter(covfname);
request.addParameter(new MLArray(covfpar));
// setup mean function
String meanfname;
double[] meanfpar;
if (meanFunction.equals("zero")) {
meanfname = "";
meanfpar = new double[] {};
}
else {
meanfname = "mean_poly";
meanfpar = new double[1];
if (meanFunction.equals("constant")) {
meanfpar[0] = 0;
}
else if (meanFunction.equals("linear")) {
meanfpar[0] = 1;
}
else {
meanfpar[0] = 2;
}
}
request.addParameter(new MLString(meanfname));
request.addParameter(new MLArray(meanfpar));
// call matlab to: create training set, setup gp, predict, optimise
logger.info("Learning emulator...");
for (String identifier : design.getInputIdentifiers()) {
DescriptiveStatistics stats = new DescriptiveStatistics(ArrayUtils.toPrimitive(design.getPoints(identifier)));
logger.debug("identifier='" + identifier + "', min=" + stats.getMin() + ", max=" + stats.getMax());
}
logger.debug("meanfname=" + meanfname + ", meanfpar=" + Arrays.toString(meanfpar) + ", covfname=" + covfname + ", covfpar=" + Arrays.toString(covfpar));
// send
try {
MLResult result = MATLAB.sendRequest(request);
double[] predictedMean = result.getResult(0).getAsArray().getArray();
double[] predictedCovariance = result.getResult(1).getAsArray().getArray();
double[][] xtrn = result.getResult(2).getAsMatrix().getMatrix();
double[][] ytrn = result.getResult(3).getAsMatrix().getMatrix();
double[] optCovParams = result.getResult(4).getAsArray().getArray();
Design trainingDesign = new Design(xtrn.length);
ProcessEvaluationResult trainingEvaluationResult = new ProcessEvaluationResult();
for (int i = 0; i < design.getInputIdentifiers().size(); i++) {
// i is our row
Double[] trn = new Double[xtrn.length];
// j is the realisation
for (int j = 0; j < xtrn.length; j++) {
trn[j] = xtrn[j][i];
}
trainingDesign.addPoints(design.getInputIdentifiers().get(i), trn);
}
double[] ytrnArr = new double[ytrn.length];
for (int i = 0; i < ytrn.length; i++) {
ytrnArr[i] = ytrn[i][0]; // as we are only looking at one output
}
trainingEvaluationResult.addResults(selectedOutputIdentifier, ytrnArr);
if (normalisation) {
NormalisedDesign nd = (NormalisedDesign)x;
NormalisedProcessEvaluationResult nper = (NormalisedProcessEvaluationResult)y;
return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1], nd.getMeans(), nd.getStdDevs(), nper.getMeans(), nper.getStdDevs());
}
else {
return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1]);
}
}
catch (MLException e) {
throw new LearningException("Couldn't perform learning: " + e.getMessage());
}
catch (IOException e) {
throw new LearningException("Couldn't connect to MATLAB.");
}
catch (ConfigException e) {
throw new LearningException("Couldn't load MATLAB config details.");
}
}
| public static LearningResult learn(Design design, ProcessEvaluationResult evaluationResult, String selectedOutputIdentifier, int trainingSetSize, String covarianceFunction, double lengthScale, double processVariance, Double nuggetVariance, String meanFunction, boolean normalisation) throws LearningException {
// setup x
Design x = design;
// setup y
ProcessEvaluationResult y = evaluationResult;
// normalise?
if (normalisation) {
logger.info("Normalising inputs and outputs...");
x = NormalisedDesign.fromDesign(x);
y = NormalisedProcessEvaluationResult.fromProcessEvaluationResult(y);
}
// setup request
MLRequest request = new MLRequest("learn_emulator", 5);
request.addParameter(new MLString((String)Config.getInstance().get("matlab", "gpml_path")));
// add x
request.addParameter(new MLMatrix(x.getPoints()));
// add y
// select output and transpose
Double[] results = y.getResults(selectedOutputIdentifier);
double[][] yt = new double[results.length][];
for (int i = 0; i < results.length; i++) {
yt[i] = new double[] { results[i] };
}
request.addParameter(new MLMatrix(yt));
// add training size
request.addParameter(new MLScalar(trainingSetSize));
// setup covariance function
MLValue covfname;
double[] covfpar;
if (covarianceFunction.equals("squared_exponential")) {
covfname = new MLString("covSEiso");
}
else {
covfname = new MLString("covMatern3iso");
}
if (nuggetVariance != null) {
covfname = new MLCell(new MLValue[] {
new MLString("covSum"),
new MLCell(new MLValue[] { covfname, new MLString("covNoise") }) });
covfpar = new double[] { lengthScale, Math.sqrt(processVariance), nuggetVariance };
}
else {
covfpar = new double[] { lengthScale, Math.sqrt(processVariance) };
}
request.addParameter(covfname);
request.addParameter(new MLArray(covfpar));
// setup mean function
String meanfname;
double[] meanfpar;
if (meanFunction.equals("zero")) {
meanfname = "";
meanfpar = new double[] {};
}
else {
meanfname = "mean_poly";
meanfpar = new double[1];
if (meanFunction.equals("constant")) {
meanfpar[0] = 0;
}
else if (meanFunction.equals("linear")) {
meanfpar[0] = 1;
}
else {
meanfpar[0] = 2;
}
}
request.addParameter(new MLString(meanfname));
request.addParameter(new MLArray(meanfpar));
// call matlab to: create training set, setup gp, predict, optimise
logger.info("Learning emulator...");
for (String identifier : design.getInputIdentifiers()) {
DescriptiveStatistics stats = new DescriptiveStatistics(ArrayUtils.toPrimitive(design.getPoints(identifier)));
logger.debug("identifier='" + identifier + "', min=" + stats.getMin() + ", max=" + stats.getMax());
}
logger.debug("meanfname=" + meanfname + ", meanfpar=" + Arrays.toString(meanfpar) + ", covfname=" + covfname + ", covfpar=" + Arrays.toString(covfpar));
// send
try {
MLResult result = MATLAB.sendRequest(request);
double[] predictedMean = result.getResult(0).getAsArray().getArray();
double[] predictedCovariance = result.getResult(1).getAsArray().getArray();
double[][] xtrn = result.getResult(2).getAsMatrix().getMatrix();
double[][] ytrn = result.getResult(3).getAsMatrix().getMatrix();
double[] optCovParams = result.getResult(4).getAsArray().getArray();
Design trainingDesign = new Design(xtrn.length);
ProcessEvaluationResult trainingEvaluationResult = new ProcessEvaluationResult();
for (int i = 0; i < design.getInputIdentifiers().size(); i++) {
// i is our row
Double[] trn = new Double[xtrn.length];
// j is the realisation
for (int j = 0; j < xtrn.length; j++) {
trn[j] = xtrn[j][i];
}
trainingDesign.addPoints(design.getInputIdentifiers().get(i), trn);
}
double[] ytrnArr = new double[ytrn.length];
for (int i = 0; i < ytrn.length; i++) {
ytrnArr[i] = ytrn[i][0]; // as we are only looking at one output
}
trainingEvaluationResult.addResults(selectedOutputIdentifier, ytrnArr);
if (normalisation) {
NormalisedDesign nd = (NormalisedDesign)x;
NormalisedProcessEvaluationResult nper = (NormalisedProcessEvaluationResult)y;
return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1], nd.getMeans(), nd.getStdDevs(), nper.getMean(selectedOutputIdentifier), nper.getStdDev(selectedOutputIdentifier));
}
else {
return new LearningResult(predictedMean, predictedCovariance, trainingDesign, trainingEvaluationResult, optCovParams[0], optCovParams[1] * optCovParams[1]);
}
}
catch (MLException e) {
throw new LearningException("Couldn't perform learning: " + e.getMessage());
}
catch (IOException e) {
throw new LearningException("Couldn't connect to MATLAB.");
}
catch (ConfigException e) {
throw new LearningException("Couldn't load MATLAB config details.");
}
}
|
diff --git a/src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java b/src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java
index 8910d216..f641582e 100644
--- a/src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java
+++ b/src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java
@@ -1,251 +1,251 @@
package com.censoredsoftware.Demigods.Engine;
import java.util.ArrayDeque;
import java.util.Deque;
import org.bukkit.ChatColor;
import org.bukkit.conversations.ConversationFactory;
import org.bukkit.plugin.Plugin;
import com.censoredsoftware.Demigods.DemigodsPlugin;
import com.censoredsoftware.Demigods.Engine.Command.DevelopmentCommands;
import com.censoredsoftware.Demigods.Engine.Command.GeneralCommands;
import com.censoredsoftware.Demigods.Engine.Command.MainCommand;
import com.censoredsoftware.Demigods.Engine.Conversation.Conversation;
import com.censoredsoftware.Demigods.Engine.Exceptions.DemigodsStartupException;
import com.censoredsoftware.Demigods.Engine.Listener.*;
import com.censoredsoftware.Demigods.Engine.Module.ConfigModule;
import com.censoredsoftware.Demigods.Engine.Module.FontModule;
import com.censoredsoftware.Demigods.Engine.Module.MessageModule;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability;
import com.censoredsoftware.Demigods.Engine.Object.Conversation.ConversationInfo;
import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity;
import com.censoredsoftware.Demigods.Engine.Object.General.DemigodsCommand;
import com.censoredsoftware.Demigods.Engine.Object.Language.Translation;
import com.censoredsoftware.Demigods.Engine.Object.Structure.StructureInfo;
import com.censoredsoftware.Demigods.Engine.Object.Task.Task;
import com.censoredsoftware.Demigods.Engine.Object.Task.TaskSet;
import com.censoredsoftware.Demigods.Engine.Utility.*;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class Demigods
{
// Public Static Access
public static DemigodsPlugin plugin;
public static ConversationFactory conversation;
// Public Modules
public static ConfigModule config;
public static FontModule font;
public static MessageModule message;
// Public Dependency Plugins
public static WorldGuardPlugin worldguard;
// The Game Data
protected static Deque<Deity> deities;
protected static Deque<TaskSet> quests;
protected static Deque<StructureInfo> structures;
protected static Deque<ConversationInfo> conversasions;
// The Engine Default Text
public static Translation text;
public interface ListedDeity
{
public Deity getDeity();
}
public interface ListedTaskSet
{
public TaskSet getTaskSet();
}
public interface ListedStructure
{
public StructureInfo getStructure();
}
public interface ListedConversation
{
public ConversationInfo getConversation();
}
public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation[] conversations) throws DemigodsStartupException
{
// Allow static access.
plugin = instance;
conversation = new ConversationFactory(instance);
// Setup public modules.
config = new ConfigModule(instance, true);
font = new FontModule();
message = new MessageModule(instance, font, config.getSettingBoolean("misc.tag_messages"));
// Define the game data.
Demigods.deities = new ArrayDeque<Deity>()
{
{
for(ListedDeity deity : deities)
add(deity.getDeity());
}
};
Demigods.quests = new ArrayDeque<TaskSet>()
{
{
for(ListedTaskSet taskSet : taskSets)
add(taskSet.getTaskSet());
}
};
Demigods.structures = new ArrayDeque<StructureInfo>()
{
{
for(ListedStructure structure : structures)
add(structure.getStructure());
}
};
Demigods.conversasions = new ArrayDeque<ConversationInfo>()
{
{
for(Conversation conversation : Conversation.values())
add(conversation.getConversation());
- for(ListedConversation conversation : conversations)
+ if(conversations != null) for(ListedConversation conversation : conversations)
add(conversation.getConversation());
}
};
Demigods.text = getTranslation();
// Initialize soft data.
new DataUtility();
if(!DataUtility.isConnected())
{
message.severe("Demigods was unable to connect to a Redis server.");
message.severe("A Redis server is required for Demigods to run.");
message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")");
instance.getServer().getPluginManager().disablePlugin(instance);
throw new DemigodsStartupException();
}
// Initialize metrics.
try
{
// (new Metrics(instance)).start();
}
catch(Exception ignored)
{}
// Finish loading the plugin based on the game data.
loadDepends(instance);
loadListeners(instance);
loadCommands();
// Finally, regenerate structures
StructureUtility.regenerateStructures();
// Start game threads.
SchedulerUtility.startThreads(instance);
if(SpigotUtility.runningSpigot()) message.info(("Spigot found, will use extra API features."));
}
/**
* Get the translation involved.
*
* @return The translation.
*/
public Translation getTranslation()
{
// Default to EnglishCharNames
return new TextUtility.English();
}
protected static void loadListeners(DemigodsPlugin instance)
{
// Engine
instance.getServer().getPluginManager().registerEvents(new AbilityListener(), instance);
instance.getServer().getPluginManager().registerEvents(new BattleListener(), instance);
instance.getServer().getPluginManager().registerEvents(new CharacterListener(), instance);
instance.getServer().getPluginManager().registerEvents(new ChatListener(), instance);
instance.getServer().getPluginManager().registerEvents(new CommandListener(), instance);
instance.getServer().getPluginManager().registerEvents(new EntityListener(), instance);
instance.getServer().getPluginManager().registerEvents(new PlayerListener(), instance);
instance.getServer().getPluginManager().registerEvents(new StructureListener(), instance);
instance.getServer().getPluginManager().registerEvents(new TributeListener(), instance);
instance.getServer().getPluginManager().registerEvents(new GriefListener(), instance);
// Deities
for(Deity deity : getLoadedDeities())
{
if(deity.getAbilities() == null) continue;
for(Ability ability : deity.getAbilities())
{
if(ability.getListener() != null) instance.getServer().getPluginManager().registerEvents(ability.getListener(), instance);
}
}
// Tasks
for(TaskSet quest : getLoadedQuests())
{
if(quest.getTasks() == null) continue;
for(Task task : quest.getTasks())
{
if(task.getListener() != null) instance.getServer().getPluginManager().registerEvents(task.getListener(), instance);
}
}
// Structures
for(StructureInfo structure : getLoadedStructures())
{
if(structure.getUniqueListener() == null) continue;
instance.getServer().getPluginManager().registerEvents(structure.getUniqueListener(), instance);
}
// Conversations
for(ConversationInfo conversation : getLoadedConversations())
{
if(conversation.getUniqueListener() == null) continue;
instance.getServer().getPluginManager().registerEvents(conversation.getUniqueListener(), instance);
}
}
protected static void loadCommands()
{
DemigodsCommand.registerCommand(new MainCommand());
DemigodsCommand.registerCommand(new GeneralCommands());
DemigodsCommand.registerCommand(new DevelopmentCommands());
}
protected static void loadDepends(DemigodsPlugin instance)
{
// WorldGuard
Plugin depend = instance.getServer().getPluginManager().getPlugin("WorldGuard");
if(depend instanceof WorldGuardPlugin) worldguard = (WorldGuardPlugin) depend;
}
public static Deque<Deity> getLoadedDeities()
{
return Demigods.deities;
}
public static Deque<TaskSet> getLoadedQuests()
{
return Demigods.quests;
}
public static Deque<StructureInfo> getLoadedStructures()
{
return Demigods.structures;
}
public static Deque<ConversationInfo> getLoadedConversations()
{
return Demigods.getLoadedConversations();
}
@Override
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}
| true | true | public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation[] conversations) throws DemigodsStartupException
{
// Allow static access.
plugin = instance;
conversation = new ConversationFactory(instance);
// Setup public modules.
config = new ConfigModule(instance, true);
font = new FontModule();
message = new MessageModule(instance, font, config.getSettingBoolean("misc.tag_messages"));
// Define the game data.
Demigods.deities = new ArrayDeque<Deity>()
{
{
for(ListedDeity deity : deities)
add(deity.getDeity());
}
};
Demigods.quests = new ArrayDeque<TaskSet>()
{
{
for(ListedTaskSet taskSet : taskSets)
add(taskSet.getTaskSet());
}
};
Demigods.structures = new ArrayDeque<StructureInfo>()
{
{
for(ListedStructure structure : structures)
add(structure.getStructure());
}
};
Demigods.conversasions = new ArrayDeque<ConversationInfo>()
{
{
for(Conversation conversation : Conversation.values())
add(conversation.getConversation());
for(ListedConversation conversation : conversations)
add(conversation.getConversation());
}
};
Demigods.text = getTranslation();
// Initialize soft data.
new DataUtility();
if(!DataUtility.isConnected())
{
message.severe("Demigods was unable to connect to a Redis server.");
message.severe("A Redis server is required for Demigods to run.");
message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")");
instance.getServer().getPluginManager().disablePlugin(instance);
throw new DemigodsStartupException();
}
// Initialize metrics.
try
{
// (new Metrics(instance)).start();
}
catch(Exception ignored)
{}
// Finish loading the plugin based on the game data.
loadDepends(instance);
loadListeners(instance);
loadCommands();
// Finally, regenerate structures
StructureUtility.regenerateStructures();
// Start game threads.
SchedulerUtility.startThreads(instance);
if(SpigotUtility.runningSpigot()) message.info(("Spigot found, will use extra API features."));
}
| public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation[] conversations) throws DemigodsStartupException
{
// Allow static access.
plugin = instance;
conversation = new ConversationFactory(instance);
// Setup public modules.
config = new ConfigModule(instance, true);
font = new FontModule();
message = new MessageModule(instance, font, config.getSettingBoolean("misc.tag_messages"));
// Define the game data.
Demigods.deities = new ArrayDeque<Deity>()
{
{
for(ListedDeity deity : deities)
add(deity.getDeity());
}
};
Demigods.quests = new ArrayDeque<TaskSet>()
{
{
for(ListedTaskSet taskSet : taskSets)
add(taskSet.getTaskSet());
}
};
Demigods.structures = new ArrayDeque<StructureInfo>()
{
{
for(ListedStructure structure : structures)
add(structure.getStructure());
}
};
Demigods.conversasions = new ArrayDeque<ConversationInfo>()
{
{
for(Conversation conversation : Conversation.values())
add(conversation.getConversation());
if(conversations != null) for(ListedConversation conversation : conversations)
add(conversation.getConversation());
}
};
Demigods.text = getTranslation();
// Initialize soft data.
new DataUtility();
if(!DataUtility.isConnected())
{
message.severe("Demigods was unable to connect to a Redis server.");
message.severe("A Redis server is required for Demigods to run.");
message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")");
instance.getServer().getPluginManager().disablePlugin(instance);
throw new DemigodsStartupException();
}
// Initialize metrics.
try
{
// (new Metrics(instance)).start();
}
catch(Exception ignored)
{}
// Finish loading the plugin based on the game data.
loadDepends(instance);
loadListeners(instance);
loadCommands();
// Finally, regenerate structures
StructureUtility.regenerateStructures();
// Start game threads.
SchedulerUtility.startThreads(instance);
if(SpigotUtility.runningSpigot()) message.info(("Spigot found, will use extra API features."));
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/model/roster/RosterEntryElement.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/model/roster/RosterEntryElement.java
index 55f8bbd8b..5809d3888 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/model/roster/RosterEntryElement.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/model/roster/RosterEntryElement.java
@@ -1,205 +1,205 @@
package de.fu_berlin.inf.dpp.ui.model.roster;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.packet.RosterPacket.ItemType;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.Saros;
import de.fu_berlin.inf.dpp.SarosPluginContext;
import de.fu_berlin.inf.dpp.net.JID;
import de.fu_berlin.inf.dpp.net.NetTransferMode;
import de.fu_berlin.inf.dpp.net.discoverymanager.DiscoveryManager;
import de.fu_berlin.inf.dpp.net.discoverymanager.DiscoveryManager.CacheMissException;
import de.fu_berlin.inf.dpp.net.internal.DataTransferManager;
import de.fu_berlin.inf.dpp.net.util.RosterUtils;
import de.fu_berlin.inf.dpp.ui.ImageManager;
import de.fu_berlin.inf.dpp.ui.Messages;
import de.fu_berlin.inf.dpp.ui.model.ITreeElement;
import de.fu_berlin.inf.dpp.ui.model.TreeElement;
/**
* Wrapper for {@link RosterEntryElement RosterEntryElements} in use with
* {@link Viewer Viewers}
*
* @author bkahlert
*/
public class RosterEntryElement extends TreeElement {
@Inject
protected DataTransferManager dataTransferManager;
@Inject
protected DiscoveryManager discoveryManager;
protected Roster roster;
protected JID jid;
public static RosterEntryElement[] createAll(Roster roster,
Collection<String> addresses) {
List<RosterEntryElement> rosterEntryElements = new ArrayList<RosterEntryElement>();
for (Iterator<String> iterator = addresses.iterator(); iterator
.hasNext();) {
String address = iterator.next();
rosterEntryElements.add(new RosterEntryElement(roster, new JID(
address)));
}
return rosterEntryElements.toArray(new RosterEntryElement[0]);
}
public RosterEntryElement(Roster roster, JID jid) {
SarosPluginContext.initComponent(this);
this.roster = roster;
this.jid = jid;
}
protected RosterEntry getRosterEntry() {
if (roster == null)
return null;
return roster.getEntry(jid.getBase());
}
@Override
public StyledString getStyledText() {
StyledString styledString = new StyledString();
final String connected_using = Messages.RosterEntryElement_connected_using;
RosterEntry rosterEntry = this.getRosterEntry();
styledString.append((rosterEntry == null) ? jid.toString()
: RosterUtils.getDisplayableName(rosterEntry));
final Presence presence = roster.getPresence(jid.getBase());
if (rosterEntry != null
&& rosterEntry.getStatus() == RosterPacket.ItemStatus.SUBSCRIPTION_PENDING) {
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_pending,
StyledString.COUNTER_STYLER);
} else if (rosterEntry != null
&& (rosterEntry.getType() == ItemType.none || rosterEntry.getType() == ItemType.from)) {
/*
* see http://xmpp.org/rfcs/rfc3921.html chapter 8.2.1, 8.3.1 and
* 8.6
*/
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_cancelled,
StyledString.COUNTER_STYLER);
} else if (presence.isAway()) {
- styledString.append(" (" + presence.getType() + ")", //$NON-NLS-1$ //$NON-NLS-2$
+ styledString.append(" (" + presence.getMode() + ")", //$NON-NLS-1$ //$NON-NLS-2$
StyledString.COUNTER_STYLER);
}
/*
* Append DataTransfer state information if debug mode is enabled.
*/
if (presence.isAvailable()) {
final NetTransferMode transferMode = dataTransferManager
.getTransferMode(jid);
if (transferMode != NetTransferMode.NONE) {
styledString.append(
" " + MessageFormat.format(connected_using, transferMode), //$NON-NLS-1$
StyledString.QUALIFIER_STYLER);
}
}
return styledString;
}
@Override
public Image getImage() {
if (this.roster == null)
return null;
final Presence presence = this.roster.getPresence(jid.getBase());
boolean sarosSupported = isSarosSupported();
if (presence.isAvailable()) {
if (presence.isAway()) {
return sarosSupported ? ImageManager.ICON_BUDDY_SAROS_AWAY
: ImageManager.ICON_BUDDY_AWAY;
} else {
return sarosSupported ? ImageManager.ICON_BUDDY_SAROS
: ImageManager.ICON_BUDDY;
}
} else {
return ImageManager.ICON_BUDDY_OFFLINE;
}
}
public boolean isOnline() {
Presence presence = this.roster.getPresence(this.jid.getBase());
return presence.isAvailable() || presence.isAway();
}
public JID getJID() {
return jid;
}
public boolean isSarosSupported() {
boolean sarosSupported = false;
try {
sarosSupported = this.discoveryManager.isSupportedNonBlock(jid,
Saros.NAMESPACE);
} catch (CacheMissException e) {
// Saros support wasn't in cache. Update the discovery manager.
discoveryManager.cacheSarosSupport(jid);
}
return sarosSupported;
}
@Override
public ITreeElement getParent() {
if (roster == null)
return null;
RosterEntry rosterEntry = this.getRosterEntry();
if (rosterEntry == null)
return null;
Collection<RosterGroup> rosterGroups = rosterEntry.getGroups();
return (rosterGroups.size() > 0) ? new RosterGroupElement(roster,
rosterGroups.iterator().next()) : null;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RosterEntryElement)) {
return false;
}
RosterEntryElement rosterEntryElement = (RosterEntryElement) obj;
return (jid == null ? rosterEntryElement.jid == null : jid
.equals(rosterEntryElement.jid));
}
@Override
public int hashCode() {
return (jid != null) ? jid.hashCode() : 0;
}
}
| true | true | public StyledString getStyledText() {
StyledString styledString = new StyledString();
final String connected_using = Messages.RosterEntryElement_connected_using;
RosterEntry rosterEntry = this.getRosterEntry();
styledString.append((rosterEntry == null) ? jid.toString()
: RosterUtils.getDisplayableName(rosterEntry));
final Presence presence = roster.getPresence(jid.getBase());
if (rosterEntry != null
&& rosterEntry.getStatus() == RosterPacket.ItemStatus.SUBSCRIPTION_PENDING) {
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_pending,
StyledString.COUNTER_STYLER);
} else if (rosterEntry != null
&& (rosterEntry.getType() == ItemType.none || rosterEntry.getType() == ItemType.from)) {
/*
* see http://xmpp.org/rfcs/rfc3921.html chapter 8.2.1, 8.3.1 and
* 8.6
*/
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_cancelled,
StyledString.COUNTER_STYLER);
} else if (presence.isAway()) {
styledString.append(" (" + presence.getType() + ")", //$NON-NLS-1$ //$NON-NLS-2$
StyledString.COUNTER_STYLER);
}
/*
* Append DataTransfer state information if debug mode is enabled.
*/
if (presence.isAvailable()) {
final NetTransferMode transferMode = dataTransferManager
.getTransferMode(jid);
if (transferMode != NetTransferMode.NONE) {
styledString.append(
" " + MessageFormat.format(connected_using, transferMode), //$NON-NLS-1$
StyledString.QUALIFIER_STYLER);
}
}
return styledString;
}
| public StyledString getStyledText() {
StyledString styledString = new StyledString();
final String connected_using = Messages.RosterEntryElement_connected_using;
RosterEntry rosterEntry = this.getRosterEntry();
styledString.append((rosterEntry == null) ? jid.toString()
: RosterUtils.getDisplayableName(rosterEntry));
final Presence presence = roster.getPresence(jid.getBase());
if (rosterEntry != null
&& rosterEntry.getStatus() == RosterPacket.ItemStatus.SUBSCRIPTION_PENDING) {
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_pending,
StyledString.COUNTER_STYLER);
} else if (rosterEntry != null
&& (rosterEntry.getType() == ItemType.none || rosterEntry.getType() == ItemType.from)) {
/*
* see http://xmpp.org/rfcs/rfc3921.html chapter 8.2.1, 8.3.1 and
* 8.6
*/
styledString.append(" ").append( //$NON-NLS-1$
Messages.RosterEntryElement_subscription_cancelled,
StyledString.COUNTER_STYLER);
} else if (presence.isAway()) {
styledString.append(" (" + presence.getMode() + ")", //$NON-NLS-1$ //$NON-NLS-2$
StyledString.COUNTER_STYLER);
}
/*
* Append DataTransfer state information if debug mode is enabled.
*/
if (presence.isAvailable()) {
final NetTransferMode transferMode = dataTransferManager
.getTransferMode(jid);
if (transferMode != NetTransferMode.NONE) {
styledString.append(
" " + MessageFormat.format(connected_using, transferMode), //$NON-NLS-1$
StyledString.QUALIFIER_STYLER);
}
}
return styledString;
}
|
diff --git a/src/main/java/org/gwaspi/samples/PlinkStandardSamplesParser.java b/src/main/java/org/gwaspi/samples/PlinkStandardSamplesParser.java
index 83a1a9f4..ddd480e0 100644
--- a/src/main/java/org/gwaspi/samples/PlinkStandardSamplesParser.java
+++ b/src/main/java/org/gwaspi/samples/PlinkStandardSamplesParser.java
@@ -1,122 +1,122 @@
package org.gwaspi.samples;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import org.gwaspi.constants.cImport;
import org.gwaspi.model.SampleInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlinkStandardSamplesParser implements SamplesParser {
private static final Logger log
= LoggerFactory.getLogger(PlinkStandardSamplesParser.class);
@Override
public Collection<SampleInfo> scanSampleInfo(String sampleInfoPath) throws IOException {
Collection<SampleInfo> sampleInfos = new LinkedList<SampleInfo>();
FileReader inputFileReader;
BufferedReader inputBufferReader;
File sampleFile = new File(sampleInfoPath);
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
char[] chunker = new char[300];
inputBufferReader.read(chunker, 0, 300);
if (String.valueOf(chunker).contains("\n")) { // SHORT PED FILE
inputBufferReader.close();
inputFileReader.close();
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
int count = 0;
while (inputBufferReader.ready()) {
String l = inputBufferReader.readLine();
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = l.split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
- String sexStr = cVals[cImport.Annotation.Plink_Binary.ped_sex];
+ String sexStr = cVals[cImport.Annotation.Plink_Standard.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
- String affectionStr = cVals[cImport.Annotation.Plink_Binary.ped_affection];
+ String affectionStr = cVals[cImport.Annotation.Plink_Standard.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
- cVals[cImport.Annotation.Plink_Binary.ped_sampleId],
- cVals[cImport.Annotation.Plink_Binary.ped_familyId],
- cVals[cImport.Annotation.Plink_Binary.ped_fatherId],
- cVals[cImport.Annotation.Plink_Binary.ped_motherId],
+ cVals[cImport.Annotation.Plink_Standard.ped_sampleId],
+ cVals[cImport.Annotation.Plink_Standard.ped_familyId],
+ cVals[cImport.Annotation.Plink_Standard.ped_fatherId],
+ cVals[cImport.Annotation.Plink_Standard.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
} else { // LONG PED FILE
// This has sucked out 1 week of my life and caused many grey hairs!
int count = 0;
while (inputBufferReader.ready()) {
if (count != 0) {
chunker = new char[300];
inputBufferReader.read(chunker, 0, 300); // Read a sizable but conrolled chunk of data into memory
}
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = String.valueOf(chunker).split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
- String sexStr = cVals[cImport.Annotation.Plink_Binary.ped_sex];
+ String sexStr = cVals[cImport.Annotation.Plink_Standard.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
- String affectionStr = cVals[cImport.Annotation.Plink_Binary.ped_affection];
+ String affectionStr = cVals[cImport.Annotation.Plink_Standard.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
- cVals[cImport.Annotation.Plink_Binary.ped_sampleId],
- cVals[cImport.Annotation.Plink_Binary.ped_familyId],
- cVals[cImport.Annotation.Plink_Binary.ped_fatherId],
- cVals[cImport.Annotation.Plink_Binary.ped_motherId],
+ cVals[cImport.Annotation.Plink_Standard.ped_sampleId],
+ cVals[cImport.Annotation.Plink_Standard.ped_familyId],
+ cVals[cImport.Annotation.Plink_Standard.ped_fatherId],
+ cVals[cImport.Annotation.Plink_Standard.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
inputBufferReader.readLine(); // Read rest of line and discard it...
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
}
inputBufferReader.close();
inputFileReader.close();
return sampleInfos;
}
}
| false | true | public Collection<SampleInfo> scanSampleInfo(String sampleInfoPath) throws IOException {
Collection<SampleInfo> sampleInfos = new LinkedList<SampleInfo>();
FileReader inputFileReader;
BufferedReader inputBufferReader;
File sampleFile = new File(sampleInfoPath);
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
char[] chunker = new char[300];
inputBufferReader.read(chunker, 0, 300);
if (String.valueOf(chunker).contains("\n")) { // SHORT PED FILE
inputBufferReader.close();
inputFileReader.close();
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
int count = 0;
while (inputBufferReader.ready()) {
String l = inputBufferReader.readLine();
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = l.split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
String sexStr = cVals[cImport.Annotation.Plink_Binary.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
String affectionStr = cVals[cImport.Annotation.Plink_Binary.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
cVals[cImport.Annotation.Plink_Binary.ped_sampleId],
cVals[cImport.Annotation.Plink_Binary.ped_familyId],
cVals[cImport.Annotation.Plink_Binary.ped_fatherId],
cVals[cImport.Annotation.Plink_Binary.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
} else { // LONG PED FILE
// This has sucked out 1 week of my life and caused many grey hairs!
int count = 0;
while (inputBufferReader.ready()) {
if (count != 0) {
chunker = new char[300];
inputBufferReader.read(chunker, 0, 300); // Read a sizable but conrolled chunk of data into memory
}
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = String.valueOf(chunker).split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
String sexStr = cVals[cImport.Annotation.Plink_Binary.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
String affectionStr = cVals[cImport.Annotation.Plink_Binary.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
cVals[cImport.Annotation.Plink_Binary.ped_sampleId],
cVals[cImport.Annotation.Plink_Binary.ped_familyId],
cVals[cImport.Annotation.Plink_Binary.ped_fatherId],
cVals[cImport.Annotation.Plink_Binary.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
inputBufferReader.readLine(); // Read rest of line and discard it...
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
}
inputBufferReader.close();
inputFileReader.close();
return sampleInfos;
}
| public Collection<SampleInfo> scanSampleInfo(String sampleInfoPath) throws IOException {
Collection<SampleInfo> sampleInfos = new LinkedList<SampleInfo>();
FileReader inputFileReader;
BufferedReader inputBufferReader;
File sampleFile = new File(sampleInfoPath);
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
char[] chunker = new char[300];
inputBufferReader.read(chunker, 0, 300);
if (String.valueOf(chunker).contains("\n")) { // SHORT PED FILE
inputBufferReader.close();
inputFileReader.close();
inputFileReader = new FileReader(sampleFile);
inputBufferReader = new BufferedReader(inputFileReader);
int count = 0;
while (inputBufferReader.ready()) {
String l = inputBufferReader.readLine();
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = l.split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
String sexStr = cVals[cImport.Annotation.Plink_Standard.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
String affectionStr = cVals[cImport.Annotation.Plink_Standard.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
cVals[cImport.Annotation.Plink_Standard.ped_sampleId],
cVals[cImport.Annotation.Plink_Standard.ped_familyId],
cVals[cImport.Annotation.Plink_Standard.ped_fatherId],
cVals[cImport.Annotation.Plink_Standard.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
} else { // LONG PED FILE
// This has sucked out 1 week of my life and caused many grey hairs!
int count = 0;
while (inputBufferReader.ready()) {
if (count != 0) {
chunker = new char[300];
inputBufferReader.read(chunker, 0, 300); // Read a sizable but conrolled chunk of data into memory
}
SampleInfo sampleInfo;
if (chunker.length > 0) {
String[] cVals = String.valueOf(chunker).split(cImport.Separators.separators_CommaSpaceTab_rgxp, 10);
String sexStr = cVals[cImport.Annotation.Plink_Standard.ped_sex];
sexStr = sexStr.equals("-9") ? "0" : sexStr;
String affectionStr = cVals[cImport.Annotation.Plink_Standard.ped_affection];
affectionStr = affectionStr.equals("-9") ? "0" : affectionStr;
SampleInfo.Sex sex = SampleInfo.Sex.parse(sexStr);
SampleInfo.Affection affection = SampleInfo.Affection.parse(affectionStr);
sampleInfo = new SampleInfo(
cVals[cImport.Annotation.Plink_Standard.ped_sampleId],
cVals[cImport.Annotation.Plink_Standard.ped_familyId],
cVals[cImport.Annotation.Plink_Standard.ped_fatherId],
cVals[cImport.Annotation.Plink_Standard.ped_motherId],
sex,
affection,
"0",
"0",
"0",
0
);
} else {
sampleInfo = new SampleInfo();
}
inputBufferReader.readLine(); // Read rest of line and discard it...
sampleInfos.add(sampleInfo);
count++;
if (count % 100 == 0) {
log.info("Parsed {} Samples for info...", count);
}
}
}
inputBufferReader.close();
inputFileReader.close();
return sampleInfos;
}
|
diff --git a/solr/src/java/org/apache/solr/search/Grouping.java b/solr/src/java/org/apache/solr/search/Grouping.java
index 178a02bc4..be4f85af5 100755
--- a/solr/src/java/org/apache/solr/search/Grouping.java
+++ b/solr/src/java/org/apache/solr/search/Grouping.java
@@ -1,840 +1,841 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.search;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.*;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.search.function.DocValues;
import org.apache.solr.search.function.ValueSource;
import java.io.IOException;
import java.util.*;
public class Grouping {
public abstract class Command {
public String key; // the name to use for this group in the response
public Sort groupSort; // the sort of the documents *within* a single group.
public Sort sort; // the sort between groups
public int docsPerGroup; // how many docs in each group - from "group.limit" param, default=1
public int groupOffset; // the offset within each group (for paging within each group)
public int numGroups; // how many groups - defaults to the "rows" parameter
public int offset; // offset into the list of groups
abstract void prepare() throws IOException;
abstract Collector createCollector() throws IOException;
Collector createNextCollector() throws IOException {
return null;
}
abstract void finish() throws IOException;
abstract int getMatches();
NamedList commonResponse() {
NamedList groupResult = new SimpleOrderedMap();
grouped.add(key, groupResult); // grouped={ key={
int this_matches = getMatches();
groupResult.add("matches", this_matches);
maxMatches = Math.max(maxMatches, this_matches);
return groupResult;
}
DocList getDocList(TopDocsCollector collector) {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
// TODO: implement a DocList impl that doesn't need to start at offset=0
TopDocs topDocs = collector.topDocs(0, docsToCollect);
int ids[] = new int[topDocs.scoreDocs.length];
float[] scores = needScores ? new float[topDocs.scoreDocs.length] : null;
for (int i=0; i<ids.length; i++) {
ids[i] = topDocs.scoreDocs[i].doc;
if (scores != null)
scores[i] = topDocs.scoreDocs[i].score;
}
float score = topDocs.getMaxScore();
maxScore = Math.max(maxScore, score);
DocSlice docs = new DocSlice(groupOffset, Math.max(0, ids.length - groupOffset), ids, scores, topDocs.totalHits, score);
if (getDocList) {
DocIterator iter = docs.iterator();
while (iter.hasNext())
idSet.add(iter.nextDoc());
}
return docs;
}
void addDocList(NamedList rsp, TopDocsCollector collector) {
rsp.add("doclist", getDocList(collector));
}
}
public class CommandQuery extends Command {
public Query query;
TopDocsCollector topCollector;
FilterCollector collector;
@Override
void prepare() throws IOException {
}
@Override
Collector createCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
DocSet groupFilt = searcher.getDocSet(query);
topCollector = newCollector(groupSort, docsToCollect, false, needScores);
collector = new FilterCollector(groupFilt, topCollector);
return collector;
}
@Override
void finish() throws IOException {
NamedList rsp = commonResponse();
addDocList(rsp, (TopDocsCollector)collector.getCollector());
}
@Override
int getMatches() {
return collector.getMatches();
}
}
public class CommandFunc extends Command {
public ValueSource groupBy;
int maxGroupToFind;
Map context;
TopGroupCollector collector = null;
Phase2GroupCollector collector2;
@Override
void prepare() throws IOException {
Map context = ValueSource.newContext();
groupBy.createWeight(context, searcher);
}
@Override
Collector createCollector() throws IOException {
maxGroupToFind = getMax(offset, numGroups, maxDoc);
if (compareSorts(sort, groupSort)) {
collector = new TopGroupCollector(groupBy, context, normalizeSort(sort), maxGroupToFind);
} else {
collector = new TopGroupSortCollector(groupBy, context, normalizeSort(sort), normalizeSort(groupSort), maxGroupToFind);
}
return collector;
}
@Override
Collector createNextCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
if (docsToCollect < 0 || docsToCollect > maxDoc) docsToCollect = maxDoc;
collector2 = new Phase2GroupCollector(collector, groupBy, context, groupSort, docsToCollect, needScores, offset);
return collector2;
}
@Override
void finish() throws IOException {
NamedList groupResult = commonResponse();
if (collector.orderedGroups == null) collector.buildSet();
List groupList = new ArrayList();
groupResult.add("groups", groupList); // grouped={ key={ groups=[
int skipCount = offset;
for (SearchGroup group : collector.orderedGroups) {
if (skipCount > 0) {
skipCount--;
continue;
}
NamedList nl = new SimpleOrderedMap();
groupList.add(nl); // grouped={ key={ groups=[ {
nl.add("groupValue", group.groupValue.toObject());
SearchGroupDocs groupDocs = collector2.groupMap.get(group.groupValue);
addDocList(nl, groupDocs.collector);
}
}
@Override
int getMatches() {
return collector.getMatches();
}
}
static Sort byScoreDesc = new Sort();
static boolean compareSorts(Sort sort1, Sort sort2) {
return sort1 == sort2 || normalizeSort(sort1).equals(normalizeSort(sort2));
}
/** returns a sort by score desc if null */
static Sort normalizeSort(Sort sort) {
return sort==null ? byScoreDesc : sort;
}
static int getMax(int offset, int len, int max) {
int v = len<0 ? max : offset + len;
if (v < 0 || v > max) v = max;
return v;
}
static TopDocsCollector newCollector(Sort sort, int numHits, boolean fillFields, boolean needScores) throws IOException {
if (sort==null || sort==byScoreDesc) {
return TopScoreDocCollector.create(numHits, true);
} else {
return TopFieldCollector.create(sort, numHits, false, needScores, needScores, true);
}
}
final SolrIndexSearcher searcher;
final SolrIndexSearcher.QueryResult qr;
final SolrIndexSearcher.QueryCommand cmd;
final List<Command> commands = new ArrayList<Command>();
public Grouping(SolrIndexSearcher searcher, SolrIndexSearcher.QueryResult qr, SolrIndexSearcher.QueryCommand cmd) {
this.searcher = searcher;
this.qr = qr;
this.cmd = cmd;
}
public void add(Grouping.Command groupingCommand) {
commands.add(groupingCommand);
}
int maxDoc;
boolean needScores;
boolean getDocSet;
boolean getDocList; // doclist needed for debugging or highlighting
Query query;
DocSet filter;
Filter luceneFilter;
NamedList grouped = new SimpleOrderedMap();
Set<Integer> idSet = new LinkedHashSet<Integer>(); // used for tracking unique docs when we need a doclist
int maxMatches; // max number of matches from any grouping command
float maxScore = Float.NEGATIVE_INFINITY; // max score seen in any doclist
public void execute() throws IOException {
DocListAndSet out = new DocListAndSet();
qr.setDocListAndSet(out);
filter = cmd.getFilter()!=null ? cmd.getFilter() : searcher.getDocSet(cmd.getFilterList());
+ luceneFilter = filter == null ? null : filter.getTopFilter();
maxDoc = searcher.maxDoc();
needScores = (cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0;
getDocSet = (cmd.getFlags() & SolrIndexSearcher.GET_DOCSET) != 0;
getDocList = (cmd.getFlags() & SolrIndexSearcher.GET_DOCLIST) != 0; // doclist needed for debugging or highlighting
query = QueryUtils.makeQueryable(cmd.getQuery());
for (Command cmd : commands) {
cmd.prepare();
}
List<Collector> collectors = new ArrayList<Collector>(commands.size());
for (Command cmd : commands) {
Collector collector = cmd.createCollector();
if (collector != null)
collectors.add(collector);
}
Collector allCollectors = MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()]));
DocSetCollector setCollector = null;
if (getDocSet) {
setCollector = new DocSetDelegateCollector(maxDoc>>6, maxDoc, allCollectors);
allCollectors = setCollector;
}
searcher.search(query, luceneFilter, allCollectors);
if (getDocSet) {
qr.setDocSet(setCollector.getDocSet());
}
collectors.clear();
for (Command cmd : commands) {
Collector collector = cmd.createNextCollector();
if (collector != null)
collectors.add(collector);
}
if (collectors.size() > 0) {
searcher.search(query, luceneFilter, MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()])));
}
for (Command cmd : commands) {
cmd.finish();
}
qr.groupedResults = grouped;
if (getDocList) {
int sz = idSet.size();
int[] ids = new int[sz];
int idx = 0;
for (int val : idSet) {
ids[idx++] = val;
}
qr.setDocList(new DocSlice(0, sz, ids, null, maxMatches, maxScore));
}
}
}
class SearchGroup {
public MutableValue groupValue;
int matches;
int topDoc;
// float topDocScore; // currently unused
int comparatorSlot;
// currently only used when sort != sort.group
FieldComparator[] sortGroupComparators;
int[] sortGroupReversed;
/***
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return groupValue.equalsSameType(((SearchGroup)obj).groupValue);
}
***/
}
abstract class GroupCollector extends Collector {
/** get the number of matches before grouping or limiting have been applied */
public abstract int getMatches();
}
class FilterCollector extends GroupCollector {
private final DocSet filter;
private final Collector collector;
private int docBase;
private int matches;
public FilterCollector(DocSet filter, Collector collector) throws IOException {
this.filter = filter;
this.collector = collector;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
if (filter.exists(doc + docBase))
collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return collector.acceptsDocsOutOfOrder();
}
@Override
public int getMatches() {
return matches;
}
Collector getCollector() {
return collector;
}
}
/** Finds the top set of groups, grouped by groupByVS when sort == group.sort */
class TopGroupCollector extends GroupCollector {
final int nGroups;
final HashMap<MutableValue, SearchGroup> groupMap;
TreeSet<SearchGroup> orderedGroups;
final ValueSource vs;
final Map context;
final FieldComparator[] comparators;
final int[] reversed;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
int spareSlot;
int matches;
public TopGroupCollector(ValueSource groupByVS, Map vsContext, Sort sort, int nGroups) throws IOException {
this.vs = groupByVS;
this.context = vsContext;
this.nGroups = nGroups;
SortField[] sortFields = sort.getSort();
this.comparators = new FieldComparator[sortFields.length];
this.reversed = new int[sortFields.length];
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
// use nGroups + 1 so we have a spare slot to use for comparing (tracked by this.spareSlot)
comparators[i] = sortField.getComparator(nGroups + 1, i);
}
this.spareSlot = nGroups;
this.groupMap = new HashMap<MutableValue, SearchGroup>(nGroups);
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (FieldComparator fc : comparators)
fc.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
// if orderedGroups != null, then we already have collected N groups and
// can short circuit by comparing this document to the smallest group
// without having to even find what group this document belongs to.
// Even if this document belongs to a group in the top N, we know that
// we don't have to update that group.
//
// Downside: if the number of unique groups is very low, this is
// wasted effort as we will most likely be updating an existing group.
if (orderedGroups != null) {
for (int i = 0;; i++) {
final int c = reversed[i] * comparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive. So don't even bother to continue
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
}
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
groupMap.put(sg.groupValue, sg);
if (groupMap.size() == nGroups) {
buildSet();
}
return;
}
// we already tested that the document is competitive, so replace
// the smallest group with this new group.
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
fc.copy(spareSlot, doc);
final int c = reversed[i] * fc.compare(group.comparatorSlot, spareSlot);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j=i+1; j<comparators.length; j++)
comparators[j].copy(spareSlot, doc);
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
void buildSet() {
Comparator<SearchGroup> comparator = new Comparator<SearchGroup>() {
public int compare(SearchGroup o1, SearchGroup o2) {
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
int c = reversed[i] * fc.compare(o1.comparatorSlot, o2.comparatorSlot);
if (c != 0) {
return c;
} else if (i == comparators.length - 1) {
return o1.topDoc - o2.topDoc;
}
}
}
};
orderedGroups = new TreeSet<SearchGroup>(comparator);
orderedGroups.addAll(groupMap.values());
if (orderedGroups.size() == 0) return;
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (int i=0; i<comparators.length; i++)
comparators[i] = comparators[i].setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
@Override
public int getMatches() {
return matches;
}
}
/**
* This class allows a different sort within a group than what is used between groups.
* Sorting between groups is done by the sort value of the first (highest ranking)
* document in that group.
*/
class TopGroupSortCollector extends TopGroupCollector {
IndexReader reader;
Sort groupSort;
public TopGroupSortCollector(ValueSource groupByVS, Map vsContext, Sort sort, Sort groupSort, int nGroups) throws IOException {
super(groupByVS, vsContext, sort, nGroups);
this.groupSort = groupSort;
}
void constructComparators(FieldComparator[] comparators, int[] reversed, SortField[] sortFields, int size) throws IOException {
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
comparators[i] = sortField.getComparator(size, i);
if (scorer != null) comparators[i].setScorer(scorer);
if (reader != null) comparators[i] = comparators[i].setNextReader(reader, docBase);
}
}
@Override
public void setScorer(Scorer scorer) throws IOException {
super.setScorer(scorer);
for (SearchGroup searchGroup : groupMap.values()) {
for (FieldComparator fc : searchGroup.sortGroupComparators) {
fc.setScorer(scorer);
}
}
}
@Override
public void collect(int doc) throws IOException {
matches++;
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
SortField[] sortGroupFields = groupSort.getSort();
sg.sortGroupComparators = new FieldComparator[sortGroupFields.length];
sg.sortGroupReversed = new int[sortGroupFields.length];
constructComparators(sg.sortGroupComparators, sg.sortGroupReversed, sortGroupFields, 1);
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
for (FieldComparator fc : sg.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(sg.groupValue, sg);
return;
}
if (orderedGroups == null) {
buildSet();
}
SearchGroup leastSignificantGroup = orderedGroups.last();
for (int i = 0;; i++) {
final int c = leastSignificantGroup.sortGroupReversed[i] * leastSignificantGroup.sortGroupComparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == leastSignificantGroup.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
for (FieldComparator fc : smallest.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
for (FieldComparator fc : smallest.sortGroupComparators)
fc.setBottom(0);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = group.sortGroupComparators[i];
final int c = group.sortGroupReversed[i] * fc.compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j = 0; j < group.sortGroupComparators.length; j++) {
group.sortGroupComparators[j].copy(0, doc);
group.sortGroupComparators[j].setBottom(0);
}
for (FieldComparator comparator : comparators) comparator.copy(spareSlot, doc);
break;
} else if (i == group.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
super.setNextReader(reader, docBase);
this.reader = reader;
for (SearchGroup searchGroup : groupMap.values()) {
for (int i=0; i<searchGroup.sortGroupComparators.length; i++)
searchGroup.sortGroupComparators[i] = searchGroup.sortGroupComparators[i].setNextReader(reader, docBase);
}
}
}
class Phase2GroupCollector extends Collector {
final HashMap<MutableValue, SearchGroupDocs> groupMap;
final ValueSource vs;
final Map context;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
// TODO: may want to decouple from the phase1 collector
public Phase2GroupCollector(TopGroupCollector topGroups, ValueSource groupByVS, Map vsContext, Sort sort, int docsPerGroup, boolean getScores, int offset) throws IOException {
boolean getSortFields = false;
if (topGroups.orderedGroups == null)
topGroups.buildSet();
groupMap = new HashMap<MutableValue, SearchGroupDocs>(topGroups.groupMap.size());
for (SearchGroup group : topGroups.orderedGroups) {
if (offset > 0) {
offset--;
continue;
}
SearchGroupDocs groupDocs = new SearchGroupDocs();
groupDocs.groupValue = group.groupValue;
if (sort==null)
groupDocs.collector = TopScoreDocCollector.create(docsPerGroup, true);
else
groupDocs.collector = TopFieldCollector.create(sort, docsPerGroup, getSortFields, getScores, getScores, true);
groupMap.put(groupDocs.groupValue, groupDocs);
}
this.vs = groupByVS;
this.context = vsContext;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (SearchGroupDocs group : groupMap.values())
group.collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
filler.fillValue(doc);
SearchGroupDocs group = groupMap.get(mval);
if (group == null) return;
group.collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (SearchGroupDocs group : groupMap.values())
group.collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
}
// TODO: merge with SearchGroup or not?
// ad: don't need to build a new hashmap
// disad: blows up the size of SearchGroup if we need many of them, and couples implementations
class SearchGroupDocs {
public MutableValue groupValue;
TopDocsCollector collector;
}
| true | true | NamedList commonResponse() {
NamedList groupResult = new SimpleOrderedMap();
grouped.add(key, groupResult); // grouped={ key={
int this_matches = getMatches();
groupResult.add("matches", this_matches);
maxMatches = Math.max(maxMatches, this_matches);
return groupResult;
}
DocList getDocList(TopDocsCollector collector) {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
// TODO: implement a DocList impl that doesn't need to start at offset=0
TopDocs topDocs = collector.topDocs(0, docsToCollect);
int ids[] = new int[topDocs.scoreDocs.length];
float[] scores = needScores ? new float[topDocs.scoreDocs.length] : null;
for (int i=0; i<ids.length; i++) {
ids[i] = topDocs.scoreDocs[i].doc;
if (scores != null)
scores[i] = topDocs.scoreDocs[i].score;
}
float score = topDocs.getMaxScore();
maxScore = Math.max(maxScore, score);
DocSlice docs = new DocSlice(groupOffset, Math.max(0, ids.length - groupOffset), ids, scores, topDocs.totalHits, score);
if (getDocList) {
DocIterator iter = docs.iterator();
while (iter.hasNext())
idSet.add(iter.nextDoc());
}
return docs;
}
void addDocList(NamedList rsp, TopDocsCollector collector) {
rsp.add("doclist", getDocList(collector));
}
}
public class CommandQuery extends Command {
public Query query;
TopDocsCollector topCollector;
FilterCollector collector;
@Override
void prepare() throws IOException {
}
@Override
Collector createCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
DocSet groupFilt = searcher.getDocSet(query);
topCollector = newCollector(groupSort, docsToCollect, false, needScores);
collector = new FilterCollector(groupFilt, topCollector);
return collector;
}
@Override
void finish() throws IOException {
NamedList rsp = commonResponse();
addDocList(rsp, (TopDocsCollector)collector.getCollector());
}
@Override
int getMatches() {
return collector.getMatches();
}
}
public class CommandFunc extends Command {
public ValueSource groupBy;
int maxGroupToFind;
Map context;
TopGroupCollector collector = null;
Phase2GroupCollector collector2;
@Override
void prepare() throws IOException {
Map context = ValueSource.newContext();
groupBy.createWeight(context, searcher);
}
@Override
Collector createCollector() throws IOException {
maxGroupToFind = getMax(offset, numGroups, maxDoc);
if (compareSorts(sort, groupSort)) {
collector = new TopGroupCollector(groupBy, context, normalizeSort(sort), maxGroupToFind);
} else {
collector = new TopGroupSortCollector(groupBy, context, normalizeSort(sort), normalizeSort(groupSort), maxGroupToFind);
}
return collector;
}
@Override
Collector createNextCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
if (docsToCollect < 0 || docsToCollect > maxDoc) docsToCollect = maxDoc;
collector2 = new Phase2GroupCollector(collector, groupBy, context, groupSort, docsToCollect, needScores, offset);
return collector2;
}
@Override
void finish() throws IOException {
NamedList groupResult = commonResponse();
if (collector.orderedGroups == null) collector.buildSet();
List groupList = new ArrayList();
groupResult.add("groups", groupList); // grouped={ key={ groups=[
int skipCount = offset;
for (SearchGroup group : collector.orderedGroups) {
if (skipCount > 0) {
skipCount--;
continue;
}
NamedList nl = new SimpleOrderedMap();
groupList.add(nl); // grouped={ key={ groups=[ {
nl.add("groupValue", group.groupValue.toObject());
SearchGroupDocs groupDocs = collector2.groupMap.get(group.groupValue);
addDocList(nl, groupDocs.collector);
}
}
@Override
int getMatches() {
return collector.getMatches();
}
}
static Sort byScoreDesc = new Sort();
static boolean compareSorts(Sort sort1, Sort sort2) {
return sort1 == sort2 || normalizeSort(sort1).equals(normalizeSort(sort2));
}
/** returns a sort by score desc if null */
static Sort normalizeSort(Sort sort) {
return sort==null ? byScoreDesc : sort;
}
static int getMax(int offset, int len, int max) {
int v = len<0 ? max : offset + len;
if (v < 0 || v > max) v = max;
return v;
}
static TopDocsCollector newCollector(Sort sort, int numHits, boolean fillFields, boolean needScores) throws IOException {
if (sort==null || sort==byScoreDesc) {
return TopScoreDocCollector.create(numHits, true);
} else {
return TopFieldCollector.create(sort, numHits, false, needScores, needScores, true);
}
}
final SolrIndexSearcher searcher;
final SolrIndexSearcher.QueryResult qr;
final SolrIndexSearcher.QueryCommand cmd;
final List<Command> commands = new ArrayList<Command>();
public Grouping(SolrIndexSearcher searcher, SolrIndexSearcher.QueryResult qr, SolrIndexSearcher.QueryCommand cmd) {
this.searcher = searcher;
this.qr = qr;
this.cmd = cmd;
}
public void add(Grouping.Command groupingCommand) {
commands.add(groupingCommand);
}
int maxDoc;
boolean needScores;
boolean getDocSet;
boolean getDocList; // doclist needed for debugging or highlighting
Query query;
DocSet filter;
Filter luceneFilter;
NamedList grouped = new SimpleOrderedMap();
Set<Integer> idSet = new LinkedHashSet<Integer>(); // used for tracking unique docs when we need a doclist
int maxMatches; // max number of matches from any grouping command
float maxScore = Float.NEGATIVE_INFINITY; // max score seen in any doclist
public void execute() throws IOException {
DocListAndSet out = new DocListAndSet();
qr.setDocListAndSet(out);
filter = cmd.getFilter()!=null ? cmd.getFilter() : searcher.getDocSet(cmd.getFilterList());
maxDoc = searcher.maxDoc();
needScores = (cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0;
getDocSet = (cmd.getFlags() & SolrIndexSearcher.GET_DOCSET) != 0;
getDocList = (cmd.getFlags() & SolrIndexSearcher.GET_DOCLIST) != 0; // doclist needed for debugging or highlighting
query = QueryUtils.makeQueryable(cmd.getQuery());
for (Command cmd : commands) {
cmd.prepare();
}
List<Collector> collectors = new ArrayList<Collector>(commands.size());
for (Command cmd : commands) {
Collector collector = cmd.createCollector();
if (collector != null)
collectors.add(collector);
}
Collector allCollectors = MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()]));
DocSetCollector setCollector = null;
if (getDocSet) {
setCollector = new DocSetDelegateCollector(maxDoc>>6, maxDoc, allCollectors);
allCollectors = setCollector;
}
searcher.search(query, luceneFilter, allCollectors);
if (getDocSet) {
qr.setDocSet(setCollector.getDocSet());
}
collectors.clear();
for (Command cmd : commands) {
Collector collector = cmd.createNextCollector();
if (collector != null)
collectors.add(collector);
}
if (collectors.size() > 0) {
searcher.search(query, luceneFilter, MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()])));
}
for (Command cmd : commands) {
cmd.finish();
}
qr.groupedResults = grouped;
if (getDocList) {
int sz = idSet.size();
int[] ids = new int[sz];
int idx = 0;
for (int val : idSet) {
ids[idx++] = val;
}
qr.setDocList(new DocSlice(0, sz, ids, null, maxMatches, maxScore));
}
}
}
class SearchGroup {
public MutableValue groupValue;
int matches;
int topDoc;
// float topDocScore; // currently unused
int comparatorSlot;
// currently only used when sort != sort.group
FieldComparator[] sortGroupComparators;
int[] sortGroupReversed;
/***
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return groupValue.equalsSameType(((SearchGroup)obj).groupValue);
}
***/
}
abstract class GroupCollector extends Collector {
/** get the number of matches before grouping or limiting have been applied */
public abstract int getMatches();
}
class FilterCollector extends GroupCollector {
private final DocSet filter;
private final Collector collector;
private int docBase;
private int matches;
public FilterCollector(DocSet filter, Collector collector) throws IOException {
this.filter = filter;
this.collector = collector;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
if (filter.exists(doc + docBase))
collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return collector.acceptsDocsOutOfOrder();
}
@Override
public int getMatches() {
return matches;
}
Collector getCollector() {
return collector;
}
}
/** Finds the top set of groups, grouped by groupByVS when sort == group.sort */
class TopGroupCollector extends GroupCollector {
final int nGroups;
final HashMap<MutableValue, SearchGroup> groupMap;
TreeSet<SearchGroup> orderedGroups;
final ValueSource vs;
final Map context;
final FieldComparator[] comparators;
final int[] reversed;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
int spareSlot;
int matches;
public TopGroupCollector(ValueSource groupByVS, Map vsContext, Sort sort, int nGroups) throws IOException {
this.vs = groupByVS;
this.context = vsContext;
this.nGroups = nGroups;
SortField[] sortFields = sort.getSort();
this.comparators = new FieldComparator[sortFields.length];
this.reversed = new int[sortFields.length];
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
// use nGroups + 1 so we have a spare slot to use for comparing (tracked by this.spareSlot)
comparators[i] = sortField.getComparator(nGroups + 1, i);
}
this.spareSlot = nGroups;
this.groupMap = new HashMap<MutableValue, SearchGroup>(nGroups);
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (FieldComparator fc : comparators)
fc.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
// if orderedGroups != null, then we already have collected N groups and
// can short circuit by comparing this document to the smallest group
// without having to even find what group this document belongs to.
// Even if this document belongs to a group in the top N, we know that
// we don't have to update that group.
//
// Downside: if the number of unique groups is very low, this is
// wasted effort as we will most likely be updating an existing group.
if (orderedGroups != null) {
for (int i = 0;; i++) {
final int c = reversed[i] * comparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive. So don't even bother to continue
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
}
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
groupMap.put(sg.groupValue, sg);
if (groupMap.size() == nGroups) {
buildSet();
}
return;
}
// we already tested that the document is competitive, so replace
// the smallest group with this new group.
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
fc.copy(spareSlot, doc);
final int c = reversed[i] * fc.compare(group.comparatorSlot, spareSlot);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j=i+1; j<comparators.length; j++)
comparators[j].copy(spareSlot, doc);
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
void buildSet() {
Comparator<SearchGroup> comparator = new Comparator<SearchGroup>() {
public int compare(SearchGroup o1, SearchGroup o2) {
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
int c = reversed[i] * fc.compare(o1.comparatorSlot, o2.comparatorSlot);
if (c != 0) {
return c;
} else if (i == comparators.length - 1) {
return o1.topDoc - o2.topDoc;
}
}
}
};
orderedGroups = new TreeSet<SearchGroup>(comparator);
orderedGroups.addAll(groupMap.values());
if (orderedGroups.size() == 0) return;
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (int i=0; i<comparators.length; i++)
comparators[i] = comparators[i].setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
@Override
public int getMatches() {
return matches;
}
}
/**
* This class allows a different sort within a group than what is used between groups.
* Sorting between groups is done by the sort value of the first (highest ranking)
* document in that group.
*/
class TopGroupSortCollector extends TopGroupCollector {
IndexReader reader;
Sort groupSort;
public TopGroupSortCollector(ValueSource groupByVS, Map vsContext, Sort sort, Sort groupSort, int nGroups) throws IOException {
super(groupByVS, vsContext, sort, nGroups);
this.groupSort = groupSort;
}
void constructComparators(FieldComparator[] comparators, int[] reversed, SortField[] sortFields, int size) throws IOException {
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
comparators[i] = sortField.getComparator(size, i);
if (scorer != null) comparators[i].setScorer(scorer);
if (reader != null) comparators[i] = comparators[i].setNextReader(reader, docBase);
}
}
@Override
public void setScorer(Scorer scorer) throws IOException {
super.setScorer(scorer);
for (SearchGroup searchGroup : groupMap.values()) {
for (FieldComparator fc : searchGroup.sortGroupComparators) {
fc.setScorer(scorer);
}
}
}
@Override
public void collect(int doc) throws IOException {
matches++;
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
SortField[] sortGroupFields = groupSort.getSort();
sg.sortGroupComparators = new FieldComparator[sortGroupFields.length];
sg.sortGroupReversed = new int[sortGroupFields.length];
constructComparators(sg.sortGroupComparators, sg.sortGroupReversed, sortGroupFields, 1);
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
for (FieldComparator fc : sg.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(sg.groupValue, sg);
return;
}
if (orderedGroups == null) {
buildSet();
}
SearchGroup leastSignificantGroup = orderedGroups.last();
for (int i = 0;; i++) {
final int c = leastSignificantGroup.sortGroupReversed[i] * leastSignificantGroup.sortGroupComparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == leastSignificantGroup.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
for (FieldComparator fc : smallest.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
for (FieldComparator fc : smallest.sortGroupComparators)
fc.setBottom(0);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = group.sortGroupComparators[i];
final int c = group.sortGroupReversed[i] * fc.compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j = 0; j < group.sortGroupComparators.length; j++) {
group.sortGroupComparators[j].copy(0, doc);
group.sortGroupComparators[j].setBottom(0);
}
for (FieldComparator comparator : comparators) comparator.copy(spareSlot, doc);
break;
} else if (i == group.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
super.setNextReader(reader, docBase);
this.reader = reader;
for (SearchGroup searchGroup : groupMap.values()) {
for (int i=0; i<searchGroup.sortGroupComparators.length; i++)
searchGroup.sortGroupComparators[i] = searchGroup.sortGroupComparators[i].setNextReader(reader, docBase);
}
}
}
class Phase2GroupCollector extends Collector {
final HashMap<MutableValue, SearchGroupDocs> groupMap;
final ValueSource vs;
final Map context;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
// TODO: may want to decouple from the phase1 collector
public Phase2GroupCollector(TopGroupCollector topGroups, ValueSource groupByVS, Map vsContext, Sort sort, int docsPerGroup, boolean getScores, int offset) throws IOException {
boolean getSortFields = false;
if (topGroups.orderedGroups == null)
topGroups.buildSet();
groupMap = new HashMap<MutableValue, SearchGroupDocs>(topGroups.groupMap.size());
for (SearchGroup group : topGroups.orderedGroups) {
if (offset > 0) {
offset--;
continue;
}
SearchGroupDocs groupDocs = new SearchGroupDocs();
groupDocs.groupValue = group.groupValue;
if (sort==null)
groupDocs.collector = TopScoreDocCollector.create(docsPerGroup, true);
else
groupDocs.collector = TopFieldCollector.create(sort, docsPerGroup, getSortFields, getScores, getScores, true);
groupMap.put(groupDocs.groupValue, groupDocs);
}
this.vs = groupByVS;
this.context = vsContext;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (SearchGroupDocs group : groupMap.values())
group.collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
filler.fillValue(doc);
SearchGroupDocs group = groupMap.get(mval);
if (group == null) return;
group.collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (SearchGroupDocs group : groupMap.values())
group.collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
}
// TODO: merge with SearchGroup or not?
// ad: don't need to build a new hashmap
// disad: blows up the size of SearchGroup if we need many of them, and couples implementations
class SearchGroupDocs {
public MutableValue groupValue;
TopDocsCollector collector;
}
| NamedList commonResponse() {
NamedList groupResult = new SimpleOrderedMap();
grouped.add(key, groupResult); // grouped={ key={
int this_matches = getMatches();
groupResult.add("matches", this_matches);
maxMatches = Math.max(maxMatches, this_matches);
return groupResult;
}
DocList getDocList(TopDocsCollector collector) {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
// TODO: implement a DocList impl that doesn't need to start at offset=0
TopDocs topDocs = collector.topDocs(0, docsToCollect);
int ids[] = new int[topDocs.scoreDocs.length];
float[] scores = needScores ? new float[topDocs.scoreDocs.length] : null;
for (int i=0; i<ids.length; i++) {
ids[i] = topDocs.scoreDocs[i].doc;
if (scores != null)
scores[i] = topDocs.scoreDocs[i].score;
}
float score = topDocs.getMaxScore();
maxScore = Math.max(maxScore, score);
DocSlice docs = new DocSlice(groupOffset, Math.max(0, ids.length - groupOffset), ids, scores, topDocs.totalHits, score);
if (getDocList) {
DocIterator iter = docs.iterator();
while (iter.hasNext())
idSet.add(iter.nextDoc());
}
return docs;
}
void addDocList(NamedList rsp, TopDocsCollector collector) {
rsp.add("doclist", getDocList(collector));
}
}
public class CommandQuery extends Command {
public Query query;
TopDocsCollector topCollector;
FilterCollector collector;
@Override
void prepare() throws IOException {
}
@Override
Collector createCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
DocSet groupFilt = searcher.getDocSet(query);
topCollector = newCollector(groupSort, docsToCollect, false, needScores);
collector = new FilterCollector(groupFilt, topCollector);
return collector;
}
@Override
void finish() throws IOException {
NamedList rsp = commonResponse();
addDocList(rsp, (TopDocsCollector)collector.getCollector());
}
@Override
int getMatches() {
return collector.getMatches();
}
}
public class CommandFunc extends Command {
public ValueSource groupBy;
int maxGroupToFind;
Map context;
TopGroupCollector collector = null;
Phase2GroupCollector collector2;
@Override
void prepare() throws IOException {
Map context = ValueSource.newContext();
groupBy.createWeight(context, searcher);
}
@Override
Collector createCollector() throws IOException {
maxGroupToFind = getMax(offset, numGroups, maxDoc);
if (compareSorts(sort, groupSort)) {
collector = new TopGroupCollector(groupBy, context, normalizeSort(sort), maxGroupToFind);
} else {
collector = new TopGroupSortCollector(groupBy, context, normalizeSort(sort), normalizeSort(groupSort), maxGroupToFind);
}
return collector;
}
@Override
Collector createNextCollector() throws IOException {
int docsToCollect = getMax(groupOffset, docsPerGroup, maxDoc);
if (docsToCollect < 0 || docsToCollect > maxDoc) docsToCollect = maxDoc;
collector2 = new Phase2GroupCollector(collector, groupBy, context, groupSort, docsToCollect, needScores, offset);
return collector2;
}
@Override
void finish() throws IOException {
NamedList groupResult = commonResponse();
if (collector.orderedGroups == null) collector.buildSet();
List groupList = new ArrayList();
groupResult.add("groups", groupList); // grouped={ key={ groups=[
int skipCount = offset;
for (SearchGroup group : collector.orderedGroups) {
if (skipCount > 0) {
skipCount--;
continue;
}
NamedList nl = new SimpleOrderedMap();
groupList.add(nl); // grouped={ key={ groups=[ {
nl.add("groupValue", group.groupValue.toObject());
SearchGroupDocs groupDocs = collector2.groupMap.get(group.groupValue);
addDocList(nl, groupDocs.collector);
}
}
@Override
int getMatches() {
return collector.getMatches();
}
}
static Sort byScoreDesc = new Sort();
static boolean compareSorts(Sort sort1, Sort sort2) {
return sort1 == sort2 || normalizeSort(sort1).equals(normalizeSort(sort2));
}
/** returns a sort by score desc if null */
static Sort normalizeSort(Sort sort) {
return sort==null ? byScoreDesc : sort;
}
static int getMax(int offset, int len, int max) {
int v = len<0 ? max : offset + len;
if (v < 0 || v > max) v = max;
return v;
}
static TopDocsCollector newCollector(Sort sort, int numHits, boolean fillFields, boolean needScores) throws IOException {
if (sort==null || sort==byScoreDesc) {
return TopScoreDocCollector.create(numHits, true);
} else {
return TopFieldCollector.create(sort, numHits, false, needScores, needScores, true);
}
}
final SolrIndexSearcher searcher;
final SolrIndexSearcher.QueryResult qr;
final SolrIndexSearcher.QueryCommand cmd;
final List<Command> commands = new ArrayList<Command>();
public Grouping(SolrIndexSearcher searcher, SolrIndexSearcher.QueryResult qr, SolrIndexSearcher.QueryCommand cmd) {
this.searcher = searcher;
this.qr = qr;
this.cmd = cmd;
}
public void add(Grouping.Command groupingCommand) {
commands.add(groupingCommand);
}
int maxDoc;
boolean needScores;
boolean getDocSet;
boolean getDocList; // doclist needed for debugging or highlighting
Query query;
DocSet filter;
Filter luceneFilter;
NamedList grouped = new SimpleOrderedMap();
Set<Integer> idSet = new LinkedHashSet<Integer>(); // used for tracking unique docs when we need a doclist
int maxMatches; // max number of matches from any grouping command
float maxScore = Float.NEGATIVE_INFINITY; // max score seen in any doclist
public void execute() throws IOException {
DocListAndSet out = new DocListAndSet();
qr.setDocListAndSet(out);
filter = cmd.getFilter()!=null ? cmd.getFilter() : searcher.getDocSet(cmd.getFilterList());
luceneFilter = filter == null ? null : filter.getTopFilter();
maxDoc = searcher.maxDoc();
needScores = (cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0;
getDocSet = (cmd.getFlags() & SolrIndexSearcher.GET_DOCSET) != 0;
getDocList = (cmd.getFlags() & SolrIndexSearcher.GET_DOCLIST) != 0; // doclist needed for debugging or highlighting
query = QueryUtils.makeQueryable(cmd.getQuery());
for (Command cmd : commands) {
cmd.prepare();
}
List<Collector> collectors = new ArrayList<Collector>(commands.size());
for (Command cmd : commands) {
Collector collector = cmd.createCollector();
if (collector != null)
collectors.add(collector);
}
Collector allCollectors = MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()]));
DocSetCollector setCollector = null;
if (getDocSet) {
setCollector = new DocSetDelegateCollector(maxDoc>>6, maxDoc, allCollectors);
allCollectors = setCollector;
}
searcher.search(query, luceneFilter, allCollectors);
if (getDocSet) {
qr.setDocSet(setCollector.getDocSet());
}
collectors.clear();
for (Command cmd : commands) {
Collector collector = cmd.createNextCollector();
if (collector != null)
collectors.add(collector);
}
if (collectors.size() > 0) {
searcher.search(query, luceneFilter, MultiCollector.wrap(collectors.toArray(new Collector[collectors.size()])));
}
for (Command cmd : commands) {
cmd.finish();
}
qr.groupedResults = grouped;
if (getDocList) {
int sz = idSet.size();
int[] ids = new int[sz];
int idx = 0;
for (int val : idSet) {
ids[idx++] = val;
}
qr.setDocList(new DocSlice(0, sz, ids, null, maxMatches, maxScore));
}
}
}
class SearchGroup {
public MutableValue groupValue;
int matches;
int topDoc;
// float topDocScore; // currently unused
int comparatorSlot;
// currently only used when sort != sort.group
FieldComparator[] sortGroupComparators;
int[] sortGroupReversed;
/***
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return groupValue.equalsSameType(((SearchGroup)obj).groupValue);
}
***/
}
abstract class GroupCollector extends Collector {
/** get the number of matches before grouping or limiting have been applied */
public abstract int getMatches();
}
class FilterCollector extends GroupCollector {
private final DocSet filter;
private final Collector collector;
private int docBase;
private int matches;
public FilterCollector(DocSet filter, Collector collector) throws IOException {
this.filter = filter;
this.collector = collector;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
if (filter.exists(doc + docBase))
collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return collector.acceptsDocsOutOfOrder();
}
@Override
public int getMatches() {
return matches;
}
Collector getCollector() {
return collector;
}
}
/** Finds the top set of groups, grouped by groupByVS when sort == group.sort */
class TopGroupCollector extends GroupCollector {
final int nGroups;
final HashMap<MutableValue, SearchGroup> groupMap;
TreeSet<SearchGroup> orderedGroups;
final ValueSource vs;
final Map context;
final FieldComparator[] comparators;
final int[] reversed;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
int spareSlot;
int matches;
public TopGroupCollector(ValueSource groupByVS, Map vsContext, Sort sort, int nGroups) throws IOException {
this.vs = groupByVS;
this.context = vsContext;
this.nGroups = nGroups;
SortField[] sortFields = sort.getSort();
this.comparators = new FieldComparator[sortFields.length];
this.reversed = new int[sortFields.length];
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
// use nGroups + 1 so we have a spare slot to use for comparing (tracked by this.spareSlot)
comparators[i] = sortField.getComparator(nGroups + 1, i);
}
this.spareSlot = nGroups;
this.groupMap = new HashMap<MutableValue, SearchGroup>(nGroups);
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (FieldComparator fc : comparators)
fc.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
matches++;
// if orderedGroups != null, then we already have collected N groups and
// can short circuit by comparing this document to the smallest group
// without having to even find what group this document belongs to.
// Even if this document belongs to a group in the top N, we know that
// we don't have to update that group.
//
// Downside: if the number of unique groups is very low, this is
// wasted effort as we will most likely be updating an existing group.
if (orderedGroups != null) {
for (int i = 0;; i++) {
final int c = reversed[i] * comparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive. So don't even bother to continue
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
}
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
groupMap.put(sg.groupValue, sg);
if (groupMap.size() == nGroups) {
buildSet();
}
return;
}
// we already tested that the document is competitive, so replace
// the smallest group with this new group.
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
fc.copy(spareSlot, doc);
final int c = reversed[i] * fc.compare(group.comparatorSlot, spareSlot);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j=i+1; j<comparators.length; j++)
comparators[j].copy(spareSlot, doc);
break;
} else if (i == comparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
void buildSet() {
Comparator<SearchGroup> comparator = new Comparator<SearchGroup>() {
public int compare(SearchGroup o1, SearchGroup o2) {
for (int i = 0;; i++) {
FieldComparator fc = comparators[i];
int c = reversed[i] * fc.compare(o1.comparatorSlot, o2.comparatorSlot);
if (c != 0) {
return c;
} else if (i == comparators.length - 1) {
return o1.topDoc - o2.topDoc;
}
}
}
};
orderedGroups = new TreeSet<SearchGroup>(comparator);
orderedGroups.addAll(groupMap.values());
if (orderedGroups.size() == 0) return;
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (int i=0; i<comparators.length; i++)
comparators[i] = comparators[i].setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
@Override
public int getMatches() {
return matches;
}
}
/**
* This class allows a different sort within a group than what is used between groups.
* Sorting between groups is done by the sort value of the first (highest ranking)
* document in that group.
*/
class TopGroupSortCollector extends TopGroupCollector {
IndexReader reader;
Sort groupSort;
public TopGroupSortCollector(ValueSource groupByVS, Map vsContext, Sort sort, Sort groupSort, int nGroups) throws IOException {
super(groupByVS, vsContext, sort, nGroups);
this.groupSort = groupSort;
}
void constructComparators(FieldComparator[] comparators, int[] reversed, SortField[] sortFields, int size) throws IOException {
for (int i = 0; i < sortFields.length; i++) {
SortField sortField = sortFields[i];
reversed[i] = sortField.getReverse() ? -1 : 1;
comparators[i] = sortField.getComparator(size, i);
if (scorer != null) comparators[i].setScorer(scorer);
if (reader != null) comparators[i] = comparators[i].setNextReader(reader, docBase);
}
}
@Override
public void setScorer(Scorer scorer) throws IOException {
super.setScorer(scorer);
for (SearchGroup searchGroup : groupMap.values()) {
for (FieldComparator fc : searchGroup.sortGroupComparators) {
fc.setScorer(scorer);
}
}
}
@Override
public void collect(int doc) throws IOException {
matches++;
filler.fillValue(doc);
SearchGroup group = groupMap.get(mval);
if (group == null) {
int num = groupMap.size();
if (groupMap.size() < nGroups) {
SearchGroup sg = new SearchGroup();
SortField[] sortGroupFields = groupSort.getSort();
sg.sortGroupComparators = new FieldComparator[sortGroupFields.length];
sg.sortGroupReversed = new int[sortGroupFields.length];
constructComparators(sg.sortGroupComparators, sg.sortGroupReversed, sortGroupFields, 1);
sg.groupValue = mval.duplicate();
sg.comparatorSlot = num++;
sg.matches = 1;
sg.topDoc = docBase + doc;
// sg.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(sg.comparatorSlot, doc);
for (FieldComparator fc : sg.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(sg.groupValue, sg);
return;
}
if (orderedGroups == null) {
buildSet();
}
SearchGroup leastSignificantGroup = orderedGroups.last();
for (int i = 0;; i++) {
final int c = leastSignificantGroup.sortGroupReversed[i] * leastSignificantGroup.sortGroupComparators[i].compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
break;
} else if (i == leastSignificantGroup.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove current smallest group
SearchGroup smallest = orderedGroups.pollLast();
groupMap.remove(smallest.groupValue);
// reuse the removed SearchGroup
smallest.groupValue.copy(mval);
smallest.matches = 1;
smallest.topDoc = docBase + doc;
// smallest.topDocScore = scorer.score();
for (FieldComparator fc : comparators)
fc.copy(smallest.comparatorSlot, doc);
for (FieldComparator fc : smallest.sortGroupComparators) {
fc.copy(0, doc);
fc.setBottom(0);
}
groupMap.put(smallest.groupValue, smallest);
orderedGroups.add(smallest);
for (FieldComparator fc : comparators)
fc.setBottom(orderedGroups.last().comparatorSlot);
for (FieldComparator fc : smallest.sortGroupComparators)
fc.setBottom(0);
return;
}
//
// update existing group
//
group.matches++; // TODO: these aren't valid if the group is every discarded then re-added. keep track if there have been discards?
for (int i = 0;; i++) {
FieldComparator fc = group.sortGroupComparators[i];
final int c = group.sortGroupReversed[i] * fc.compareBottom(doc);
if (c < 0) {
// Definitely not competitive.
return;
} else if (c > 0) {
// Definitely competitive.
// Set remaining comparators
for (int j = 0; j < group.sortGroupComparators.length; j++) {
group.sortGroupComparators[j].copy(0, doc);
group.sortGroupComparators[j].setBottom(0);
}
for (FieldComparator comparator : comparators) comparator.copy(spareSlot, doc);
break;
} else if (i == group.sortGroupComparators.length - 1) {
// Here c=0. If we're at the last comparator, this doc is not
// competitive, since docs are visited in doc Id order, which means
// this doc cannot compete with any other document in the queue.
return;
}
}
// remove before updating the group since lookup is done via comparators
// TODO: optimize this
if (orderedGroups != null)
orderedGroups.remove(group);
group.topDoc = docBase + doc;
// group.topDocScore = scorer.score();
int tmp = spareSlot; spareSlot = group.comparatorSlot; group.comparatorSlot=tmp; // swap slots
// re-add the changed group
if (orderedGroups != null)
orderedGroups.add(group);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
super.setNextReader(reader, docBase);
this.reader = reader;
for (SearchGroup searchGroup : groupMap.values()) {
for (int i=0; i<searchGroup.sortGroupComparators.length; i++)
searchGroup.sortGroupComparators[i] = searchGroup.sortGroupComparators[i].setNextReader(reader, docBase);
}
}
}
class Phase2GroupCollector extends Collector {
final HashMap<MutableValue, SearchGroupDocs> groupMap;
final ValueSource vs;
final Map context;
DocValues docValues;
DocValues.ValueFiller filler;
MutableValue mval;
Scorer scorer;
int docBase;
// TODO: may want to decouple from the phase1 collector
public Phase2GroupCollector(TopGroupCollector topGroups, ValueSource groupByVS, Map vsContext, Sort sort, int docsPerGroup, boolean getScores, int offset) throws IOException {
boolean getSortFields = false;
if (topGroups.orderedGroups == null)
topGroups.buildSet();
groupMap = new HashMap<MutableValue, SearchGroupDocs>(topGroups.groupMap.size());
for (SearchGroup group : topGroups.orderedGroups) {
if (offset > 0) {
offset--;
continue;
}
SearchGroupDocs groupDocs = new SearchGroupDocs();
groupDocs.groupValue = group.groupValue;
if (sort==null)
groupDocs.collector = TopScoreDocCollector.create(docsPerGroup, true);
else
groupDocs.collector = TopFieldCollector.create(sort, docsPerGroup, getSortFields, getScores, getScores, true);
groupMap.put(groupDocs.groupValue, groupDocs);
}
this.vs = groupByVS;
this.context = vsContext;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
for (SearchGroupDocs group : groupMap.values())
group.collector.setScorer(scorer);
}
@Override
public void collect(int doc) throws IOException {
filler.fillValue(doc);
SearchGroupDocs group = groupMap.get(mval);
if (group == null) return;
group.collector.collect(doc);
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.docBase = docBase;
docValues = vs.getValues(context, reader);
filler = docValues.getValueFiller();
mval = filler.getValue();
for (SearchGroupDocs group : groupMap.values())
group.collector.setNextReader(reader, docBase);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
}
// TODO: merge with SearchGroup or not?
// ad: don't need to build a new hashmap
// disad: blows up the size of SearchGroup if we need many of them, and couples implementations
class SearchGroupDocs {
public MutableValue groupValue;
TopDocsCollector collector;
}
|
diff --git a/src/java/com/stackframe/sarariman/WeeknightTask.java b/src/java/com/stackframe/sarariman/WeeknightTask.java
index c19bfcd..62ba295 100644
--- a/src/java/com/stackframe/sarariman/WeeknightTask.java
+++ b/src/java/com/stackframe/sarariman/WeeknightTask.java
@@ -1,58 +1,56 @@
package com.stackframe.sarariman;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Collections;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author mcculley
*/
public class WeeknightTask extends TimerTask {
private final Sarariman sarariman;
private final Directory directory;
private final EmailDispatcher emailDispatcher;
private final Logger logger = Logger.getLogger(getClass().getName());
public WeeknightTask(Sarariman sarariman, Directory directory, EmailDispatcher emailDispatcher) {
this.sarariman = sarariman;
this.directory = directory;
this.emailDispatcher = emailDispatcher;
}
public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) {
java.util.Date todayDate = today.getTime();
try {
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
- if (employee.isFulltime()) {
- Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
+ Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
+ if (!timesheet.isSubmitted()) {
if (dayOfWeek == Calendar.FRIDAY) {
- if (!timesheet.isSubmitted()) {
- emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
- "timesheet", "Please submit your timesheet for the week of " + week + ".");
- }
+ emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
+ "timesheet", "Please submit your timesheet for the week of " + week + ".");
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
- if (hoursRecorded == 0.0) {
+ if (hoursRecorded == 0.0 && employee.isFulltime()) {
emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
"timesheet", "Please record your time if you worked today.");
}
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
}
| false | true | public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) {
java.util.Date todayDate = today.getTime();
try {
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
if (employee.isFulltime()) {
Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
if (dayOfWeek == Calendar.FRIDAY) {
if (!timesheet.isSubmitted()) {
emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
"timesheet", "Please submit your timesheet for the week of " + week + ".");
}
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
if (hoursRecorded == 0.0) {
emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
"timesheet", "Please record your time if you worked today.");
}
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
| public void run() {
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) {
java.util.Date todayDate = today.getTime();
try {
Date week = new Date(DateUtils.weekStart(todayDate).getTime());
for (Employee employee : directory.getByUserName().values()) {
Timesheet timesheet = new Timesheet(sarariman, employee.getNumber(), week);
if (!timesheet.isSubmitted()) {
if (dayOfWeek == Calendar.FRIDAY) {
emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
"timesheet", "Please submit your timesheet for the week of " + week + ".");
} else {
double hoursRecorded = timesheet.getHours(new Date(todayDate.getTime()));
if (hoursRecorded == 0.0 && employee.isFulltime()) {
emailDispatcher.send(employee.getEmail(), Collections.singleton(sarariman.getApprover().getEmail()),
"timesheet", "Please record your time if you worked today.");
}
}
}
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "could not get hours for " + today, se);
}
}
}
|
diff --git a/src/com/piusvelte/remoteauthclient/RemoteAuthClientService.java b/src/com/piusvelte/remoteauthclient/RemoteAuthClientService.java
index beace6e..f974522 100644
--- a/src/com/piusvelte/remoteauthclient/RemoteAuthClientService.java
+++ b/src/com/piusvelte/remoteauthclient/RemoteAuthClientService.java
@@ -1,413 +1,413 @@
package com.piusvelte.remoteauthclient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.RemoteViews;
public class RemoteAuthClientService extends Service implements OnSharedPreferenceChangeListener {
private static final String TAG = "RemoteAuthClientService";
public static final String ACTION_TOGGLE = "com.piusvelte.remoteAuthClient.ACTION_TOGGLE";
public static final String EXTRA_DEVICE_ADDRESS = "com.piusvelte.remoteAuthClient.EXTRA_DEVICE_ADDRESS";
public static final String EXTRA_DEVICE_NAME = "com.piusvelte.remoteAuthClient.EXTRA_DEVICE_NAME";
public static final String EXTRA_DEVICE_STATE = "com.piusvelte.remoteAuthClient.EXTRA_DEVICE_STATE";
private BluetoothAdapter mBtAdapter;
// private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private String mQueueAddress;
private String mQueueState;
private boolean mStartedBT = false;
private String mDeviceFound = null;
private String[] mDevices = new String[0];
private static final UUID sRemoteAuthServerUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected String mMessage = "";
protected final Handler mHandler = new Handler();
protected final Runnable mRunnable = new Runnable() {
public void run() {
if (mMessage != null)
Log.d(TAG, mMessage);
if (mUIInterface != null) {
try {
if (mMessage != null)
mUIInterface.setMessage(mMessage);
else
mUIInterface.setStateFinished();
} catch (RemoteException e) {
Log.e(TAG, e.toString());
}
}
}
};
private IRemoteAuthClientUI mUIInterface;
private final IRemoteAuthClientService.Stub mServiceInterface = new IRemoteAuthClientService.Stub() {
@Override
public void setCallback(IBinder uiBinder) throws RemoteException {
if (uiBinder != null)
mUIInterface = IRemoteAuthClientUI.Stub.asInterface(uiBinder);
}
@Override
public void write(String address, String state) throws RemoteException {
requestWrite(address, state);
}
@Override
public void stop() throws RemoteException {
if (mStartedBT)
mBtAdapter.disable();
}
};
@Override
public void onCreate() {
super.onCreate();
onSharedPreferenceChanged(getSharedPreferences(getString(R.string.key_preferences), Context.MODE_PRIVATE), getString(R.string.key_devices));
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (state == BluetoothAdapter.STATE_ON) {
// if pending...
if (mStartedBT) {
if ((mQueueAddress != null) && (mQueueState != null))
requestWrite(mQueueAddress, mQueueState);
} else if (!mBtAdapter.isDiscovering())
mBtAdapter.startDiscovery();
} else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
stopThreads();
if (mUIInterface == null)
RemoteAuthClientService.this.stopSelf();
}
// When discovery finds a device
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// connect if configured
String address = device.getAddress();
for (String d : mDevices) {
String[] parts = RemoteAuthClientUI.parseDeviceString(d);
if (parts[RemoteAuthClientUI.DEVICE_ADDRESS].equals(address)) {
// if queued
if ((mQueueAddress != null) && mQueueAddress.equals(address) && (mQueueState != null))
mDeviceFound = address;
break;
}
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mDeviceFound != null) {
if (mConnectThread == null) {
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
} else if (!mConnectThread.isConnected()) {
mConnectThread.shutdown();
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
}
mDeviceFound = null;
mQueueAddress = null;
mQueueState = null;
}
- } else if (action.equals(ACTION_TOGGLE) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
+ } else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
requestWrite(address, Integer.toString(RemoteAuthClientUI.STATE_TOGGLE));
- } else if (action.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
+ } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
// create widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// check if the widget exists, otherwise add it
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME) && intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS)) {
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets)
newWidgets.add(widget);
String name = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME);
String address = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS);
String widgetString = name + " " + Integer.toString(appWidgetId) + " " + address;
// store the widget
if (!newWidgets.contains(widgetString))
newWidgets.add(widgetString);
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
} else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) {
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int appWidgetId : appWidgetIds)
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
}
- } else if (action.equals(AppWidgetManager.ACTION_APPWIDGET_DELETED)) {
+ } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets) {
String[] widgetParts = RemoteAuthClientUI.parseDeviceString(widget);
if (!widgetParts[RemoteAuthClientUI.DEVICE_PASSPHRASE].equals(Integer.toString(appWidgetId)))
newWidgets.add(widget);
}
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return mServiceInterface;
}
@Override
public void onDestroy() {
super.onDestroy();
stopThreads();
if (mStartedBT)
mBtAdapter.disable();
}
private RemoteViews buildWidget(Intent intent, int appWidgetId, Set<String> widgets) {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget);
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME)) {
views.setTextViewText(R.id.device_name, intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME));
} else {
String name = getString(R.string.widget_device_name);
for (String widget : widgets) {
String[] widgetParts = RemoteAuthClientUI.parseDeviceString(widget);
if (widgetParts[RemoteAuthClientUI.DEVICE_PASSPHRASE].equals(Integer.toString(appWidgetId))) {
name = widgetParts[RemoteAuthClientUI.DEVICE_NAME];
break;
}
}
views.setTextViewText(R.id.device_name, name);
}
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_STATE))
views.setTextViewText(R.id.device_state, intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_STATE));
else
views.setTextViewText(R.id.device_state, getString(R.string.widget_device_state));
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS))
views.setOnClickPendingIntent(R.id.widget, PendingIntent.getBroadcast(this, 0, new Intent(this, RemoteAuthClientWidget.class).setAction(RemoteAuthClientService.ACTION_TOGGLE).putExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS, intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS)), 0));
return views;
}
private synchronized void requestWrite(String address, String state) {
if (mBtAdapter.isEnabled()) {
if (mConnectThread != null) {
if (mConnectThread.isConnected(address)) {
mConnectThread.write(state);
return;
}
mConnectThread.shutdown();
}
// attempt connect
mConnectThread = new ConnectThread(address, state);
mConnectThread.start();
} else {
mQueueAddress = address;
mQueueState = state;
mStartedBT = true;
mBtAdapter.enable();
}
}
private synchronized void stopThreads() {
if (mConnectThread != null)
mConnectThread.shutdown();
}
private class ConnectThread extends Thread {
private BluetoothSocket mSocket = null;
private InputStream mInStream;
private OutputStream mOutStream;
private String mChallenge;
private MessageDigest mDigest;
private String mAddress;
private String mState;
public ConnectThread(String address, String state) {
mAddress = address;
mState = state;
BluetoothDevice device = mBtAdapter.getRemoteDevice(mAddress);
BluetoothSocket tmp = null;
try {
// tmp = device.createInsecureRfcommSocketToServiceRecord(sRemoteAuthServerUUID);
tmp = device.createRfcommSocketToServiceRecord(sRemoteAuthServerUUID);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
mSocket = tmp;
}
public void run() {
if (mSocket == null) {
mMessage = "failed to get a socket";
mHandler.post(mRunnable);
} else {
if (!mSocket.isConnected()) {
if (mBtAdapter.isDiscovering())
mBtAdapter.cancelDiscovery();
try {
mSocket.connect();
} catch (IOException e) {
mMessage = "failed to connect";
mHandler.post(mRunnable);
shutdown();
return;
}
}
// Get the BluetoothSocket input and output streams
try {
mInStream = mSocket.getInputStream();
mOutStream = mSocket.getOutputStream();
} catch (IOException e) {
mMessage = "failed to get streams";
mHandler.post(mRunnable);
shutdown();
return;
}
byte[] buffer = new byte[1024];
int readBytes = -1;
try {
readBytes = mInStream.read(buffer);
} catch (IOException e1) {
mMessage = "failed to read input stream";
mHandler.post(mRunnable);
}
if (readBytes != -1) {
// construct a string from the valid bytes in the buffer
String message = new String(buffer, 0, readBytes);
// listen for challenge, then process a response
if ((message.length() > 10) && (message.substring(0, 9).equals("challenge")))
mChallenge = message.substring(10);
write(mState);
}
}
shutdown();
}
public void write(String state) {
// get passphrase
String passphrase = null;
if (mSocket != null) {
BluetoothDevice bd = mSocket.getRemoteDevice();
if (bd != null) {
String address = bd.getAddress();
if (address != null) {
for (String d : mDevices) {
String[] parts = RemoteAuthClientUI.parseDeviceString(d);
if (parts[RemoteAuthClientUI.DEVICE_ADDRESS].equals(address)) {
if ((passphrase = parts[RemoteAuthClientUI.DEVICE_PASSPHRASE]) != null) {
String challenge = mChallenge;
// the challenge is stale after it's used
mChallenge = null;
if (challenge != null) {
if (mDigest == null) {
try {
mDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
mMessage = "failed to get message digest instance";
mHandler.post(mRunnable);
}
}
if (mDigest != null) {
mDigest.reset();
try {
mDigest.update((challenge + passphrase + state).getBytes("UTF-8"));
String request = new BigInteger(1, mDigest.digest()).toString(16);
mOutStream.write(request.getBytes());
} catch (IOException e) {
mMessage = "failed to write to output stream";
mHandler.post(mRunnable);
}
}
}
}
break;
}
}
}
}
}
}
public boolean isConnected() {
return (mSocket != null) && mSocket.isConnected() && (mInStream != null) && (mOutStream != null);
}
public boolean isConnected(String address) {
if ((mSocket != null) && (mInStream != null) && (mOutStream != null)) {
return address.equals(mAddress);
} else
return false;
}
public void shutdown() {
mInStream = null;
mOutStream = null;
if (mSocket != null) {
try {
mSocket.close();
} catch (IOException e) {
Log.e(TAG, e.toString());
}
mSocket = null;
}
mConnectThread = null;
mMessage = null;
mHandler.post(mRunnable);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.key_devices))) {
Set<String> devices = sharedPreferences.getStringSet(getString(R.string.key_devices), null);
if (devices != null) {
mDevices = new String[devices.size()];
int d = 0;
Iterator<String> iter = devices.iterator();
while (iter.hasNext())
mDevices[d++] = iter.next();
} else
mDevices = new String[0];
}
}
}
| false | true | public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (state == BluetoothAdapter.STATE_ON) {
// if pending...
if (mStartedBT) {
if ((mQueueAddress != null) && (mQueueState != null))
requestWrite(mQueueAddress, mQueueState);
} else if (!mBtAdapter.isDiscovering())
mBtAdapter.startDiscovery();
} else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
stopThreads();
if (mUIInterface == null)
RemoteAuthClientService.this.stopSelf();
}
// When discovery finds a device
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// connect if configured
String address = device.getAddress();
for (String d : mDevices) {
String[] parts = RemoteAuthClientUI.parseDeviceString(d);
if (parts[RemoteAuthClientUI.DEVICE_ADDRESS].equals(address)) {
// if queued
if ((mQueueAddress != null) && mQueueAddress.equals(address) && (mQueueState != null))
mDeviceFound = address;
break;
}
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mDeviceFound != null) {
if (mConnectThread == null) {
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
} else if (!mConnectThread.isConnected()) {
mConnectThread.shutdown();
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
}
mDeviceFound = null;
mQueueAddress = null;
mQueueState = null;
}
} else if (action.equals(ACTION_TOGGLE) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
requestWrite(address, Integer.toString(RemoteAuthClientUI.STATE_TOGGLE));
} else if (action.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
// create widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// check if the widget exists, otherwise add it
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME) && intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS)) {
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets)
newWidgets.add(widget);
String name = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME);
String address = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS);
String widgetString = name + " " + Integer.toString(appWidgetId) + " " + address;
// store the widget
if (!newWidgets.contains(widgetString))
newWidgets.add(widgetString);
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
} else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) {
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int appWidgetId : appWidgetIds)
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
}
} else if (action.equals(AppWidgetManager.ACTION_APPWIDGET_DELETED)) {
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets) {
String[] widgetParts = RemoteAuthClientUI.parseDeviceString(widget);
if (!widgetParts[RemoteAuthClientUI.DEVICE_PASSPHRASE].equals(Integer.toString(appWidgetId)))
newWidgets.add(widget);
}
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
}
return START_STICKY;
}
| public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (state == BluetoothAdapter.STATE_ON) {
// if pending...
if (mStartedBT) {
if ((mQueueAddress != null) && (mQueueState != null))
requestWrite(mQueueAddress, mQueueState);
} else if (!mBtAdapter.isDiscovering())
mBtAdapter.startDiscovery();
} else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
stopThreads();
if (mUIInterface == null)
RemoteAuthClientService.this.stopSelf();
}
// When discovery finds a device
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
// connect if configured
String address = device.getAddress();
for (String d : mDevices) {
String[] parts = RemoteAuthClientUI.parseDeviceString(d);
if (parts[RemoteAuthClientUI.DEVICE_ADDRESS].equals(address)) {
// if queued
if ((mQueueAddress != null) && mQueueAddress.equals(address) && (mQueueState != null))
mDeviceFound = address;
break;
}
}
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (mDeviceFound != null) {
if (mConnectThread == null) {
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
} else if (!mConnectThread.isConnected()) {
mConnectThread.shutdown();
mConnectThread = new ConnectThread(mDeviceFound, mQueueState);
mConnectThread.start();
}
mDeviceFound = null;
mQueueAddress = null;
mQueueState = null;
}
} else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) {
String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS);
requestWrite(address, Integer.toString(RemoteAuthClientUI.STATE_TOGGLE));
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
// create widget
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// check if the widget exists, otherwise add it
if (intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME) && intent.hasExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS)) {
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets)
newWidgets.add(widget);
String name = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_NAME);
String address = intent.getStringExtra(RemoteAuthClientService.EXTRA_DEVICE_ADDRESS);
String widgetString = name + " " + Integer.toString(appWidgetId) + " " + address;
// store the widget
if (!newWidgets.contains(widgetString))
newWidgets.add(widgetString);
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
} else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) {
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int appWidgetId : appWidgetIds)
appWidgetManager.updateAppWidget(appWidgetId, buildWidget(intent, appWidgetId, widgets));
}
} else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
SharedPreferences sp = getSharedPreferences(getString(R.string.key_preferences), MODE_PRIVATE);
Set<String> widgets = sp.getStringSet(getString(R.string.key_widgets), (new HashSet<String>()));
Set<String> newWidgets = new HashSet<String>();
for (String widget : widgets) {
String[] widgetParts = RemoteAuthClientUI.parseDeviceString(widget);
if (!widgetParts[RemoteAuthClientUI.DEVICE_PASSPHRASE].equals(Integer.toString(appWidgetId)))
newWidgets.add(widget);
}
SharedPreferences.Editor spe = sp.edit();
spe.putStringSet(getString(R.string.key_widgets), newWidgets);
spe.commit();
}
}
return START_STICKY;
}
|
diff --git a/playground/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisTK.java b/playground/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisTK.java
index c3f325c71..64fe01628 100644
--- a/playground/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisTK.java
+++ b/playground/java/src/org/broadinstitute/sting/gatk/GenomeAnalysisTK.java
@@ -1,135 +1,135 @@
package org.broadinstitute.sting.gatk;
import net.sf.samtools.SAMFileReader.ValidationStringency;
import edu.mit.broad.picard.cmdline.CommandLineProgram;
import edu.mit.broad.picard.cmdline.Usage;
import edu.mit.broad.picard.cmdline.Option;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedData;
import org.broadinstitute.sting.gatk.refdata.rodDbSNP;
import org.broadinstitute.sting.gatk.refdata.rodGFF;
import java.io.*;
import java.util.HashMap;
public class GenomeAnalysisTK extends CommandLineProgram {
// Usage and parameters
@Usage(programVersion="0.1") public String USAGE = "SAM Validator\n";
@Option(shortName="I", doc="SAM or BAM file for validation") public File INPUT_FILE;
@Option(shortName="M", doc="Maximum number of reads to process before exiting", optional=true) public String MAX_READS_ARG = "-1";
@Option(shortName="S", doc="How strict should we be with validation", optional=true) public String STRICTNESS_ARG = "strict";
@Option(shortName="R", doc="Reference sequence file", optional=true) public File REF_FILE_ARG = null;
@Option(shortName="B", doc="Debugging output", optional=true) public String DEBUGGING_STR = null;
@Option(shortName="L", doc="Genome region to operation on: from chr:start-end", optional=true) public String REGION_STR = null;
@Option(shortName="T", doc="Type of analysis to run") public String Analysis_Name = null;
@Option(shortName="DBSNP", doc="DBSNP file", optional=true) public String DBSNP_FILE = null;
@Option(shortName="THREADED_IO", doc="If true, enables threaded I/O operations", optional=true) public String ENABLED_THREADED_IO = "false";
@Option(shortName="U", doc="If true, enables unsafe operations, nothing will be checked at runtime. You better know what you are doing if you set this flag.", optional=false) public String UNSAFE = "false";
@Option(shortName="SORT_ON_FLY", doc="If true, enables on fly sorting of reads file.", optional=false) public String ENABLED_SORT_ON_FLY = "false";
public static HashMap<String, Object> MODULES = new HashMap<String,Object>();
public static void addModule(final String name, final Object walker) {
System.out.printf("* Adding module %s%n", name);
MODULES.put(name, walker);
}
static {
addModule("CountLoci", new CountLociWalker());
addModule("Pileup", new PileupWalker());
addModule("CountReads", new CountReadsWalker());
addModule("PrintReads", new PrintReadsWalker());
addModule("Base_Quality_Histogram", new BaseQualityHistoWalker());
addModule("Aligned_Reads_Histogram", new AlignedReadsHistoWalker());
addModule("AlleleFrequency", new AlleleFrequencyWalker());
addModule("SingleSampleGenotyper", new SingleSampleGenotyper());
addModule("Null", new NullWalker());
addModule("DepthOfCoverage", new DepthOfCoverageWalker());
addModule("CountMismatches", new MismatchCounterWalker());
}
private TraversalEngine engine = null;
public boolean DEBUGGING = false;
/** Required main method implementation. */
public static void main(String[] argv) {
System.exit(new GenomeAnalysisTK().instanceMain(argv));
}
protected int doWork() {
final boolean TEST_ROD = false;
ReferenceOrderedData[] rods = null;
if ( TEST_ROD ) {
ReferenceOrderedData gff = new ReferenceOrderedData(new File("trunk/data/gFFTest.gff"), rodGFF.class );
gff.testMe();
//ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("trunk/data/dbSNP_head.txt"), rodDbSNP.class );
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("/Volumes/Users/mdepristo/broad/ATK/exampleSAMs/dbSNP_chr20.txt"), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else if ( DBSNP_FILE != null ) {
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File(DBSNP_FILE), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else {
rods = new ReferenceOrderedData[] {}; // { gff, dbsnp };
}
this.engine = new TraversalEngine(INPUT_FILE, REF_FILE_ARG, rods);
ValidationStringency strictness;
if ( STRICTNESS_ARG == null ) {
strictness = ValidationStringency.STRICT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("lenient") ) {
strictness = ValidationStringency.LENIENT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("silent") ) {
strictness = ValidationStringency.SILENT;
}
else {
strictness = ValidationStringency.STRICT;
}
System.err.println("Strictness is " + strictness);
engine.setStrictness(strictness);
engine.setDebugging(! ( DEBUGGING_STR == null || DEBUGGING_STR.toLowerCase().equals("true")));
engine.setMaxReads(Integer.parseInt(MAX_READS_ARG));
if ( REGION_STR != null ) {
engine.setLocation(REGION_STR);
}
engine.setSafetyChecking(! UNSAFE.toLowerCase().equals("true"));
- engine.setSortOnFly(! ENABLED_SORT_ON_FLY.toLowerCase().equals("true"));
+ engine.setSortOnFly(ENABLED_SORT_ON_FLY.toLowerCase().equals("true"));
engine.initialize(ENABLED_THREADED_IO.toLowerCase().equals("true"));
//engine.testReference();
//LocusWalker<Integer,Integer> walker = new PileupWalker();
// Try to get the module specified
Object my_module;
if (MODULES.containsKey(Analysis_Name)) {
my_module = MODULES.get(Analysis_Name);
} else {
System.out.println("Could not find module "+Analysis_Name);
return 0;
}
try {
LocusWalker<?, ?> walker = (LocusWalker<?, ?>)my_module;
engine.traverseByLoci(walker);
}
catch ( java.lang.ClassCastException e ) {
// I guess we're a read walker LOL
ReadWalker<?, ?> walker = (ReadWalker<?, ?>)my_module;
engine.traverseByRead(walker);
}
return 0;
}
}
| true | true | protected int doWork() {
final boolean TEST_ROD = false;
ReferenceOrderedData[] rods = null;
if ( TEST_ROD ) {
ReferenceOrderedData gff = new ReferenceOrderedData(new File("trunk/data/gFFTest.gff"), rodGFF.class );
gff.testMe();
//ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("trunk/data/dbSNP_head.txt"), rodDbSNP.class );
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("/Volumes/Users/mdepristo/broad/ATK/exampleSAMs/dbSNP_chr20.txt"), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else if ( DBSNP_FILE != null ) {
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File(DBSNP_FILE), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else {
rods = new ReferenceOrderedData[] {}; // { gff, dbsnp };
}
this.engine = new TraversalEngine(INPUT_FILE, REF_FILE_ARG, rods);
ValidationStringency strictness;
if ( STRICTNESS_ARG == null ) {
strictness = ValidationStringency.STRICT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("lenient") ) {
strictness = ValidationStringency.LENIENT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("silent") ) {
strictness = ValidationStringency.SILENT;
}
else {
strictness = ValidationStringency.STRICT;
}
System.err.println("Strictness is " + strictness);
engine.setStrictness(strictness);
engine.setDebugging(! ( DEBUGGING_STR == null || DEBUGGING_STR.toLowerCase().equals("true")));
engine.setMaxReads(Integer.parseInt(MAX_READS_ARG));
if ( REGION_STR != null ) {
engine.setLocation(REGION_STR);
}
engine.setSafetyChecking(! UNSAFE.toLowerCase().equals("true"));
engine.setSortOnFly(! ENABLED_SORT_ON_FLY.toLowerCase().equals("true"));
engine.initialize(ENABLED_THREADED_IO.toLowerCase().equals("true"));
//engine.testReference();
//LocusWalker<Integer,Integer> walker = new PileupWalker();
// Try to get the module specified
Object my_module;
if (MODULES.containsKey(Analysis_Name)) {
my_module = MODULES.get(Analysis_Name);
} else {
System.out.println("Could not find module "+Analysis_Name);
return 0;
}
try {
LocusWalker<?, ?> walker = (LocusWalker<?, ?>)my_module;
engine.traverseByLoci(walker);
}
catch ( java.lang.ClassCastException e ) {
// I guess we're a read walker LOL
ReadWalker<?, ?> walker = (ReadWalker<?, ?>)my_module;
engine.traverseByRead(walker);
}
return 0;
}
| protected int doWork() {
final boolean TEST_ROD = false;
ReferenceOrderedData[] rods = null;
if ( TEST_ROD ) {
ReferenceOrderedData gff = new ReferenceOrderedData(new File("trunk/data/gFFTest.gff"), rodGFF.class );
gff.testMe();
//ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("trunk/data/dbSNP_head.txt"), rodDbSNP.class );
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File("/Volumes/Users/mdepristo/broad/ATK/exampleSAMs/dbSNP_chr20.txt"), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else if ( DBSNP_FILE != null ) {
ReferenceOrderedData dbsnp = new ReferenceOrderedData(new File(DBSNP_FILE), rodDbSNP.class );
//dbsnp.testMe();
rods = new ReferenceOrderedData[] { dbsnp }; // { gff, dbsnp };
}
else {
rods = new ReferenceOrderedData[] {}; // { gff, dbsnp };
}
this.engine = new TraversalEngine(INPUT_FILE, REF_FILE_ARG, rods);
ValidationStringency strictness;
if ( STRICTNESS_ARG == null ) {
strictness = ValidationStringency.STRICT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("lenient") ) {
strictness = ValidationStringency.LENIENT;
}
else if ( STRICTNESS_ARG.toLowerCase().equals("silent") ) {
strictness = ValidationStringency.SILENT;
}
else {
strictness = ValidationStringency.STRICT;
}
System.err.println("Strictness is " + strictness);
engine.setStrictness(strictness);
engine.setDebugging(! ( DEBUGGING_STR == null || DEBUGGING_STR.toLowerCase().equals("true")));
engine.setMaxReads(Integer.parseInt(MAX_READS_ARG));
if ( REGION_STR != null ) {
engine.setLocation(REGION_STR);
}
engine.setSafetyChecking(! UNSAFE.toLowerCase().equals("true"));
engine.setSortOnFly(ENABLED_SORT_ON_FLY.toLowerCase().equals("true"));
engine.initialize(ENABLED_THREADED_IO.toLowerCase().equals("true"));
//engine.testReference();
//LocusWalker<Integer,Integer> walker = new PileupWalker();
// Try to get the module specified
Object my_module;
if (MODULES.containsKey(Analysis_Name)) {
my_module = MODULES.get(Analysis_Name);
} else {
System.out.println("Could not find module "+Analysis_Name);
return 0;
}
try {
LocusWalker<?, ?> walker = (LocusWalker<?, ?>)my_module;
engine.traverseByLoci(walker);
}
catch ( java.lang.ClassCastException e ) {
// I guess we're a read walker LOL
ReadWalker<?, ?> walker = (ReadWalker<?, ?>)my_module;
engine.traverseByRead(walker);
}
return 0;
}
|
diff --git a/src/edu/berkeley/gamesman/JythonInterface.java b/src/edu/berkeley/gamesman/JythonInterface.java
index cfb127be..da382731 100644
--- a/src/edu/berkeley/gamesman/JythonInterface.java
+++ b/src/edu/berkeley/gamesman/JythonInterface.java
@@ -1,84 +1,87 @@
package edu.berkeley.gamesman;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.prefs.Preferences;
import jline.ConsoleReader;
import jline.Terminal;
import org.python.core.PyObject;
import org.python.util.InteractiveConsole;
import org.python.util.JLineConsole;
import org.python.util.ReadlineConsole;
public final class JythonInterface {
private enum Consoles {
dumb,readline,jline
}
/**
* @param args
* @throws IOException something bad happened
*/
public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(JythonInterface.class);
String consoleName = prefs.get("console", "ask");
Consoles console = null;
if(consoleName.equals("ask")){
System.out.print("What console would you like to use? "+Arrays.toString(Consoles.values())+": ");
System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
consoleName = br.readLine();
if((console = Consoles.valueOf(consoleName)) != null){
prefs.put("console", consoleName);
}
- }
+ }else
+ console = Consoles.valueOf(consoleName);
InteractiveConsole rc = null;
switch(console){
case dumb:
rc = new InteractiveConsole();
+ break;
case jline:
try {
ConsoleReader cr = new ConsoleReader();
System.out.print("Press enter to start gamesman-jython!\n");
if(cr.readLine() != null) //eclipse doesn't work with jline
rc = new JLineConsole();
} catch(Error e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//if jline isn't working for some reason
rc = new InteractiveConsole() {
@Override
public String raw_input(PyObject prompt) {
return super.raw_input(prompt);
}
};
+ break;
case readline:
rc = new ReadlineConsole();
}
//this will let us put .py files in the junk directory, and things will just work =)
rc.exec("import sys");
addpath(rc, "jython_lib");
addpath(rc, "junk");
addpath(rc, "jobs");
rc.exec("from Play import *");
rc.interact();
}
private static void addpath(InteractiveConsole ic, String what){
String ud = System.getProperty("user.dir");
ic.exec(String.format("sys.path.append('%s/%s'); sys.path.append('%s/../%s');",
ud, what, ud, what));
}
}
| false | true | public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(JythonInterface.class);
String consoleName = prefs.get("console", "ask");
Consoles console = null;
if(consoleName.equals("ask")){
System.out.print("What console would you like to use? "+Arrays.toString(Consoles.values())+": ");
System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
consoleName = br.readLine();
if((console = Consoles.valueOf(consoleName)) != null){
prefs.put("console", consoleName);
}
}
InteractiveConsole rc = null;
switch(console){
case dumb:
rc = new InteractiveConsole();
case jline:
try {
ConsoleReader cr = new ConsoleReader();
System.out.print("Press enter to start gamesman-jython!\n");
if(cr.readLine() != null) //eclipse doesn't work with jline
rc = new JLineConsole();
} catch(Error e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//if jline isn't working for some reason
rc = new InteractiveConsole() {
@Override
public String raw_input(PyObject prompt) {
return super.raw_input(prompt);
}
};
case readline:
rc = new ReadlineConsole();
}
//this will let us put .py files in the junk directory, and things will just work =)
rc.exec("import sys");
addpath(rc, "jython_lib");
addpath(rc, "junk");
addpath(rc, "jobs");
rc.exec("from Play import *");
rc.interact();
}
| public static void main(String[] args) throws Exception {
Preferences prefs = Preferences.userNodeForPackage(JythonInterface.class);
String consoleName = prefs.get("console", "ask");
Consoles console = null;
if(consoleName.equals("ask")){
System.out.print("What console would you like to use? "+Arrays.toString(Consoles.values())+": ");
System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
consoleName = br.readLine();
if((console = Consoles.valueOf(consoleName)) != null){
prefs.put("console", consoleName);
}
}else
console = Consoles.valueOf(consoleName);
InteractiveConsole rc = null;
switch(console){
case dumb:
rc = new InteractiveConsole();
break;
case jline:
try {
ConsoleReader cr = new ConsoleReader();
System.out.print("Press enter to start gamesman-jython!\n");
if(cr.readLine() != null) //eclipse doesn't work with jline
rc = new JLineConsole();
} catch(Error e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//if jline isn't working for some reason
rc = new InteractiveConsole() {
@Override
public String raw_input(PyObject prompt) {
return super.raw_input(prompt);
}
};
break;
case readline:
rc = new ReadlineConsole();
}
//this will let us put .py files in the junk directory, and things will just work =)
rc.exec("import sys");
addpath(rc, "jython_lib");
addpath(rc, "junk");
addpath(rc, "jobs");
rc.exec("from Play import *");
rc.interact();
}
|
diff --git a/src/sidekick/coffeescript/ParserConfig.java b/src/sidekick/coffeescript/ParserConfig.java
index 690759c..f87fd39 100644
--- a/src/sidekick/coffeescript/ParserConfig.java
+++ b/src/sidekick/coffeescript/ParserConfig.java
@@ -1,95 +1,104 @@
package sidekick.coffeescript;
import javax.swing.tree.DefaultMutableTreeNode;
import org.gjt.sp.util.Log;
import org.gjt.sp.jedit.Buffer;
import errorlist.DefaultErrorSource;
import errorlist.ErrorSource;
/**
* Configuration object for the parser, providing options and callbacks for
* TreeNode construction, error reporting and logging.
*/
public class ParserConfig {
public boolean showErrors;
public boolean displayCodeParameters = false;;
public boolean isCakefile = false;
public int line = 0;
private final Buffer buffer;
private final DefaultErrorSource errorSource;
private
ParserConfig(Buffer buffer, DefaultErrorSource errorSource) {
this.buffer = buffer;
this.errorSource = errorSource;
}
/**
* Build config for parsing.
*/
static ParserConfig
forParsing(Buffer buffer, DefaultErrorSource errorSource) {
ParserConfig config = new ParserConfig(buffer, errorSource);
config.showErrors = Options.getBool("showErrors");
config.displayCodeParameters = Options.getBool("displayCodeParameters");
config.isCakefile = buffer.getName().equals("Cakefile");
return config;
}
/**
* Build config for compiling.
*/
static ParserConfig
forCompiling(Buffer buffer, DefaultErrorSource errorSource) {
ParserConfig config = new ParserConfig(buffer, errorSource);
config.showErrors = true;
return config;
}
/**
* Logger function for the CoffeeScript parser.
*/
public void
logError(String message) {
Log.log(Log.ERROR, CoffeeScriptSideKickParser.class, message);
}
/**
* Reporter function for the CoffeeScript parser.
*/
public void
- reportError(Integer line, String message) {
+ reportError(String message,
+ Integer line, Integer first_column, Integer last_column) {
if (showErrors) {
if (line == null) {
line = Integer.MAX_VALUE;
+ first_column = last_column = 0;
+ } else if (first_column == null) {
+ first_column = last_column = 0;
+ } else if (last_column == null) {
+ last_column = first_column;
+ } else {
+ last_column += 1; // span ends _after_ the last character
}
this.errorSource.addError(
new DefaultErrorSource.DefaultError(this.errorSource,
ErrorSource.ERROR,
this.buffer.getPath(),
line,
- 0, 0,
+ first_column,
+ last_column,
message));
}
}
/**
* TreeNode factory for the CoffeeScript parser.
*/
public DefaultMutableTreeNode
makeTreeNode(String name, String type, String qualifier,
int firstLine, int lastLine) {
CoffeeAsset asset = new CoffeeAsset(name, type, qualifier);
asset.setStart(
this.buffer.createPosition(
this.buffer.getLineStartOffset(firstLine)));
asset.setEnd(
this.buffer.createPosition(
this.buffer.getLineEndOffset(lastLine) - 1));
return new DefaultMutableTreeNode(asset);
}
}
| false | true | public void
reportError(Integer line, String message) {
if (showErrors) {
if (line == null) {
line = Integer.MAX_VALUE;
}
this.errorSource.addError(
new DefaultErrorSource.DefaultError(this.errorSource,
ErrorSource.ERROR,
this.buffer.getPath(),
line,
0, 0,
message));
}
}
| public void
reportError(String message,
Integer line, Integer first_column, Integer last_column) {
if (showErrors) {
if (line == null) {
line = Integer.MAX_VALUE;
first_column = last_column = 0;
} else if (first_column == null) {
first_column = last_column = 0;
} else if (last_column == null) {
last_column = first_column;
} else {
last_column += 1; // span ends _after_ the last character
}
this.errorSource.addError(
new DefaultErrorSource.DefaultError(this.errorSource,
ErrorSource.ERROR,
this.buffer.getPath(),
line,
first_column,
last_column,
message));
}
}
|
diff --git a/source/de/anomic/http/httpTemplate.java b/source/de/anomic/http/httpTemplate.java
index 81e78c93a..56b4374f7 100644
--- a/source/de/anomic/http/httpTemplate.java
+++ b/source/de/anomic/http/httpTemplate.java
@@ -1,430 +1,427 @@
// httpTemplate.java
// -------------------------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
// last major change: 16.01.2005
//
// extended for multi- and alternatives-templates by Alexander Schier
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notice above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
package de.anomic.http;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.util.Hashtable;
import de.anomic.server.serverFileUtils;
import de.anomic.server.logging.serverLog;
/**
* A template engine, which substitutes patterns in strings<br>
*
* The template engine supports four types of templates:<br>
* <ol>
* <li>Normal templates: the template will be replaced by a string.</li>
* <li>Multi templates: the template will be used more than one time.<br>
* i.e. for lists</li>
* <li>3. Alternatives: the program chooses one of multiple alternatives.</li>
* <li>Includes: another file with templates will be included.</li>
* </ol>
*
* All these templates can be used recursivly.<p>
* <b>HTML-Example</b><br>
* <pre>
* <html><head></head><body>
* #{times}#
* Good #(daytime)#morning::evening#(/daytime)#, #[name]#!(#[num]#. Greeting)<br>
* #{/times}#
* </body></html>
* </pre>
* <p>
* The corresponding Hashtable to use this Template:<br>
* <b>Java Example</b><br>
* <pre>
* Hashtable pattern;
* pattern.put("times", 10); //10 greetings
* for(int i=0;i<=9;i++){
* pattern.put("times_"+i+"_daytime", 1); //index: 1, second Entry, evening
* pattern.put("times_"+i+"_name", "John Connor");
* pattern.put("times_"+i+"_num", (i+1));
* }
* </pre>
* <p>
* <b>Recursion</b><br>
* If you use recursive templates, the templates will be used from
* the external to the internal templates.
* In our Example, the Template in #{times}##{/times}# will be repeated ten times.<br>
* Then the inner Templates will be applied.
* <p>
* The inner templates have a prefix, so they may have the same name as a template on another level,
* or templates which are in another recursive template.<br>
* <b>The Prefixes:</b>
* <ul>
* <li>Multi templates: multitemplatename_index_</li>
* <li>Alterantives: alternativename_</li>
* </ul>
* So the Names in the Hashtable are:
* <ul>
* <li>Multi templates: multitemplatename_index_templatename</li>
* <li>Alterantives: alternativename_templatename</li>
* </ul>
* <i>#(alternative)#::#{repeat}##[test]##{/repeat}##(/alternative)#</i><br>
* would be adressed as "alternative_repeat_"+number+"_test"
*/
public final class httpTemplate {
private static final byte hash = (byte)'#';
private static final byte[] hasha = {hash};
private static final byte lbr = (byte)'[';
private static final byte rbr = (byte)']';
private static final byte[] pOpen = {hash, lbr};
private static final byte[] pClose = {rbr, hash};
private static final byte lcbr = (byte)'{';
private static final byte rcbr = (byte)'}';
private static final byte[] mOpen = {hash, lcbr};
private static final byte[] mClose = {rcbr, hash};
private static final byte lrbr = (byte)'(';
private static final byte rrbr = (byte)')';
private static final byte[] aOpen = {hash, lrbr};
private static final byte[] aClose = {rrbr, hash};
private static final byte ps = (byte)'%';
private static final byte[] iOpen = {hash, ps};
private static final byte[] iClose = {ps, hash};
/**
* transfer until a specified pattern is found; everything but the pattern is transfered so far
* the function returns true, if the pattern is found
*/
private static boolean transferUntil(PushbackInputStream i, OutputStream o, byte[] pattern) throws IOException {
int ppos = 0;
int b, bb;
boolean equal;
while ((b = i.read()) > 0) {
if ((b & 0xFF) == pattern[0]) {
// read the whole pattern
equal = true;
for (int n = 1; n < pattern.length; n++) {
if (((bb = i.read()) & 0xFF) != pattern[n]) {
// push back all
i.unread(bb);
equal = false;
for (int nn = n - 1; nn > 0; nn--) i.unread(pattern[nn]);
break;
}
}
if (equal) return true;
}
o.write(b);
}
return false;
}
public static void writeTemplate(InputStream in, OutputStream out, Hashtable pattern, byte[] dflt) throws IOException {
writeTemplate(in, out, pattern, dflt, "");
}
/**
* Reads a input stream, and writes the data with replaced templates on a output stream
*/
public static void writeTemplate(InputStream in, OutputStream out, Hashtable pattern, byte[] dflt, String prefix) throws IOException {
PushbackInputStream pis = new PushbackInputStream(in, 100);
ByteArrayOutputStream keyStream;
String key;
String multi_key;
boolean consistent;
byte[] replacement;
int bb;
while (transferUntil(pis, out, hasha)) {
bb = pis.read();
keyStream = new ByteArrayOutputStream();
if( (bb & 0xFF) == lcbr ){ //multi
if( transferUntil(pis, keyStream, mClose) ){ //close tag
//multi_key = "_" + keyStream.toString(); //for _Key
bb = pis.read();
if( (bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = keyStream.toString(); //IMPORTANT: no prefix here
keyStream = new ByteArrayOutputStream(); //reset stream
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+multi_key+ "; Value: "+pattern.get(prefix+multi_key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+multi_key);
}
*/
//this needs multi_key without prefix
if( transferUntil(pis, keyStream, (new String(mOpen) + "/" + multi_key + new String(mClose)).getBytes()) ){
bb = pis.read();
if((bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = prefix + multi_key; //OK, now add the prefix
String text=keyStream.toString(); //text between #{key}# an #{/key}#
int num=0;
if(pattern.containsKey(multi_key) && pattern.get(multi_key) != null){
try{
num=(int)Integer.parseInt((String)pattern.get(multi_key)); // Key contains the iteration number as string
}catch(NumberFormatException e){
num=0;
}
//System.out.println(multi_key + ": " + num); //DEBUG
}else{
//0 interations - no display
//System.out.println("_"+new String(multi_key)+" is null or does not exist"); //DEBUG
}
//Enumeration enx = pattern.keys(); while (enx.hasMoreElements()) System.out.println("KEY=" + enx.nextElement()); // DEBUG
for(int i=0;i < num;i++ ){
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//System.out.println("recursing with text(prefix="+ multi_key + "_" + i + "_" +"):"); //DEBUG
//System.out.println(text);
writeTemplate(pis2, out, pattern, dflt, multi_key + "_" + i + "_");
}//for
}else{//transferUntil
serverLog.logError("TEMPLATE", "No Close Key found for #{"+multi_key+"}#");
}
}
}else if( (bb & 0xFF) == lrbr ){ //alternatives
int others=0;
String text="";
PushbackInputStream pis2;
transferUntil(pis, keyStream, aClose);
key = keyStream.toString(); //Caution: Key does not contain prefix
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+key+ "; Value: "+pattern.get(prefix+key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+key);
}
*/
keyStream=new ByteArrayOutputStream(); //clear
boolean byName=false;
int whichPattern=0;
String patternName="";
if(pattern.containsKey(prefix + key) && pattern.get(prefix + key) != null){
+ String patternId=(String)pattern.get(prefix + key);
try{
- Object tmp=pattern.get(prefix + key); //lookup by index OR Name
- if(tmp instanceof String){
- byName=true;
- patternName=(String)tmp;//Name
- }else{
- whichPattern=(int)Integer.parseInt((String)pattern.get(prefix + key)); //index
- }
+ whichPattern=(int)Integer.parseInt(patternId); //index
}catch(NumberFormatException e){
whichPattern=0;
+ byName=true;
+ patternName=patternId;
}
}else{
//System.out.println("Pattern \""+new String(prefix + key)+"\" is not set"); //DEBUG
}
int currentPattern=0;
boolean found=false;
keyStream = new ByteArrayOutputStream(); //reset stream
if(byName){
//TODO: better Error Handling
transferUntil(pis, keyStream, (new String("%%"+patternName)).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No such Template: %%"+patternName);
return;
}
keyStream=new ByteArrayOutputStream();
transferUntil(pis, keyStream, "::".getBytes());
pis2 = new PushbackInputStream(new ByteArrayInputStream(keyStream.toString().getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Name)");
}
}else{
while(!found){
bb=pis.read();
if( (bb & 0xFF) == hash){
bb=pis.read();
if( (bb & 0xFF) == lrbr){
transferUntil(pis, keyStream, aClose);
//reached the end. output last string.
if(keyStream.toString().equals("/" + key)){
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//this maybe the wrong, but its the last
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
found=true;
}else if(others >0 && keyStream.toString().startsWith("/")){ //close nested
others--;
text += "#("+keyStream.toString()+")#";
}else{ //nested
others++;
text += "#("+keyStream.toString()+")#";
}
keyStream = new ByteArrayOutputStream(); //reset stream
continue;
}else{ //is not #(
pis.unread(bb);//is processed in next loop
bb = (hash);//will be added to text this loop
//text += "#";
}
}else if( (bb & 0xFF) == ':' && others==0){//ignore :: in nested Expressions
bb=pis.read();
if( (bb & 0xFF) == ':'){
if(currentPattern == whichPattern){ //found the pattern
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());//to #(/key)#.
found=true;
}
currentPattern++;
text="";
continue;
}else{
text += ":";
}
}
if(!found){
text += (char)bb;
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Index)");
found=true;
}
}
}//while
}//if(byName) (else branch)
}else if( (bb & 0xFF) == lbr ){ //normal
if (transferUntil(pis, keyStream, pClose)) {
// pattern detected, write replacement
key = prefix + keyStream.toString();
replacement = replacePattern(key, pattern, dflt); //replace
/* DEBUG
try{
System.out.println("Key: "+key+ "; Value: "+pattern.get(key));
}catch(NullPointerException e){
System.out.println("Key: "+key);
}
*/
serverFileUtils.write(replacement, out);
} else {
// inconsistency, simply finalize this
serverFileUtils.copy(pis, out);
return;
}
}else if( (bb & 0xFF) == ps){ //include
String include = "";
String line = "";
keyStream = new ByteArrayOutputStream(); //reset stream
if(transferUntil(pis, keyStream, iClose)){
String filename = keyStream.toString();
if(filename.startsWith( Character.toString((char)lbr) ) && filename.endsWith( Character.toString((char)rbr) )){ //simple pattern for filename
filename= new String(replacePattern( prefix + filename.substring(1, filename.length()-1), pattern, dflt));
}
if ((!filename.equals("")) && (!filename.equals(dflt))) {
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream( new File("htroot", filename) )));
//Read the Include
while( (line = br.readLine()) != null ){
include+=line+de.anomic.server.serverCore.crlfString;
}
}catch(IOException e){
//file not found?
serverLog.logError("FILEHANDLER","Include Error with file: "+filename);
} finally {
if (br!=null) try{br.close(); br=null;}catch(Exception e){}
}
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix);
}
}
}else{ //no match, but a single hash (output # + bb)
byte[] tmp=new byte[2];
tmp[0]=hash;
tmp[1]=(byte)bb;
serverFileUtils.write(tmp, out);
}
}
}
public static byte[] replacePattern(String key, Hashtable pattern, byte dflt[]){
byte[] replacement;
Object value;
if (pattern.containsKey(key)) {
value = pattern.get(key);
if (value instanceof byte[]) replacement = (byte[]) value;
else if (value instanceof String) replacement = ((String) value).getBytes();
else replacement = value.toString().getBytes();
} else {
replacement = dflt;
}
return replacement;
}
public static void main(String[] args) {
// arg1 = test input; arg2 = replacement for pattern 'test'; arg3 = default replacement
try {
InputStream i = new ByteArrayInputStream(args[0].getBytes());
Hashtable h = new Hashtable();
h.put("test", args[1].getBytes());
writeTemplate(new PushbackInputStream(i, 100), System.out, h, args[2].getBytes());
System.out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| false | true | public static void writeTemplate(InputStream in, OutputStream out, Hashtable pattern, byte[] dflt, String prefix) throws IOException {
PushbackInputStream pis = new PushbackInputStream(in, 100);
ByteArrayOutputStream keyStream;
String key;
String multi_key;
boolean consistent;
byte[] replacement;
int bb;
while (transferUntil(pis, out, hasha)) {
bb = pis.read();
keyStream = new ByteArrayOutputStream();
if( (bb & 0xFF) == lcbr ){ //multi
if( transferUntil(pis, keyStream, mClose) ){ //close tag
//multi_key = "_" + keyStream.toString(); //for _Key
bb = pis.read();
if( (bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = keyStream.toString(); //IMPORTANT: no prefix here
keyStream = new ByteArrayOutputStream(); //reset stream
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+multi_key+ "; Value: "+pattern.get(prefix+multi_key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+multi_key);
}
*/
//this needs multi_key without prefix
if( transferUntil(pis, keyStream, (new String(mOpen) + "/" + multi_key + new String(mClose)).getBytes()) ){
bb = pis.read();
if((bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = prefix + multi_key; //OK, now add the prefix
String text=keyStream.toString(); //text between #{key}# an #{/key}#
int num=0;
if(pattern.containsKey(multi_key) && pattern.get(multi_key) != null){
try{
num=(int)Integer.parseInt((String)pattern.get(multi_key)); // Key contains the iteration number as string
}catch(NumberFormatException e){
num=0;
}
//System.out.println(multi_key + ": " + num); //DEBUG
}else{
//0 interations - no display
//System.out.println("_"+new String(multi_key)+" is null or does not exist"); //DEBUG
}
//Enumeration enx = pattern.keys(); while (enx.hasMoreElements()) System.out.println("KEY=" + enx.nextElement()); // DEBUG
for(int i=0;i < num;i++ ){
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//System.out.println("recursing with text(prefix="+ multi_key + "_" + i + "_" +"):"); //DEBUG
//System.out.println(text);
writeTemplate(pis2, out, pattern, dflt, multi_key + "_" + i + "_");
}//for
}else{//transferUntil
serverLog.logError("TEMPLATE", "No Close Key found for #{"+multi_key+"}#");
}
}
}else if( (bb & 0xFF) == lrbr ){ //alternatives
int others=0;
String text="";
PushbackInputStream pis2;
transferUntil(pis, keyStream, aClose);
key = keyStream.toString(); //Caution: Key does not contain prefix
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+key+ "; Value: "+pattern.get(prefix+key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+key);
}
*/
keyStream=new ByteArrayOutputStream(); //clear
boolean byName=false;
int whichPattern=0;
String patternName="";
if(pattern.containsKey(prefix + key) && pattern.get(prefix + key) != null){
try{
Object tmp=pattern.get(prefix + key); //lookup by index OR Name
if(tmp instanceof String){
byName=true;
patternName=(String)tmp;//Name
}else{
whichPattern=(int)Integer.parseInt((String)pattern.get(prefix + key)); //index
}
}catch(NumberFormatException e){
whichPattern=0;
}
}else{
//System.out.println("Pattern \""+new String(prefix + key)+"\" is not set"); //DEBUG
}
int currentPattern=0;
boolean found=false;
keyStream = new ByteArrayOutputStream(); //reset stream
if(byName){
//TODO: better Error Handling
transferUntil(pis, keyStream, (new String("%%"+patternName)).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No such Template: %%"+patternName);
return;
}
keyStream=new ByteArrayOutputStream();
transferUntil(pis, keyStream, "::".getBytes());
pis2 = new PushbackInputStream(new ByteArrayInputStream(keyStream.toString().getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Name)");
}
}else{
while(!found){
bb=pis.read();
if( (bb & 0xFF) == hash){
bb=pis.read();
if( (bb & 0xFF) == lrbr){
transferUntil(pis, keyStream, aClose);
//reached the end. output last string.
if(keyStream.toString().equals("/" + key)){
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//this maybe the wrong, but its the last
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
found=true;
}else if(others >0 && keyStream.toString().startsWith("/")){ //close nested
others--;
text += "#("+keyStream.toString()+")#";
}else{ //nested
others++;
text += "#("+keyStream.toString()+")#";
}
keyStream = new ByteArrayOutputStream(); //reset stream
continue;
}else{ //is not #(
pis.unread(bb);//is processed in next loop
bb = (hash);//will be added to text this loop
//text += "#";
}
}else if( (bb & 0xFF) == ':' && others==0){//ignore :: in nested Expressions
bb=pis.read();
if( (bb & 0xFF) == ':'){
if(currentPattern == whichPattern){ //found the pattern
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());//to #(/key)#.
found=true;
}
currentPattern++;
text="";
continue;
}else{
text += ":";
}
}
if(!found){
text += (char)bb;
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Index)");
found=true;
}
}
}//while
}//if(byName) (else branch)
}else if( (bb & 0xFF) == lbr ){ //normal
if (transferUntil(pis, keyStream, pClose)) {
// pattern detected, write replacement
key = prefix + keyStream.toString();
replacement = replacePattern(key, pattern, dflt); //replace
/* DEBUG
try{
System.out.println("Key: "+key+ "; Value: "+pattern.get(key));
}catch(NullPointerException e){
System.out.println("Key: "+key);
}
*/
serverFileUtils.write(replacement, out);
} else {
// inconsistency, simply finalize this
serverFileUtils.copy(pis, out);
return;
}
}else if( (bb & 0xFF) == ps){ //include
String include = "";
String line = "";
keyStream = new ByteArrayOutputStream(); //reset stream
if(transferUntil(pis, keyStream, iClose)){
String filename = keyStream.toString();
if(filename.startsWith( Character.toString((char)lbr) ) && filename.endsWith( Character.toString((char)rbr) )){ //simple pattern for filename
filename= new String(replacePattern( prefix + filename.substring(1, filename.length()-1), pattern, dflt));
}
if ((!filename.equals("")) && (!filename.equals(dflt))) {
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream( new File("htroot", filename) )));
//Read the Include
while( (line = br.readLine()) != null ){
include+=line+de.anomic.server.serverCore.crlfString;
}
}catch(IOException e){
//file not found?
serverLog.logError("FILEHANDLER","Include Error with file: "+filename);
} finally {
if (br!=null) try{br.close(); br=null;}catch(Exception e){}
}
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix);
}
}
}else{ //no match, but a single hash (output # + bb)
byte[] tmp=new byte[2];
tmp[0]=hash;
tmp[1]=(byte)bb;
serverFileUtils.write(tmp, out);
}
}
}
| public static void writeTemplate(InputStream in, OutputStream out, Hashtable pattern, byte[] dflt, String prefix) throws IOException {
PushbackInputStream pis = new PushbackInputStream(in, 100);
ByteArrayOutputStream keyStream;
String key;
String multi_key;
boolean consistent;
byte[] replacement;
int bb;
while (transferUntil(pis, out, hasha)) {
bb = pis.read();
keyStream = new ByteArrayOutputStream();
if( (bb & 0xFF) == lcbr ){ //multi
if( transferUntil(pis, keyStream, mClose) ){ //close tag
//multi_key = "_" + keyStream.toString(); //for _Key
bb = pis.read();
if( (bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = keyStream.toString(); //IMPORTANT: no prefix here
keyStream = new ByteArrayOutputStream(); //reset stream
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+multi_key+ "; Value: "+pattern.get(prefix+multi_key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+multi_key);
}
*/
//this needs multi_key without prefix
if( transferUntil(pis, keyStream, (new String(mOpen) + "/" + multi_key + new String(mClose)).getBytes()) ){
bb = pis.read();
if((bb & 0xFF) != 10){ //kill newline
pis.unread(bb);
}
multi_key = prefix + multi_key; //OK, now add the prefix
String text=keyStream.toString(); //text between #{key}# an #{/key}#
int num=0;
if(pattern.containsKey(multi_key) && pattern.get(multi_key) != null){
try{
num=(int)Integer.parseInt((String)pattern.get(multi_key)); // Key contains the iteration number as string
}catch(NumberFormatException e){
num=0;
}
//System.out.println(multi_key + ": " + num); //DEBUG
}else{
//0 interations - no display
//System.out.println("_"+new String(multi_key)+" is null or does not exist"); //DEBUG
}
//Enumeration enx = pattern.keys(); while (enx.hasMoreElements()) System.out.println("KEY=" + enx.nextElement()); // DEBUG
for(int i=0;i < num;i++ ){
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//System.out.println("recursing with text(prefix="+ multi_key + "_" + i + "_" +"):"); //DEBUG
//System.out.println(text);
writeTemplate(pis2, out, pattern, dflt, multi_key + "_" + i + "_");
}//for
}else{//transferUntil
serverLog.logError("TEMPLATE", "No Close Key found for #{"+multi_key+"}#");
}
}
}else if( (bb & 0xFF) == lrbr ){ //alternatives
int others=0;
String text="";
PushbackInputStream pis2;
transferUntil(pis, keyStream, aClose);
key = keyStream.toString(); //Caution: Key does not contain prefix
/* DEBUG - print key + value
try{
System.out.println("Key: "+prefix+key+ "; Value: "+pattern.get(prefix+key));
}catch(NullPointerException e){
System.out.println("Key: "+prefix+key);
}
*/
keyStream=new ByteArrayOutputStream(); //clear
boolean byName=false;
int whichPattern=0;
String patternName="";
if(pattern.containsKey(prefix + key) && pattern.get(prefix + key) != null){
String patternId=(String)pattern.get(prefix + key);
try{
whichPattern=(int)Integer.parseInt(patternId); //index
}catch(NumberFormatException e){
whichPattern=0;
byName=true;
patternName=patternId;
}
}else{
//System.out.println("Pattern \""+new String(prefix + key)+"\" is not set"); //DEBUG
}
int currentPattern=0;
boolean found=false;
keyStream = new ByteArrayOutputStream(); //reset stream
if(byName){
//TODO: better Error Handling
transferUntil(pis, keyStream, (new String("%%"+patternName)).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No such Template: %%"+patternName);
return;
}
keyStream=new ByteArrayOutputStream();
transferUntil(pis, keyStream, "::".getBytes());
pis2 = new PushbackInputStream(new ByteArrayInputStream(keyStream.toString().getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Name)");
}
}else{
while(!found){
bb=pis.read();
if( (bb & 0xFF) == hash){
bb=pis.read();
if( (bb & 0xFF) == lrbr){
transferUntil(pis, keyStream, aClose);
//reached the end. output last string.
if(keyStream.toString().equals("/" + key)){
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
//this maybe the wrong, but its the last
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
found=true;
}else if(others >0 && keyStream.toString().startsWith("/")){ //close nested
others--;
text += "#("+keyStream.toString()+")#";
}else{ //nested
others++;
text += "#("+keyStream.toString()+")#";
}
keyStream = new ByteArrayOutputStream(); //reset stream
continue;
}else{ //is not #(
pis.unread(bb);//is processed in next loop
bb = (hash);//will be added to text this loop
//text += "#";
}
}else if( (bb & 0xFF) == ':' && others==0){//ignore :: in nested Expressions
bb=pis.read();
if( (bb & 0xFF) == ':'){
if(currentPattern == whichPattern){ //found the pattern
pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix + key + "_");
transferUntil(pis, keyStream, (new String("#(/"+key+")#")).getBytes());//to #(/key)#.
found=true;
}
currentPattern++;
text="";
continue;
}else{
text += ":";
}
}
if(!found){
text += (char)bb;
if(pis.available()==0){
serverLog.logError("TEMPLATE", "No Close Key found for #("+key+")# (by Index)");
found=true;
}
}
}//while
}//if(byName) (else branch)
}else if( (bb & 0xFF) == lbr ){ //normal
if (transferUntil(pis, keyStream, pClose)) {
// pattern detected, write replacement
key = prefix + keyStream.toString();
replacement = replacePattern(key, pattern, dflt); //replace
/* DEBUG
try{
System.out.println("Key: "+key+ "; Value: "+pattern.get(key));
}catch(NullPointerException e){
System.out.println("Key: "+key);
}
*/
serverFileUtils.write(replacement, out);
} else {
// inconsistency, simply finalize this
serverFileUtils.copy(pis, out);
return;
}
}else if( (bb & 0xFF) == ps){ //include
String include = "";
String line = "";
keyStream = new ByteArrayOutputStream(); //reset stream
if(transferUntil(pis, keyStream, iClose)){
String filename = keyStream.toString();
if(filename.startsWith( Character.toString((char)lbr) ) && filename.endsWith( Character.toString((char)rbr) )){ //simple pattern for filename
filename= new String(replacePattern( prefix + filename.substring(1, filename.length()-1), pattern, dflt));
}
if ((!filename.equals("")) && (!filename.equals(dflt))) {
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream( new File("htroot", filename) )));
//Read the Include
while( (line = br.readLine()) != null ){
include+=line+de.anomic.server.serverCore.crlfString;
}
}catch(IOException e){
//file not found?
serverLog.logError("FILEHANDLER","Include Error with file: "+filename);
} finally {
if (br!=null) try{br.close(); br=null;}catch(Exception e){}
}
PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
writeTemplate(pis2, out, pattern, dflt, prefix);
}
}
}else{ //no match, but a single hash (output # + bb)
byte[] tmp=new byte[2];
tmp[0]=hash;
tmp[1]=(byte)bb;
serverFileUtils.write(tmp, out);
}
}
}
|
diff --git a/src/org/openmrs/module/sync/SyncUtil.java b/src/org/openmrs/module/sync/SyncUtil.java
index cf2e34d..d57f3f3 100644
--- a/src/org/openmrs/module/sync/SyncUtil.java
+++ b/src/org/openmrs/module/sync/SyncUtil.java
@@ -1,1010 +1,1023 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.sync;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.Drug;
import org.openmrs.DrugOrder;
import org.openmrs.Encounter;
import org.openmrs.EncounterType;
import org.openmrs.Form;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.OpenmrsObject;
import org.openmrs.OrderType;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientProgram;
import org.openmrs.PatientState;
import org.openmrs.Person;
import org.openmrs.PersonAddress;
import org.openmrs.PersonAttributeType;
import org.openmrs.PersonName;
import org.openmrs.Program;
import org.openmrs.ProgramWorkflow;
import org.openmrs.ProgramWorkflowState;
import org.openmrs.Relationship;
import org.openmrs.RelationshipType;
import org.openmrs.api.APIException;
import org.openmrs.api.context.Context;
import org.openmrs.api.db.LoginCredential;
import org.openmrs.module.sync.api.SyncService;
import org.openmrs.module.sync.serialization.BinaryNormalizer;
import org.openmrs.module.sync.serialization.DefaultNormalizer;
import org.openmrs.module.sync.serialization.FilePackage;
import org.openmrs.module.sync.serialization.IItem;
import org.openmrs.module.sync.serialization.Item;
import org.openmrs.module.sync.serialization.LocaleNormalizer;
import org.openmrs.module.sync.serialization.Normalizer;
import org.openmrs.module.sync.serialization.Record;
import org.openmrs.module.sync.serialization.TimestampNormalizer;
import org.openmrs.module.sync.server.RemoteServer;
import org.openmrs.notification.Message;
import org.openmrs.notification.MessageException;
import org.openmrs.util.OpenmrsUtil;
import org.springframework.util.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Collection of helpful methods in sync
*/
public class SyncUtil {
private static Log log = LogFactory.getLog(SyncUtil.class);
// safetypes are *hibernate* types that we know how to serialize with help
// of Normalizers
public static final Map<String, Normalizer> safetypes;
static {
DefaultNormalizer defN = new DefaultNormalizer();
TimestampNormalizer dateN = new TimestampNormalizer();
BinaryNormalizer byteN = new BinaryNormalizer();
safetypes = new HashMap<String, Normalizer>();
// safetypes.put("binary", defN);
// blob
safetypes.put("boolean", defN);
// safetypes.put("big_integer", defN);
// safetypes.put("big_decimal", defN);
safetypes.put("binary", byteN);
safetypes.put("byte[]", byteN);
// calendar
// calendar_date
// character
// clob
// currency
safetypes.put("date", dateN);
// dbtimestamp
safetypes.put("double", defN);
safetypes.put("float", defN);
safetypes.put("integer", defN);
safetypes.put("locale", new LocaleNormalizer());
safetypes.put("long", defN);
safetypes.put("short", defN);
safetypes.put("string", defN);
safetypes.put("text", defN);
safetypes.put("timestamp", dateN);
// time
// timezone
}
/**
* Convenience method to get the normalizer (see {@link #safetypes}) for the given class.
*
* @param c class to normalize
* @return the {@link Normalizer} to use
* @see #getNormalizer(String)
*/
public static Normalizer getNormalizer(Class c) {
String simpleClassName = c.getSimpleName().toLowerCase();
return getNormalizer(simpleClassName);
}
/**
* Convenience method to get the normalizer (see {@link #safetypes}) for the given class.
*
* @param simpleClassName the lowercase key for the {@link #safetypes} map
* @return the {@link Normalizer} for the given key
*/
public static Normalizer getNormalizer(String simpleClassName) {
return safetypes.get(simpleClassName);
}
/**
* Get the sync work directory in the openmrs application data directory
* @return a file pointing to the sync output dir
*/
public static File getSyncApplicationDir() {
return OpenmrsUtil.getDirectoryInApplicationDataDirectory("sync");
}
public static Object getRootObject(String incoming)
throws Exception {
Object o = null;
if ( incoming != null ) {
Record xml = Record.create(incoming);
Item root = xml.getRootItem();
String className = root.getNode().getNodeName();
o = SyncUtil.newObject(className);
}
return o;
}
public static NodeList getChildNodes(String incoming)
throws Exception {
NodeList nodes = null;
if ( incoming != null ) {
Record xml = Record.create(incoming);
Item root = xml.getRootItem();
nodes = root.getNode().getChildNodes();
}
return nodes;
}
public static void setProperty(Object o, Node n, ArrayList<Field> allFields )
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
String propName = n.getNodeName();
Object propVal = null;
propVal = SyncUtil.valForField(propName, n.getTextContent(), allFields, n);
log.debug("Trying to set value to " + propVal + " when propName is " + propName + " and context is " + n.getTextContent());
if ( propVal != null ) {
SyncUtil.setProperty(o, propName, propVal);
log.debug("Successfully called set" + SyncUtil.propCase(propName) + "(" + propVal + ")" );
}
}
public static void setProperty(Object o, String propName, Object propVal)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Object[] setterParams = new Object[] { propVal };
log.debug("getting setter method");
Method m = SyncUtil.getSetterMethod(o.getClass(), propName, propVal.getClass());
boolean acc = m.isAccessible();
m.setAccessible(true);
log.debug("about to call " + m.getName());
try {
Object voidObj = m.invoke(o, setterParams);
}
finally {
m.setAccessible(acc);
}
}
public static String getAttribute(NodeList nodes, String attName, ArrayList<Field> allFields ) {
String ret = null;
if ( nodes != null && attName != null ) {
for ( int i = 0; i < nodes.getLength(); i++ ) {
Node n = nodes.item(i);
String propName = n.getNodeName();
if ( attName.equals(propName) ) {
Object obj = SyncUtil.valForField(propName, n.getTextContent(), allFields, n);
if ( obj != null ) ret = obj.toString();
}
}
}
return ret;
}
public static String propCase(String text) {
if ( text != null ) {
return text.substring(0, 1).toUpperCase() + text.substring(1);
} else {
return null;
}
}
public static Object newObject(String className) throws Exception {
Object o = null;
if ( className != null ) {
Class clazz = Context.loadClass(className);
Constructor ct = clazz.getConstructor();
o = ct.newInstance();
}
return o;
}
public static ArrayList<Field> getAllFields(Object o) {
Class clazz = o.getClass();
ArrayList<Field> allFields = new ArrayList<Field>();
if ( clazz != null ) {
Field[] nativeFields = clazz.getDeclaredFields();
Field[] superFields = null;
Class superClazz = clazz.getSuperclass();
while ( superClazz != null && !(superClazz.equals(Object.class)) ) {
// loop through to make sure we get ALL relevant superclasses and their fields
if (log.isDebugEnabled())
log.debug("Now inspecting superclass: " + superClazz.getName());
superFields = superClazz.getDeclaredFields();
if ( superFields != null ) {
for ( Field f : superFields ) {
allFields.add(f);
}
}
superClazz = superClazz.getSuperclass();
}
if ( nativeFields != null ) {
// add native fields
for ( Field f : nativeFields ) {
allFields.add(f);
}
}
}
return allFields;
}
public static OpenmrsObject getOpenmrsObj(String className, String uuid) {
try {
OpenmrsObject o = Context.getService(SyncService.class).getOpenmrsObjectByUuid((Class<OpenmrsObject>) Context.loadClass(className), uuid);
if (log.isDebugEnabled()) {
if ( o == null ) {
log.debug("Unable to get an object of type " + className + " with Uuid " + uuid + ";");
}
}
return o;
} catch (ClassNotFoundException ex) {
log.warn("getOpenmrsObj couldn't find class: " + className, ex);
return null;
}
}
public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
Object o = null;
// the String value on the node specifying the "type"
String nodeDefinedClassName = null;
if (n != null) {
Node tmpNode = n.getAttributes().getNamedItem("type");
if (tmpNode != null)
nodeDefinedClassName = tmpNode.getTextContent();
}
// TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ?
// TODO: Speed up sync by returning after "o" is first set? Or are we doing "last field wins" ?
for ( Field f : allFields ) {
//log.debug("field is " + f.getName());
if ( f.getName().equals(fieldName) ) {
log.debug("found Field " + fieldName + " with type is " + f.getGenericType());
Class classType = null;
String className = f.getGenericType().toString(); // the string class name for the actual field
// if its a collection, set, list, etc
if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
ParameterizedType pType = (ParameterizedType)f.getGenericType();
classType = (Class)pType.getRawType(); // can this be anything but Class at this point?!
}
if ( className.startsWith("class ") ) {
className = className.substring("class ".length());
classType = (Class)f.getGenericType();
}
else {
log.trace("Abnormal className for " + f.getGenericType());
}
// we have to explicitly create a new value object here because all we have is a string - won't know how to convert
if ( OpenmrsObject.class.isAssignableFrom(classType) ) {
o = getOpenmrsObj(className, fieldVal);
}
else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) )) {
// if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
// an integer to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still an integer because thats what the db stores. we need to convert the uuid to the pk integer and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
o = obj.getId();
}
else if ("java.lang.String".equals(className) && !("string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName) || "integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
// if we're dealing with a field like PersonAttribute.value, the actual value was changed from
// a string to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still String because thats what the db stores. we need to convert the uuid to the pk integer/string and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
- o = obj.getId().toString(); // call toString so the class types match when looking up the setter
+ if (obj == null) {
+ if (StringUtils.hasText(fieldVal)) {
+ // throw a warning if we're having trouble converting what should be a valid value
+ log.error("Unable to convert value '" + fieldVal + "' into a " + className);
+ throw new SyncException("Unable to convert value '" + fieldVal + "' into a " + className);
+ }
+ else {
+ // if fieldVal is empty, just save an empty string here too
+ o = "";
+ }
+ }
+ else {
+ o = obj.getId().toString(); // call toString so the class types match when looking up the setter
+ }
}
else if (Collection.class.isAssignableFrom(classType)) {
// this is a collection of items. this is intentionally not in the convertStringToObject method
Collection tmpCollection = null;
if (Set.class.isAssignableFrom(classType))
tmpCollection = new LinkedHashSet();
else
tmpCollection = new Vector();
// get the type of class held in the collection
String collectionTypeClassName = null;
java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType)f.getGenericType()).getActualTypeArguments()[0];
if ( collectionType.toString().startsWith("class ") )
collectionTypeClassName = collectionType.toString().substring("class ".length());
// get the type of class defined in the text node
// if it is different, we could be dealing with something like Cohort.memberIds
// node type comes through as java.util.Set<classname>
String nodeDefinedCollectionType = null;
int indexOfLT = nodeDefinedClassName.indexOf("<");
if (indexOfLT > 0)
nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT+1, nodeDefinedClassName.length()-1);
// change the string to just a comma delimited list
fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");
for (String eachFieldVal : fieldVal.split(",")) {
eachFieldVal = eachFieldVal.trim(); // take out whitespace
// try to convert to a simple object
Object tmpObject = convertStringToObject(eachFieldVal, (Class)collectionType);
// convert to an openmrs object
if (tmpObject == null && nodeDefinedCollectionType != null)
tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();
if (tmpObject == null)
log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
else
tmpCollection.add(tmpObject);
}
o = tmpCollection;
}
else if (Map.class.isAssignableFrom(classType)) {
// TODO implement this like Collection
}
else if ((o = convertStringToObject(fieldVal, classType)) != null) {
log.trace("Converted " + fieldVal + " into " + classType.getName());
}
else {
log.debug("Don't know how to deserialize class: " + className);
}
}
}
if ( o == null )
log.debug("Never found a property named: " + fieldName + " for this class");
return o;
}
/**
* Converts the given string into an object of the given className. Supports basic objects like String,
* Integer, Long, Float, Double, Boolean, Date, and Locale.
*
* @param fieldVal the string object representation
* @param clazz the {@link Class} to turn this string into
* @return object of type "clazz" or null if unable to convert it
* @see SyncUtil#getNormalizer(Class)
*/
private static Object convertStringToObject(String fieldVal, Class clazz) {
Normalizer normalizer = getNormalizer(clazz);
if (normalizer == null) {
log.error("Unable to parse value: " + fieldVal + " into object of class: " + clazz.getName());
return null;
}
else {
return normalizer.fromString(clazz, fieldVal);
}
}
/**
*
* Finds property 'get' accessor based on target type and property name.
*
* @return Method object matching name and param, else null
*
* @see getPropertyAccessor(Class objType, String methodName, Class propValType)
*/
public static Method getGetterMethod(Class objType, String propName) {
String methodName = "get" + propCase(propName);
return SyncUtil.getPropertyAccessor(objType, methodName, null);
}
/**
*
* Finds property 'set' accessor based on target type, property name, and set method parameter type.
*
* @return Method object matching name and param, else null
*
* @see getPropertyAccessor(Class objType, String methodName, Class propValType)
*/
public static Method getSetterMethod(Class objType, String propName, Class propValType) {
String methodName = "set" + propCase(propName);
return SyncUtil.getPropertyAccessor(objType, methodName, propValType);
}
/**
*
* Constructs a Method object for invocation on instances of objType class
* based on methodName and the method parameter type. Handles only propery accessors - thus takes
* Class propValType and not Class[] propValTypes.
* <p>
* If necessary, this implementation traverses both objType and propValTypes type hierarchies in search for the
* method signature match.
*
* @param objType Type to examine.
* @param methodName Method name.
* @param propValType Type of the parameter that method takes. If none (i.e. getter), pass null.
* @return Method object matching name and param, else null
*/
private static Method getPropertyAccessor(Class objType, String methodName, Class propValType) {
// need to try to get setter, both in this object, and its parent class
Method m = null;
boolean continueLoop = true;
// Fix - CA - 22 Jan 2008 - extremely odd Java Bean convention that says getter/setter for fields
// where 2nd letter is capitalized (like "aIsToB") first letter stays lower in getter/setter methods
// like "getaIsToB()". Hence we need to try that out too
String altMethodName = methodName.substring(0, 3) + methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
try {
Class[] setterParamClasses = null;
if (propValType != null) { //it is a setter
setterParamClasses = new Class[1];
setterParamClasses[0] = propValType;
}
Class clazz = objType;
// it could be that the setter method itself is in a superclass of objectClass/clazz, so loop through those
while ( continueLoop && m == null && clazz != null && !clazz.equals(Object.class) ) {
try {
m = clazz.getMethod(methodName, setterParamClasses);
continueLoop = false;
break; //yahoo - we got it using exact type match
} catch (SecurityException e) {
m = null;
} catch (NoSuchMethodException e) {
m = null;
}
//not so lucky: try to find method by name, and then compare params for compatibility
//instead of looking for the exact method sig match
Method[] mes = objType.getMethods();
for (Method me : mes) {
if (me.getName().equals(methodName) || me.getName().equals(altMethodName) ) {
Class[] meParamTypes = me.getParameterTypes();
if (propValType != null && meParamTypes != null && meParamTypes.length == 1 && meParamTypes[0].isAssignableFrom(propValType)) {
m = me;
continueLoop = false; //aha! found it
break;
}
}
}
if ( continueLoop ) clazz = clazz.getSuperclass();
}
}
catch(Exception ex) {
//whatever happened, we didn't find the method - return null
m = null;
log.warn("Unexpected exception while looking for a Method object, returning null",ex);
}
if (m == null) {
if (log.isWarnEnabled())
log.warn("Failed to find matching method. type: " + objType.getName() + ", methodName: " + methodName);
}
return m;
}
private static OpenmrsObject findByUuid(Collection<? extends OpenmrsObject> list, OpenmrsObject toCheck){
for(OpenmrsObject element:list){
if(element.getUuid().equals(toCheck.getUuid()))
return element;
}
return null;
}
/**
* Uses the generic hibernate API to perform the save<br/>
*
* Remarks: <br/>
* Obs: if an obs comes through with a non-null voidReason, make sure we change it back to using a PK.
*
* @param o object to save
* @param className type
* @param Uuid unique id of the object that is being saved
* @param true if it is an update scenario
*/
public static synchronized void updateOpenmrsObject(OpenmrsObject o, String className, String Uuid) {
if (o == null) {
log.warn("Will not update OpenMRS object that is NULL");
return;
}
if ("org.openmrs.Obs".equals(className)) {
// if an obs comes through with a non-null voidReason, make sure we change it back to using a PK
Obs obs = (Obs)o;
String voidReason = obs.getVoidReason();
if (StringUtils.hasLength(voidReason)) {
int start = voidReason.lastIndexOf(" ") + 1; // assumes uuids don't have spaces
int end = voidReason.length() - 1;
String uuid = voidReason.substring(start, end);
try {
OpenmrsObject openmrsObject = getOpenmrsObj("org.openmrs.Obs", uuid);
Integer obsId = openmrsObject.getId();
obs.setVoidReason(voidReason.substring(0, start) + obsId + ")");
}
catch (Exception e) {
log.trace("unable to get uuid from obs uuid: " + uuid, e);
}
}
}
else if ("org.openmrs.api.db.LoginCredential".equals(className)) {
LoginCredential login = (LoginCredential)o;
OpenmrsObject openmrsObject = getOpenmrsObj("org.openmrs.User", login.getUuid());
Integer userId = openmrsObject.getId();
login.setUserId(userId);
}
// now do the save
Context.getService(SyncService.class).saveOrUpdate(o);
return;
}
/**
* Helper method for the {@link UUID#randomUUID()} method.
*
* @return a generated random uuid
*/
public static String generateUuid() {
return UUID.randomUUID().toString();
}
public static String displayName(String className, String Uuid) {
String ret = "";
// get more identifying info about this object so it's more user-friendly
if ( className.equals("Person") || className.equals("User") || className.equals("Patient") ) {
Person person = Context.getPersonService().getPersonByUuid(Uuid);
if ( person != null ) ret = person.getPersonName().toString();
}
if ( className.equals("Encounter") ) {
Encounter encounter = Context.getEncounterService().getEncounterByUuid(Uuid);
if ( encounter != null ) {
ret = encounter.getEncounterType().getName()
+ (encounter.getForm() == null ? "" : " (" + encounter.getForm().getName() + ")");
}
}
if ( className.equals("Concept") ) {
Concept concept = Context.getConceptService().getConceptByUuid(Uuid);
if ( concept != null ) ret = concept.getName(Context.getLocale()).getName();
}
if ( className.equals("Drug") ) {
Drug drug = Context.getConceptService().getDrugByUuid(Uuid);
if ( drug != null ) ret = drug.getName();
}
if ( className.equals("Obs") ) {
Obs obs = Context.getObsService().getObsByUuid(Uuid);
if ( obs != null ) ret = obs.getConcept().getName(Context.getLocale()).getName();
}
if ( className.equals("DrugOrder") ) {
DrugOrder drugOrder = (DrugOrder)Context.getOrderService().getOrderByUuid(Uuid);
if ( drugOrder != null ) ret = drugOrder.getDrug().getConcept().getName(Context.getLocale()).getName();
}
if ( className.equals("Program") ) {
Program program = Context.getProgramWorkflowService().getProgramByUuid(Uuid);
if ( program != null ) ret = program.getConcept().getName(Context.getLocale()).getName();
}
if ( className.equals("ProgramWorkflow") ) {
ProgramWorkflow workflow = Context.getProgramWorkflowService().getWorkflowByUuid(Uuid);
if ( workflow != null ) ret = workflow.getConcept().getName(Context.getLocale()).getName();
}
if ( className.equals("ProgramWorkflowState") ) {
ProgramWorkflowState state = Context.getProgramWorkflowService().getStateByUuid(Uuid);
if ( state != null ) ret = state.getConcept().getName(Context.getLocale()).getName();
}
if ( className.equals("PatientProgram") ) {
PatientProgram patientProgram = Context.getProgramWorkflowService().getPatientProgramByUuid(Uuid);
String pat = patientProgram.getPatient().getPersonName().toString();
String prog = patientProgram.getProgram().getConcept().getName(Context.getLocale()).getName();
if ( pat != null && prog != null ) ret = pat + " - " + prog;
}
if ( className.equals("PatientState") ) {
PatientState patientState = Context.getProgramWorkflowService().getPatientStateByUuid(Uuid);
String pat = patientState.getPatientProgram().getPatient().getPersonName().toString();
String st = patientState.getState().getConcept().getName(Context.getLocale()).getName();
if ( pat != null && st != null ) ret = pat + " - " + st;
}
if ( className.equals("PersonAddress") ) {
PersonAddress address = Context.getPersonService().getPersonAddressByUuid(Uuid);
String name = address.getPerson().getFamilyName() + " " + address.getPerson().getGivenName();
name += address.getAddress1() != null && address.getAddress1().length() > 0 ? address.getAddress1() + " " : "";
name += address.getAddress2() != null && address.getAddress2().length() > 0 ? address.getAddress2() + " " : "";
name += address.getCityVillage() != null && address.getCityVillage().length() > 0 ? address.getCityVillage() + " " : "";
name += address.getStateProvince() != null && address.getStateProvince().length() > 0 ? address.getStateProvince() + " " : "";
if ( name != null ) ret = name;
}
if ( className.equals("PersonName") ) {
PersonName personName = Context.getPersonService().getPersonNameByUuid(Uuid);
String name = personName.getFamilyName() + " " + personName.getGivenName();
if ( name != null ) ret = name;
}
if ( className.equals("Relationship") ) {
Relationship relationship = Context.getPersonService().getRelationshipByUuid(Uuid);
String from = relationship.getPersonA().getFamilyName() + " " + relationship.getPersonA().getGivenName();
String to = relationship.getPersonB().getFamilyName() + " " + relationship.getPersonB().getGivenName();
if ( from != null && to != null ) ret += from + " to " + to;
}
if ( className.equals("RelationshipType") ) {
RelationshipType type = Context.getPersonService().getRelationshipTypeByUuid(Uuid);
ret += type.getaIsToB() + " - " + type.getbIsToA();
}
if ( className.equals("PersonAttributeType") ) {
PersonAttributeType type = Context.getPersonService().getPersonAttributeTypeByUuid(Uuid);
ret += type.getName();
}
if ( className.equals("Location") ) {
Location loc = Context.getLocationService().getLocationByUuid(Uuid);
ret += loc.getName();
}
if ( className.equals("EncounterType") ) {
EncounterType type = Context.getEncounterService().getEncounterTypeByUuid(Uuid);
ret += type.getName();
}
if ( className.equals("OrderType") ) {
OrderType type = Context.getOrderService().getOrderTypeByUuid(Uuid);
ret += type.getName();
}
return ret;
}
/**
* Deletes instance of OpenmrsObject. Used to process SyncItems with state of deleted.
*
* Remarks: <br />
* Delete of PatientIdentifier is a special case: we need to remove it from parent collection
* and then re-save patient: it has all-delete-cascade therefore it will
* take care of this itself; more over attempts to delete it explicitly result in hibernate
* error.
*/
public static synchronized void deleteOpenmrsObject(OpenmrsObject o) {
if (o != null && (o instanceof org.openmrs.PatientIdentifier)) {
//if this is a delete of patient identifier, just do the remove from collection
PatientIdentifier piToRemove = (org.openmrs.PatientIdentifier)o;
org.openmrs.Patient p = piToRemove.getPatient();
if (p == null) {
//we don't know what to do here, throw exception
log.error("deleteOpenmrsObject cannot proceed: asked to process PatientIdentifier but no patient id was set. pat_identifier: " + piToRemove.toString());
throw new SyncException("deleteOpenmrsObject cannot proceed: asked to process PatientIdentifier but no patient id was set. pat_identifier: " + piToRemove.toString());
}
//now just remove from collection
p.removeIdentifier(piToRemove);
if (p.getIdentifiers().size() > 0) {
//...and make sure save patient is queued up if there is something to be saved,
//can't save patient with no IDs - API error
Context.getPatientService().savePatient(p);
}
} else if (o instanceof org.openmrs.Concept || o instanceof org.openmrs.ConceptName) {
//delete concept words explicitly, TODO -- is this still needed?
Context.getService(SyncService.class).deleteOpenmrsObject(o);
}
else {
//default behavior: just call plain delete via service API
Context.getService(SyncService.class).deleteOpenmrsObject(o);
}
}
public static void sendSyncErrorMessage(SyncRecord syncRecord, RemoteServer server, Exception exception) {
try {
String adminEmail = Context.getService(SyncService.class).getAdminEmail();
if (adminEmail == null || adminEmail.length() == 0 ) {
log.warn("Sync error message could not be sent because " + SyncConstants.PROPERTY_SYNC_ADMIN_EMAIL + " is not configured.");
}
else if (adminEmail != null) {
log.info("Preparing to send sync error message via email to " + adminEmail);
Message message = new Message();
message.setSender("[email protected]");
message.setSentDate(new Date());
message.setSubject(exception.getMessage());
message.addRecipient(adminEmail);
StringBuffer content = new StringBuffer();
content.
append("ALERT: Synchronization has stopped between\n").
append("local server (").append(Context.getService(SyncService.class).getServerName()).
append(") and remote server ").append(server.getNickname()).append("\n\n").
append("Summary of failing record\n").
append("Original Uuid: " + syncRecord.getOriginalUuid()).
append("Contained classes: " + syncRecord.getContainedClassSet()).
append("Contents:\n");
try {
log.info("Sending email with sync record: " + syncRecord);
for (SyncItem item :syncRecord.getItems()) {
log.info("Sync item content: " + item.getContent());
}
FilePackage pkg = new FilePackage();
Record record = pkg.createRecordForWrite("SyncRecord");
Item top = record.getRootItem();
((IItem) syncRecord).save(record, top);
content.append(record.toString());
} catch (Exception e) {
log.warn("An error occurred while retrieving sync record payload", e);
log.warn("Sync record: " + syncRecord.toString());
}
message.setContent(content.toString());
// Send message
Context.getMessageService().sendMessage(message);
log.info("Sent sync error message to " + adminEmail);
}
} catch (MessageException e) {
log.error("An error occurred while sending the sync error message", e);
}
}
/**
*
*
* @param inputStream
* @return
* @throws Exception
*/
public static String readContents(InputStream inputStream, boolean isCompressed) throws Exception {
StringBuffer contents = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, SyncConstants.UTF8));
String line = "";
while ((line = reader.readLine()) != null) {
contents.append(line);
}
return contents.toString();
}
public static byte [] compress(String content) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CheckedOutputStream cos = new CheckedOutputStream(baos, new CRC32());
GZIPOutputStream zos = new GZIPOutputStream(new BufferedOutputStream(cos));
IOUtils.copy(new ByteArrayInputStream(content.getBytes()), zos);
return baos.toByteArray();
}
public static String decompress(byte[] data) throws IOException {
ByteArrayInputStream bais2 = new ByteArrayInputStream(data);
CheckedInputStream cis = new CheckedInputStream(bais2, new CRC32());
GZIPInputStream zis = new GZIPInputStream(new BufferedInputStream(cis));
InputStreamReader reader = new InputStreamReader(zis);
BufferedReader br = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
/**
* Rebuilds XSN form. This is needed for ingest when form is received from
* remote server; template files that are contained in xsn in fromentry_xsn
* table need to be updated. Supported way to do this is to ask formentry
* module to rebuild XSN. Invoking method via reflection is temporary
* workaround until sync is in trunk: at that point advice point should be
* registered on sync service that formentry could respond to by calling
* rebuild.
*
* @param xsn
* the xsn to be rebuilt.
*/
public static void rebuildXSN(OpenmrsObject xsn) {
Class c = null;
Method m = null;
String msg = null;
if (xsn == null) {
return;
}
try {
// only rebuild non-archived xsns
try {
m = xsn.getClass().getDeclaredMethod("getArchived");
} catch (Exception e) { }
if (m == null) {
log.warn("Failed to retrieve handle to getArchived method; is formentry module loaded?");
return;
}
Boolean isArchived = (Boolean) m.invoke(xsn, null);
if (isArchived)
return;
// get the form id of the xsn
try {
m = xsn.getClass().getDeclaredMethod("getForm");
} catch (Exception e) { }
if (m == null) {
log.warn("Failed to retrieve handle to getForm method in FormEntryXsn; is formentry module loaded?");
return;
}
Form form = (Form) m.invoke(xsn, null);
msg = "Processing form with id: " + form.getFormId();
// now get methods to rebuild the form
try {
c = Context.loadClass("org.openmrs.module.formentry.FormEntryUtil");
} catch (Exception e) { }
if (c == null) {
log.warn("Failed to retrieve handle to FormEntryUtil in formentry module; is formentry module loaded? " + msg);
return;
}
try {
m = c.getDeclaredMethod("rebuildXSN", new Class[] { Form.class });
} catch (Exception e) { }
if (m == null) {
log.warn("Failed to retrieve handle to rebuildXSN method in FormEntryUtil; is formentry module loaded? " + msg);
return;
}
// finally actually do the rebuilding
m.invoke(null, form);
} catch (Exception e) {
log.error("FormEntry module present but failed to rebuild XSN, see stack for error detail." + msg, e);
throw new SyncException("FormEntry module present but failed to rebuild XSN, see server log for the stacktrace for error details " + msg, e);
}
return;
}
/**
* Rebuilds XSN form. Same helper method as above, but takes Form as input.
*
* @param form form to rebuild xsn for
*/
public static void rebuildXSNForForm(Form form) {
Object o = null;
Class c = null;
Method m = null;
String msg = null;
Object xsn = null;
if (form == null) {
return;
}
try {
msg = "Processing form with id: " + form.getFormId().toString();
boolean rebuildXsn = true;
try {
c = Context.loadClass("org.openmrs.module.formentry.FormEntryService");
} catch(Exception e){}
if (c==null) {
log.warn("Failed to find FormEntryService in formentry module; is module loaded? " + msg);
return;
}
try {
Object formentryservice = Context.getService(c);
m = formentryservice.getClass().getDeclaredMethod("getFormEntryXsn", new Class[]{form.getClass()});
xsn = m.invoke(formentryservice, form);
if (xsn == null)
rebuildXsn = false;
}
catch (Exception e) {
log.warn("Failed to test for formentry xsn existance");
}
if (rebuildXsn) {
SyncUtil.rebuildXSN((OpenmrsObject)xsn);
}
}
catch (Exception e) {
log.error("FormEntry module present but failed to rebuild XSN, see stack for error detail." + msg,e);
throw new SyncException("FormEntry module present but failed to rebuild XSN, see server log for the stacktrace for error details " + msg, e);
}
return;
}
/**
* Checks that given class to see if its "getId()" method returns an {@link UnsupportedOperationException}.
* <br/>
* The <code>entryClassName</code> should be of type {@link OpenmrsObject}
*
* @param entryClassName class name of OpenmrsObject to check
* @return true if getId() throws an {@link UnsupportedOperationException}
*/
public static boolean hasNoAutomaticPrimaryKey(String entryClassName) {
try {
Class<OpenmrsObject> c = (Class<OpenmrsObject>) Context.loadClass(entryClassName);
OpenmrsObject o = c.newInstance();
o.getId();
return false;
}
catch (UnsupportedOperationException e) {
return true;
}
catch (Exception e) {
throw new APIException("Can't load class named " + entryClassName, e);
}
}
}
| true | true | public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
Object o = null;
// the String value on the node specifying the "type"
String nodeDefinedClassName = null;
if (n != null) {
Node tmpNode = n.getAttributes().getNamedItem("type");
if (tmpNode != null)
nodeDefinedClassName = tmpNode.getTextContent();
}
// TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ?
// TODO: Speed up sync by returning after "o" is first set? Or are we doing "last field wins" ?
for ( Field f : allFields ) {
//log.debug("field is " + f.getName());
if ( f.getName().equals(fieldName) ) {
log.debug("found Field " + fieldName + " with type is " + f.getGenericType());
Class classType = null;
String className = f.getGenericType().toString(); // the string class name for the actual field
// if its a collection, set, list, etc
if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
ParameterizedType pType = (ParameterizedType)f.getGenericType();
classType = (Class)pType.getRawType(); // can this be anything but Class at this point?!
}
if ( className.startsWith("class ") ) {
className = className.substring("class ".length());
classType = (Class)f.getGenericType();
}
else {
log.trace("Abnormal className for " + f.getGenericType());
}
// we have to explicitly create a new value object here because all we have is a string - won't know how to convert
if ( OpenmrsObject.class.isAssignableFrom(classType) ) {
o = getOpenmrsObj(className, fieldVal);
}
else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) )) {
// if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
// an integer to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still an integer because thats what the db stores. we need to convert the uuid to the pk integer and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
o = obj.getId();
}
else if ("java.lang.String".equals(className) && !("string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName) || "integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
// if we're dealing with a field like PersonAttribute.value, the actual value was changed from
// a string to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still String because thats what the db stores. we need to convert the uuid to the pk integer/string and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
o = obj.getId().toString(); // call toString so the class types match when looking up the setter
}
else if (Collection.class.isAssignableFrom(classType)) {
// this is a collection of items. this is intentionally not in the convertStringToObject method
Collection tmpCollection = null;
if (Set.class.isAssignableFrom(classType))
tmpCollection = new LinkedHashSet();
else
tmpCollection = new Vector();
// get the type of class held in the collection
String collectionTypeClassName = null;
java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType)f.getGenericType()).getActualTypeArguments()[0];
if ( collectionType.toString().startsWith("class ") )
collectionTypeClassName = collectionType.toString().substring("class ".length());
// get the type of class defined in the text node
// if it is different, we could be dealing with something like Cohort.memberIds
// node type comes through as java.util.Set<classname>
String nodeDefinedCollectionType = null;
int indexOfLT = nodeDefinedClassName.indexOf("<");
if (indexOfLT > 0)
nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT+1, nodeDefinedClassName.length()-1);
// change the string to just a comma delimited list
fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");
for (String eachFieldVal : fieldVal.split(",")) {
eachFieldVal = eachFieldVal.trim(); // take out whitespace
// try to convert to a simple object
Object tmpObject = convertStringToObject(eachFieldVal, (Class)collectionType);
// convert to an openmrs object
if (tmpObject == null && nodeDefinedCollectionType != null)
tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();
if (tmpObject == null)
log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
else
tmpCollection.add(tmpObject);
}
o = tmpCollection;
}
else if (Map.class.isAssignableFrom(classType)) {
// TODO implement this like Collection
}
else if ((o = convertStringToObject(fieldVal, classType)) != null) {
log.trace("Converted " + fieldVal + " into " + classType.getName());
}
else {
log.debug("Don't know how to deserialize class: " + className);
}
}
}
if ( o == null )
log.debug("Never found a property named: " + fieldName + " for this class");
return o;
}
| public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
Object o = null;
// the String value on the node specifying the "type"
String nodeDefinedClassName = null;
if (n != null) {
Node tmpNode = n.getAttributes().getNamedItem("type");
if (tmpNode != null)
nodeDefinedClassName = tmpNode.getTextContent();
}
// TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ?
// TODO: Speed up sync by returning after "o" is first set? Or are we doing "last field wins" ?
for ( Field f : allFields ) {
//log.debug("field is " + f.getName());
if ( f.getName().equals(fieldName) ) {
log.debug("found Field " + fieldName + " with type is " + f.getGenericType());
Class classType = null;
String className = f.getGenericType().toString(); // the string class name for the actual field
// if its a collection, set, list, etc
if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
ParameterizedType pType = (ParameterizedType)f.getGenericType();
classType = (Class)pType.getRawType(); // can this be anything but Class at this point?!
}
if ( className.startsWith("class ") ) {
className = className.substring("class ".length());
classType = (Class)f.getGenericType();
}
else {
log.trace("Abnormal className for " + f.getGenericType());
}
// we have to explicitly create a new value object here because all we have is a string - won't know how to convert
if ( OpenmrsObject.class.isAssignableFrom(classType) ) {
o = getOpenmrsObj(className, fieldVal);
}
else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) )) {
// if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
// an integer to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still an integer because thats what the db stores. we need to convert the uuid to the pk integer and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
o = obj.getId();
}
else if ("java.lang.String".equals(className) && !("string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName) || "integer".equals(nodeDefinedClassName) || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
// if we're dealing with a field like PersonAttribute.value, the actual value was changed from
// a string to a uuid by the HibernateSyncInterceptor. The nodeDefinedClassName is the node.type which is the
// actual classname as defined by the PersonAttributeType.format. However, the field.getClassName is
// still String because thats what the db stores. we need to convert the uuid to the pk integer/string and return it
OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
if (obj == null) {
if (StringUtils.hasText(fieldVal)) {
// throw a warning if we're having trouble converting what should be a valid value
log.error("Unable to convert value '" + fieldVal + "' into a " + className);
throw new SyncException("Unable to convert value '" + fieldVal + "' into a " + className);
}
else {
// if fieldVal is empty, just save an empty string here too
o = "";
}
}
else {
o = obj.getId().toString(); // call toString so the class types match when looking up the setter
}
}
else if (Collection.class.isAssignableFrom(classType)) {
// this is a collection of items. this is intentionally not in the convertStringToObject method
Collection tmpCollection = null;
if (Set.class.isAssignableFrom(classType))
tmpCollection = new LinkedHashSet();
else
tmpCollection = new Vector();
// get the type of class held in the collection
String collectionTypeClassName = null;
java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType)f.getGenericType()).getActualTypeArguments()[0];
if ( collectionType.toString().startsWith("class ") )
collectionTypeClassName = collectionType.toString().substring("class ".length());
// get the type of class defined in the text node
// if it is different, we could be dealing with something like Cohort.memberIds
// node type comes through as java.util.Set<classname>
String nodeDefinedCollectionType = null;
int indexOfLT = nodeDefinedClassName.indexOf("<");
if (indexOfLT > 0)
nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT+1, nodeDefinedClassName.length()-1);
// change the string to just a comma delimited list
fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");
for (String eachFieldVal : fieldVal.split(",")) {
eachFieldVal = eachFieldVal.trim(); // take out whitespace
// try to convert to a simple object
Object tmpObject = convertStringToObject(eachFieldVal, (Class)collectionType);
// convert to an openmrs object
if (tmpObject == null && nodeDefinedCollectionType != null)
tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();
if (tmpObject == null)
log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
else
tmpCollection.add(tmpObject);
}
o = tmpCollection;
}
else if (Map.class.isAssignableFrom(classType)) {
// TODO implement this like Collection
}
else if ((o = convertStringToObject(fieldVal, classType)) != null) {
log.trace("Converted " + fieldVal + " into " + classType.getName());
}
else {
log.debug("Don't know how to deserialize class: " + className);
}
}
}
if ( o == null )
log.debug("Never found a property named: " + fieldName + " for this class");
return o;
}
|
diff --git a/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/FlatFilePermissions.java b/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/FlatFilePermissions.java
index 6ccb728..7c2b9ec 100644
--- a/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/FlatFilePermissions.java
+++ b/src/main/java/de/hydrox/bukkit/DroxPerms/data/flatfile/FlatFilePermissions.java
@@ -1,507 +1,507 @@
package de.hydrox.bukkit.DroxPerms.data.flatfile;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;
import de.hydrox.bukkit.DroxPerms.data.IDataProvider;
/**
*
* @author Matthias Söhnholz
*
*/
public class FlatFilePermissions implements IDataProvider {
public static final String NODE = "FlatFile";
protected static Plugin plugin = null;
private Configuration groupsConfig;
private Configuration usersConfig;
private Configuration tracksConfig;
public FlatFilePermissions() {
groupsConfig = new Configuration(new File("groupsConfig.yml"));
usersConfig = new Configuration(new File("usersConfig.yml"));
tracksConfig = new Configuration(new File("tracksConfig.yml"));
}
public FlatFilePermissions(Plugin plugin) {
FlatFilePermissions.plugin = plugin;
// Write some default configuration
groupsConfig = new Configuration(new File(plugin.getDataFolder(), "groups.yml"));
usersConfig = new Configuration(new File(plugin.getDataFolder(), "users.yml"));
tracksConfig = new Configuration(new File(plugin.getDataFolder(), "tracks.yml"));
if (!new File(plugin.getDataFolder(), "groups.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default groups.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
tmp.put("default", new Group("default").toConfigurationNode());
groupsConfig.setProperty("groups", tmp);
groupsConfig.save();
}
groupsConfig.load();
// System.out.println(groupsConfig.getKeys().toString());
Map<String, ConfigurationNode> groups = groupsConfig.getNodes("groups");
Iterator<String> iter = groups.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load group: " + key);
ConfigurationNode conf = groups.get(key);
Group newGroup = new Group(key, conf);
Group.addGroup(newGroup);
}
if (!new File(plugin.getDataFolder(), "users.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default users.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
usersConfig.setProperty("users", tmp);
usersConfig.save();
}
usersConfig.load();
// System.out.println(usersConfig.getKeys().toString());
String fileVersion = usersConfig.getString("fileversion");
if (fileVersion == null || !fileVersion.equals(plugin.getDescription().getVersion())) {
plugin.getServer().getLogger().info("[DroxPerms] users.yml-version to old or unknown. Doing full conversion");
usersConfig.setProperty("fileversion", plugin.getDescription().getVersion());
Map<String, ConfigurationNode> users = usersConfig.getNodes("users");
iter = users.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
- plugin.getServer().getLogger().info("load user: " + key);
+ plugin.getServer().getLogger().fine("load user: " + key);
ConfigurationNode conf = users.get(key);
User newUser = new User(key, conf);
newUser.dirty();
User.addUser(newUser);
}
}
tracksConfig.load();
Map<String, ConfigurationNode> tracks = tracksConfig.getNodes("tracks");
if(tracks !=null){
iter = tracks.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load track: " + key);
ConfigurationNode conf = tracks.get(key);
Track newTrack = new Track(key, conf);
Track.addTrack(newTrack);
}
}
}
public void save() {
HashMap<String,Object> tmp = new HashMap<String,Object>();
Iterator<Group> iter = Group.iter();
while (iter.hasNext()) {
Group group = iter.next();
tmp.put(group.getName().toLowerCase(), group.toConfigurationNode());
}
groupsConfig.setProperty("groups", tmp);
groupsConfig.save();
tmp = new HashMap<String,Object>();
Iterator<User> iter2 = User.iter();
while (iter2.hasNext()) {
User user = iter2.next();
if (user.isDirty()) {
usersConfig.getNode("users").setProperty(user.getName(), user.toConfigurationNode());
user.clean();
}
}
usersConfig.save();
}
public boolean createPlayer(String name) {
if (User.existUser(name)) {
return false;
} else {
User.addUser(new User(name));
return true;
}
}
public boolean createGroup(CommandSender sender, String name) {
if (Group.existGroup(name)) {
return false;
} else {
Group.addGroup(new Group(name));
return true;
}
}
public String getPlayerGroup(String player) {
User user = getUser(player);
if (user != null) {
return user.getGroup();
} else {
return "";
}
}
public boolean setPlayerGroup(CommandSender sender, String player, String group) {
User user = getUser(player);
if (user != null) {
boolean result = user.setGroup(group);
if (result) {
sender.sendMessage("Set group of player " + player + " to " + group);
return true;
} else {
sender.sendMessage("Couldn't set group of player " + player);
return false;
}
} else {
return false;
}
}
public ArrayList<String> getPlayerSubgroups(String player) {
User user = getUser(player);
if (user != null) {
ArrayList<String> result = calculateSubgroups(user.getSubgroups());
return result;
} else {
return null;
}
}
private ArrayList<String> calculateSubgroups(ArrayList<String> input) {
boolean dirty = true;
ArrayList<String> result = new ArrayList<String>(input);
ArrayList<String> toTest = new ArrayList<String>(input);
while (toTest.size()!=0) {
String string = toTest.get(0);
ArrayList<String> subgroups = Group.getGroup(string).getSubgroups();
for (String string2 : subgroups) {
if (!result.contains(string2)) {
result.add(string2);
toTest.add(string2);
dirty = true;
}
}
toTest.remove(string);
}
return result;
}
public boolean addPlayerSubgroup(CommandSender sender, String player, String subgroup) {
User user = getUser(player);
if (user != null) {
boolean result = user.addSubgroup(subgroup);
if (result) {
sender.sendMessage("Added " + subgroup + " to subgrouplist of player " + player);
return true;
} else {
sender.sendMessage("Couldn't add subgroup to player " + player);
return false;
}
} else {
return false;
}
}
public boolean removePlayerSubgroup(CommandSender sender, String player, String subgroup) {
User user = getUser(player);
if (user != null) {
boolean result = user.removeSubgroup(subgroup);
if (result) {
sender.sendMessage("removed " + subgroup + " from subgrouplist of player " + player);
return true;
} else {
sender.sendMessage("Couldn't remove subgroup from player " + player);
return false;
}
} else {
return false;
}
}
public boolean addPlayerPermission(CommandSender sender, String player, String world, String node) {
User user = getUser(player);
if (user != null) {
boolean result = user.addPermission(world, node);
if (result) {
sender.sendMessage("Added " + node + " to permissionslist of player " + player);
return true;
} else {
sender.sendMessage("Couldn't add permission to player " + player);
return false;
}
} else {
return false;
}
}
public boolean removePlayerPermission(CommandSender sender, String player, String world, String node) {
User user = getUser(player);
if (user != null) {
boolean result = user.removePermission(world, node);
if (result) {
sender.sendMessage("removed " + node + " from permissionslist of player " + player);
return true;
} else {
sender.sendMessage("Couldn't remove permission from player " + player);
return false;
}
} else {
return false;
}
}
public HashMap<String, ArrayList<String>> getPlayerPermissions(String player, String world) {
User user = getUser(player);
if (user == null) {
plugin.getServer().getLogger().info("[DroxPerms] User " + player + " doesn't exist yet. Creating ...");
user = new User(player);
User.addUser(user);
return user.getPermissions(world);
}
return user.getPermissions(world);
}
public boolean setPlayerInfo(CommandSender sender, String player, String node, String data) {
User user = getUser(player);
if (user != null) {
boolean result = user.setInfo(node, data);
if (result) {
sender.sendMessage("set info-node " + node + " of player " + player);
return true;
} else {
sender.sendMessage("Couldn't set info-node of player " + player);
return false;
}
} else {
return false;
}
}
public String getPlayerInfo(CommandSender sender, String player, String node) {
User user = getUser(player);
if (user != null) {
return user.getInfo(node);
} else {
return null;
}
}
public boolean addGroupPermission(CommandSender sender, String group, String world, String node) {
if (Group.existGroup(group)) {
boolean result = Group.getGroup(group).addPermission(world, node);
if (result) {
sender.sendMessage("Added " + node + " to permissionslist of group " + group);
return true;
} else {
sender.sendMessage("Couldn't add permission to group " + group);
return false;
}
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return false;
}
}
public boolean removeGroupPermission(CommandSender sender, String group, String world, String node) {
if (Group.existGroup(group)) {
boolean result = Group.getGroup(group).removePermission(world, node);
if (result) {
sender.sendMessage("removed " + node + " from permissionslist of group " + group);
return true;
} else {
sender.sendMessage("Couldn't remove permission from group " + group);
return false;
}
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return false;
}
}
public ArrayList<String> getGroupSubgroups(String groupName) {
Group group = Group.getGroup(groupName);
if (group != null) {
ArrayList<String> result = calculateSubgroups(group.getSubgroups());
return result;
} else {
return null;
}
}
public boolean addGroupSubgroup(CommandSender sender, String group, String subgroup) {
if (Group.existGroup(group)) {
boolean result = Group.getGroup(group).addSubgroup(subgroup);
if (result) {
sender.sendMessage("Added " + subgroup + " to subgrouplist of group " + group);
return true;
} else {
sender.sendMessage("Couldn't add subgroup to group " + group);
return false;
}
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return false;
}
}
public boolean removeGroupSubgroup(CommandSender sender, String group, String subgroup) {
if (Group.existGroup(group)) {
boolean result = Group.getGroup(group).removeSubgroup(subgroup);
if (result) {
sender.sendMessage("removed " + subgroup + " from subgrouplist of group " + group);
return true;
} else {
sender.sendMessage("Couldn't remove subgroup from group " + group);
return false;
}
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return false;
}
}
public HashMap<String, ArrayList<String>> getGroupPermissions(String groupName, String world) {
Group group = Group.getGroup(groupName);
if (group == null) {
return null;
}
return group.getPermissions(world);
}
public boolean setGroupInfo(CommandSender sender, String group, String node, String data) {
if (Group.existGroup(group)) {
boolean result = Group.getGroup(group).setInfo(node, data);
if (result) {
sender.sendMessage("set info-node " + node + " for group " + group);
return true;
} else {
sender.sendMessage("Couldn't set info-node for group " + group);
return false;
}
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return false;
}
}
public String getGroupInfo(CommandSender sender, String group, String node) {
if (Group.existGroup(group)) {
return Group.getGroup(group).getInfo(node);
} else {
sender.sendMessage("Group " + group + " doesn't exist.");
return null;
}
}
private User getUser(String name) {
User user = null;
if (User.existUser(name)) {
user = User.getUser(name);
} else {
ConfigurationNode node = usersConfig.getNode("users." + name);
if (node != null) {
user = new User(name, node);
User.addUser(user);
}
}
return user;
}
@Override
public boolean promotePlayer(CommandSender sender, String player,
String track) {
Track selectedTrack = Track.getTrack(track);
if (selectedTrack == null) {
sender.sendMessage("Could not find Track " + track + ".");
return false;
}
User user = getUser(player);
if (user != null) {
String newGroup = selectedTrack.getPromoteGroup(user.getGroup());
if (newGroup == null) {
sender.sendMessage("Could not promote on Track " + track + ".");
return false;
}
return setPlayerGroup(sender, player, newGroup);
} else {
sender.sendMessage("Could not find User " + player + ".");
return false;
}
}
@Override
public boolean demotePlayer(CommandSender sender, String player,
String track) {
Track selectedTrack = Track.getTrack(track);
if (selectedTrack == null) {
sender.sendMessage("Could not find Track " + track + ".");
return false;
}
User user = getUser(player);
if (user != null) {
String newGroup = selectedTrack.getDemoteGroup(user.getGroup());
if (newGroup == null) {
sender.sendMessage("Could not demote on Track " + track + ".");
return false;
}
return setPlayerGroup(sender, player, newGroup);
} else {
sender.sendMessage("Could not find User " + player + ".");
return false;
}
}
@Override
public HashMap<String, ArrayList<String>> getGroupMembers() {
HashMap<String, ArrayList<String>> result = new HashMap<String, ArrayList<String>>();
Iterator<Group> groups = Group.iter();
while (groups.hasNext()) {
Group group = (Group) groups.next();
result.put(group.getName(), new ArrayList<String>());
}
Map<String, ConfigurationNode> users = usersConfig.getNodes("users");
Iterator<String> iter = users.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
ConfigurationNode conf = users.get(key);
User user = new User(key, conf);
result.get(user.getGroup()).add(user.getName());
}
return result;
}
@Override
public HashMap<String, ArrayList<String>> getSubgroupMembers() {
HashMap<String, ArrayList<String>> result = new HashMap<String, ArrayList<String>>();
Iterator<Group> groups = Group.iter();
while (groups.hasNext()) {
Group group = (Group) groups.next();
result.put(group.getName(), new ArrayList<String>());
}
Map<String, ConfigurationNode> users = usersConfig.getNodes("users");
Iterator<String> iter = users.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
ConfigurationNode conf = users.get(key);
User user = new User(key, conf);
ArrayList<String> subgroups = user.getSubgroups();
for (String subgroup : subgroups) {
result.get(subgroup).add(user.getName());
}
}
return result;
}
}
| true | true | public FlatFilePermissions(Plugin plugin) {
FlatFilePermissions.plugin = plugin;
// Write some default configuration
groupsConfig = new Configuration(new File(plugin.getDataFolder(), "groups.yml"));
usersConfig = new Configuration(new File(plugin.getDataFolder(), "users.yml"));
tracksConfig = new Configuration(new File(plugin.getDataFolder(), "tracks.yml"));
if (!new File(plugin.getDataFolder(), "groups.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default groups.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
tmp.put("default", new Group("default").toConfigurationNode());
groupsConfig.setProperty("groups", tmp);
groupsConfig.save();
}
groupsConfig.load();
// System.out.println(groupsConfig.getKeys().toString());
Map<String, ConfigurationNode> groups = groupsConfig.getNodes("groups");
Iterator<String> iter = groups.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load group: " + key);
ConfigurationNode conf = groups.get(key);
Group newGroup = new Group(key, conf);
Group.addGroup(newGroup);
}
if (!new File(plugin.getDataFolder(), "users.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default users.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
usersConfig.setProperty("users", tmp);
usersConfig.save();
}
usersConfig.load();
// System.out.println(usersConfig.getKeys().toString());
String fileVersion = usersConfig.getString("fileversion");
if (fileVersion == null || !fileVersion.equals(plugin.getDescription().getVersion())) {
plugin.getServer().getLogger().info("[DroxPerms] users.yml-version to old or unknown. Doing full conversion");
usersConfig.setProperty("fileversion", plugin.getDescription().getVersion());
Map<String, ConfigurationNode> users = usersConfig.getNodes("users");
iter = users.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().info("load user: " + key);
ConfigurationNode conf = users.get(key);
User newUser = new User(key, conf);
newUser.dirty();
User.addUser(newUser);
}
}
tracksConfig.load();
Map<String, ConfigurationNode> tracks = tracksConfig.getNodes("tracks");
if(tracks !=null){
iter = tracks.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load track: " + key);
ConfigurationNode conf = tracks.get(key);
Track newTrack = new Track(key, conf);
Track.addTrack(newTrack);
}
}
}
| public FlatFilePermissions(Plugin plugin) {
FlatFilePermissions.plugin = plugin;
// Write some default configuration
groupsConfig = new Configuration(new File(plugin.getDataFolder(), "groups.yml"));
usersConfig = new Configuration(new File(plugin.getDataFolder(), "users.yml"));
tracksConfig = new Configuration(new File(plugin.getDataFolder(), "tracks.yml"));
if (!new File(plugin.getDataFolder(), "groups.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default groups.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
tmp.put("default", new Group("default").toConfigurationNode());
groupsConfig.setProperty("groups", tmp);
groupsConfig.save();
}
groupsConfig.load();
// System.out.println(groupsConfig.getKeys().toString());
Map<String, ConfigurationNode> groups = groupsConfig.getNodes("groups");
Iterator<String> iter = groups.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load group: " + key);
ConfigurationNode conf = groups.get(key);
Group newGroup = new Group(key, conf);
Group.addGroup(newGroup);
}
if (!new File(plugin.getDataFolder(), "users.yml").exists()) {
plugin.getServer().getLogger().info("[DroxPerms] Generating default users.yml");
HashMap<String,Object> tmp = new HashMap<String,Object>();
usersConfig.setProperty("users", tmp);
usersConfig.save();
}
usersConfig.load();
// System.out.println(usersConfig.getKeys().toString());
String fileVersion = usersConfig.getString("fileversion");
if (fileVersion == null || !fileVersion.equals(plugin.getDescription().getVersion())) {
plugin.getServer().getLogger().info("[DroxPerms] users.yml-version to old or unknown. Doing full conversion");
usersConfig.setProperty("fileversion", plugin.getDescription().getVersion());
Map<String, ConfigurationNode> users = usersConfig.getNodes("users");
iter = users.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load user: " + key);
ConfigurationNode conf = users.get(key);
User newUser = new User(key, conf);
newUser.dirty();
User.addUser(newUser);
}
}
tracksConfig.load();
Map<String, ConfigurationNode> tracks = tracksConfig.getNodes("tracks");
if(tracks !=null){
iter = tracks.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
plugin.getServer().getLogger().fine("load track: " + key);
ConfigurationNode conf = tracks.get(key);
Track newTrack = new Track(key, conf);
Track.addTrack(newTrack);
}
}
}
|
diff --git a/web/src/main/java/eionet/eunis/dao/impl/ReferencesDaoImpl.java b/web/src/main/java/eionet/eunis/dao/impl/ReferencesDaoImpl.java
index 1eb90539..e09ffe7a 100644
--- a/web/src/main/java/eionet/eunis/dao/impl/ReferencesDaoImpl.java
+++ b/web/src/main/java/eionet/eunis/dao/impl/ReferencesDaoImpl.java
@@ -1,447 +1,447 @@
package eionet.eunis.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.displaytag.properties.SortOrderEnum;
import ro.finsiel.eunis.search.Utilities;
import ro.finsiel.eunis.utilities.EunisUtil;
import eionet.eunis.dao.IReferencesDao;
import eionet.eunis.dto.AttributeDto;
import eionet.eunis.dto.DcIndexDTO;
import eionet.eunis.dto.DesignationDcObjectDTO;
import eionet.eunis.dto.PairDTO;
import eionet.eunis.dto.ReferenceDTO;
import eionet.eunis.dto.readers.DcIndexDTOReader;
import eionet.eunis.dto.readers.ReferenceDTOReader;
import eionet.eunis.stripes.actions.ReferencesActionBean;
import eionet.eunis.util.CustomPaginatedList;
/**
* @author Risto Alt <a href="mailto:[email protected]">contact</a>
*/
public class ReferencesDaoImpl extends MySqlBaseDao implements IReferencesDao {
public ReferencesDaoImpl() {
}
/**
* @see eionet.eunis.dao.IReferencesDao#getReferences(int page, int defaltPageSize, String sort, String dir) {@inheritDoc}
*/
@Override
public CustomPaginatedList<ReferenceDTO> getReferences(int page, int defaltPageSize, String sort, String dir, String like) {
CustomPaginatedList<ReferenceDTO> ret = new CustomPaginatedList<ReferenceDTO>();
page = Math.max(page, 1);
int offset = (page - 1) * defaltPageSize;
String order = "";
if (sort != null) {
if (sort.equals("idRef")) {
order = "ID_DC";
} else if (sort.equals("refTitle")) {
order = "TITLE";
} else if (sort.equals("author")) {
order = "SOURCE";
} else if (sort.equals("refYear")) {
order = "CREATED";
}
}
if (order != null && order.length() > 0) {
if (dir == null || (!dir.equalsIgnoreCase("asc") && !dir.equalsIgnoreCase("desc"))) {
dir = "ASC";
}
order = order + " " + dir.toUpperCase();
}
String query = "SELECT ID_DC, TITLE, ALTERNATIVE, SOURCE, CREATED FROM DC_INDEX";
String trimmedLike = "";
boolean likeAdded = false;
if (like != null) {
trimmedLike = like.trim();
if (trimmedLike.length() > 0 && !trimmedLike.equalsIgnoreCase(ReferencesActionBean.DEFAULT_FILTER_VALUE)) {
query = query + " WHERE (TITLE LIKE ? OR SOURCE LIKE ?) ";
likeAdded = true;
}
}
if (order != null && order.length() > 0) {
query = query + " ORDER BY " + order;
}
query = query + (defaltPageSize > 0 ? " LIMIT " + (offset > 0 ? offset + "," : "") + defaltPageSize : "");
List<Object> values = new ArrayList<Object>();
if (likeAdded) {
values.add("%" + trimmedLike + "%");
values.add("%" + trimmedLike + "%");
}
ReferenceDTOReader rsReader = new ReferenceDTOReader();
try {
executeQuery(query, values, rsReader);
List<ReferenceDTO> docs = rsReader.getResultList();
int listSize = getReferencesCnt(like);
ret.setList(docs);
ret.setFullListSize(listSize);
ret.setObjectsPerPage(defaltPageSize);
if (page == 0) {
page = 1;
}
ret.setPageNumber(page);
ret.setSortCriterion(sort);
if (dir != null && dir.equals("asc")) {
ret.setSortDirection(SortOrderEnum.ASCENDING);
} else if (dir != null && dir.equals("desc")) {
ret.setSortDirection(SortOrderEnum.DESCENDING);
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
*
* @param like
* @return
*/
private int getReferencesCnt(String like) {
int ret = 0;
String trimmedLike = like == null ? StringUtils.EMPTY : like.trim();
String query = "SELECT COUNT(*) FROM DC_INDEX";
if (trimmedLike.length() > 0 && !trimmedLike.equalsIgnoreCase(ReferencesActionBean.DEFAULT_FILTER_VALUE)) {
query += " WHERE (TITLE LIKE ? OR SOURCE LIKE ?) ";
}
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement = con.prepareStatement(query);
if (trimmedLike.length() > 0 && !trimmedLike.equalsIgnoreCase(ReferencesActionBean.DEFAULT_FILTER_VALUE)) {
preparedStatement.setString(1, "%" + trimmedLike + "%");
preparedStatement.setString(2, "%" + trimmedLike + "%");
}
rs = preparedStatement.executeQuery();
while (rs.next()) {
ret = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* @see eionet.eunis.dao.IReferencesDao#getDcAttributes(java.lang.String) {@inheritDoc}
*/
@Override
public List<AttributeDto> getDcAttributes(String idDc) {
List<AttributeDto> ret = new ArrayList<AttributeDto>();
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement =
con.prepareStatement(
"SELECT " +
"a.NAME, b.LABEL, a.OBJECT, a.OBJECTLANG, a.TYPE " +
"from dc_attributes AS a " +
"LEFT OUTER JOIN dc_attribute_labels AS b ON a.NAME = b.NAME " +
"WHERE ID_DC = ?");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
//List<String> localReferenceIds = new ArrayList<String>();
while (rs.next()) {
String name = rs.getString("NAME");
String object = rs.getString("OBJECT");
String lang = rs.getString("OBJECTLANG");
String type = rs.getString("TYPE");
String label = rs.getString("LABEL");
if (label == null) {
label = name;
}
AttributeDto attr = new AttributeDto(name, type, object, lang, label);
ret.add(attr);
}
// Retrieving reference labels for objects of type "localref"
- preparedStatement =
- con.prepareStatement(
- "SELECT ID_DC, TITLE FROM DC_INDEX WHERE ID_DC IN (" +
- "SELECT OBJECT FROM dc_attributes WHERE type LIKE 'localref' AND ID_DC = ?)");
+ preparedStatement = con.prepareStatement(
+ "SELECT OBJECT AS ID_DC, COALESCE(TITLE, OBJECT) AS TITLE FROM DC_ATTRIBUTES"
+ + " LEFT JOIN DC_INDEX ON DC_INDEX.ID_DC=DC_ATTRIBUTES.OBJECT"
+ + " WHERE TYPE='localref' AND DC_ATTRIBUTES.ID_DC = ? ORDER BY TITLE");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
Map<String, String> localrefTitles = new HashMap<String, String>();
while (rs.next()) {
String id = rs.getString("ID_DC");
String title = rs.getString("TITLE");
localrefTitles.put(id, title);
}
// Connecting labels to localref attributes.
- for(int i=0; i < ret.size(); i++){
- if (ret.get(i).getType().equals("localref")){
+ for(int i = 0; i < ret.size(); i++) {
+ if (ret.get(i).getType().equals("localref")) {
ret.get(i).setObjectLabel(localrefTitles.get(ret.get(i).getValue()));
- if (ret.get(i).getObjectLabel() == null){
+ if (ret.get(i).getObjectLabel() == null) {
ret.get(i).setObjectLabel("references/"+ret.get(i).getValue());
}
} else {
String objectLabel = ret.get(i).getValue();
- if (objectLabel!= null && objectLabel.length() > 0){
- if (objectLabel.split("#").length > 1){
+ if (objectLabel != null && objectLabel.length() > 0) {
+ if (objectLabel.split("#").length > 1) {
String[] splitted = objectLabel.split("#");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
- } else if (objectLabel.split("/").length > 1){
+ } else if (objectLabel.split("/").length > 1) {
String[] splitted = objectLabel.split("/");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
} else {
ret.get(i).setObjectLabel(objectLabel);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return ret;
}
/**
* @see eionet.eunis.dao.IReferencesDao#getDcIndex(String id) {@inheritDoc}
*/
@Override
public DcIndexDTO getDcIndex(String id) {
DcIndexDTO object = null;
String query = "SELECT * FROM DC_INDEX WHERE ID_DC = ?";
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, id);
rs = preparedStatement.executeQuery();
while (rs.next()) {
object = new DcIndexDTO();
object.setIdDc(rs.getString("ID_DC"));
object.setComment(rs.getString("COMMENT"));
object.setRefCd(rs.getString("REFCD"));
object.setReference(rs.getString("REFERENCE"));
object.setSource(rs.getString("SOURCE"));
object.setEditor(rs.getString("EDITOR"));
object.setJournalTitle(rs.getString("JOURNAL_TITLE"));
object.setBookTitle(rs.getString("BOOK_TITLE"));
object.setJournalIssue(rs.getString("JOURNAL_ISSUE"));
object.setIsbn(rs.getString("ISBN"));
object.setUrl(rs.getString("URL"));
object.setCreated(rs.getString("CREATED"));
object.setTitle(rs.getString("TITLE"));
object.setAlternative(rs.getString("ALTERNATIVE"));
object.setPublisher(rs.getString("PUBLISHER"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return object;
}
/**
* @see eionet.eunis.dao.IReferencesDao#getDcObjects() {@inheritDoc}
*/
@Override
public List<DcIndexDTO> getDcObjects() {
List<DcIndexDTO> ret = new ArrayList<DcIndexDTO>();
String query = "SELECT * FROM DC_INDEX";
List<Object> values = new ArrayList<Object>();
DcIndexDTOReader rsReader = new DcIndexDTOReader();
try {
executeQuery(query, values, rsReader);
ret = rsReader.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
@Override
public Integer insertSource(String title, String source, String publisher, String editor, String url, String year)
throws Exception {
Integer ret = null;
if (source != null) {
int id_dc = getId("SELECT MAX(ID_DC) FROM DC_INDEX");
id_dc++;
ret = new Integer(id_dc);
String insertIndex =
"INSERT INTO dc_index (ID_DC, REFERENCE, COMMENT, REFCD, "
+ "TITLE, PUBLISHER, CREATED, SOURCE, EDITOR, URL) VALUES (?,-1,'RED_LIST',0,?,?,?,?,?,?)";
Connection con = null;
PreparedStatement psIndex = null;
try {
con = getConnection();
psIndex = con.prepareStatement(insertIndex);
psIndex.setInt(1, id_dc);
psIndex.setString(2, title);
psIndex.setString(3, publisher);
if (year != null && year.length() == 4) {
psIndex.setInt(4, new Integer(year).intValue());
} else {
psIndex.setInt(4, Types.NULL);
}
psIndex.setString(5, source);
psIndex.setString(6, editor);
psIndex.setString(7, url);
psIndex.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
psIndex.close();
}
}
return ret;
}
private int getId(String query) throws ParseException {
String maxId = ExecuteSQL(query);
int maxIdInt = 0;
if (maxId != null && maxId.length() > 0) {
maxIdInt = new Integer(maxId).intValue();
}
return maxIdInt;
}
@Override
public DesignationDcObjectDTO getDesignationDcObject(String idDesig, String idGeo) throws Exception {
DesignationDcObjectDTO ret = null;
String query =
"SELECT SOURCE, EDITOR, CREATED, TITLE, PUBLISHER " + "FROM CHM62EDT_DESIGNATIONS "
+ "INNER JOIN DC_INDEX ON (CHM62EDT_DESIGNATIONS.ID_DC = DC_INDEX.ID_DC) "
+ "WHERE CHM62EDT_DESIGNATIONS.ID_DESIGNATION = ? AND CHM62EDT_DESIGNATIONS.ID_GEOSCOPE = ?";
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, idDesig);
preparedStatement.setString(2, idGeo);
rs = preparedStatement.executeQuery();
while (rs.next()) {
ret = new DesignationDcObjectDTO();
ret.setAuthor(Utilities.formatString(Utilities.FormatDatabaseFieldName(rs.getString(1)), ""));
ret.setEditor(Utilities.formatString(Utilities.FormatDatabaseFieldName(rs.getString(2)), ""));
ret.setDate(Utilities.formatString(Utilities.formatReferencesDate(rs.getDate(3)), ""));
ret.setTitle(Utilities.formatString(Utilities.FormatDatabaseFieldName(rs.getString(4)), ""));
ret.setPublisher(Utilities.formatString(Utilities.FormatDatabaseFieldName(rs.getString(5)), ""));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return ret;
}
@Override
public List<PairDTO> getRedListSources() throws Exception {
List<PairDTO> ret = new ArrayList<PairDTO>();
String query =
"SELECT I.ID_DC, I.SOURCE, I.TITLE " + "FROM chm62edt_reports AS R, chm62edt_report_type AS T, DC_INDEX AS I "
+ "WHERE R.ID_REPORT_TYPE = T.ID_REPORT_TYPE AND T.LOOKUP_TYPE = 'CONSERVATION_STATUS' "
+ "AND R.ID_DC = I.ID_DC GROUP BY R.ID_DC ORDER BY I.TITLE";
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement = con.prepareStatement(query);
rs = preparedStatement.executeQuery();
while (rs.next()) {
String idDc = rs.getString("ID_DC");
String title = rs.getString("TITLE");
String source = rs.getString("SOURCE");
String heading = EunisUtil.threeDots(title, 50) + " (" + source + ")";
PairDTO pair = new PairDTO();
pair.setKey(idDc);
pair.setValue(heading);
ret.add(pair);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return ret;
}
}
| false | true | public List<AttributeDto> getDcAttributes(String idDc) {
List<AttributeDto> ret = new ArrayList<AttributeDto>();
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement =
con.prepareStatement(
"SELECT " +
"a.NAME, b.LABEL, a.OBJECT, a.OBJECTLANG, a.TYPE " +
"from dc_attributes AS a " +
"LEFT OUTER JOIN dc_attribute_labels AS b ON a.NAME = b.NAME " +
"WHERE ID_DC = ?");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
//List<String> localReferenceIds = new ArrayList<String>();
while (rs.next()) {
String name = rs.getString("NAME");
String object = rs.getString("OBJECT");
String lang = rs.getString("OBJECTLANG");
String type = rs.getString("TYPE");
String label = rs.getString("LABEL");
if (label == null) {
label = name;
}
AttributeDto attr = new AttributeDto(name, type, object, lang, label);
ret.add(attr);
}
// Retrieving reference labels for objects of type "localref"
preparedStatement =
con.prepareStatement(
"SELECT ID_DC, TITLE FROM DC_INDEX WHERE ID_DC IN (" +
"SELECT OBJECT FROM dc_attributes WHERE type LIKE 'localref' AND ID_DC = ?)");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
Map<String, String> localrefTitles = new HashMap<String, String>();
while (rs.next()) {
String id = rs.getString("ID_DC");
String title = rs.getString("TITLE");
localrefTitles.put(id, title);
}
// Connecting labels to localref attributes.
for(int i=0; i < ret.size(); i++){
if (ret.get(i).getType().equals("localref")){
ret.get(i).setObjectLabel(localrefTitles.get(ret.get(i).getValue()));
if (ret.get(i).getObjectLabel() == null){
ret.get(i).setObjectLabel("references/"+ret.get(i).getValue());
}
} else {
String objectLabel = ret.get(i).getValue();
if (objectLabel!= null && objectLabel.length() > 0){
if (objectLabel.split("#").length > 1){
String[] splitted = objectLabel.split("#");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
} else if (objectLabel.split("/").length > 1){
String[] splitted = objectLabel.split("/");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
} else {
ret.get(i).setObjectLabel(objectLabel);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return ret;
}
| public List<AttributeDto> getDcAttributes(String idDc) {
List<AttributeDto> ret = new ArrayList<AttributeDto>();
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
try {
con = getConnection();
preparedStatement =
con.prepareStatement(
"SELECT " +
"a.NAME, b.LABEL, a.OBJECT, a.OBJECTLANG, a.TYPE " +
"from dc_attributes AS a " +
"LEFT OUTER JOIN dc_attribute_labels AS b ON a.NAME = b.NAME " +
"WHERE ID_DC = ?");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
//List<String> localReferenceIds = new ArrayList<String>();
while (rs.next()) {
String name = rs.getString("NAME");
String object = rs.getString("OBJECT");
String lang = rs.getString("OBJECTLANG");
String type = rs.getString("TYPE");
String label = rs.getString("LABEL");
if (label == null) {
label = name;
}
AttributeDto attr = new AttributeDto(name, type, object, lang, label);
ret.add(attr);
}
// Retrieving reference labels for objects of type "localref"
preparedStatement = con.prepareStatement(
"SELECT OBJECT AS ID_DC, COALESCE(TITLE, OBJECT) AS TITLE FROM DC_ATTRIBUTES"
+ " LEFT JOIN DC_INDEX ON DC_INDEX.ID_DC=DC_ATTRIBUTES.OBJECT"
+ " WHERE TYPE='localref' AND DC_ATTRIBUTES.ID_DC = ? ORDER BY TITLE");
preparedStatement.setString(1, idDc);
rs = preparedStatement.executeQuery();
Map<String, String> localrefTitles = new HashMap<String, String>();
while (rs.next()) {
String id = rs.getString("ID_DC");
String title = rs.getString("TITLE");
localrefTitles.put(id, title);
}
// Connecting labels to localref attributes.
for(int i = 0; i < ret.size(); i++) {
if (ret.get(i).getType().equals("localref")) {
ret.get(i).setObjectLabel(localrefTitles.get(ret.get(i).getValue()));
if (ret.get(i).getObjectLabel() == null) {
ret.get(i).setObjectLabel("references/"+ret.get(i).getValue());
}
} else {
String objectLabel = ret.get(i).getValue();
if (objectLabel != null && objectLabel.length() > 0) {
if (objectLabel.split("#").length > 1) {
String[] splitted = objectLabel.split("#");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
} else if (objectLabel.split("/").length > 1) {
String[] splitted = objectLabel.split("/");
ret.get(i).setObjectLabel(splitted[splitted.length - 1]);
} else {
ret.get(i).setObjectLabel(objectLabel);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAllResources(con, preparedStatement, rs);
}
return ret;
}
|
diff --git a/src/net/sf/gogui/xml/XmlWriter.java b/src/net/sf/gogui/xml/XmlWriter.java
index e3a3f663..c3f477d5 100644
--- a/src/net/sf/gogui/xml/XmlWriter.java
+++ b/src/net/sf/gogui/xml/XmlWriter.java
@@ -1,279 +1,280 @@
//----------------------------------------------------------------------------
// XmlWriter.java
//----------------------------------------------------------------------------
package net.sf.gogui.xml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.EnumSet;
import java.util.Map;
import net.sf.gogui.game.ConstGameInfo;
import net.sf.gogui.game.ConstGameTree;
import net.sf.gogui.game.ConstNode;
import net.sf.gogui.game.ConstSgfProperties;
import net.sf.gogui.game.NodeUtil;
import net.sf.gogui.game.MarkType;
import net.sf.gogui.game.StringInfo;
import net.sf.gogui.game.StringInfoColor;
import net.sf.gogui.go.GoColor;
import static net.sf.gogui.go.GoColor.BLACK;
import static net.sf.gogui.go.GoColor.EMPTY;
import static net.sf.gogui.go.GoColor.WHITE;
import net.sf.gogui.go.ConstPointList;
import net.sf.gogui.go.GoPoint;
import net.sf.gogui.go.Move;
import net.sf.gogui.util.HtmlUtil;
/** Write a game or board position in XML style to a stream.
This class uses Jago's XML format, see http://www.rene-grothmann.de/jago
*/
public class XmlWriter
{
/** Construct writer and write tree. */
public XmlWriter(OutputStream out, ConstGameTree tree, String application)
{
try
{
m_out = new PrintStream(out, false, "UTF-8");
m_out.print("<?xml version='1.0' encoding='utf-8'?>\n");
}
catch (UnsupportedEncodingException e)
{
// Every Java implementation is required to support UTF-8
assert false;
m_out = new PrintStream(out, false);
m_out.print("<?xml version='1.0'?>\n");
}
ConstNode root = tree.getRootConst();
ConstGameInfo info = tree.getGameInfoConst(root);
m_out.print("<!DOCTYPE Go SYSTEM \"go.dtd\">\n" +
"<Go xmlns='http://www.rene-grothmann.de/jago'>\n" +
"<GoGame>\n");
m_boardSize = tree.getBoardSize();
printGameInfo(application, info);
m_out.print("<Nodes>\n");
printNode(root, true);
m_out.print("</Nodes>\n" +
"</GoGame>\n" +
"</Go>\n");
m_out.close();
}
private int m_boardSize;
private PrintStream m_out;
private String getSgfPoint(GoPoint p)
{
if (p == null)
return "";
int x = 'a' + p.getX();
int y = 'a' + (m_boardSize - p.getY() - 1);
return "" + (char)x + (char)y;
}
private void printComment(String comment)
{
if (comment == null)
return;
BufferedReader reader = new BufferedReader(new StringReader(comment));
m_out.print("<Comment>\n");
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
if (line.trim().equals(""))
continue;
m_out.print("<P>");
m_out.print(HtmlUtil.escape(line));
m_out.print("</P>\n");
}
}
catch (IOException e)
{
assert(false);
}
m_out.print("</Comment>\n");
}
private void printGameInfo(String application, ConstGameInfo info)
{
m_out.print("<Information>\n" +
"<Application>" + application + "</Application>\n" +
"<BoardSize>" + m_boardSize + "</BoardSize>\n");
printInfo("WhitePlayer", info.get(StringInfoColor.NAME, WHITE));
printInfo("BlackPlayer", info.get(StringInfoColor.NAME, BLACK));
printInfo("WhiteRank", info.get(StringInfoColor.RANK, WHITE));
printInfo("BlackRank", info.get(StringInfoColor.RANK, BLACK));
printInfo("Date", info.get(StringInfo.DATE));
printInfo("Rules", info.get(StringInfo.RULES));
if (info.getHandicap() > 0)
printInfo("Handicap", Integer.toString(info.getHandicap()));
if (info.getKomi() != null)
printInfo("Komi", info.getKomi().toString());
if (info.getTimeSettings() != null)
printInfo("Time", info.getTimeSettings().toString());
printInfo("Result", info.get(StringInfo.RESULT));
printInfo("WhiteTeam", info.get(StringInfoColor.TEAM, WHITE));
printInfo("BlackTeam", info.get(StringInfoColor.TEAM, BLACK));
printInfo("User", info.get(StringInfo.USER));
printInfo("Copyright", info.get(StringInfo.COPYRIGHT));
printInfo("Annotation", info.get(StringInfo.ANNOTATION));
printInfo("Source", info.get(StringInfo.SOURCE));
printInfo("Round", info.get(StringInfo.ROUND));
m_out.print("</Information>\n");
}
private void printInfo(String tag, String value)
{
if (value == null)
return;
m_out.print("<" + tag + ">" + value + "</" + tag + ">\n");
}
private void printMarkup(ConstNode node)
{
printMarkup(node, MarkType.MARK, "");
printMarkup(node, MarkType.CIRCLE, " type=\"circle\"");
printMarkup(node, MarkType.SQUARE, " type=\"square\"");
printMarkup(node, MarkType.TRIANGLE, " type=\"triangle\"");
printMarkup(node, MarkType.TERRITORY_BLACK, " territory=\"black\"");
printMarkup(node, MarkType.TERRITORY_WHITE, " territory=\"white\"");
ConstPointList pointList = node.getMarkedConst(MarkType.SELECT);
if (pointList != null)
// There is no type select in the Mark element -> use SGF/SL
for (GoPoint p : pointList)
m_out.print("<SGF type=\"SL\"><Arg>" + getSgfPoint(p)
+ "</Arg></SGF>\n");
Map<GoPoint,String> labels = node.getLabelsUnmodifiable();
if (labels != null)
for (Map.Entry<GoPoint,String> e : labels.entrySet())
m_out.print("<Mark at=\"" + e.getKey() + "\" label=\""
+ e.getValue() + "\"/>\n");
}
private void printMarkup(ConstNode node, MarkType type, String attributes)
{
ConstPointList pointList = node.getMarkedConst(type);
if (pointList == null)
return;
for (GoPoint p : pointList)
m_out.print("<Mark at=\"" + p + "\"" + attributes + "/>\n");
}
private void printMove(ConstNode node)
{
Move move = node.getMove();
if (move == null)
return;
GoPoint p = move.getPoint();
String at = (p == null ? "" : p.toString());
GoColor c = move.getColor();
int number = NodeUtil.getMoveNumber(node);
String timeLeftAtt = "";
double timeLeft = node.getTimeLeft(c);
if (! Double.isNaN(timeLeft))
timeLeftAtt = " timeleft=\"" + timeLeft + "\"";
if (c == BLACK)
m_out.print("<Black number=\"" + number + "\" at=\"" + at
+ "\"" + timeLeftAtt + "/>\n");
else if (c == WHITE)
m_out.print("<White number=\"" + number + "\" at=\"" + at
+ "\"" + timeLeftAtt + "/>\n");
int movesLeft = node.getMovesLeft(c);
// There is no movesleft attribute in Black/White -> use SGF/OW,OB
if (movesLeft >= 0)
{
if (c == BLACK)
m_out.print("<SGF type=\"OB\"><Arg>" + movesLeft
+ "</Arg></SGF>\n");
else if (c == WHITE)
m_out.print("<SGF type=\"OW\"><Arg>" + movesLeft
+ "</Arg></SGF>\n");
}
}
private void printNode(ConstNode node, boolean isRoot)
{
// TODO: Save game information as SGF, if game information for
// this node is not stored in the root node
Move move = node.getMove();
String comment = node.getComment();
ConstSgfProperties sgfProperties = node.getSgfPropertiesConst();
Map<GoPoint,String> labels = node.getLabelsUnmodifiable();
boolean hasMarkup = (labels != null && ! labels.isEmpty());
if (! hasMarkup)
for (MarkType type : EnumSet.allOf(MarkType.class))
{
ConstPointList pointList = node.getMarkedConst(type);
if (pointList != null && ! node.getMarkedConst(type).isEmpty())
{
hasMarkup = true;
break;
}
}
boolean hasSetup = node.hasSetup();
// Moves left are currently written as SGF element, which needs a Node
boolean hasMovesLeft =
(move != null && node.getMovesLeft(move.getColor()) != -1);
boolean needsNode = (move == null || sgfProperties != null || hasSetup
- || hasMarkup || hasMovesLeft);
- boolean isEmptyRoot = (isRoot && ! node.isEmpty());
+ || hasMarkup || hasMovesLeft
+ || (move == null && comment != null));
+ boolean isEmptyRoot = (isRoot && node.isEmpty());
if (needsNode && ! isEmptyRoot)
m_out.print("<Node>\n");
printMove(node);
printSetup(node);
printMarkup(node);
printComment(comment);
printSgfProperties(node);
if (needsNode && ! isEmptyRoot)
m_out.print("</Node>\n");
ConstNode father = node.getFatherConst();
if (father != null && father.getChildConst() == node)
{
int numberChildren = father.getNumberChildren();
for (int i = 1; i < numberChildren; ++i)
{
m_out.print("<Variation>\n");
printNode(father.getChildConst(i), false);
m_out.print("</Variation>\n");
}
}
ConstNode child = node.getChildConst();
if (child != null)
printNode(child, false);
}
private void printSgfProperties(ConstNode node)
{
ConstSgfProperties sgfProperties = node.getSgfPropertiesConst();
if (sgfProperties == null)
return;
for (String key : sgfProperties.getKeys())
{
m_out.print("<SGF type=\"" + key + "\">");
int numberValues = sgfProperties.getNumberValues(key);
for (int i = 0; i < numberValues; ++i)
m_out.print("<Arg>" +
HtmlUtil.escape(sgfProperties.getValue(key, i))
+ "</Arg>");
m_out.print("</SGF>\n");
}
}
private void printSetup(ConstNode node)
{
for (GoPoint p : node.getSetup(BLACK))
m_out.print("<AddBlack at=\"" + p + "\"/>\n");
for (GoPoint p : node.getSetup(WHITE))
m_out.print("<AddWhite at=\"" + p + "\"/>\n");
for (GoPoint p : node.getSetup(EMPTY))
m_out.print("<Delete at=\"" + p + "\"/>\n");
}
}
| true | true | private void printNode(ConstNode node, boolean isRoot)
{
// TODO: Save game information as SGF, if game information for
// this node is not stored in the root node
Move move = node.getMove();
String comment = node.getComment();
ConstSgfProperties sgfProperties = node.getSgfPropertiesConst();
Map<GoPoint,String> labels = node.getLabelsUnmodifiable();
boolean hasMarkup = (labels != null && ! labels.isEmpty());
if (! hasMarkup)
for (MarkType type : EnumSet.allOf(MarkType.class))
{
ConstPointList pointList = node.getMarkedConst(type);
if (pointList != null && ! node.getMarkedConst(type).isEmpty())
{
hasMarkup = true;
break;
}
}
boolean hasSetup = node.hasSetup();
// Moves left are currently written as SGF element, which needs a Node
boolean hasMovesLeft =
(move != null && node.getMovesLeft(move.getColor()) != -1);
boolean needsNode = (move == null || sgfProperties != null || hasSetup
|| hasMarkup || hasMovesLeft);
boolean isEmptyRoot = (isRoot && ! node.isEmpty());
if (needsNode && ! isEmptyRoot)
m_out.print("<Node>\n");
printMove(node);
printSetup(node);
printMarkup(node);
printComment(comment);
printSgfProperties(node);
if (needsNode && ! isEmptyRoot)
m_out.print("</Node>\n");
ConstNode father = node.getFatherConst();
if (father != null && father.getChildConst() == node)
{
int numberChildren = father.getNumberChildren();
for (int i = 1; i < numberChildren; ++i)
{
m_out.print("<Variation>\n");
printNode(father.getChildConst(i), false);
m_out.print("</Variation>\n");
}
}
ConstNode child = node.getChildConst();
if (child != null)
printNode(child, false);
}
| private void printNode(ConstNode node, boolean isRoot)
{
// TODO: Save game information as SGF, if game information for
// this node is not stored in the root node
Move move = node.getMove();
String comment = node.getComment();
ConstSgfProperties sgfProperties = node.getSgfPropertiesConst();
Map<GoPoint,String> labels = node.getLabelsUnmodifiable();
boolean hasMarkup = (labels != null && ! labels.isEmpty());
if (! hasMarkup)
for (MarkType type : EnumSet.allOf(MarkType.class))
{
ConstPointList pointList = node.getMarkedConst(type);
if (pointList != null && ! node.getMarkedConst(type).isEmpty())
{
hasMarkup = true;
break;
}
}
boolean hasSetup = node.hasSetup();
// Moves left are currently written as SGF element, which needs a Node
boolean hasMovesLeft =
(move != null && node.getMovesLeft(move.getColor()) != -1);
boolean needsNode = (move == null || sgfProperties != null || hasSetup
|| hasMarkup || hasMovesLeft
|| (move == null && comment != null));
boolean isEmptyRoot = (isRoot && node.isEmpty());
if (needsNode && ! isEmptyRoot)
m_out.print("<Node>\n");
printMove(node);
printSetup(node);
printMarkup(node);
printComment(comment);
printSgfProperties(node);
if (needsNode && ! isEmptyRoot)
m_out.print("</Node>\n");
ConstNode father = node.getFatherConst();
if (father != null && father.getChildConst() == node)
{
int numberChildren = father.getNumberChildren();
for (int i = 1; i < numberChildren; ++i)
{
m_out.print("<Variation>\n");
printNode(father.getChildConst(i), false);
m_out.print("</Variation>\n");
}
}
ConstNode child = node.getChildConst();
if (child != null)
printNode(child, false);
}
|
diff --git a/src/main/java/com/github/notyy/testing/priceCalculatorWithDI/PriceCalculator.java b/src/main/java/com/github/notyy/testing/priceCalculatorWithDI/PriceCalculator.java
index f3fb34c..94db786 100644
--- a/src/main/java/com/github/notyy/testing/priceCalculatorWithDI/PriceCalculator.java
+++ b/src/main/java/com/github/notyy/testing/priceCalculatorWithDI/PriceCalculator.java
@@ -1,28 +1,28 @@
package com.github.notyy.testing.priceCalculatorWithDI;
import com.github.notyy.testing.common.DiscountDAO;
import com.github.notyy.testing.common.MessageSender;
public class PriceCalculator {
private DiscountDAO discountDAO;
private MessageSender messageSender;
public PriceCalculator(DiscountDAO discountDAO, MessageSender messageSender) {
this.discountDAO = discountDAO;
this.messageSender = messageSender;
}
public double getPrice(int quantity, double itemPrice) {
double basePrice = quantity * itemPrice;
- if(basePrice < 100) {
+ if(quantity < 100) {
throw new IllegalArgumentException("quantity must be >= 100");
}
double discountFactor = discountDAO.findDiscount(basePrice);
double resultPrice = basePrice * discountFactor;
messageSender.send("resultPrice:"+resultPrice);
return resultPrice;
}
}
| true | true | public double getPrice(int quantity, double itemPrice) {
double basePrice = quantity * itemPrice;
if(basePrice < 100) {
throw new IllegalArgumentException("quantity must be >= 100");
}
double discountFactor = discountDAO.findDiscount(basePrice);
double resultPrice = basePrice * discountFactor;
messageSender.send("resultPrice:"+resultPrice);
return resultPrice;
}
| public double getPrice(int quantity, double itemPrice) {
double basePrice = quantity * itemPrice;
if(quantity < 100) {
throw new IllegalArgumentException("quantity must be >= 100");
}
double discountFactor = discountDAO.findDiscount(basePrice);
double resultPrice = basePrice * discountFactor;
messageSender.send("resultPrice:"+resultPrice);
return resultPrice;
}
|
diff --git a/stax-mate/src/main/java/com/cedarsoft/serialization/stax/mate/CollectionSerializer.java b/stax-mate/src/main/java/com/cedarsoft/serialization/stax/mate/CollectionSerializer.java
index fda67e44..cbf0a051 100644
--- a/stax-mate/src/main/java/com/cedarsoft/serialization/stax/mate/CollectionSerializer.java
+++ b/stax-mate/src/main/java/com/cedarsoft/serialization/stax/mate/CollectionSerializer.java
@@ -1,80 +1,80 @@
/**
* Copyright (C) cedarsoft GmbH.
*
* Licensed under the GNU General Public License version 3 (the "License")
* with Classpath Exception; you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.cedarsoft.org/gpl3ce
* (GPL 3 with Classpath Exception)
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3 only, as
* published by the Free Software Foundation. cedarsoft GmbH designates this
* particular file as subject to the "Classpath" exception as provided
* by cedarsoft GmbH in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 3 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
* or visit www.cedarsoft.com if you need additional information or
* have any questions.
*/
package com.cedarsoft.serialization.stax.mate;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nonnull;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.staxmate.out.SMOutputElement;
import com.cedarsoft.version.Version;
import com.cedarsoft.version.VersionException;
import com.cedarsoft.version.VersionRange;
/**
* @author Johannes Schneider (<a href="mailto:[email protected]">[email protected]</a>)
* @param T the type of the elements that are serialized
*/
public class CollectionSerializer<T> extends AbstractStaxMateSerializer<List<? extends T>> {
@Nonnull
private final Class<T> type;
protected CollectionSerializer(@Nonnull Class<T> type, @Nonnull AbstractStaxMateSerializer<T> serializer) {
this(type, serializer, serializer.getDefaultElementName() + "s", serializer.getNameSpaceBase() + "s", serializer.getFormatVersionRange());
}
public CollectionSerializer(@Nonnull Class<T> type, @Nonnull AbstractStaxMateSerializer<T> serializer, @Nonnull String defaultElementName, @Nonnull String nameSpaceUriBase, @Nonnull VersionRange formatVersionRange) {
super(defaultElementName, nameSpaceUriBase, formatVersionRange);
this.type = type;
- add(serializer).responsibleFor(type).map(formatVersionRange.getMax()).toDelegateVersion(serializer.getFormatVersion());
+ add(serializer).responsibleFor(type).map(formatVersionRange).toDelegateVersion(serializer.getFormatVersion());
assert getDelegatesMappings().verify();
}
@Override
public void serialize(@Nonnull SMOutputElement serializeTo, @Nonnull List<? extends T> object, @Nonnull Version formatVersion) throws IOException, VersionException, XMLStreamException {
verifyVersionWritable(formatVersion);
serializeCollection(object, type, serializeTo, formatVersion);
}
@Nonnull
@Override
public List<? extends T> deserialize(@Nonnull XMLStreamReader deserializeFrom, @Nonnull Version formatVersion) throws IOException, VersionException, XMLStreamException {
verifyVersionReadable(formatVersion);
return deserializeCollection(deserializeFrom, type, formatVersion);
}
}
| true | true | public CollectionSerializer(@Nonnull Class<T> type, @Nonnull AbstractStaxMateSerializer<T> serializer, @Nonnull String defaultElementName, @Nonnull String nameSpaceUriBase, @Nonnull VersionRange formatVersionRange) {
super(defaultElementName, nameSpaceUriBase, formatVersionRange);
this.type = type;
add(serializer).responsibleFor(type).map(formatVersionRange.getMax()).toDelegateVersion(serializer.getFormatVersion());
assert getDelegatesMappings().verify();
}
| public CollectionSerializer(@Nonnull Class<T> type, @Nonnull AbstractStaxMateSerializer<T> serializer, @Nonnull String defaultElementName, @Nonnull String nameSpaceUriBase, @Nonnull VersionRange formatVersionRange) {
super(defaultElementName, nameSpaceUriBase, formatVersionRange);
this.type = type;
add(serializer).responsibleFor(type).map(formatVersionRange).toDelegateVersion(serializer.getFormatVersion());
assert getDelegatesMappings().verify();
}
|
diff --git a/javanet/gnu/cajo/utils/extra/Queue.java b/javanet/gnu/cajo/utils/extra/Queue.java
index dde199f3..41e9110c 100644
--- a/javanet/gnu/cajo/utils/extra/Queue.java
+++ b/javanet/gnu/cajo/utils/extra/Queue.java
@@ -1,104 +1,105 @@
package gnu.cajo.utils.extra;
import java.util.LinkedList;
import gnu.cajo.invoke.Remote;
/*
* cajo asynchronous object method invocation queue
* Copyright (C) 2006 John Catherino
* The cajo project: https://cajo.dev.java.net
*
* For issues or suggestions mailto:[email protected]
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, at version 2.1 of the license, or any
* later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You can receive a copy of the GNU Lesser General Public License from their
* website, http://fsf.org/licenses/lgpl.html; or via snail mail, Free
* Software Foundation Inc., 51 Franklin Street, Boston MA 02111-1301, USA
*/
/**
* This class is a cajo-based implementation of the message based
* communication paradigm. By virtue of returning successfully, a client can
* be certain its invocation has been enqueued, and will be invoked on the
* wrapped object. The client can be either local, or remote, the operation
* is completely asynchronous.<p>
* A client enqueues its invocations for the server item, by invoking the
* corresponding method on its reference to an instance of this object. Its
* argument(s), if any, will be invoked on the matching method of the server
* item, in a separate thread. This creates a dynamic buffer of invocations.
* <p><i><u>Note</u>:</i> the wrapped item can be a remote object reference.
* This can allow one or more separate JVMs, to perform the invocation
* enqueue process.
*
* @version 1.0, 25-Jun-06
* @author John Catherino
*/
public final class Queue implements gnu.cajo.invoke.Invoke {
private LinkedList list;
/**
* This is the thread performing the dequeue operation, and invoking
* the corresponding method on the wrapped object. It is instantiated
* dynamically, upon the first enqueue invocation. If the local JVM wishes
* to terminate the operation of this queue, it can invoke interrupt() on
* this field.
*/
public Thread thread;
/**
* This is the object for which invocation queueing is being performed.
* It can be local to this JVM, or remote.
*/
public final Object object;
/**
* The constructor simply assigns the provided object reference for
* queued method invocation.
* @param object The object reference to be wrapped, local or remote.
*/
public Queue(Object object) { this.object = object; }
/**
* This is the method a client, local or remote, would invoke, to be
* performed in a message-based fashion.
* @param method The public method name on the wrapped object to be
* invoked.
* @param args The argument(s) to invoke on the wrapped item's method.
* It can be a single object, and Object array of arguments, or null.
* presumably, the wrapped object has a matching public method signature.
* @return Boolean.TRUE Indicating the enqueue operation was successful.
* Since the operation is performed asynchronously, there can be
* no synchronous return data. A callback object reference can be provided
* as an argument, if result data is required. When no arguments are
* provided, the operation is essentially a semaphore.
* @throws java.rmi.RemoteException If the invocation failed to enqueue,
* due to a network related error.
*/
public synchronized Object invoke(String method, Object args) {
if (list == null) {
list = new LinkedList();
thread = new Thread(new Runnable() {
public void run() {
try {
- while (list.size() == 0)
- synchronized(Queue.this) { Queue.this.wait(); }
+ synchronized(Queue.this) {
+ while (list.size() == 0) Queue.this.wait();
+ }
String method = (String)list.removeFirst();
Object args = list.removeFirst();
Remote.invoke(object, method, args);
} catch(InterruptedException x) { return; }
catch(Exception x) { x.printStackTrace(); }
}
});
thread.start();
}
list.add(method);
list.add(args);
notify();
return Boolean.TRUE;
}
}
| true | true | public synchronized Object invoke(String method, Object args) {
if (list == null) {
list = new LinkedList();
thread = new Thread(new Runnable() {
public void run() {
try {
while (list.size() == 0)
synchronized(Queue.this) { Queue.this.wait(); }
String method = (String)list.removeFirst();
Object args = list.removeFirst();
Remote.invoke(object, method, args);
} catch(InterruptedException x) { return; }
catch(Exception x) { x.printStackTrace(); }
}
});
thread.start();
}
list.add(method);
list.add(args);
notify();
return Boolean.TRUE;
}
| public synchronized Object invoke(String method, Object args) {
if (list == null) {
list = new LinkedList();
thread = new Thread(new Runnable() {
public void run() {
try {
synchronized(Queue.this) {
while (list.size() == 0) Queue.this.wait();
}
String method = (String)list.removeFirst();
Object args = list.removeFirst();
Remote.invoke(object, method, args);
} catch(InterruptedException x) { return; }
catch(Exception x) { x.printStackTrace(); }
}
});
thread.start();
}
list.add(method);
list.add(args);
notify();
return Boolean.TRUE;
}
|
diff --git a/src/com/java/gwt/libertycinema/client/LibertyCinema.java b/src/com/java/gwt/libertycinema/client/LibertyCinema.java
index 2391663..d3e81f4 100644
--- a/src/com/java/gwt/libertycinema/client/LibertyCinema.java
+++ b/src/com/java/gwt/libertycinema/client/LibertyCinema.java
@@ -1,34 +1,34 @@
package com.java.gwt.libertycinema.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.java.gwt.libertycinema.client.BodyPanel;
public class LibertyCinema implements EntryPoint {
private DockLayoutPanel main = new DockLayoutPanel(Unit.EM);
private BodyPanel body = new BodyPanel();
private FooterBar footer;
private TopNavBar header;
public void onModuleLoad() {
- // Setup Topbar
- header = new TopNavBar(body);
- main.addNorth(header.getTopBarPanel(), 7);
+ // Setup Topbar
+ header = new TopNavBar(body);
+ main.addNorth(header.getTopBarPanel(), 7);
- // Setup footer
- footer = new FooterBar(body);
- main.addSouth(footer.getFooterPanel(), 2);
+ // Setup footer
+ footer = new FooterBar(body);
+ main.addSouth(footer.getFooterPanel(), 2);
- // Setup main
- main.add(body);
+ // Setup main
+ main.add(body);
- RootLayoutPanel.get().add(main);
+ RootLayoutPanel.get().add(main);
}
}
| false | true | public void onModuleLoad() {
// Setup Topbar
header = new TopNavBar(body);
main.addNorth(header.getTopBarPanel(), 7);
// Setup footer
footer = new FooterBar(body);
main.addSouth(footer.getFooterPanel(), 2);
// Setup main
main.add(body);
RootLayoutPanel.get().add(main);
}
| public void onModuleLoad() {
// Setup Topbar
header = new TopNavBar(body);
main.addNorth(header.getTopBarPanel(), 7);
// Setup footer
footer = new FooterBar(body);
main.addSouth(footer.getFooterPanel(), 2);
// Setup main
main.add(body);
RootLayoutPanel.get().add(main);
}
|
diff --git a/src/powercrystals/minefactoryreloaded/setup/BehaviorDispenseSafariNet.java b/src/powercrystals/minefactoryreloaded/setup/BehaviorDispenseSafariNet.java
index 2f750f6e..d486f5bf 100644
--- a/src/powercrystals/minefactoryreloaded/setup/BehaviorDispenseSafariNet.java
+++ b/src/powercrystals/minefactoryreloaded/setup/BehaviorDispenseSafariNet.java
@@ -1,33 +1,33 @@
package powercrystals.minefactoryreloaded.setup;
import powercrystals.minefactoryreloaded.entity.EntitySafariNet;
import net.minecraft.block.BlockDispenser;
import net.minecraft.dispenser.BehaviorDefaultDispenseItem;
import net.minecraft.dispenser.IBlockSource;
import net.minecraft.dispenser.IPosition;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public class BehaviorDispenseSafariNet extends BehaviorDefaultDispenseItem
{
@Override
public ItemStack dispenseStack(IBlockSource dispenser, ItemStack stack)
{
World world = dispenser.getWorld();
IPosition dispenserPos = BlockDispenser.getIPositionFromBlockSource(dispenser);
- EnumFacing dispenserFacing = EnumFacing.getFront(dispenser.getBlockMetadata());
- EntitySafariNet proj = new EntitySafariNet(world, dispenserPos.getX(), dispenserPos.getY(), dispenserPos.getZ(), stack);
- proj.setThrowableHeading((double)dispenserFacing.getFrontOffsetX(), 0.10000000149011612D, (double)dispenserFacing.getFrontOffsetZ(), 1.1F, 6.0F);
+ EnumFacing dispenserFacing = BlockDispenser.getFacing(dispenser.getBlockMetadata());
+ EntitySafariNet proj = new EntitySafariNet(world, dispenserPos.getX(), dispenserPos.getY(), dispenserPos.getZ(), stack.copy());
+ proj.setThrowableHeading(dispenserFacing.getFrontOffsetX(), dispenserFacing.getFrontOffsetY() + 0.1, dispenserFacing.getFrontOffsetZ(), 1.1F, 6.0F);
world.spawnEntityInWorld((Entity)proj);
stack.splitStack(1);
return stack;
}
@Override
protected void playDispenseSound(IBlockSource dispenser)
{
dispenser.getWorld().playAuxSFX(1002, dispenser.getXInt(), dispenser.getYInt(), dispenser.getZInt(), 0);
}
}
| true | true | public ItemStack dispenseStack(IBlockSource dispenser, ItemStack stack)
{
World world = dispenser.getWorld();
IPosition dispenserPos = BlockDispenser.getIPositionFromBlockSource(dispenser);
EnumFacing dispenserFacing = EnumFacing.getFront(dispenser.getBlockMetadata());
EntitySafariNet proj = new EntitySafariNet(world, dispenserPos.getX(), dispenserPos.getY(), dispenserPos.getZ(), stack);
proj.setThrowableHeading((double)dispenserFacing.getFrontOffsetX(), 0.10000000149011612D, (double)dispenserFacing.getFrontOffsetZ(), 1.1F, 6.0F);
world.spawnEntityInWorld((Entity)proj);
stack.splitStack(1);
return stack;
}
| public ItemStack dispenseStack(IBlockSource dispenser, ItemStack stack)
{
World world = dispenser.getWorld();
IPosition dispenserPos = BlockDispenser.getIPositionFromBlockSource(dispenser);
EnumFacing dispenserFacing = BlockDispenser.getFacing(dispenser.getBlockMetadata());
EntitySafariNet proj = new EntitySafariNet(world, dispenserPos.getX(), dispenserPos.getY(), dispenserPos.getZ(), stack.copy());
proj.setThrowableHeading(dispenserFacing.getFrontOffsetX(), dispenserFacing.getFrontOffsetY() + 0.1, dispenserFacing.getFrontOffsetZ(), 1.1F, 6.0F);
world.spawnEntityInWorld((Entity)proj);
stack.splitStack(1);
return stack;
}
|
diff --git a/src/org/jactiveresource/ActiveResource.java b/src/org/jactiveresource/ActiveResource.java
index bf0883c..ba0734e 100644
--- a/src/org/jactiveresource/ActiveResource.java
+++ b/src/org/jactiveresource/ActiveResource.java
@@ -1,291 +1,292 @@
/*
Copyright (c) 2008, Jared Crapo All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of jactiveresource.org nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.jactiveresource;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.HttpException;
import org.jactiveresource.annotation.CollectionName;
/**
* an abstract class which you can subclass to easily connect to RESTful
* resources provided by Ruby on Rails
*
* @version $LastChangedRevision$ <br>
* $LastChangedDate$
* @author $LastChangedBy$
*/
public abstract class ActiveResource {
/**
* get the object with a given id
*
* @param <T>
* @param clazz
* @param c
* @param id
* @return
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
protected static <T extends ActiveResource> T find( Class<T> clazz,
Connection c, String id ) throws HttpException, IOException,
InterruptedException, URISyntaxException {
String collection = getCollectionName( clazz );
String url = "/" + collection + "/" + id + c.getFormat().extension();
return getOne( clazz, c, url );
}
/**
* get the url on a given connection, and try and deserialize one object
* from the response
*
* @param <T>
* @param clazz
* the type of object to try and deserialize
* @param c
* the connection to use
* @param url
* the url, including parameters, to get
* @return an object of type <T>
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
protected static <T extends ActiveResource> T getOne( Class<T> clazz,
Connection c, String url ) throws HttpException, IOException,
InterruptedException, URISyntaxException {
String xml = c.get( url );
return deserialize( clazz, c, xml );
}
/**
* get all objects of the given type
*
* @param <T>
* @param clazz
* @param c
* @return
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
protected static <T extends ActiveResource> ArrayList<T> findAll(
Class<T> clazz, Connection c ) throws HttpException, IOException,
InterruptedException, URISyntaxException {
String collection = getCollectionName( clazz );
String url = "/" + collection + c.getFormat().extension();
return getMany( clazz, c, url );
}
/**
* get the url on a given connection, and try and deserialize a list of
* objects from the response
*
* @param <T>
* @param clazz
* the type of objects to try and deserialize
* @param c
* the connection to use
* @param url
* the url, including parameters, to get
* @return an ArrayList of objects of type <T>
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
@SuppressWarnings("unchecked")
protected static <T extends ActiveResource> ArrayList<T> getMany(
Class<T> clazz, Connection c, String url ) throws HttpException,
IOException, InterruptedException, URISyntaxException {
BufferedReader xml = c.getStream( url );
ObjectInputStream in = c.getXStream().createObjectInputStream( xml );
ArrayList<T> list = new ArrayList<T>();
while ( true ) {
try {
list.add( (T) in.readObject() );
} catch ( EOFException e ) {
break;
} catch ( ClassNotFoundException e ) {
// do nothing
}
}
+ in.close();
return list;
}
/**
* A static method that returns whether a resource exists or not.
*
* @param <T>
* @param clazz
* the class representing the resource you want to check
* @param c
* the connection to check against
* @param id
* the id you want to see if exists
* @return true if the resource exists, false if it does not
*/
protected static <T extends ActiveResource> boolean exists( Class<T> clazz,
Connection c, String id ) {
String collection = getCollectionName( clazz );
String u = "/" + collection + "/" + id + c.getFormat().extension();
try {
c.get( u );
return true;
} catch ( HttpException e ) {
return false;
} catch ( IOException e ) {
return false;
} catch ( InterruptedException e ) {
return false;
} catch ( URISyntaxException e ) {
return false;
}
}
/*
* protected static <T extends ActiveResource> void delete( Class<T> clazz,
* Connection connection, String id ) { }
*/
@SuppressWarnings("unchecked")
protected static <T extends ActiveResource> T deserialize( Class<T> clazz,
Connection c, String xml ) {
return (T) c.getXStream().fromXML( xml );
}
/**
* guess the collection name for a particular class. Can be overridden by
* with a CollectionName annotation.
*
* @param className
* @return
*/
protected static String getCollectionName(
Class<? extends ActiveResource> clazz ) {
String name;
CollectionName cn = clazz.getAnnotation( CollectionName.class );
if ( cn != null ) {
name = cn.value();
} else {
name = Inflector.underscore( clazz.getSimpleName() );
name = Inflector.pluralize( name );
}
return name;
}
/**
* guess the collection name for an instance of a subclass of
* ActiveResource. Calls the static getCollectionName() method.
*
* @return
*/
protected String getCollectionName() {
return ActiveResource.getCollectionName( this.getClass() );
}
/**
* serialize this object
*
* @param c
* @return
*/
public String serialize( Connection c ) {
return c.getXStream().toXML( this );
}
public boolean isNew() {
// TODO ticket:1
return true;
}
/**
* save this resource to the specified connection
*
* @param c
* @throws InterruptedException
* @throws IOException
* @throws HttpException
* @throws URISyntaxException
*/
public void save( Connection c ) throws URISyntaxException, HttpException,
IOException, InterruptedException {
if ( isNew() )
create( c );
else
update( c );
}
public void create( Connection c ) {
// do a post
}
public void update( Connection c ) throws URISyntaxException,
HttpException, IOException, InterruptedException {
// do a put
String collection = getCollectionName( this.getClass() );
String u = "/" + collection + "/" + this.getId()
+ c.getFormat().extension();
String xml = serialize( c );
c.put( u, xml );
}
public void delete( Connection c ) {
}
public void destroy( Connection c ) {
delete( c );
}
public abstract String getId();
public abstract void setId( String id );
}
| true | true | protected static <T extends ActiveResource> ArrayList<T> getMany(
Class<T> clazz, Connection c, String url ) throws HttpException,
IOException, InterruptedException, URISyntaxException {
BufferedReader xml = c.getStream( url );
ObjectInputStream in = c.getXStream().createObjectInputStream( xml );
ArrayList<T> list = new ArrayList<T>();
while ( true ) {
try {
list.add( (T) in.readObject() );
} catch ( EOFException e ) {
break;
} catch ( ClassNotFoundException e ) {
// do nothing
}
}
return list;
}
| protected static <T extends ActiveResource> ArrayList<T> getMany(
Class<T> clazz, Connection c, String url ) throws HttpException,
IOException, InterruptedException, URISyntaxException {
BufferedReader xml = c.getStream( url );
ObjectInputStream in = c.getXStream().createObjectInputStream( xml );
ArrayList<T> list = new ArrayList<T>();
while ( true ) {
try {
list.add( (T) in.readObject() );
} catch ( EOFException e ) {
break;
} catch ( ClassNotFoundException e ) {
// do nothing
}
}
in.close();
return list;
}
|
diff --git a/AndroidAsync/src/com/koushikdutta/async/http/server/AsyncHttpServer.java b/AndroidAsync/src/com/koushikdutta/async/http/server/AsyncHttpServer.java
index 1fde5ca..78e0e71 100644
--- a/AndroidAsync/src/com/koushikdutta/async/http/server/AsyncHttpServer.java
+++ b/AndroidAsync/src/com/koushikdutta/async/http/server/AsyncHttpServer.java
@@ -1,394 +1,394 @@
package com.koushikdutta.async.http.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import junit.framework.Assert;
import android.content.Context;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.AsyncServerSocket;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.CompletedEmitter;
import com.koushikdutta.async.Util;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ListenCallback;
import com.koushikdutta.async.http.AsyncHttpGet;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.UrlEncodedFormBody;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.WebSocketImpl;
import com.koushikdutta.async.http.libcore.RawHeaders;
import com.koushikdutta.async.http.libcore.RequestHeaders;
public class AsyncHttpServer implements CompletedEmitter {
ArrayList<AsyncServerSocket> mListeners = new ArrayList<AsyncServerSocket>();
public void stop() {
if (mListeners != null) {
for (AsyncServerSocket listener: mListeners) {
listener.stop();
}
}
}
ListenCallback mListenCallback = new ListenCallback() {
@Override
public void onAccepted(final AsyncSocket socket) {
AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() {
Pair match;
String fullPath;
String path;
boolean responseComplete;
boolean requestComplete;
AsyncHttpServerResponseImpl res;
boolean hasContinued;
@Override
protected void onHeadersReceived() {
RawHeaders headers = getRawHeaders();
// should the negotiation of 100 continue be here, or in the request impl?
// probably here, so AsyncResponse can negotiate a 100 continue.
if (!hasContinued && "100-continue".equals(headers.get("Expect"))) {
pause();
// System.out.println("continuing...");
Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n".getBytes(), new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
resume();
if (ex != null) {
report(ex);
return;
}
hasContinued = true;
onHeadersReceived();
}
});
return;
}
// System.out.println(headers.toHeaderString());
String statusLine = headers.getStatusLine();
String[] parts = statusLine.split(" ");
fullPath = parts[1];
path = fullPath.split("\\?")[0];
String action = parts[0];
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs != null) {
for (Pair p: pairs) {
Matcher m = p.regex.matcher(path);
if (m.matches()) {
mMatcher = m;
match = p;
break;
}
}
}
}
res = new AsyncHttpServerResponseImpl(socket) {
@Override
protected void onEnd() {
responseComplete = true;
// reuse the socket for a subsequent request.
handleOnCompleted();
}
};
if (match == null) {
res.responseCode(404);
res.end();
return;
}
if (!getBody().readFullyOnRequest()) {
// Assert.assertTrue(getBody() instanceof CompletedEmitter);
// CompletedEmitter completed = (CompletedEmitter)getBody();
// completed.setCompletedCallback(this);
match.callback.onRequest(this, res);
}
else if (requestComplete) {
match.callback.onRequest(this, res);
}
}
@Override
public void onCompleted(Exception e) {
requestComplete = true;
super.onCompleted(e);
mSocket.setDataCallback(null);
mSocket.pause();
handleOnCompleted();
if (getBody().readFullyOnRequest()) {
match.callback.onRequest(this, res);
}
}
private void handleOnCompleted() {
if (requestComplete && responseComplete) {
onAccepted(socket);
}
}
@Override
public String getPath() {
return path;
}
@Override
public Map<String, String> getQuery() {
String[] parts = fullPath.split("\\?", 2);
if (parts.length < 2)
- new Hashtable<String, String>();
+ return new Hashtable<String, String>();
return UrlEncodedFormBody.parse(parts[1]);
}
};
req.setSocket(socket);
socket.resume();
}
@Override
public void onCompleted(Exception error) {
report(error);
}
@Override
public void onListening(AsyncServerSocket socket) {
mListeners.add(socket);
}
};
public void listen(AsyncServer server, int port) {
server.listen(null, port, mListenCallback);
}
private void report(Exception ex) {
if (mCompletedCallback != null)
mCompletedCallback.onCompleted(ex);
}
public void listen(int port) {
listen(AsyncServer.getDefault(), port);
}
public ListenCallback getListenCallback() {
return mListenCallback;
}
CompletedCallback mCompletedCallback;
@Override
public void setCompletedCallback(CompletedCallback callback) {
mCompletedCallback = callback;
}
@Override
public CompletedCallback getCompletedCallback() {
return mCompletedCallback;
}
private static class Pair {
Pattern regex;
HttpServerRequestCallback callback;
}
Hashtable<String, ArrayList<Pair>> mActions = new Hashtable<String, ArrayList<Pair>>();
public void addAction(String action, String regex, HttpServerRequestCallback callback) {
Pair p = new Pair();
p.regex = Pattern.compile("^" + regex);
p.callback = callback;
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs == null) {
pairs = new ArrayList<AsyncHttpServer.Pair>();
mActions.put(action, pairs);
}
pairs.add(p);
}
}
public static interface WebSocketRequestCallback {
public void onConnected(WebSocket webSocket, RequestHeaders headers);
}
public void websocket(String regex, final WebSocketRequestCallback callback) {
get(regex, new HttpServerRequestCallback() {
@Override
public void onRequest(final AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
boolean hasUpgrade = false;
String connection = request.getHeaders().getHeaders().get("Connection");
if (connection != null) {
String[] connections = connection.split(",");
for (String c: connections) {
if ("Upgrade".equalsIgnoreCase(c.trim())) {
hasUpgrade = true;
break;
}
}
}
if (!"websocket".equals(request.getHeaders().getHeaders().get("Upgrade")) || !hasUpgrade) {
response.responseCode(404);
response.end();
return;
}
callback.onConnected(new WebSocketImpl(request, response), request.getHeaders());
}
});
}
public void get(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpGet.METHOD, regex, callback);
}
public void post(String regex, HttpServerRequestCallback callback) {
addAction(AsyncHttpPost.METHOD, regex, callback);
}
public static InputStream getAssetStream(final Context context, String asset) {
String apkPath = context.getPackageResourcePath();
String assetPath = "assets/" + asset;
try {
ZipFile zip = new ZipFile(apkPath);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.getName().equals(assetPath)) {
return zip.getInputStream(entry);
}
}
}
catch (Exception ex) {
}
return null;
}
static Hashtable<String, String> mContentTypes = new Hashtable<String, String>();
{
mContentTypes.put("js", "application/javascript");
mContentTypes.put("json", "application/json");
mContentTypes.put("png", "image/png");
mContentTypes.put("jpg", "image/jpeg");
mContentTypes.put("html", "text/html");
mContentTypes.put("css", "text/css");
mContentTypes.put("mp4", "video/mp4");
}
public static String getContentType(String path) {
int index = path.lastIndexOf(".");
if (index != -1) {
String e = path.substring(index + 1);
String ct = mContentTypes.get(e);
if (ct != null)
return ct;
}
return "text/plain";
}
public void directory(Context _context, String regex, final String assetPath) {
final Context context = _context.getApplicationContext();
addAction("GET", regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
InputStream is = getAssetStream(context, assetPath + path);
if (is == null) {
response.responseCode(404);
response.end();
return;
}
response.responseCode(200);
response.getHeaders().getHeaders().add("Content-Type", getContentType(path));
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
}
});
}
});
}
public void directory(String regex, final File directory) {
directory(regex, directory, false);
}
public void directory(String regex, final File directory, final boolean list) {
Assert.assertTrue(directory.isDirectory());
addAction("GET", regex, new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, final AsyncHttpServerResponse response) {
String path = request.getMatcher().replaceAll("");
File file = new File(directory, path);
if (file.isDirectory() && list) {
ArrayList<File> dirs = new ArrayList<File>();
ArrayList<File> files = new ArrayList<File>();
for (File f: file.listFiles()) {
if (f.isDirectory())
dirs.add(f);
else
files.add(f);
}
Comparator<File> c = new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
return lhs.getName().compareTo(rhs.getName());
}
};
Collections.sort(dirs, c);
Collections.sort(files, c);
files.addAll(0, dirs);
return;
}
if (!file.isFile()) {
response.responseCode(404);
response.end();
return;
}
try {
FileInputStream is = new FileInputStream(file);
response.responseCode(200);
Util.pump(is, response, new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
response.end();
}
});
}
catch (Exception ex) {
response.responseCode(404);
response.end();
return;
}
}
});
}
private static Hashtable<Integer, String> mCodes = new Hashtable<Integer, String>();
static {
mCodes.put(200, "OK");
mCodes.put(101, "Switching Protocols");
mCodes.put(404, "Not Found");
}
public static String getResponseCodeDescription(int code) {
String d = mCodes.get(code);
if (d == null)
return "Unknown";
return d;
}
}
| true | true | public void onAccepted(final AsyncSocket socket) {
AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() {
Pair match;
String fullPath;
String path;
boolean responseComplete;
boolean requestComplete;
AsyncHttpServerResponseImpl res;
boolean hasContinued;
@Override
protected void onHeadersReceived() {
RawHeaders headers = getRawHeaders();
// should the negotiation of 100 continue be here, or in the request impl?
// probably here, so AsyncResponse can negotiate a 100 continue.
if (!hasContinued && "100-continue".equals(headers.get("Expect"))) {
pause();
// System.out.println("continuing...");
Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n".getBytes(), new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
resume();
if (ex != null) {
report(ex);
return;
}
hasContinued = true;
onHeadersReceived();
}
});
return;
}
// System.out.println(headers.toHeaderString());
String statusLine = headers.getStatusLine();
String[] parts = statusLine.split(" ");
fullPath = parts[1];
path = fullPath.split("\\?")[0];
String action = parts[0];
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs != null) {
for (Pair p: pairs) {
Matcher m = p.regex.matcher(path);
if (m.matches()) {
mMatcher = m;
match = p;
break;
}
}
}
}
res = new AsyncHttpServerResponseImpl(socket) {
@Override
protected void onEnd() {
responseComplete = true;
// reuse the socket for a subsequent request.
handleOnCompleted();
}
};
if (match == null) {
res.responseCode(404);
res.end();
return;
}
if (!getBody().readFullyOnRequest()) {
// Assert.assertTrue(getBody() instanceof CompletedEmitter);
// CompletedEmitter completed = (CompletedEmitter)getBody();
// completed.setCompletedCallback(this);
match.callback.onRequest(this, res);
}
else if (requestComplete) {
match.callback.onRequest(this, res);
}
}
@Override
public void onCompleted(Exception e) {
requestComplete = true;
super.onCompleted(e);
mSocket.setDataCallback(null);
mSocket.pause();
handleOnCompleted();
if (getBody().readFullyOnRequest()) {
match.callback.onRequest(this, res);
}
}
private void handleOnCompleted() {
if (requestComplete && responseComplete) {
onAccepted(socket);
}
}
@Override
public String getPath() {
return path;
}
@Override
public Map<String, String> getQuery() {
String[] parts = fullPath.split("\\?", 2);
if (parts.length < 2)
new Hashtable<String, String>();
return UrlEncodedFormBody.parse(parts[1]);
}
};
req.setSocket(socket);
socket.resume();
}
| public void onAccepted(final AsyncSocket socket) {
AsyncHttpServerRequestImpl req = new AsyncHttpServerRequestImpl() {
Pair match;
String fullPath;
String path;
boolean responseComplete;
boolean requestComplete;
AsyncHttpServerResponseImpl res;
boolean hasContinued;
@Override
protected void onHeadersReceived() {
RawHeaders headers = getRawHeaders();
// should the negotiation of 100 continue be here, or in the request impl?
// probably here, so AsyncResponse can negotiate a 100 continue.
if (!hasContinued && "100-continue".equals(headers.get("Expect"))) {
pause();
// System.out.println("continuing...");
Util.writeAll(mSocket, "HTTP/1.1 100 Continue\r\n".getBytes(), new CompletedCallback() {
@Override
public void onCompleted(Exception ex) {
resume();
if (ex != null) {
report(ex);
return;
}
hasContinued = true;
onHeadersReceived();
}
});
return;
}
// System.out.println(headers.toHeaderString());
String statusLine = headers.getStatusLine();
String[] parts = statusLine.split(" ");
fullPath = parts[1];
path = fullPath.split("\\?")[0];
String action = parts[0];
synchronized (mActions) {
ArrayList<Pair> pairs = mActions.get(action);
if (pairs != null) {
for (Pair p: pairs) {
Matcher m = p.regex.matcher(path);
if (m.matches()) {
mMatcher = m;
match = p;
break;
}
}
}
}
res = new AsyncHttpServerResponseImpl(socket) {
@Override
protected void onEnd() {
responseComplete = true;
// reuse the socket for a subsequent request.
handleOnCompleted();
}
};
if (match == null) {
res.responseCode(404);
res.end();
return;
}
if (!getBody().readFullyOnRequest()) {
// Assert.assertTrue(getBody() instanceof CompletedEmitter);
// CompletedEmitter completed = (CompletedEmitter)getBody();
// completed.setCompletedCallback(this);
match.callback.onRequest(this, res);
}
else if (requestComplete) {
match.callback.onRequest(this, res);
}
}
@Override
public void onCompleted(Exception e) {
requestComplete = true;
super.onCompleted(e);
mSocket.setDataCallback(null);
mSocket.pause();
handleOnCompleted();
if (getBody().readFullyOnRequest()) {
match.callback.onRequest(this, res);
}
}
private void handleOnCompleted() {
if (requestComplete && responseComplete) {
onAccepted(socket);
}
}
@Override
public String getPath() {
return path;
}
@Override
public Map<String, String> getQuery() {
String[] parts = fullPath.split("\\?", 2);
if (parts.length < 2)
return new Hashtable<String, String>();
return UrlEncodedFormBody.parse(parts[1]);
}
};
req.setSocket(socket);
socket.resume();
}
|
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index 1c98522bc..338b9c3d5 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -1,3236 +1,3236 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.*;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import android.util.Pair;
import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
// true = use a "More Apps" folder for non-workspace apps on upgrade
// false = strew non-workspace apps across the workspace on upgrade
public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false;
private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
private final boolean mAppsCanBeOnRemoveableStorage;
private final LauncherAppState mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private LoaderTask mLoaderTask;
private boolean mIsLoaderTaskRunning;
private volatile boolean mFlushingWorkerThread;
// Specific runnable types that are run on the main thread deferred handler, this allows us to
// clear all queued binding runnables when the Launcher activity is destroyed.
private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
// We start off with everything not loaded. After that, we assume that
// our monitoring of the package manager provides all updates and we never
// need to do a requery. These are only ever touched from the loader thread.
private boolean mWorkspaceLoaded;
private boolean mAllAppsLoaded;
// When we are loading pages synchronously, we can't just post the binding of items on the side
// pages as this delays the rotation process. Instead, we wait for a callback from the first
// draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
// a normal load, we also clear this set of Runnables.
static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
private WeakReference<Callbacks> mCallbacks;
// < only access in worker thread >
AllAppsList mBgAllAppsList;
// The lock that must be acquired before referencing any static bg data structures. Unlike
// other locks, this one can generally be held long-term because we never expect any of these
// static data structures to be referenced outside of the worker thread except on the first
// load after configuration change.
static final Object sBgLock = new Object();
// sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
// LauncherModel to their ids
static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
// sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
// created by LauncherModel that are directly on the home screen (however, no widgets or
// shortcuts within folders).
static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
// sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
// sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
// sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
// sBgWorkspaceScreens is the ordered set of workspace screens.
static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
// </ only access in worker thread >
private IconCache mIconCache;
private Bitmap mDefaultIcon;
protected int mPreviousConfigMcc;
public interface Callbacks {
public boolean setLoadOnResume();
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
boolean forceAnimateIcons);
public void bindScreens(ArrayList<Long> orderedScreenIds);
public void bindAddScreens(ArrayList<Long> orderedScreenIds);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems(boolean upgradePath);
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<Long> newScreens,
ArrayList<ItemInfo> addNotAnimated,
ArrayList<ItemInfo> addAnimated);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindComponentsRemoved(ArrayList<String> packageNames,
ArrayList<ApplicationInfo> appInfos,
boolean matchPackageNamesOnly);
public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
public void bindSearchablesChanged();
public void onPageBoundSynchronously(int page);
public void dumpLogsToLocalData(boolean email);
}
public interface ItemInfoFilter {
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
}
LauncherModel(LauncherAppState app, IconCache iconCache) {
final Context context = app.getContext();
mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable();
mApp = app;
mBgAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
mIconCache.getFullResDefaultActivityIcon(), context);
final Resources res = context.getResources();
Configuration config = res.getConfiguration();
mPreviousConfigMcc = config.mcc;
}
/** Runs the specified runnable immediately if called from the main thread, otherwise it is
* posted on the main thread handler. */
private void runOnMainThread(Runnable r) {
runOnMainThread(r, 0);
}
private void runOnMainThread(Runnable r, int type) {
if (sWorkerThread.getThreadId() == Process.myTid()) {
// If we are on the worker thread, post onto the main handler
mHandler.post(r);
} else {
r.run();
}
}
/** Runs the specified runnable immediately if called from the worker thread, otherwise it is
* posted on the worker thread handler. */
private static void runOnWorkerThread(Runnable r) {
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
// If we are not on the worker thread, then post to the worker handler
sWorker.post(r);
}
}
static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
long screen) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
final int xCount = (int) grid.numColumns;
final int yCount = (int) grid.numRows;
boolean[][] occupied = new boolean[xCount][yCount];
int cellX, cellY, spanX, spanY;
for (int i = 0; i < items.size(); ++i) {
final ItemInfo item = items.get(i);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (item.screenId == screen) {
cellX = item.cellX;
cellY = item.cellY;
spanX = item.spanX;
spanY = item.spanY;
for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
occupied[x][y] = true;
}
}
}
}
}
return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
}
static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Intent launchIntent,
int firstScreenIndex,
ArrayList<Long> workspaceScreens) {
// Lock on the app so that we don't try and get the items while apps are being added
LauncherAppState app = LauncherAppState.getInstance();
LauncherModel model = app.getModel();
boolean found = false;
synchronized (app) {
if (sWorkerThread.getThreadId() != Process.myTid()) {
// Flush the LauncherModel worker thread, so that if we just did another
// processInstallShortcut, we give it time for its shortcut to get added to the
// database (getItemsInLocalCoordinates reads the database)
model.flushWorkerThread();
}
final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
// Try adding to the workspace screens incrementally, starting at the default or center
// screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size());
int count = workspaceScreens.size();
for (int screen = firstScreenIndex; screen < count && !found; screen++) {
int[] tmpCoordinates = new int[2];
if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
workspaceScreens.get(screen))) {
// Update the Launcher db
return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates);
}
}
}
return null;
}
public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added,
final Callbacks callbacks) {
Launcher.addDumpLog(TAG, "10249126 - addAndBindAddedApps()", true);
if (added.isEmpty()) {
return;
}
// Process the newly added applications and add them to the database first
Runnable r = new Runnable() {
public void run() {
final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
// Get the list of workspace screens. We need to append to this list and
// can not use sBgWorkspaceScreens because loadWorkspace() may not have been
// called.
ArrayList<Long> workspaceScreens = new ArrayList<Long>();
TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context);
for (Integer i : orderedScreens.keySet()) {
long screenId = orderedScreens.get(i);
workspaceScreens.add(screenId);
}
synchronized(sBgLock) {
Iterator<ItemInfo> iter = added.iterator();
while (iter.hasNext()) {
ItemInfo a = iter.next();
final String name = a.title.toString();
final Intent launchIntent = a.getIntent();
// Short-circuit this logic if the icon exists somewhere on the workspace
if (LauncherModel.shortcutExists(context, name, launchIntent)) {
continue;
}
// Add this icon to the db, creating a new page if necessary
int startSearchPageIndex = 1;
Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
name, launchIntent, startSearchPageIndex, workspaceScreens);
if (coords == null) {
LauncherProvider lp = LauncherAppState.getLauncherProvider();
// If we can't find a valid position, then just add a new screen.
// This takes time so we need to re-queue the add until the new
// page is added. Create as many screens as necessary to satisfy
// the startSearchPageIndex.
int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 -
workspaceScreens.size());
while (numPagesToAdd > 0) {
long screenId = lp.generateNewScreenId();
Launcher.addDumpLog(TAG, "10249126 - addAndBindAddedApps(" + screenId + ")", true);
// Save the screen id for binding in the workspace
workspaceScreens.add(screenId);
addedWorkspaceScreensFinal.add(screenId);
numPagesToAdd--;
}
// Find the coordinate again
coords = LauncherModel.findNextAvailableIconSpace(context,
name, launchIntent, startSearchPageIndex, workspaceScreens);
}
if (coords == null) {
throw new RuntimeException("Coordinates should not be null");
}
ShortcutInfo shortcutInfo;
if (a instanceof ShortcutInfo) {
shortcutInfo = (ShortcutInfo) a;
} else if (a instanceof ApplicationInfo) {
shortcutInfo = ((ApplicationInfo) a).makeShortcut();
} else {
throw new RuntimeException("Unexpected info type");
}
// Add the shortcut to the db
addItemToDatabase(context, shortcutInfo,
LauncherSettings.Favorites.CONTAINER_DESKTOP,
coords.first, coords.second[0], coords.second[1], false);
// Save the ShortcutInfo for binding in the workspace
addedShortcutsFinal.add(shortcutInfo);
}
}
Launcher.addDumpLog(TAG, "10249126 - addAndBindAddedApps - updateWorkspaceScreenOrder(" + workspaceScreens.size() + ")", true);
// Update the workspace screens
updateWorkspaceScreenOrder(context, workspaceScreens);
if (!addedShortcutsFinal.isEmpty()) {
runOnMainThread(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1);
long lastScreenId = info.screenId;
final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>();
final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>();
for (ItemInfo i : addedShortcutsFinal) {
if (i.screenId == lastScreenId) {
addAnimated.add(i);
} else {
addNotAnimated.add(i);
}
}
callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
addNotAnimated, addAnimated);
}
}
});
}
}
};
runOnWorkerThread(r);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
public void unbindItemInfosAndClearQueuedBindRunnables() {
if (sWorkerThread.getThreadId() == Process.myTid()) {
throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
"main thread");
}
// Clear any deferred bind runnables
mDeferredBindRunnables.clear();
// Remove any queued bind runnables
mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
// Unbind all the workspace items
unbindWorkspaceItemsOnMainThread();
}
/** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
void unbindWorkspaceItemsOnMainThread() {
// Ensure that we don't use the same workspace items data structure on the main thread
// by making a copy of workspace items first.
final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
synchronized (sBgLock) {
tmpWorkspaceItems.addAll(sBgWorkspaceItems);
tmpAppWidgets.addAll(sBgAppWidgets);
}
Runnable r = new Runnable() {
@Override
public void run() {
for (ItemInfo item : tmpWorkspaceItems) {
item.unbind();
}
for (ItemInfo item : tmpAppWidgets) {
item.unbind();
}
}
};
runOnMainThread(r);
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
long screenId, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screenId, cellX, cellY);
}
}
static void checkItemInfoLocked(
final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
ItemInfo modelItem = sBgItemsIdMap.get(itemId);
if (modelItem != null && item != modelItem) {
// check all the data is consistent
if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
ShortcutInfo shortcut = (ShortcutInfo) item;
if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
modelShortcut.intent.filterEquals(shortcut.intent) &&
modelShortcut.id == shortcut.id &&
modelShortcut.itemType == shortcut.itemType &&
modelShortcut.container == shortcut.container &&
modelShortcut.screenId == shortcut.screenId &&
modelShortcut.cellX == shortcut.cellX &&
modelShortcut.cellY == shortcut.cellY &&
modelShortcut.spanX == shortcut.spanX &&
modelShortcut.spanY == shortcut.spanY &&
((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
(modelShortcut.dropPos != null &&
shortcut.dropPos != null &&
modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
// For all intents and purposes, this is the same object
return;
}
}
// the modelItem needs to match up perfectly with item if our model is
// to be consistent with the database-- for now, just require
// modelItem == item or the equality check above
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " +
((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to checkItemInfo doesn't match original";
RuntimeException e = new RuntimeException(msg);
if (stackTrace != null) {
e.setStackTrace(stackTrace);
}
// TODO: something breaks this in the upgrade path
//throw e;
}
}
static void checkItemInfo(final ItemInfo item) {
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
final long itemId = item.id;
Runnable r = new Runnable() {
public void run() {
synchronized (sBgLock) {
checkItemInfoLocked(itemId, item, stackTrace);
}
}
};
runOnWorkerThread(r);
}
static void updateItemInDatabaseHelper(Context context, final ContentValues values,
final ItemInfo item, final String callingFunction) {
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
final ContentResolver cr = context.getContentResolver();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Runnable r = new Runnable() {
public void run() {
cr.update(uri, values, null, null);
updateItemArrays(item, itemId, stackTrace);
}
};
runOnWorkerThread(r);
}
static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
final ArrayList<ItemInfo> items, final String callingFunction) {
final ContentResolver cr = context.getContentResolver();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Runnable r = new Runnable() {
public void run() {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int count = items.size();
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
ContentValues values = valuesList.get(i);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
updateItemArrays(item, itemId, stackTrace);
}
try {
cr.applyBatch(LauncherProvider.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
};
runOnWorkerThread(r);
}
static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(itemId, item, stackTrace);
if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// Item is in a folder, make sure this folder exists
if (!sBgFolders.containsKey(item.container)) {
// An items container is being set to a that of an item which is not in
// the list of Folders.
String msg = "item: " + item + " container being set to: " +
item.container + ", not in the list of folders";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
// Items are added/removed from the corresponding FolderInfo elsewhere, such
// as in Workspace.onDrop. Here, we just add/remove them from the list of items
// that are on the desktop, as appropriate
ItemInfo modelItem = sBgItemsIdMap.get(itemId);
if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
switch (modelItem.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
if (!sBgWorkspaceItems.contains(modelItem)) {
sBgWorkspaceItems.add(modelItem);
}
break;
default:
break;
}
} else {
sBgWorkspaceItems.remove(modelItem);
}
}
}
public void flushWorkerThread() {
mFlushingWorkerThread = true;
Runnable waiter = new Runnable() {
public void run() {
synchronized (this) {
notifyAll();
mFlushingWorkerThread = false;
}
}
};
synchronized(waiter) {
runOnWorkerThread(waiter);
if (mLoaderTask != null) {
synchronized(mLoaderTask) {
mLoaderTask.notify();
}
}
boolean success = false;
while (!success) {
try {
waiter.wait();
success = true;
} catch (InterruptedException e) {
}
}
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY) {
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
" (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
}
/**
* Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
* cellX, cellY have already been updated on the ItemInfos.
*/
static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
final long container, final int screen) {
ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
int count = items.size();
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
+ ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
+ item.cellX + ", " + item.cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
item.container = container;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
item.cellY);
} else {
item.screenId = screen;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
contentValues.add(values);
}
updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
}
/**
* Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
*/
static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
" (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
item.cellX = cellX;
item.cellY = cellY;
item.spanX = spanX;
item.spanY = spanY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SPANX, item.spanX);
values.put(LauncherSettings.Favorites.SPANY, item.spanY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = Math.max(1, c.getInt(spanXIndex));
item.spanY = Math.max(1, c.getInt(spanYIndex));
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder()", true);
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - remove: " + id + ")", true);
iter.remove();
}
}
// Dump the screens copy
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - screensCopy", true);
for (Long l : screensCopy) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screensCopy.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screensCopy.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder(" + screenId + ", " + i + ")", true);
values[i] = v;
}
cr.bulkInsert(uri, values);
synchronized (sBgLock) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/** Loads the workspace screens db into a map of Rank -> ScreenId */
private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
final ContentResolver contentResolver = context.getContentResolver();
final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
Launcher.addDumpLog(TAG, "10249126 - loadWorkspaceScreensDb(" + screenId + ", " + rank + ")", true);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
}
}
} finally {
sc.close();
}
return orderedScreens;
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
/** Returns whether this is an upgrade path */
private boolean loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
boolean isUpgradePath = false;
if (!mWorkspaceLoaded) {
isUpgradePath = loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadAndBindWorkspace() stopped", true);
return isUpgradePath;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1, isUpgradePath);
return isUpgradePath;
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage, false);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
boolean isUpgrade = false;
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
isUpgrade = loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Ensure that all the applications that are in the system are represented on the home
// screen.
Launcher.addDumpLog(TAG, "10249126 - verifyApplications - useMoreApps="
+ UPGRADE_USE_MORE_APPS_FOLDER + " isUpgrade=" + isUpgrade, true);
if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Launcher.addDumpLog(TAG, "10249126 - verifyApplications(" + isUpgrade + ")", true);
verifyApplications();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
Launcher.addDumpLog(TAG, "10249126 - STOPPED", true);
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void verifyApplications() {
final Context context = mApp.getContext();
// Cross reference all the applications in our apps list with items in the workspace
ArrayList<ItemInfo> tmpInfos;
ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
synchronized (sBgLock) {
for (ApplicationInfo app : mBgAllAppsList.data) {
tmpInfos = getItemInfoForComponentName(app.componentName);
Launcher.addDumpLog(TAG, "10249126 - \t" + app.componentName.getPackageName() + ", " + tmpInfos.isEmpty(), true);
if (tmpInfos.isEmpty()) {
// We are missing an application icon, so add this to the workspace
added.add(app);
// This is a rare event, so lets log it
Log.e(TAG, "Missing Application on load: " + app);
}
}
}
if (!added.isEmpty()) {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
}
private boolean checkItemDimensions(ItemInfo info) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
return (info.cellX + info.spanX) > (int) grid.numColumns ||
(info.cellY + info.spanY) > (int) grid.numRows;
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
/** Clears all the sBg data structures */
private void clearSBgDataStructures() {
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
}
}
/** Returns whether this is an upgradge path */
private boolean loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
// Make sure the default workspace is loaded, if needed
LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
// Check if we need to do any upgrade-path logic
boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
synchronized (sBgLock) {
clearSBgDataStructures();
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace()", true);
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
Launcher.addDumpLog(TAG, "10249126 - Num rows: " + c.getCount(), true);
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
id = c.getLong(idIndex);
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
ComponentName cn = intent.getComponent();
- if (!isValidPackageComponent(manager, cn)) {
+ if (cn != null && !isValidPackageComponent(manager, cn)) {
if (!mAppsCanBeOnRemoveableStorage) {
// Log the invalid package, and remove it from the db
Uri uri = LauncherSettings.Favorites.getContentUri(id,
false);
contentResolver.delete(uri, null, null);
Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
} else {
// If apps can be on external storage, then we just
// leave them for the user to remove (maybe add
// visual treatment to it)
Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
}
continue;
}
} catch (URISyntaxException e) {
Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.id = id;
info.intent = intent;
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
info.spanX = 1;
info.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(info)) {
Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: "
+ info + ", " + grid.numColumns + "x" + grid.numRows, true);
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
throw new RuntimeException("Unexpected null ShortcutInfo");
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
folderInfo.spanX = 1;
folderInfo.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(folderInfo)) {
Log.d(TAG, "Skipped loading out of bounds folder");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.addDumpLog(TAG, log, false);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(appWidgetInfo)) {
Log.d(TAG, "Skipped loading out of bounds app widget");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true);
}
}
} finally {
if (c != null) {
c.close();
}
}
// Break early if we've stopped loading
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace() - Stopped", true);
clearSBgDataStructures();
return false;
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadedOldDb) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - loadedOldDb", true);
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")", true);
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
// Update the max item id after we load an old db
long maxItemId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
maxItemId = Math.max(maxItemId, item.id);
}
LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
} else {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - !loadedOldDb [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
for (Integer i : orderedScreens.keySet()) {
Launcher.addDumpLog(TAG, "10249126 - adding to sBgWorkspaceScreens: " + orderedScreens.get(i), true);
sBgWorkspaceScreens.add(orderedScreens.get(i));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - unused screens: " + l, true);
}
Launcher.addDumpLog(TAG, "10249126 - sBgItemsIdMap [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
Launcher.addDumpLog(TAG, "10249126 - \t" + item.container + ", " + screenId + " - " + unusedScreens.contains(screenId) + " | " + item, true);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
Launcher.addDumpLog(TAG, "10249126 - \t\tRemoving " + screenId, true);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - \t\t\t unused screens: " + l, true);
}
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.removeAll(unusedScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < countY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < countX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
return loadedOldDb;
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
final LauncherAppState app = LauncherAppState.getInstance();
final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = (int) grid.numColumns;
int cellCountY = (int) grid.numRows;
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspaceScreens()", true);
// Dump the orderedScreens
synchronized (sBgLock) {
Launcher.addDumpLog(TAG, "10249126 - orderedScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspace(" + synchronizeBindPage + ", " + isUpgradePath + ")", true);
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(isUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, addedInfos, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
// Write all the logs to disk
Launcher.addDumpLog(TAG, "10249126 - PackageUpdatedTask - dumping logs to disk", true);
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.dumpLogsToLocalData(false);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
if (cn == null) {
return false;
}
try {
// Skip if the application is disabled
PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
return false;
}
// Check the activity
return (pm.getActivityInfo(cn, 0) != null);
} catch (NameNotFoundException e) {
return false;
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
ComponentName componentName = intent.getComponent();
final ShortcutInfo info = new ShortcutInfo();
- if (!isValidPackageComponent(manager, componentName)) {
+ if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
return null;
} else {
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " +
componentName.getPackageName());
}
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
Bitmap icon = null;
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnRemoveableStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = Math.max(1, c.getInt(spanXIndex));
item.spanY = Math.max(1, c.getInt(spanYIndex));
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder()", true);
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - remove: " + id + ")", true);
iter.remove();
}
}
// Dump the screens copy
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - screensCopy", true);
for (Long l : screensCopy) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screensCopy.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screensCopy.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder(" + screenId + ", " + i + ")", true);
values[i] = v;
}
cr.bulkInsert(uri, values);
synchronized (sBgLock) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/** Loads the workspace screens db into a map of Rank -> ScreenId */
private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
final ContentResolver contentResolver = context.getContentResolver();
final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
Launcher.addDumpLog(TAG, "10249126 - loadWorkspaceScreensDb(" + screenId + ", " + rank + ")", true);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
}
}
} finally {
sc.close();
}
return orderedScreens;
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
/** Returns whether this is an upgrade path */
private boolean loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
boolean isUpgradePath = false;
if (!mWorkspaceLoaded) {
isUpgradePath = loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadAndBindWorkspace() stopped", true);
return isUpgradePath;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1, isUpgradePath);
return isUpgradePath;
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage, false);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
boolean isUpgrade = false;
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
isUpgrade = loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Ensure that all the applications that are in the system are represented on the home
// screen.
Launcher.addDumpLog(TAG, "10249126 - verifyApplications - useMoreApps="
+ UPGRADE_USE_MORE_APPS_FOLDER + " isUpgrade=" + isUpgrade, true);
if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Launcher.addDumpLog(TAG, "10249126 - verifyApplications(" + isUpgrade + ")", true);
verifyApplications();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
Launcher.addDumpLog(TAG, "10249126 - STOPPED", true);
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void verifyApplications() {
final Context context = mApp.getContext();
// Cross reference all the applications in our apps list with items in the workspace
ArrayList<ItemInfo> tmpInfos;
ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
synchronized (sBgLock) {
for (ApplicationInfo app : mBgAllAppsList.data) {
tmpInfos = getItemInfoForComponentName(app.componentName);
Launcher.addDumpLog(TAG, "10249126 - \t" + app.componentName.getPackageName() + ", " + tmpInfos.isEmpty(), true);
if (tmpInfos.isEmpty()) {
// We are missing an application icon, so add this to the workspace
added.add(app);
// This is a rare event, so lets log it
Log.e(TAG, "Missing Application on load: " + app);
}
}
}
if (!added.isEmpty()) {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
}
private boolean checkItemDimensions(ItemInfo info) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
return (info.cellX + info.spanX) > (int) grid.numColumns ||
(info.cellY + info.spanY) > (int) grid.numRows;
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
/** Clears all the sBg data structures */
private void clearSBgDataStructures() {
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
}
}
/** Returns whether this is an upgradge path */
private boolean loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
// Make sure the default workspace is loaded, if needed
LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
// Check if we need to do any upgrade-path logic
boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
synchronized (sBgLock) {
clearSBgDataStructures();
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace()", true);
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
Launcher.addDumpLog(TAG, "10249126 - Num rows: " + c.getCount(), true);
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
id = c.getLong(idIndex);
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
ComponentName cn = intent.getComponent();
if (!isValidPackageComponent(manager, cn)) {
if (!mAppsCanBeOnRemoveableStorage) {
// Log the invalid package, and remove it from the db
Uri uri = LauncherSettings.Favorites.getContentUri(id,
false);
contentResolver.delete(uri, null, null);
Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
} else {
// If apps can be on external storage, then we just
// leave them for the user to remove (maybe add
// visual treatment to it)
Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
}
continue;
}
} catch (URISyntaxException e) {
Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.id = id;
info.intent = intent;
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
info.spanX = 1;
info.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(info)) {
Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: "
+ info + ", " + grid.numColumns + "x" + grid.numRows, true);
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
throw new RuntimeException("Unexpected null ShortcutInfo");
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
folderInfo.spanX = 1;
folderInfo.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(folderInfo)) {
Log.d(TAG, "Skipped loading out of bounds folder");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.addDumpLog(TAG, log, false);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(appWidgetInfo)) {
Log.d(TAG, "Skipped loading out of bounds app widget");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true);
}
}
} finally {
if (c != null) {
c.close();
}
}
// Break early if we've stopped loading
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace() - Stopped", true);
clearSBgDataStructures();
return false;
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadedOldDb) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - loadedOldDb", true);
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")", true);
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
// Update the max item id after we load an old db
long maxItemId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
maxItemId = Math.max(maxItemId, item.id);
}
LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
} else {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - !loadedOldDb [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
for (Integer i : orderedScreens.keySet()) {
Launcher.addDumpLog(TAG, "10249126 - adding to sBgWorkspaceScreens: " + orderedScreens.get(i), true);
sBgWorkspaceScreens.add(orderedScreens.get(i));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - unused screens: " + l, true);
}
Launcher.addDumpLog(TAG, "10249126 - sBgItemsIdMap [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
Launcher.addDumpLog(TAG, "10249126 - \t" + item.container + ", " + screenId + " - " + unusedScreens.contains(screenId) + " | " + item, true);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
Launcher.addDumpLog(TAG, "10249126 - \t\tRemoving " + screenId, true);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - \t\t\t unused screens: " + l, true);
}
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.removeAll(unusedScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < countY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < countX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
return loadedOldDb;
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
final LauncherAppState app = LauncherAppState.getInstance();
final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = (int) grid.numColumns;
int cellCountY = (int) grid.numRows;
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspaceScreens()", true);
// Dump the orderedScreens
synchronized (sBgLock) {
Launcher.addDumpLog(TAG, "10249126 - orderedScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspace(" + synchronizeBindPage + ", " + isUpgradePath + ")", true);
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(isUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, addedInfos, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
// Write all the logs to disk
Launcher.addDumpLog(TAG, "10249126 - PackageUpdatedTask - dumping logs to disk", true);
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.dumpLogsToLocalData(false);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
if (cn == null) {
return false;
}
try {
// Skip if the application is disabled
PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
return false;
}
// Check the activity
return (pm.getActivityInfo(cn, 0) != null);
} catch (NameNotFoundException e) {
return false;
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
ComponentName componentName = intent.getComponent();
final ShortcutInfo info = new ShortcutInfo();
if (!isValidPackageComponent(manager, componentName)) {
Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
return null;
} else {
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " +
componentName.getPackageName());
}
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
Bitmap icon = null;
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnRemoveableStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = Math.max(1, c.getInt(spanXIndex));
item.spanY = Math.max(1, c.getInt(spanYIndex));
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.id = LauncherAppState.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.addDumpLog(TAG, transaction, true);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder()", true);
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - remove: " + id + ")", true);
iter.remove();
}
}
// Dump the screens copy
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - screensCopy", true);
for (Long l : screensCopy) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screensCopy.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screensCopy.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder(" + screenId + ", " + i + ")", true);
values[i] = v;
}
cr.bulkInsert(uri, values);
synchronized (sBgLock) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post clear", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/** Loads the workspace screens db into a map of Rank -> ScreenId */
private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
final ContentResolver contentResolver = context.getContentResolver();
final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
Launcher.addDumpLog(TAG, "10249126 - loadWorkspaceScreensDb(" + screenId + ", " + rank + ")", true);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
}
}
} finally {
sc.close();
}
return orderedScreens;
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
/** Returns whether this is an upgrade path */
private boolean loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
boolean isUpgradePath = false;
if (!mWorkspaceLoaded) {
isUpgradePath = loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadAndBindWorkspace() stopped", true);
return isUpgradePath;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1, isUpgradePath);
return isUpgradePath;
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage, false);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
boolean isUpgrade = false;
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
isUpgrade = loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Ensure that all the applications that are in the system are represented on the home
// screen.
Launcher.addDumpLog(TAG, "10249126 - verifyApplications - useMoreApps="
+ UPGRADE_USE_MORE_APPS_FOLDER + " isUpgrade=" + isUpgrade, true);
if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) {
Launcher.addDumpLog(TAG, "10249126 - verifyApplications(" + isUpgrade + ")", true);
verifyApplications();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
Launcher.addDumpLog(TAG, "10249126 - STOPPED", true);
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void verifyApplications() {
final Context context = mApp.getContext();
// Cross reference all the applications in our apps list with items in the workspace
ArrayList<ItemInfo> tmpInfos;
ArrayList<ItemInfo> added = new ArrayList<ItemInfo>();
synchronized (sBgLock) {
for (ApplicationInfo app : mBgAllAppsList.data) {
tmpInfos = getItemInfoForComponentName(app.componentName);
Launcher.addDumpLog(TAG, "10249126 - \t" + app.componentName.getPackageName() + ", " + tmpInfos.isEmpty(), true);
if (tmpInfos.isEmpty()) {
// We are missing an application icon, so add this to the workspace
added.add(app);
// This is a rare event, so lets log it
Log.e(TAG, "Missing Application on load: " + app);
}
}
}
if (!added.isEmpty()) {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
}
private boolean checkItemDimensions(ItemInfo info) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
return (info.cellX + info.spanX) > (int) grid.numColumns ||
(info.cellY + info.spanY) > (int) grid.numRows;
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
/** Clears all the sBg data structures */
private void clearSBgDataStructures() {
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
}
}
/** Returns whether this is an upgradge path */
private boolean loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
int countX = (int) grid.numColumns;
int countY = (int) grid.numRows;
// Make sure the default workspace is loaded, if needed
LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0);
// Check if we need to do any upgrade-path logic
boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb();
synchronized (sBgLock) {
clearSBgDataStructures();
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace()", true);
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI;
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
Launcher.addDumpLog(TAG, "10249126 - Num rows: " + c.getCount(), true);
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
id = c.getLong(idIndex);
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
ComponentName cn = intent.getComponent();
if (cn != null && !isValidPackageComponent(manager, cn)) {
if (!mAppsCanBeOnRemoveableStorage) {
// Log the invalid package, and remove it from the db
Uri uri = LauncherSettings.Favorites.getContentUri(id,
false);
contentResolver.delete(uri, null, null);
Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true);
} else {
// If apps can be on external storage, then we just
// leave them for the user to remove (maybe add
// visual treatment to it)
Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true);
}
continue;
}
} catch (URISyntaxException e) {
Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true);
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.id = id;
info.intent = intent;
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
info.spanX = 1;
info.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(info)) {
Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: "
+ info + ", " + grid.numColumns + "x" + grid.numRows, true);
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
throw new RuntimeException("Unexpected null ShortcutInfo");
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
folderInfo.spanX = 1;
folderInfo.spanY = 1;
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(folderInfo)) {
Log.d(TAG, "Skipped loading out of bounds folder");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.addDumpLog(TAG, log, false);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// Skip loading items that are out of bounds
if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (checkItemDimensions(appWidgetInfo)) {
Log.d(TAG, "Skipped loading out of bounds app widget");
continue;
}
}
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true);
}
}
} finally {
if (c != null) {
c.close();
}
}
// Break early if we've stopped loading
if (mStopped) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace() - Stopped", true);
clearSBgDataStructures();
return false;
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadedOldDb) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - loadedOldDb", true);
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace-loadedOldDb(" + screenId + ")", true);
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
// Update the max item id after we load an old db
long maxItemId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
maxItemId = Math.max(maxItemId, item.id);
}
LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId);
} else {
Launcher.addDumpLog(TAG, "10249126 - loadWorkspace - !loadedOldDb [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext);
for (Integer i : orderedScreens.keySet()) {
Launcher.addDumpLog(TAG, "10249126 - adding to sBgWorkspaceScreens: " + orderedScreens.get(i), true);
sBgWorkspaceScreens.add(orderedScreens.get(i));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - unused screens: " + l, true);
}
Launcher.addDumpLog(TAG, "10249126 - sBgItemsIdMap [" + sWorkerThread.getThreadId() + ", " + Process.myTid() + "]", true);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
Launcher.addDumpLog(TAG, "10249126 - \t" + item.container + ", " + screenId + " - " + unusedScreens.contains(screenId) + " | " + item, true);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
Launcher.addDumpLog(TAG, "10249126 - \t\tRemoving " + screenId, true);
for (Long l : unusedScreens) {
Launcher.addDumpLog(TAG, "10249126 - \t\t\t unused screens: " + l, true);
}
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - pre removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
sBgWorkspaceScreens.removeAll(unusedScreens);
// Dump the sBgWorkspaceScreens
Launcher.addDumpLog(TAG, "10249126 - updateWorkspaceScreenOrder - sBgWorkspaceScreens - post removeAll", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < countY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < countX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
return loadedOldDb;
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
final LauncherAppState app = LauncherAppState.getInstance();
final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = (int) grid.numColumns;
int cellCountY = (int) grid.numRows;
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspaceScreens()", true);
// Dump the orderedScreens
synchronized (sBgLock) {
Launcher.addDumpLog(TAG, "10249126 - orderedScreens", true);
for (Long l : sBgWorkspaceScreens) {
Launcher.addDumpLog(TAG, "10249126\t- " + l, true);
}
}
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) {
Launcher.addDumpLog(TAG, "10249126 - bindWorkspace(" + synchronizeBindPage + ", " + isUpgradePath + ")", true);
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(isUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added);
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, addedInfos, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
// Write all the logs to disk
Launcher.addDumpLog(TAG, "10249126 - PackageUpdatedTask - dumping logs to disk", true);
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.dumpLogsToLocalData(false);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) {
if (cn == null) {
return false;
}
try {
// Skip if the application is disabled
PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
return false;
}
// Check the activity
return (pm.getActivityInfo(cn, 0) != null);
} catch (NameNotFoundException e) {
return false;
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
ComponentName componentName = intent.getComponent();
final ShortcutInfo info = new ShortcutInfo();
if (componentName != null && !isValidPackageComponent(manager, componentName)) {
Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName);
return null;
} else {
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " +
componentName.getPackageName());
}
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
Bitmap icon = null;
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnRemoveableStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
|
diff --git a/comReader/main/gui/ReceiverView.java b/comReader/main/gui/ReceiverView.java
index eb24694..e02905a 100644
--- a/comReader/main/gui/ReceiverView.java
+++ b/comReader/main/gui/ReceiverView.java
@@ -1,329 +1,329 @@
/*
*
*
*/
package gui;
import gui.observer.Observable;
import gui.observer.Observer;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import utilities.Utilities;
import components.Receiver;
/**
* Graphical representation of a <code>Receiver</code> object on the <code>MapPreviewPanel</code>. This class serves as
* a view for <code>Receiver</code> object model. It is added to the <code>MapPreviewPanel</code> when opening the
* <code>AddMapDialog</code> window (if a map already has <code>Receiver</code>s placed on it) and on the press of a
* <code>ReceiverButton</code>.
*
* @see ReceiverButton
* @see AddMapDialog
* @see MapPreviewPanel
* @author Danilo
*/
public class ReceiverView extends JComponent implements Observable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant RECEIVER_ITEM_WIDTH. */
public static final int RECEIVER_ITEM_WIDTH = 30;
/** The Constant RECEIVER_ITEM_HEIGHT. */
public static final int RECEIVER_ITEM_HEIGHT = 30;
/** The Constant LABEL_X_POSITION. */
private static final int LABEL_X_POSITION = 10;
/** The Constant LABEL_Y_POSITION. */
private static final int LABEL_Y_POSITION = 20;
/** The receiver model. */
private Receiver receiver;
/** The image. */
private BufferedImage image;
/** Parent object of type MapPreviewPanel. */
private MapPreviewPanel parent;
/** The observers. */
private List<Observer> observers;
/**
* Instantiates a new <code>ReceiverView</code>.
*
* @param receiver
* Receiver object used as a model
* @param parent
* Parent panel
*/
public ReceiverView(Receiver receiver, MapPreviewPanel parent) {
this.receiver = receiver;
this.parent = parent;
observers = new ArrayList<Observer>();
observers.add(parent);
initializeGui();
}
/**
* Initializes the <code>ReceiverView</code>.
*/
private void initializeGui() {
setSize(RECEIVER_ITEM_WIDTH, RECEIVER_ITEM_HEIGHT);
setPreferredSize(new Dimension(RECEIVER_ITEM_WIDTH, RECEIVER_ITEM_HEIGHT));
setCursor(new Cursor(Cursor.HAND_CURSOR));
addMouseListener(new ReceiverViewMouseListener(this));
addComponentListener(new ReceiverViewComponentListener(this));
setDoubleBuffered(true);
BufferedImage myPicture = (BufferedImage) Utilities.loadImage("images/receiverView" + (int) receiver.getAngle()
+ ".png");
image = Utilities.scaleImageToFitContainer(myPicture, ReceiverView.RECEIVER_ITEM_WIDTH,
ReceiverView.RECEIVER_ITEM_HEIGHT);
setOpaque(true);
}
/**
* Gets the <code>Receiver</code>.
*
* @return <code>Receiver</code> object
*/
public Receiver getReceiver() {
return receiver;
}
/**
* Paint component.
*
* @param g
* <code>Graphics</code> object
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.image, 0, 0, this);
g.drawString("" + receiver.getID(), LABEL_X_POSITION, LABEL_Y_POSITION);
}
/**
* Rotates a <code>Receiver</code> for a specified <code>angle</code>.
*
* @param angle
* <code>double</code> amount to rotate
*/
public void rotate(double angle) {
receiver.setAngle(receiver.getAngle() + angle);
BufferedImage myPicture = null;
try {
- String path = Utilities.class.getResource("images/receiverView" + (int) receiver.getAngle() + ".png")
+ String path = Utilities.class.getResource("/images/receiverView" + (int) receiver.getAngle() + ".png")
.getPath();
myPicture = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
image = Utilities.scaleImageToFitContainer(myPicture, ReceiverView.RECEIVER_ITEM_WIDTH,
ReceiverView.RECEIVER_ITEM_HEIGHT);
this.repaint();
}
/**
* The listener interface for receiving receiverViewComponent events. The class that is interested in processing a
* receiverViewComponent event implements this interface, and the object created with that class is registered with
* a component using the component's <code>addReceiverViewComponentListener</code> method. When the
* receiverViewComponent event occurs, that object's appropriate method is invoked.
*
* @see ReceiverViewComponentEvent
*/
private class ReceiverViewComponentListener implements ComponentListener {
/** The receiver view. */
private ReceiverView receiverView;
/**
* Instantiates a new receiver view component listener.
*
* @param receiverView
* the receiver view
*/
public ReceiverViewComponentListener(ReceiverView receiverView) {
this.receiverView = receiverView;
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
*/
@Override
public void componentResized(ComponentEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
*/
@Override
public void componentMoved(ComponentEvent e) {
parent.focusReceiverView(receiverView);
notifyObservers(receiverView);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
*/
@Override
public void componentShown(ComponentEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
*/
@Override
public void componentHidden(ComponentEvent e) {
}
}
/**
* The listener interface for receiving receiverViewMouse events. The class that is interested in processing a
* receiverViewMouse event implements this interface, and the object created with that class is registered with a
* component using the component's <code>addReceiverViewMouseListener</code> method. When the receiverViewMouse
* event occurs, that object's appropriate method is invoked.
*
* @see ReceiverViewMouseEvent
*/
private class ReceiverViewMouseListener implements MouseListener {
/** The receiver view. */
private ReceiverView receiverView;
/**
* Instantiates a new receiver view mouse listener.
*
* @param receiverView
* the receiver view
*/
public ReceiverViewMouseListener(ReceiverView receiverView) {
this.receiverView = receiverView;
}
/*
* (non-Javadoc)
*
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
@Override
public void mouseClicked(MouseEvent e) {
parent.focusReceiverView(receiverView);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(MouseEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/*
* (non-Javadoc)
*
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(MouseEvent e) {
}
}
/**
* Registers an observer.
*
* @param observer
* <code>Observer</code> object
*/
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
/**
* Unregisters an observer.
*
* @param observer
* <code>Observer</code> object
*/
@Override
public void unregisterObserver(Observer observer) {
if (observers.contains(observer)) {
observers.remove(observer);
}
}
/**
* Notifies observers.
*
* @param observable
* <code>Observable</code> self object. <code>Observer</code>s need <code>Observable</code> object itself
* to track changes.
*/
@Override
public void notifyObservers(Observable observable) {
for (Observer observer : observers) {
observer.update(observable);
}
}
}
| true | true | public void rotate(double angle) {
receiver.setAngle(receiver.getAngle() + angle);
BufferedImage myPicture = null;
try {
String path = Utilities.class.getResource("images/receiverView" + (int) receiver.getAngle() + ".png")
.getPath();
myPicture = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
image = Utilities.scaleImageToFitContainer(myPicture, ReceiverView.RECEIVER_ITEM_WIDTH,
ReceiverView.RECEIVER_ITEM_HEIGHT);
this.repaint();
}
| public void rotate(double angle) {
receiver.setAngle(receiver.getAngle() + angle);
BufferedImage myPicture = null;
try {
String path = Utilities.class.getResource("/images/receiverView" + (int) receiver.getAngle() + ".png")
.getPath();
myPicture = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
image = Utilities.scaleImageToFitContainer(myPicture, ReceiverView.RECEIVER_ITEM_WIDTH,
ReceiverView.RECEIVER_ITEM_HEIGHT);
this.repaint();
}
|
diff --git a/flume-ng-node/src/main/java/org/apache/flume/conf/file/AbstractFileConfigurationProvider.java b/flume-ng-node/src/main/java/org/apache/flume/conf/file/AbstractFileConfigurationProvider.java
index 64f4e355..15ee8adc 100644
--- a/flume-ng-node/src/main/java/org/apache/flume/conf/file/AbstractFileConfigurationProvider.java
+++ b/flume-ng-node/src/main/java/org/apache/flume/conf/file/AbstractFileConfigurationProvider.java
@@ -1,211 +1,210 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flume.conf.file;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.flume.ChannelFactory;
import org.apache.flume.CounterGroup;
import org.apache.flume.SinkFactory;
import org.apache.flume.SourceFactory;
import org.apache.flume.lifecycle.LifecycleState;
import org.apache.flume.node.ConfigurationProvider;
import org.apache.flume.node.nodemanager.NodeConfigurationAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
public abstract class AbstractFileConfigurationProvider implements
ConfigurationProvider {
private final Logger logger = LoggerFactory.getLogger(getClass());
private File file;
private ChannelFactory channelFactory;
private SourceFactory sourceFactory;
private SinkFactory sinkFactory;
private String nodeName;
private NodeConfigurationAware configurationAware;
private LifecycleState lifecycleState;
private ScheduledExecutorService executorService;
private CounterGroup counterGroup;
public AbstractFileConfigurationProvider() {
lifecycleState = LifecycleState.IDLE;
counterGroup = new CounterGroup();
}
@Override
public String toString() {
return "{ file:" + file + " counterGroup:" + counterGroup + " provider:"
+ getClass().getCanonicalName() + " nodeName:" + nodeName + " }";
}
@Override
public void start() {
logger.info("Configuration provider starting");
Preconditions.checkState(file != null,
"The parameter file must not be null");
- executorService = Executors
- .newScheduledThreadPool(1,
+ executorService = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d")
.build());
FileWatcherRunnable fileWatcherRunnable = new FileWatcherRunnable();
fileWatcherRunnable.file = file;
fileWatcherRunnable.counterGroup = counterGroup;
- executorService.scheduleAtFixedRate(fileWatcherRunnable, 0, 30,
+ executorService.scheduleWithFixedDelay(fileWatcherRunnable, 0, 30,
TimeUnit.SECONDS);
lifecycleState = LifecycleState.START;
logger.debug("Configuration provider started");
}
@Override
public void stop() {
logger.info("Configuration provider stopping");
executorService.shutdown();
while (!executorService.isTerminated()) {
try {
logger.debug("Waiting for file watcher to terminate");
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.debug("Interrupted while waiting for file watcher to terminate");
Thread.currentThread().interrupt();
}
}
lifecycleState = LifecycleState.STOP;
logger.debug("Configuration provider stopped");
}
protected abstract void load();
// Synchronized wrapper to call the load function
private synchronized void doLoad() {
Preconditions
.checkState(nodeName != null,
"No node name specified - Unable to determine what part of the config to load");
Preconditions.checkState(channelFactory != null,
"No channel factory configured");
Preconditions.checkState(sourceFactory != null,
"No source factory configured");
Preconditions.checkState(sinkFactory != null, "No sink factory configured");
load();
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
@Override
public LifecycleState getLifecycleState() {
return lifecycleState;
}
public ChannelFactory getChannelFactory() {
return channelFactory;
}
public void setChannelFactory(ChannelFactory channelFactory) {
this.channelFactory = channelFactory;
}
public SourceFactory getSourceFactory() {
return sourceFactory;
}
public void setSourceFactory(SourceFactory sourceFactory) {
this.sourceFactory = sourceFactory;
}
public SinkFactory getSinkFactory() {
return sinkFactory;
}
public void setSinkFactory(SinkFactory sinkFactory) {
this.sinkFactory = sinkFactory;
}
public NodeConfigurationAware getConfigurationAware() {
return configurationAware;
}
public void setConfigurationAware(NodeConfigurationAware configurationAware) {
this.configurationAware = configurationAware;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public class FileWatcherRunnable implements Runnable {
private File file;
private CounterGroup counterGroup;
private long lastChange;
@Override
public void run() {
logger.debug("Checking file:{} for changes", file);
counterGroup.incrementAndGet("file.checks");
long lastModified = file.lastModified();
if (lastModified > lastChange) {
logger.info("Reloading configuration file:{}", file);
counterGroup.incrementAndGet("file.loads");
lastChange = lastModified;
try {
doLoad();
} catch (Exception e) {
logger.error("Failed to load configuration data. Exception follows.",
e);
}
}
}
}
}
| false | true | public void start() {
logger.info("Configuration provider starting");
Preconditions.checkState(file != null,
"The parameter file must not be null");
executorService = Executors
.newScheduledThreadPool(1,
new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d")
.build());
FileWatcherRunnable fileWatcherRunnable = new FileWatcherRunnable();
fileWatcherRunnable.file = file;
fileWatcherRunnable.counterGroup = counterGroup;
executorService.scheduleAtFixedRate(fileWatcherRunnable, 0, 30,
TimeUnit.SECONDS);
lifecycleState = LifecycleState.START;
logger.debug("Configuration provider started");
}
| public void start() {
logger.info("Configuration provider starting");
Preconditions.checkState(file != null,
"The parameter file must not be null");
executorService = Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d")
.build());
FileWatcherRunnable fileWatcherRunnable = new FileWatcherRunnable();
fileWatcherRunnable.file = file;
fileWatcherRunnable.counterGroup = counterGroup;
executorService.scheduleWithFixedDelay(fileWatcherRunnable, 0, 30,
TimeUnit.SECONDS);
lifecycleState = LifecycleState.START;
logger.debug("Configuration provider started");
}
|
diff --git a/working-capital/src/module/workingCapital/domain/WorkingCapitalProcess.java b/working-capital/src/module/workingCapital/domain/WorkingCapitalProcess.java
index 3797de23..b0bd03d9 100644
--- a/working-capital/src/module/workingCapital/domain/WorkingCapitalProcess.java
+++ b/working-capital/src/module/workingCapital/domain/WorkingCapitalProcess.java
@@ -1,253 +1,256 @@
package module.workingCapital.domain;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import module.workflow.activities.ActivityInformation;
import module.workflow.activities.WorkflowActivity;
import module.workflow.domain.ProcessFile;
import module.workflow.domain.WorkflowProcess;
import module.workflow.domain.utils.WorkflowCommentCounter;
import module.workflow.util.HasPresentableProcessState;
import module.workflow.util.PresentableProcessState;
import module.workflow.widgets.UnreadCommentsWidget;
import module.workingCapital.domain.activity.AcceptResponsabilityForWorkingCapitalActivity;
import module.workingCapital.domain.activity.AllocateFundsActivity;
import module.workingCapital.domain.activity.ApproveActivity;
import module.workingCapital.domain.activity.ApproveWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.AuthorizeActivity;
import module.workingCapital.domain.activity.CancelReenforceWorkingCapitalInitializationActivity;
import module.workingCapital.domain.activity.CancelWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.CancelWorkingCapitalInitializationActivity;
import module.workingCapital.domain.activity.ChangeWorkingCapitalAccountingUnitActivity;
import module.workingCapital.domain.activity.CorrectWorkingCapitalAcquisitionClassificationActivity;
import module.workingCapital.domain.activity.EditInitializationActivity;
import module.workingCapital.domain.activity.EditWorkingCapitalActivity;
import module.workingCapital.domain.activity.ExceptionalCapitalRestitutionActivity;
import module.workingCapital.domain.activity.PayCapitalActivity;
import module.workingCapital.domain.activity.ReenforceWorkingCapitalInitializationActivity;
import module.workingCapital.domain.activity.RegisterCapitalRefundActivity;
import module.workingCapital.domain.activity.RegisterWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.RejectVerifyWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.RejectWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.RejectWorkingCapitalInitializationActivity;
import module.workingCapital.domain.activity.RequestCapitalActivity;
import module.workingCapital.domain.activity.RequestCapitalRestitutionActivity;
import module.workingCapital.domain.activity.SubmitForValidationActivity;
import module.workingCapital.domain.activity.TerminateWorkingCapitalActivity;
import module.workingCapital.domain.activity.UnAllocateFundsActivity;
import module.workingCapital.domain.activity.UnApproveActivity;
import module.workingCapital.domain.activity.UnApproveWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.UnAuthorizeActivity;
import module.workingCapital.domain.activity.UnRequestCapitalActivity;
import module.workingCapital.domain.activity.UnRequestCapitalRestitutionActivity;
import module.workingCapital.domain.activity.UnTerminateWorkingCapitalActivity;
import module.workingCapital.domain.activity.UnVerifyActivity;
import module.workingCapital.domain.activity.UnVerifyWorkingCapitalAcquisitionActivity;
import module.workingCapital.domain.activity.UndoCancelOrRejectWorkingCapitalInitializationActivity;
import module.workingCapital.domain.activity.VerifyActivity;
import module.workingCapital.domain.activity.VerifyWorkingCapitalAcquisitionActivity;
import myorg.applicationTier.Authenticate.UserView;
import myorg.domain.RoleType;
import myorg.domain.User;
import myorg.domain.VirtualHost;
import myorg.util.BundleUtil;
import myorg.util.ClassNameBundle;
import pt.ist.emailNotifier.domain.Email;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
@ClassNameBundle(key = "label.module.workingCapital", bundle = "resources/WorkingCapitalResources")
public class WorkingCapitalProcess extends WorkingCapitalProcess_Base implements HasPresentableProcessState {
public static final Comparator<WorkingCapitalProcess> COMPARATOR_BY_UNIT_NAME = new Comparator<WorkingCapitalProcess>() {
@Override
public int compare(WorkingCapitalProcess o1, WorkingCapitalProcess o2) {
final int c = Collator.getInstance().compare(o1.getWorkingCapital().getUnit().getName(),
o2.getWorkingCapital().getUnit().getName());
return c == 0 ? o2.hashCode() - o1.hashCode() : c;
}
};
private static final List<WorkflowActivity<? extends WorkflowProcess, ? extends ActivityInformation>> activities;
static {
final List<WorkflowActivity<? extends WorkflowProcess, ? extends ActivityInformation>> activitiesAux = new ArrayList<WorkflowActivity<? extends WorkflowProcess, ? extends ActivityInformation>>();
activitiesAux.add(new AcceptResponsabilityForWorkingCapitalActivity());
activitiesAux.add(new CancelWorkingCapitalInitializationActivity());
activitiesAux.add(new EditInitializationActivity());
activitiesAux.add(new ChangeWorkingCapitalAccountingUnitActivity());
activitiesAux.add(new ApproveActivity());
activitiesAux.add(new UnApproveActivity());
activitiesAux.add(new VerifyActivity());
activitiesAux.add(new UnVerifyActivity());
activitiesAux.add(new AllocateFundsActivity());
activitiesAux.add(new UnAllocateFundsActivity());
activitiesAux.add(new AuthorizeActivity());
activitiesAux.add(new UnAuthorizeActivity());
activitiesAux.add(new RejectWorkingCapitalInitializationActivity());
activitiesAux.add(new UndoCancelOrRejectWorkingCapitalInitializationActivity());
activitiesAux.add(new RequestCapitalActivity());
activitiesAux.add(new UnRequestCapitalActivity());
activitiesAux.add(new PayCapitalActivity());
activitiesAux.add(new RegisterWorkingCapitalAcquisitionActivity());
activitiesAux.add(new CancelWorkingCapitalAcquisitionActivity());
activitiesAux.add(new EditWorkingCapitalActivity());
activitiesAux.add(new CorrectWorkingCapitalAcquisitionClassificationActivity());
activitiesAux.add(new ApproveWorkingCapitalAcquisitionActivity());
activitiesAux.add(new RejectWorkingCapitalAcquisitionActivity());
activitiesAux.add(new UnApproveWorkingCapitalAcquisitionActivity());
activitiesAux.add(new VerifyWorkingCapitalAcquisitionActivity());
activitiesAux.add(new RejectVerifyWorkingCapitalAcquisitionActivity());
activitiesAux.add(new UnVerifyWorkingCapitalAcquisitionActivity());
activitiesAux.add(new SubmitForValidationActivity());
activitiesAux.add(new RequestCapitalRestitutionActivity());
activitiesAux.add(new UnRequestCapitalRestitutionActivity());
activitiesAux.add(new TerminateWorkingCapitalActivity());
activitiesAux.add(new UnTerminateWorkingCapitalActivity());
activitiesAux.add(new RegisterCapitalRefundActivity());
activitiesAux.add(new ReenforceWorkingCapitalInitializationActivity());
activitiesAux.add(new CancelReenforceWorkingCapitalInitializationActivity());
activitiesAux.add(new ExceptionalCapitalRestitutionActivity());
activities = Collections.unmodifiableList(activitiesAux);
UnreadCommentsWidget.register(new WorkflowCommentCounter(WorkingCapitalProcess.class));
}
public WorkingCapitalProcess() {
super();
}
public WorkingCapitalProcess(final WorkingCapital workingCapital) {
this();
setWorkingCapital(workingCapital);
}
@Override
public <T extends WorkflowActivity<? extends WorkflowProcess, ? extends ActivityInformation>> List<T> getActivities() {
return (List) activities;
}
@Override
public boolean isActive() {
return true;
}
@Override
public boolean isAccessible(final User user) {
final WorkingCapital workingCapital = getWorkingCapital();
return user != null
&& user.hasPerson()
&& (user.hasRoleType(RoleType.MANAGER)
|| (user.hasExpenditurePerson() && ExpenditureTrackingSystem
.isAcquisitionsProcessAuditorGroupMember(user))
|| (workingCapital.hasMovementResponsible() && user.getPerson() == workingCapital
.getMovementResponsible()) || workingCapital.isRequester(user)
|| workingCapital.getWorkingCapitalSystem().isManagementMember(user)
|| workingCapital.isAnyAccountingEmployee(user) || workingCapital.isAccountingResponsible(user)
|| workingCapital.isTreasuryMember(user) || workingCapital.isResponsibleFor(user));
}
public boolean isPendingAproval(final User user) {
return getWorkingCapital().isPendingAproval(user);
}
public boolean isPendingDirectAproval(final User user) {
return getWorkingCapital().isPendingDirectAproval(user);
}
public boolean isPendingVerification(User user) {
return getWorkingCapital().isPendingVerification(user);
}
public boolean isPendingFundAllocation(User user) {
return getWorkingCapital().isPendingFundAllocation(user);
}
public boolean isPendingAuthorization(User user) {
return getWorkingCapital().isPendingAuthorization(user);
}
@Override
public User getProcessCreator() {
return getWorkingCapital().getRequester();
}
@Override
public void notifyUserDueToComment(final User user, final String comment) {
List<String> toAddress = new ArrayList<String>();
toAddress.clear();
final String email = user.getExpenditurePerson().getEmail();
if (email != null) {
toAddress.add(email);
final User loggedUser = UserView.getCurrentUser();
final WorkingCapital workingCapital = getWorkingCapital();
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
new Email(virtualHost.getApplicationSubTitle().getContent(), virtualHost.getSystemEmailAddress(), new String[] {},
toAddress, Collections.EMPTY_LIST, Collections.EMPTY_LIST, BundleUtil.getFormattedStringFromResourceBundle(
"resources/WorkingCapitalResources", "label.email.commentCreated.subject", workingCapital.getUnit()
.getPresentationName(), workingCapital.getWorkingCapitalYear().getYear().toString()),
BundleUtil.getFormattedStringFromResourceBundle("resources/WorkingCapitalResources",
- "label.email.commentCreated.body", loggedUser.getPerson().getName(), workingCapital.getUnit()
- .getPresentationName(), workingCapital.getWorkingCapitalYear().getYear().toString(), comment));
+ "label.email.commentCreated.body",
+ loggedUser.getPerson().getName(),
+ workingCapital.getUnit().getPresentationName(),
+ workingCapital.getWorkingCapitalYear().getYear().toString(), comment),
+ VirtualHost.getVirtualHostForThread().getHostname());
}
}
@Override
public List<Class<? extends ProcessFile>> getAvailableFileTypes() {
List<Class<? extends ProcessFile>> availableFileTypes = super.getAvailableFileTypes();
availableFileTypes.add(WorkingCapitalInvoiceFile.class);
return availableFileTypes;
}
@Override
public List<Class<? extends ProcessFile>> getUploadableFileTypes() {
return super.getAvailableFileTypes();
}
public void submitAcquisitionsForValidation() {
final WorkingCapital workingCapital = getWorkingCapital();
workingCapital.submitAcquisitionsForValidation();
}
public void unsubmitAcquisitionsForValidation() {
final WorkingCapital workingCapital = getWorkingCapital();
workingCapital.unsubmitAcquisitionsForValidation();
}
@Override
public List<Class<? extends ProcessFile>> getDisplayableFileTypes() {
final List<Class<? extends ProcessFile>> fileTypes = new ArrayList<Class<? extends ProcessFile>>();
fileTypes.addAll(super.getDisplayableFileTypes());
fileTypes.remove(WorkingCapitalInvoiceFile.class);
return fileTypes;
}
@Override
public boolean isTicketSupportAvailable() {
return false;
}
@Override
public List<? extends PresentableProcessState> getAvailablePresentableStates() {
return Arrays.asList(WorkingCapitalProcessState.values());
}
@Override
public PresentableProcessState getPresentableAcquisitionProcessState() {
return getWorkingCapital().getPresentableAcquisitionProcessState();
}
@Override
public boolean isConnectedToCurrentHost() {
return getWorkingCapitalSystem() == WorkingCapitalSystem.getInstanceForCurrentHost();
}
public WorkingCapitalSystem getWorkingCapitalSystem() {
return getWorkingCapital().getWorkingCapitalSystem();
}
}
| true | true | public void notifyUserDueToComment(final User user, final String comment) {
List<String> toAddress = new ArrayList<String>();
toAddress.clear();
final String email = user.getExpenditurePerson().getEmail();
if (email != null) {
toAddress.add(email);
final User loggedUser = UserView.getCurrentUser();
final WorkingCapital workingCapital = getWorkingCapital();
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
new Email(virtualHost.getApplicationSubTitle().getContent(), virtualHost.getSystemEmailAddress(), new String[] {},
toAddress, Collections.EMPTY_LIST, Collections.EMPTY_LIST, BundleUtil.getFormattedStringFromResourceBundle(
"resources/WorkingCapitalResources", "label.email.commentCreated.subject", workingCapital.getUnit()
.getPresentationName(), workingCapital.getWorkingCapitalYear().getYear().toString()),
BundleUtil.getFormattedStringFromResourceBundle("resources/WorkingCapitalResources",
"label.email.commentCreated.body", loggedUser.getPerson().getName(), workingCapital.getUnit()
.getPresentationName(), workingCapital.getWorkingCapitalYear().getYear().toString(), comment));
}
}
| public void notifyUserDueToComment(final User user, final String comment) {
List<String> toAddress = new ArrayList<String>();
toAddress.clear();
final String email = user.getExpenditurePerson().getEmail();
if (email != null) {
toAddress.add(email);
final User loggedUser = UserView.getCurrentUser();
final WorkingCapital workingCapital = getWorkingCapital();
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
new Email(virtualHost.getApplicationSubTitle().getContent(), virtualHost.getSystemEmailAddress(), new String[] {},
toAddress, Collections.EMPTY_LIST, Collections.EMPTY_LIST, BundleUtil.getFormattedStringFromResourceBundle(
"resources/WorkingCapitalResources", "label.email.commentCreated.subject", workingCapital.getUnit()
.getPresentationName(), workingCapital.getWorkingCapitalYear().getYear().toString()),
BundleUtil.getFormattedStringFromResourceBundle("resources/WorkingCapitalResources",
"label.email.commentCreated.body",
loggedUser.getPerson().getName(),
workingCapital.getUnit().getPresentationName(),
workingCapital.getWorkingCapitalYear().getYear().toString(), comment),
VirtualHost.getVirtualHostForThread().getHostname());
}
}
|
diff --git a/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java b/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java
index 7a94c5b30..b4f970408 100644
--- a/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java
+++ b/src/commons/org/codehaus/groovy/grails/validation/RangeConstraint.java
@@ -1,87 +1,87 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.validation;
import groovy.lang.Range;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.springframework.validation.Errors;
/**
* A Constraint that validates a range
*
* @author Graeme Rocher
* @since 0.4
* <p/>
* Created: Jan 19, 2007
* Time: 8:17:32 AM
*/
class RangeConstraint extends AbstractConstraint {
Range range;
/**
* @return Returns the range.
*/
public Range getRange() {
return range;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.validation.Constraint#supports(java.lang.Class)
*/
public boolean supports(Class type) {
return type != null && (Comparable.class.isAssignableFrom(type) ||
GrailsClassUtils.isAssignableOrConvertibleFrom(Number.class, type));
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.validation.ConstrainedProperty.AbstractConstraint#setParameter(java.lang.Object)
*/
public void setParameter(Object constraintParameter) {
if(!(constraintParameter instanceof Range))
throw new IllegalArgumentException("Parameter for constraint ["+ConstrainedProperty.RANGE_CONSTRAINT+"] of property ["+constraintPropertyName+"] of class ["+constraintOwningClass+"] must be a of type [groovy.lang.Range]");
this.range = (Range)constraintParameter;
super.setParameter(constraintParameter);
}
public String getName() {
return ConstrainedProperty.RANGE_CONSTRAINT;
}
protected void processValidate(Object target, Object propertyValue, Errors errors) {
if(!this.range.contains(propertyValue)) {
Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() };
Comparable from = range.getFrom();
Comparable to = range.getTo();
if(from instanceof Number && propertyValue instanceof Number) {
// Upgrade the numbers to Long, so all integer types can be compared.
- from = ((Number) from).longValue();
- to = ((Number) to).longValue();
- propertyValue = ((Number) propertyValue).longValue();
+ from = new Long(((Number) from).longValue());
+ to = new Long(((Number) to).longValue());
+ propertyValue = new Long(((Number) propertyValue).longValue());
}
if(from.compareTo(propertyValue) > 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args );
}
else if (to.compareTo(propertyValue) < 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args );
}
}
}
}
| true | true | protected void processValidate(Object target, Object propertyValue, Errors errors) {
if(!this.range.contains(propertyValue)) {
Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() };
Comparable from = range.getFrom();
Comparable to = range.getTo();
if(from instanceof Number && propertyValue instanceof Number) {
// Upgrade the numbers to Long, so all integer types can be compared.
from = ((Number) from).longValue();
to = ((Number) to).longValue();
propertyValue = ((Number) propertyValue).longValue();
}
if(from.compareTo(propertyValue) > 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args );
}
else if (to.compareTo(propertyValue) < 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args );
}
}
}
| protected void processValidate(Object target, Object propertyValue, Errors errors) {
if(!this.range.contains(propertyValue)) {
Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue, range.getFrom(), range.getTo() };
Comparable from = range.getFrom();
Comparable to = range.getTo();
if(from instanceof Number && propertyValue instanceof Number) {
// Upgrade the numbers to Long, so all integer types can be compared.
from = new Long(((Number) from).longValue());
to = new Long(((Number) to).longValue());
propertyValue = new Long(((Number) propertyValue).longValue());
}
if(from.compareTo(propertyValue) > 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOSMALL_SUFFIX,args );
}
else if (to.compareTo(propertyValue) < 0) {
super.rejectValue(target,errors,ConstrainedProperty.DEFAULT_INVALID_RANGE_MESSAGE_CODE, ConstrainedProperty.RANGE_CONSTRAINT + ConstrainedProperty.TOOBIG_SUFFIX,args );
}
}
}
|
diff --git a/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java b/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
index ab4b12a..903782f 100644
--- a/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
+++ b/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
@@ -1,98 +1,98 @@
package me.shanked.nicatronTg.darklight.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
/**
* Generates an html file using the template and current stats from the engine
*
* @author Isaac Grant
* @author Lucas Nicodemus
* @version .1
*
*/
public class VulnerabilityOutputGenerator {
private HashMap<String, String> fixedIssues = new HashMap<String, String>();
/**
*
* @return The fixedIssues HashMap used to format the template
*/
public HashMap<String, String> getFixedIssues() {
return fixedIssues;
}
/**
* Set the fixedIssues HashMap that the template is formatted with
* @param fixedIssues HashMap to format the template with
*/
public void setFixedIssues(HashMap<String, String> fixedIssues) {
this.fixedIssues = fixedIssues;
}
public VulnerabilityOutputGenerator() {
}
/**
* Format the template with the given issues and issue count
* @throws InvalidTemplateException The template does not contain the require flags ([fixedcount] and [issues])
* @throws IOException Template does not exist, or error reading/writing formatted template
*/
public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
- File f = new File(templatePath);
+ File f = new File(new File("."), templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
template += scanner.nextLine();
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
String tempString = "<li class=\"span10 offset2\">" + key + " - " + fixedIssues.get(key) + "</li>";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
- File outputFile = new File(outputPath);
+ File outputFile = new File(new File("."), outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
class InvalidTemplateException extends Exception {
private static final long serialVersionUID = 8843494291724959640L;
public InvalidTemplateException() { }
public InvalidTemplateException(String msg) {
super(msg);
}
}
}
| false | true | public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
File f = new File(templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
template += scanner.nextLine();
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
String tempString = "<li class=\"span10 offset2\">" + key + " - " + fixedIssues.get(key) + "</li>";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
File outputFile = new File(outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
| public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
File f = new File(new File("."), templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
template += scanner.nextLine();
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
String tempString = "<li class=\"span10 offset2\">" + key + " - " + fixedIssues.get(key) + "</li>";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
File outputFile = new File(new File("."), outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
|
diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java
index 8c8572635..2b1b89c72 100644
--- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java
+++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java
@@ -1,89 +1,91 @@
package org.jclouds.rackspace.cloudservers.compute.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rackspace.cloudservers.domain.Addresses;
import org.jclouds.rackspace.cloudservers.domain.Server;
import org.jclouds.rackspace.cloudservers.domain.ServerStatus;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "cloudservers.ServerToNodeMetadataTest")
public class ServerToNodeMetadataTest {
@SuppressWarnings("unchecked")
@Test
public void testApplySetsTagFromNameAndSetsMetadata() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = createMock(Map.class);
Map<String, org.jclouds.compute.domain.Image> images = createMock(Map.class);
Server server = createMock(Server.class);
expect(server.getId()).andReturn(10000).atLeastOnce();
expect(server.getName()).andReturn("adriancole-cloudservers-ea3").atLeastOnce();
+ expect(server.getHostId()).andReturn("AHOST").atLeastOnce();
expect(server.getMetadata()).andReturn(ImmutableMap.<String, String> of()).atLeastOnce();
expect(server.getStatus()).andReturn(ServerStatus.ACTIVE).atLeastOnce();
expect(serverStateToNodeState.get(ServerStatus.ACTIVE)).andReturn(NodeState.RUNNING);
- Location location = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
+ Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
+ Location location = new LocationImpl(LocationScope.HOST, "AHOST", "AHOST", provider);
Addresses addresses = createMock(Addresses.class);
expect(server.getAddresses()).andReturn(addresses).atLeastOnce();
Set<InetAddress> publicAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 12,
10, 10, 1 }));
Set<InetAddress> privateAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 10,
10, 10, 1 }));
expect(addresses.getPublicAddresses()).andReturn(publicAddresses);
expect(addresses.getPrivateAddresses()).andReturn(privateAddresses);
expect(server.getImageId()).andReturn(2000).atLeastOnce();
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
expect(images.get("2000")).andReturn(jcImage);
replay(addresses);
replay(serverStateToNodeState);
replay(server);
replay(images);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, images,
- location);
+ provider);
NodeMetadata metadata = parser.apply(server);
assertEquals(metadata.getLocation(), location);
assertEquals(metadata.getImage(), jcImage);
assert metadata.getUserMetadata() != null;
assertEquals(metadata.getTag(), "cloudservers");
assertEquals(metadata.getCredentials(), null);
assertEquals(metadata.getPrivateAddresses(), privateAddresses);
assertEquals(metadata.getPublicAddresses(), publicAddresses);
verify(addresses);
verify(serverStateToNodeState);
verify(server);
verify(images);
}
}
| false | true | public void testApplySetsTagFromNameAndSetsMetadata() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = createMock(Map.class);
Map<String, org.jclouds.compute.domain.Image> images = createMock(Map.class);
Server server = createMock(Server.class);
expect(server.getId()).andReturn(10000).atLeastOnce();
expect(server.getName()).andReturn("adriancole-cloudservers-ea3").atLeastOnce();
expect(server.getMetadata()).andReturn(ImmutableMap.<String, String> of()).atLeastOnce();
expect(server.getStatus()).andReturn(ServerStatus.ACTIVE).atLeastOnce();
expect(serverStateToNodeState.get(ServerStatus.ACTIVE)).andReturn(NodeState.RUNNING);
Location location = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
Addresses addresses = createMock(Addresses.class);
expect(server.getAddresses()).andReturn(addresses).atLeastOnce();
Set<InetAddress> publicAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 12,
10, 10, 1 }));
Set<InetAddress> privateAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 10,
10, 10, 1 }));
expect(addresses.getPublicAddresses()).andReturn(publicAddresses);
expect(addresses.getPrivateAddresses()).andReturn(privateAddresses);
expect(server.getImageId()).andReturn(2000).atLeastOnce();
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
expect(images.get("2000")).andReturn(jcImage);
replay(addresses);
replay(serverStateToNodeState);
replay(server);
replay(images);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, images,
location);
NodeMetadata metadata = parser.apply(server);
assertEquals(metadata.getLocation(), location);
assertEquals(metadata.getImage(), jcImage);
assert metadata.getUserMetadata() != null;
assertEquals(metadata.getTag(), "cloudservers");
assertEquals(metadata.getCredentials(), null);
assertEquals(metadata.getPrivateAddresses(), privateAddresses);
assertEquals(metadata.getPublicAddresses(), publicAddresses);
verify(addresses);
verify(serverStateToNodeState);
verify(server);
verify(images);
}
| public void testApplySetsTagFromNameAndSetsMetadata() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = createMock(Map.class);
Map<String, org.jclouds.compute.domain.Image> images = createMock(Map.class);
Server server = createMock(Server.class);
expect(server.getId()).andReturn(10000).atLeastOnce();
expect(server.getName()).andReturn("adriancole-cloudservers-ea3").atLeastOnce();
expect(server.getHostId()).andReturn("AHOST").atLeastOnce();
expect(server.getMetadata()).andReturn(ImmutableMap.<String, String> of()).atLeastOnce();
expect(server.getStatus()).andReturn(ServerStatus.ACTIVE).atLeastOnce();
expect(serverStateToNodeState.get(ServerStatus.ACTIVE)).andReturn(NodeState.RUNNING);
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
Location location = new LocationImpl(LocationScope.HOST, "AHOST", "AHOST", provider);
Addresses addresses = createMock(Addresses.class);
expect(server.getAddresses()).andReturn(addresses).atLeastOnce();
Set<InetAddress> publicAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 12,
10, 10, 1 }));
Set<InetAddress> privateAddresses = ImmutableSet.of(InetAddress.getByAddress(new byte[] { 10,
10, 10, 1 }));
expect(addresses.getPublicAddresses()).andReturn(publicAddresses);
expect(addresses.getPrivateAddresses()).andReturn(privateAddresses);
expect(server.getImageId()).andReturn(2000).atLeastOnce();
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
expect(images.get("2000")).andReturn(jcImage);
replay(addresses);
replay(serverStateToNodeState);
replay(server);
replay(images);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, images,
provider);
NodeMetadata metadata = parser.apply(server);
assertEquals(metadata.getLocation(), location);
assertEquals(metadata.getImage(), jcImage);
assert metadata.getUserMetadata() != null;
assertEquals(metadata.getTag(), "cloudservers");
assertEquals(metadata.getCredentials(), null);
assertEquals(metadata.getPrivateAddresses(), privateAddresses);
assertEquals(metadata.getPublicAddresses(), publicAddresses);
verify(addresses);
verify(serverStateToNodeState);
verify(server);
verify(images);
}
|
diff --git a/plugins/org.eclipse.mylyn.docs.intent.collab.ide/src/org/eclipse/mylyn/docs/intent/collab/ide/repository/WorkspaceRepository.java b/plugins/org.eclipse.mylyn.docs.intent.collab.ide/src/org/eclipse/mylyn/docs/intent/collab/ide/repository/WorkspaceRepository.java
index 327be523..9b4b2e8f 100644
--- a/plugins/org.eclipse.mylyn.docs.intent.collab.ide/src/org/eclipse/mylyn/docs/intent/collab/ide/repository/WorkspaceRepository.java
+++ b/plugins/org.eclipse.mylyn.docs.intent.collab.ide/src/org/eclipse/mylyn/docs/intent/collab/ide/repository/WorkspaceRepository.java
@@ -1,374 +1,373 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.docs.intent.collab.ide.repository;
import com.google.common.base.Predicate;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage.Registry;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.impl.InternalTransactionalEditingDomain;
import org.eclipse.mylyn.docs.intent.collab.handlers.RepositoryClient;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.RepositoryAdapter;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.RepositoryStructurer;
import org.eclipse.mylyn.docs.intent.collab.ide.adapters.WorkspaceAdapter;
import org.eclipse.mylyn.docs.intent.collab.repository.Repository;
import org.eclipse.mylyn.docs.intent.collab.repository.RepositoryConnectionException;
/**
* Representation of a Workspace as a repository.
*
* @author <a href="mailto:[email protected]">Alex Lagarde</a>
*/
public class WorkspaceRepository implements Repository {
/**
* The default extension for any element stored on the repository.
*/
private static final String WORKSPACE_RESOURCE_EXTENSION = "repomodel";
/**
* Represents this repository configuration.
*/
private WorkspaceConfig workspaceConfig;
/**
* Session that will notify any listening entities about changes on Workspace resources corresponding to
* repository resources.
*/
private WorkspaceSession session;
/**
* Indicates if the repository resource set has been initialized.
*/
private boolean isResourceSetLoaded;
/**
* The repository editing domain.
*/
private TransactionalEditingDomain editingDomain;
/**
* The repository structurer.
*/
private RepositoryStructurer repositoryStructurer;
/**
* Used to determine if a resource can be unloaded: if the root has one of this unloadableTypes, then it
* will be unloaded.
*/
private EClass[] unloadableTypes;
/**
* WorkspaceRepository constructor.
*
* @param workspaceConfig
* this repository configuration
* @param unloadableTypes
* the list of types which cannot be unloaded
*/
public WorkspaceRepository(WorkspaceConfig workspaceConfig, EClass... unloadableTypes) {
this.unloadableTypes = unloadableTypes;
this.workspaceConfig = workspaceConfig;
this.editingDomain = TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain();
isResourceSetLoaded = false;
}
/**
* Initializes the resource set using the repository content ; if the repository content is empty, creates
* all the declared indexes.
*
* @throws CoreException
* it the resourceSet cannot be initialized
*/
private void initializeResourceSet() throws CoreException {
// We first get the project on which the repository is defined
IProject project = workspaceConfig.getProject();
if (!project.exists()) {
project.create(null);
}
if (!project.isOpen()) {
project.open(null);
}
IFolder folder = project.getFolder(workspaceConfig.getRepositoryRelativePath());
// We created a WorkspaceRepositoryLoader using the indexPathList
WorkspaceRepositoryLoader loader = new WorkspaceRepositoryLoader(this, this.getWorkspaceConfig()
.getIndexesPathList());
// If the repository folder exists
if (folder.exists()) {
// We load the resourceSet
loader.loadResourceSet();
} else {
// If the repository folder doesn't exist
// We create it
folder.create(IResource.NONE, true, null);
// And use the RepositoryLoader to initialize the resource set with empty content
- // loader.loadResourceSet();
- // loader.createResourceSet();
+ loader.loadResourceSet();
}
isResourceSetLoaded = true;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#register(org.eclipse.mylyn.docs.intent.collab.handlers.RepositoryClient)
*/
public void register(RepositoryClient client) {
// No need to register
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#unregister(org.eclipse.mylyn.docs.intent.collab.handlers.RepositoryClient)
*/
public void unregister(RepositoryClient client) {
// No need to unregister
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#getOrCreateSession()
*/
public synchronized Object getOrCreateSession() throws RepositoryConnectionException {
// We first initialize the resource set if needed
if (!isResourceSetLoaded) {
try {
initializeResourceSet();
} catch (CoreException e) {
throw new RepositoryConnectionException(e.getMessage());
}
}
if (this.session == null) {
// Creation of a Workspace session that will send notifications when the workspace's resources
// corresponding to repository resources change
this.session = new WorkspaceSession(this);
IWorkspace workspace = ResourcesPlugin.getWorkspace();
workspace.addResourceChangeListener(session);
}
return this.session;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#closeSession()
*/
public synchronized void closeSession() throws RepositoryConnectionException {
if (this.session != null) {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(session);
this.session.close();
this.session = null;
}
// If a transaction is being executed, we abort it
if (((InternalTransactionalEditingDomain)this.editingDomain).getActiveTransaction() != null) {
((InternalTransactionalEditingDomain)this.editingDomain).getActiveTransaction().abort(
Status.CANCEL_STATUS);
}
this.editingDomain.dispose();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#getPackageRegistry()
*/
public Registry getPackageRegistry() throws RepositoryConnectionException {
// Return the resourceset's package registry
return getResourceSet().getPackageRegistry();
}
// ---- SPECIFIC BEHAVIORS
/**
* Indicates if the given path represents a location in the repository.
*
* @param path
* the path to study
* @return true if the given path represents a location in the repository, false otherwise
*/
public boolean isInRepositoryPath(String path) {
return path.startsWith(this.workspaceConfig.getRepositoryRelativePath());
}
/**
* Indicates if the given resource is included in the given path.
*
* @param path
* is the path
* @param resource
* the resource to determine if it's included in the given path
* @return true if the resource's associated path starts with or is equals to the given path, false
* otherwise
*/
public boolean isIncludedInPath(String path, Resource resource) {
// We first get the complete URI of the given path
URI uriPath = getURIMatchingPath(path);
// We compare the two URI
return resource.getURI().toString().startsWith(uriPath.toString());
}
/**
* Returns the Repository URI corresponding to the given path.
* <p>
* The complete path is calculated by prefixing the given path by this repository path and postfixing it
* by the default file extension.
* </p>
*
* @param path
* is the path
* @return the Repository URI corresponding to the given path
*/
public URI getURIMatchingPath(String path) {
String completePath = this.getWorkspaceConfig().getRepositoryAbsolutePath() + path;
// If the path don't ends with '/' (i.e isn't a folder), we add the file extension
if (shouldHaveWorkspaceResourceExtension(completePath)) {
completePath += "." + WORKSPACE_RESOURCE_EXTENSION;
}
completePath = completePath.trim();
URI uri = URI.createPlatformResourceURI(completePath, false);
return uri;
}
/**
* Indicates if the Repository resource located at the given path should be association with the
* {@link WorkspaceRepository#WORKSPACE_RESOURCE_EXTENSION} extension.
*
* @param path
* the path of the Repository resource
* @return true if the Repository resource located at the given path should be association with the
* {@link WorkspaceRepository#WORKSPACE_RESOURCE_EXTENSION} extension, false otherwise
*/
public boolean shouldHaveWorkspaceResourceExtension(String path) {
return !path.endsWith("/");
}
/**
* Returns the EMF ResourceSet of this Workspace repository.
* <p>
* It will handle resource creation, package registry management...
* </p>
*
* @return the resourceSet the EMF ResourceSet of this Workspace repository
*/
public ResourceSet getResourceSet() {
return editingDomain.getResourceSet();
}
/**
* Returns this repository configuration.
*
* @return this repository configuration
*/
public WorkspaceConfig getWorkspaceConfig() {
return workspaceConfig;
}
/**
* Returns the default extension for any element stored on the repository.
*
* @return the default extension for any element stored on the repository
*/
public static String getWorkspaceResourceExtension() {
return WORKSPACE_RESOURCE_EXTENSION;
}
public TransactionalEditingDomain getEditingDomain() {
return editingDomain;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#setRepositoryStructurer(org.eclipse.mylyn.docs.intent.collab.handlers.adapters.RepositoryStructurer)
*/
public void setRepositoryStructurer(RepositoryStructurer structurer) {
this.repositoryStructurer = structurer;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#createRepositoryAdapter()
*/
public RepositoryAdapter createRepositoryAdapter() {
WorkspaceAdapter workspaceAdapter = new WorkspaceAdapter(this);
if (this.repositoryStructurer != null) {
workspaceAdapter.attachRepositoryStructurer(this.repositoryStructurer);
}
// We set a new unloadable Resource Predicate
workspaceAdapter.setUnloadableResourcePredicate(new Predicate<Resource>() {
public boolean apply(Resource resource) {
// The Intent index should never be unloaded
if (!resource.getContents().isEmpty()) {
boolean res = false;
EObject root = resource.getContents().iterator().next();
for (EClass unloadableType : unloadableTypes) {
if (root.eClass().equals(unloadableType)) {
res = true;
}
}
return res;
}
return false;
}
});
return workspaceAdapter;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#getIdentifier()
*/
public String getIdentifier() {
return workspaceConfig.getProject().getName();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#getRepositoryLocation()
*/
public String getRepositoryLocation() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation().toPortableString()
+ getWorkspaceConfig().getRepositoryAbsolutePath().replace(".repository", "");
}
/**
* {@inheritDoc}
*
* @see org.eclipse.mylyn.docs.intent.collab.repository.Repository#getRepositoryURI()
*/
public URI getRepositoryURI() {
return URI.createPlatformResourceURI(getIdentifier(), true);
}
}
| true | true | private void initializeResourceSet() throws CoreException {
// We first get the project on which the repository is defined
IProject project = workspaceConfig.getProject();
if (!project.exists()) {
project.create(null);
}
if (!project.isOpen()) {
project.open(null);
}
IFolder folder = project.getFolder(workspaceConfig.getRepositoryRelativePath());
// We created a WorkspaceRepositoryLoader using the indexPathList
WorkspaceRepositoryLoader loader = new WorkspaceRepositoryLoader(this, this.getWorkspaceConfig()
.getIndexesPathList());
// If the repository folder exists
if (folder.exists()) {
// We load the resourceSet
loader.loadResourceSet();
} else {
// If the repository folder doesn't exist
// We create it
folder.create(IResource.NONE, true, null);
// And use the RepositoryLoader to initialize the resource set with empty content
// loader.loadResourceSet();
// loader.createResourceSet();
}
isResourceSetLoaded = true;
}
| private void initializeResourceSet() throws CoreException {
// We first get the project on which the repository is defined
IProject project = workspaceConfig.getProject();
if (!project.exists()) {
project.create(null);
}
if (!project.isOpen()) {
project.open(null);
}
IFolder folder = project.getFolder(workspaceConfig.getRepositoryRelativePath());
// We created a WorkspaceRepositoryLoader using the indexPathList
WorkspaceRepositoryLoader loader = new WorkspaceRepositoryLoader(this, this.getWorkspaceConfig()
.getIndexesPathList());
// If the repository folder exists
if (folder.exists()) {
// We load the resourceSet
loader.loadResourceSet();
} else {
// If the repository folder doesn't exist
// We create it
folder.create(IResource.NONE, true, null);
// And use the RepositoryLoader to initialize the resource set with empty content
loader.loadResourceSet();
}
isResourceSetLoaded = true;
}
|
diff --git a/core/src/main/java/cx/ath/mancel01/webframework/routing/Router.java b/core/src/main/java/cx/ath/mancel01/webframework/routing/Router.java
index bb2212a..0562aae 100644
--- a/core/src/main/java/cx/ath/mancel01/webframework/routing/Router.java
+++ b/core/src/main/java/cx/ath/mancel01/webframework/routing/Router.java
@@ -1,305 +1,311 @@
/*
* Copyright 2011 mathieuancelin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* under the License.
*/
package cx.ath.mancel01.webframework.routing;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import cx.ath.mancel01.webframework.WebFramework;
import cx.ath.mancel01.webframework.annotation.Controller;
import cx.ath.mancel01.webframework.http.Request;
import cx.ath.mancel01.webframework.routing.Param.TypeMapper;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
*
* @author mathieuancelin
*/
public class Router {
private Map<String, WebMethod> registeredControllers = new HashMap<String, WebMethod>();
private List<String> uselessMethods = new ArrayList<String>();
public Router() {
List<Method> methods = Arrays.asList(Object.class.getMethods());
for (Method m : methods) {
uselessMethods.add(m.getName());
}
}
public void reset() {
this.registeredControllers.clear();
}
public WebMethod route(Request request, String contextRoot) {
String path = request.path;
if (!"/".equals(contextRoot)) {
path = path.replace(contextRoot, "");
}
for (String url : registeredControllers.keySet()) {
if (path.matches(url)) {
return registeredControllers.get(url);
}
}
throw new RuntimeException("Can't find an applicable controller method for " + path);
}
public void registrerController(Class<?> clazz) {
if (clazz.isAnnotationPresent(Controller.class)) {
String prefix = "";
if (clazz.isAnnotationPresent(Path.class)) {
Path path = clazz.getAnnotation(Path.class);
prefix = path.value().trim();
if (!prefix.startsWith("/")) {
prefix = "/" + prefix;
}
} else {
prefix = "/" + clazz.getSimpleName().toLowerCase();
}
for (Method method : clazz.getMethods()) {
if (!uselessMethods.contains(method.getName())) {
if (method.isAnnotationPresent(Path.class)) {
Path methodPath = method.getAnnotation(Path.class);
String value = methodPath.value().trim();
if (value.startsWith("/")) {
registerRoute(value, clazz, method);
} else {
String url = "";
if (prefix.endsWith("/")) {
url = prefix + value;
} else {
url = prefix + "/" + value;
}
registerRoute(url, clazz, method);
}
}
if (WebFramework.keepDefaultRoutes) {
String url = "";
if (prefix.endsWith("/")) {
url = prefix + method.getName();
} else {
url = prefix + "/" + method.getName();
}
registerRoute(url, clazz, method);
// TODO : register without @Path prefix
}
}
}
} else {
throw new RuntimeException("You can't register a controller without @Controller annotation");
}
}
private void registerRoute(String url, Class clazz, Method method) {
WebMethod webMethod = new WebMethod();
webMethod.setClazz(clazz);
webMethod.setFullUrl(url);
webMethod.setMethod(method);
if (url.startsWith("/")) {
webMethod.setComparisonUrl(Param.replaceParamsWithWildcard(url));
} else {
webMethod.setComparisonUrl("/" + Param.replaceParamsWithWildcard(url));
}
if (method.isAnnotationPresent(Consumes.class)) {
final Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than one parameter");
}
Consumes consumes = method.getAnnotation(Consumes.class);
String[] types = consumes.value();
if (types.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than consume type");
}
String type = types[0];
if (MediaType.APPLICATION_JSON.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
.create();
return gson.fromJson(value, paramTypes[0]);
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else if (MediaType.APPLICATION_OCTET_STREAM.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
FileOutputStream out = null;
try {
String path = WebFramework.TARGET.getAbsolutePath()
+ "/file" + System.currentTimeMillis();
out = new FileOutputStream(path);
out.write(value.getBytes());
out.close();
return new File(path);
} catch (Exception ex) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
throw new RuntimeException(ex);
}
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else if (MediaType.APPLICATION_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
try {
JAXBContext jc = JAXBContext.newInstance(paramTypes[0]);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ByteArrayInputStream input = new ByteArrayInputStream(value.getBytes());
return unmarshaller.unmarshal(input);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else if (MediaType.TEXT_HTML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else if (MediaType.TEXT_PLAIN.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else if (MediaType.TEXT_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
- webMethod.getParams().put(param.name(), param);
+// webMethod.getParams().put(param.name(), param);
+ webMethod.addParam(param);
} else {
throw new RuntimeException("unsupported @Consumes type");
}
} else {
Annotation[][] annotations = method.getParameterAnnotations();
Class<?>[] types = method.getParameterTypes();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
for (int j = 0; j < annotations[i].length; j++) {
Annotation annotation = annotations[i][j];
Param param = new Param(annotation, url, types[i]);
//webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
}
}
Matcher matcher = Param.PATH_PARAM_DECLARATION.matcher(url);
while (matcher.find()) {
String name = matcher.group().replaceAll("\\{|\\}", "");
if (webMethod.getParams().containsKey(name)) {
webMethod.getParams().get(name).setPathParamName(matcher);
} else {
throw new RuntimeException("the @Path on method " + method.getName()
+ " is missing path param : " + name);
}
}
}
}
String niceUrl = null;
if (url.startsWith("/")) {
niceUrl = Param.replaceParamsWithWildcard(url);
} else {
niceUrl = "/" + Param.replaceParamsWithWildcard(url);
}
if (!registeredControllers.containsKey(niceUrl)) {
//WebFramework.logger.trace("route registered @ " + niceUrl);
registeredControllers.put(niceUrl, webMethod);
} else {
throw new RuntimeException("the url " + url + " is already registered.");
}
}
public Set<String> getRoutes() {
return registeredControllers.keySet();
}
public String getHtmlRoutesTable() {
StringBuilder routes = new StringBuilder();
routes.append("<table>");
int row = 0;
for (Entry<String, WebMethod> route : this.registeredControllers.entrySet()) {
row++;
if (row % 2 == 0) {
routes.append("<tr>");
} else {
routes.append("<tr bgcolor=\"EEEEEE\">");
}
routes.append("<td>");
routes.append(route.getKey());
routes.append("</td><td width=\"100px\" align=\"center\">");
routes.append(" => ");
routes.append("</td><td>");
routes.append(route.getValue().getClazz().getSimpleName());
routes.append(".");
routes.append(route.getValue().getMethod().getName());
routes.append("(");
Set<String> params = route.getValue().getParams().keySet();
int nbrParam = params.size();
int i = 0;
for (String param : params) {
i++;
routes.append(param);
if (nbrParam > 1) {
if (i != nbrParam)
routes.append(", ");
}
}
routes.append(")");
routes.append("</td>");
routes.append("</tr>");
}
routes.append("</table>");
return routes.toString();
}
}
| false | true | private void registerRoute(String url, Class clazz, Method method) {
WebMethod webMethod = new WebMethod();
webMethod.setClazz(clazz);
webMethod.setFullUrl(url);
webMethod.setMethod(method);
if (url.startsWith("/")) {
webMethod.setComparisonUrl(Param.replaceParamsWithWildcard(url));
} else {
webMethod.setComparisonUrl("/" + Param.replaceParamsWithWildcard(url));
}
if (method.isAnnotationPresent(Consumes.class)) {
final Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than one parameter");
}
Consumes consumes = method.getAnnotation(Consumes.class);
String[] types = consumes.value();
if (types.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than consume type");
}
String type = types[0];
if (MediaType.APPLICATION_JSON.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
.create();
return gson.fromJson(value, paramTypes[0]);
}
});
webMethod.getParams().put(param.name(), param);
} else if (MediaType.APPLICATION_OCTET_STREAM.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
FileOutputStream out = null;
try {
String path = WebFramework.TARGET.getAbsolutePath()
+ "/file" + System.currentTimeMillis();
out = new FileOutputStream(path);
out.write(value.getBytes());
out.close();
return new File(path);
} catch (Exception ex) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
throw new RuntimeException(ex);
}
}
});
webMethod.getParams().put(param.name(), param);
} else if (MediaType.APPLICATION_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
try {
JAXBContext jc = JAXBContext.newInstance(paramTypes[0]);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ByteArrayInputStream input = new ByteArrayInputStream(value.getBytes());
return unmarshaller.unmarshal(input);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
});
webMethod.getParams().put(param.name(), param);
} else if (MediaType.TEXT_HTML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
webMethod.getParams().put(param.name(), param);
} else if (MediaType.TEXT_PLAIN.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
webMethod.getParams().put(param.name(), param);
} else if (MediaType.TEXT_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
webMethod.getParams().put(param.name(), param);
} else {
throw new RuntimeException("unsupported @Consumes type");
}
} else {
Annotation[][] annotations = method.getParameterAnnotations();
Class<?>[] types = method.getParameterTypes();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
for (int j = 0; j < annotations[i].length; j++) {
Annotation annotation = annotations[i][j];
Param param = new Param(annotation, url, types[i]);
//webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
}
}
Matcher matcher = Param.PATH_PARAM_DECLARATION.matcher(url);
while (matcher.find()) {
String name = matcher.group().replaceAll("\\{|\\}", "");
if (webMethod.getParams().containsKey(name)) {
webMethod.getParams().get(name).setPathParamName(matcher);
} else {
throw new RuntimeException("the @Path on method " + method.getName()
+ " is missing path param : " + name);
}
}
}
}
String niceUrl = null;
if (url.startsWith("/")) {
niceUrl = Param.replaceParamsWithWildcard(url);
} else {
niceUrl = "/" + Param.replaceParamsWithWildcard(url);
}
if (!registeredControllers.containsKey(niceUrl)) {
//WebFramework.logger.trace("route registered @ " + niceUrl);
registeredControllers.put(niceUrl, webMethod);
} else {
throw new RuntimeException("the url " + url + " is already registered.");
}
}
| private void registerRoute(String url, Class clazz, Method method) {
WebMethod webMethod = new WebMethod();
webMethod.setClazz(clazz);
webMethod.setFullUrl(url);
webMethod.setMethod(method);
if (url.startsWith("/")) {
webMethod.setComparisonUrl(Param.replaceParamsWithWildcard(url));
} else {
webMethod.setComparisonUrl("/" + Param.replaceParamsWithWildcard(url));
}
if (method.isAnnotationPresent(Consumes.class)) {
final Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than one parameter");
}
Consumes consumes = method.getAnnotation(Consumes.class);
String[] types = consumes.value();
if (types.length > 1) {
throw new RuntimeException("can't register an @Consumes method with more than consume type");
}
String type = types[0];
if (MediaType.APPLICATION_JSON.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
.create();
return gson.fromJson(value, paramTypes[0]);
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else if (MediaType.APPLICATION_OCTET_STREAM.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
FileOutputStream out = null;
try {
String path = WebFramework.TARGET.getAbsolutePath()
+ "/file" + System.currentTimeMillis();
out = new FileOutputStream(path);
out.write(value.getBytes());
out.close();
return new File(path);
} catch (Exception ex) {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
throw new RuntimeException(ex);
}
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else if (MediaType.APPLICATION_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
try {
JAXBContext jc = JAXBContext.newInstance(paramTypes[0]);
Unmarshaller unmarshaller = jc.createUnmarshaller();
ByteArrayInputStream input = new ByteArrayInputStream(value.getBytes());
return unmarshaller.unmarshal(input);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else if (MediaType.TEXT_HTML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else if (MediaType.TEXT_PLAIN.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else if (MediaType.TEXT_XML.equals(type)) {
Param param = new Param(paramTypes[0], url, new TypeMapper() {
@Override
public Object map(String value) {
return value;
}
});
// webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
} else {
throw new RuntimeException("unsupported @Consumes type");
}
} else {
Annotation[][] annotations = method.getParameterAnnotations();
Class<?>[] types = method.getParameterTypes();
if (annotations != null) {
for (int i = 0; i < annotations.length; i++) {
for (int j = 0; j < annotations[i].length; j++) {
Annotation annotation = annotations[i][j];
Param param = new Param(annotation, url, types[i]);
//webMethod.getParams().put(param.name(), param);
webMethod.addParam(param);
}
}
Matcher matcher = Param.PATH_PARAM_DECLARATION.matcher(url);
while (matcher.find()) {
String name = matcher.group().replaceAll("\\{|\\}", "");
if (webMethod.getParams().containsKey(name)) {
webMethod.getParams().get(name).setPathParamName(matcher);
} else {
throw new RuntimeException("the @Path on method " + method.getName()
+ " is missing path param : " + name);
}
}
}
}
String niceUrl = null;
if (url.startsWith("/")) {
niceUrl = Param.replaceParamsWithWildcard(url);
} else {
niceUrl = "/" + Param.replaceParamsWithWildcard(url);
}
if (!registeredControllers.containsKey(niceUrl)) {
//WebFramework.logger.trace("route registered @ " + niceUrl);
registeredControllers.put(niceUrl, webMethod);
} else {
throw new RuntimeException("the url " + url + " is already registered.");
}
}
|
diff --git a/om/src/main/java/de/escidoc/core/om/business/fedora/item/ItemHandlerCreate.java b/om/src/main/java/de/escidoc/core/om/business/fedora/item/ItemHandlerCreate.java
index b2610fe57..260e3bb37 100644
--- a/om/src/main/java/de/escidoc/core/om/business/fedora/item/ItemHandlerCreate.java
+++ b/om/src/main/java/de/escidoc/core/om/business/fedora/item/ItemHandlerCreate.java
@@ -1,559 +1,559 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2008 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.core.om.business.fedora.item;
import de.escidoc.core.common.business.Constants;
import de.escidoc.core.common.business.fedora.TripleStoreUtility;
import de.escidoc.core.common.business.fedora.Utility;
import de.escidoc.core.common.business.fedora.datastream.Datastream;
import de.escidoc.core.common.business.fedora.resources.item.Component;
import de.escidoc.core.common.exceptions.application.invalid.InvalidContentException;
import de.escidoc.core.common.exceptions.application.invalid.InvalidStatusException;
import de.escidoc.core.common.exceptions.application.invalid.XmlCorruptedException;
import de.escidoc.core.common.exceptions.application.invalid.XmlSchemaValidationException;
import de.escidoc.core.common.exceptions.application.missing.MissingContentException;
import de.escidoc.core.common.exceptions.application.missing.MissingElementValueException;
import de.escidoc.core.common.exceptions.application.notfound.FileNotFoundException;
import de.escidoc.core.common.exceptions.application.notfound.ResourceNotFoundException;
import de.escidoc.core.common.exceptions.application.notfound.StreamNotFoundException;
import de.escidoc.core.common.exceptions.application.violated.LockingException;
import de.escidoc.core.common.exceptions.application.violated.ReadonlyAttributeViolationException;
import de.escidoc.core.common.exceptions.application.violated.ReadonlyElementViolationException;
import de.escidoc.core.common.exceptions.system.EncodingSystemException;
import de.escidoc.core.common.exceptions.system.FedoraSystemException;
import de.escidoc.core.common.exceptions.system.IntegritySystemException;
import de.escidoc.core.common.exceptions.system.SystemException;
import de.escidoc.core.common.exceptions.system.TripleStoreSystemException;
import de.escidoc.core.common.exceptions.system.WebserverSystemException;
import de.escidoc.core.common.exceptions.system.XmlParserSystemException;
import de.escidoc.core.common.util.configuration.EscidocConfiguration;
import de.escidoc.core.common.util.stax.StaxParser;
import de.escidoc.core.common.util.stax.handler.AddNewSubTreesToDatastream;
import de.escidoc.core.common.util.stax.handler.MultipleExtractor;
import de.escidoc.core.common.util.xml.Elements;
import de.escidoc.core.common.util.xml.XmlUtility;
import de.escidoc.core.common.util.xml.factory.FoXmlProvider;
import de.escidoc.core.common.util.xml.factory.XmlTemplateProvider;
import de.escidoc.core.common.util.xml.stax.events.Attribute;
import de.escidoc.core.common.util.xml.stax.events.StartElement;
import de.escidoc.core.common.util.xml.stax.events.StartElementWithChildElements;
import de.escidoc.core.common.util.xml.stax.handler.DefaultHandler;
import de.escidoc.core.om.business.stax.handler.item.ComponentMetadataHandler;
import de.escidoc.core.om.business.stax.handler.item.OneComponentContentHandler;
import de.escidoc.core.om.business.stax.handler.item.OneComponentPropertiesHandler;
import de.escidoc.core.om.business.stax.handler.item.OneComponentTitleHandler;
import org.escidoc.core.services.fedora.IngestPathParam;
import org.escidoc.core.services.fedora.IngestQueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Contains methods pertaining creation of an item. Is extended at least by FedoraItemHandler.
*
* @author Michael Schneider
*/
public class ItemHandlerCreate extends ItemResourceListener {
private static final String DATASTREAM_CONTENT = "content";
private static final Pattern PATTERN_INVALID_FOXML =
Pattern.compile("fedora.server.errors.ObjectValidityException");
private static final Logger LOGGER = LoggerFactory.getLogger(ItemHandlerCreate.class);
/**
* Render RELS-EXT of a Component.
*
* @param id Objid of Component.
* @param properties Component properties
* @param inCreate Set true if Component is to create, false if it's an update.
* @return RELS-EXT XML representation of Component
* @throws WebserverSystemException Thrown in case of internal error.
*/
protected String getComponentRelsExtWithVelocity(
final String id, final Map<String, String> properties, final boolean inCreate) throws WebserverSystemException {
return getFoxmlRenderer().renderComponentRelsExt(id, properties, inCreate);
}
/**
* Get FoXML for Component (rendered with Velocity).
*
* @param id Objid of Component.
* @param contentMimeType MIME type of content.
* @param dataStreams Map with data (chaotic structure)
* @param metadataAttributes Map with attributes of md-records.
* @param nsUri Name space URI
* @param storage Type of storage.
* @return FoXML representation of Component
*/
private String getComponentFoxmlWithVelocity(
final String id, final String contentMimeType, final Map dataStreams,
final Map<String, Map<String, String>> metadataAttributes, final String nsUri, final String storage)
throws WebserverSystemException, EncodingSystemException, InvalidContentException {
final Map<String, Object> values = new HashMap<String, Object>();
// dc-mapping prototyping
if (dataStreams.containsKey(XmlUtility.NAME_MDRECORDS)
&& ((Map) dataStreams.get(XmlUtility.NAME_MDRECORDS)).containsKey(Elements.MANDATORY_MD_RECORD_NAME)) {
final String dcXml;
try {
// no content model id for component dc-mapping, default mapping
// should be applied
dcXml =
XmlUtility.createDC(nsUri, ((ByteArrayOutputStream) ((Map) dataStreams
.get(XmlUtility.NAME_MDRECORDS)).get(Elements.MANDATORY_MD_RECORD_NAME))
.toString(XmlUtility.CHARACTER_ENCODING), id, null);
}
catch (final UnsupportedEncodingException e) {
throw new EncodingSystemException(e.getMessage(), e);
}
if (dcXml != null) {
values.put(XmlTemplateProvider.DC, dcXml);
}
}
values.put(XmlTemplateProvider.OBJID, id);
values.put(XmlTemplateProvider.TITLE, "Component " + id);
if (dataStreams.get(Datastream.RELS_EXT_DATASTREAM) != null) {
values.put(XmlTemplateProvider.RELS_EXT, dataStreams.get(Datastream.RELS_EXT_DATASTREAM));
}
if (dataStreams.get("uploadUrl") != null) {
values.put(XmlTemplateProvider.MIME_TYPE, contentMimeType);
final String theUrl = Utility.processUrl((String) dataStreams.get("uploadUrl"), null, null);
values.put(XmlTemplateProvider.REF, theUrl);
values.put(XmlTemplateProvider.REF_TYPE, "URL");
if (storage.equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_URL)) {
values.put(XmlTemplateProvider.CONTROL_GROUP, "R");
}
else if (storage.equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED)) {
values.put(XmlTemplateProvider.CONTROL_GROUP, "E");
}
else if (storage.equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_INTERNAL_MANAGED)) {
values.put(XmlTemplateProvider.CONTROL_GROUP, "M");
}
values.put(XmlTemplateProvider.REF_TYPE, "URL");
values.put(XmlTemplateProvider.CONTENT_CHECKSUM_ALGORITHM, EscidocConfiguration.getInstance().get(
EscidocConfiguration.ESCIDOC_CORE_OM_CONTENT_CHECKSUM_ALGORITHM, "DISABLED"));
}
if (dataStreams.get(FoXmlProvider.DATASTREAM_MD_RECORDS) != null) {
final Map mdRecordsStreams = (Map) dataStreams.get(FoXmlProvider.DATASTREAM_MD_RECORDS);
if (!mdRecordsStreams.isEmpty()) {
final Collection<Map<String, String>> mdRecords =
new ArrayList<Map<String, String>>(mdRecordsStreams.size());
values.put(XmlTemplateProvider.MD_RECORDS, mdRecords);
for (final Object o : mdRecordsStreams.keySet()) {
final String key = (String) o;
final ByteArrayOutputStream mdRecordStream = (ByteArrayOutputStream) mdRecordsStreams.get(key);
final Map<String, String> mdRecord = new HashMap<String, String>();
final Map<String, String> mdAttributes = metadataAttributes.get(key);
String schema = null;
String type = null;
if (mdAttributes != null) {
schema = mdAttributes.get("schema");
type = mdAttributes.get("type");
}
mdRecord.put(XmlTemplateProvider.MD_RECORD_SCHEMA, schema);
mdRecord.put(XmlTemplateProvider.MD_RECORD_TYPE, type);
mdRecord.put(XmlTemplateProvider.MD_RECORD_NAME, key);
try {
mdRecord.put(XmlTemplateProvider.MD_RECORD_CONTENT, mdRecordStream
.toString(XmlUtility.CHARACTER_ENCODING));
}
catch (final UnsupportedEncodingException e) {
throw new EncodingSystemException(e);
}
mdRecords.add(mdRecord);
}
}
}
return getFoxmlRenderer().renderComponent(values);
}
/**
* Get WOV as XML representation.
*
* @return XML representation of WOV
*/
protected String getWovDatastream(
final String id, final String title, final String versionNo, final String lastModificationDate,
final String versionStatus, final String comment) throws WebserverSystemException {
return getFoxmlRenderer().renderWov(id, title, versionNo, lastModificationDate, versionStatus, comment);
}
/**
* Add a component to the item.
*
* @param xmlData The component xml.
* @return The xml representation of the component after creation.
* @throws SystemException Thrown in case of an internal system error.
* @throws XmlCorruptedException If xml data is corrupt.
* @throws XmlSchemaValidationException If xml schema validation fails.
* @throws LockingException If the item is locked and the current user is not the one who locked it.
* @throws InvalidStatusException If the item is not in a status to add a component.
* @throws FileNotFoundException If binary content can not be retrieved.
* @throws MissingElementValueException If a required value is missing in xml data.
* @throws ReadonlyElementViolationException
* If a read-only Element is set.
* @throws ReadonlyAttributeViolationException
* If a read-only attribute is set.
* @throws InvalidContentException If there is invalid content in xml data.
* @throws MissingContentException If some required content is missing in xml data.
*/
public String addComponent(final String xmlData) throws SystemException, FileNotFoundException,
MissingElementValueException, ReadonlyElementViolationException, ReadonlyAttributeViolationException,
InvalidContentException, MissingContentException, XmlParserSystemException, WebserverSystemException {
// TODO move all precondition checks to service method
// checkLocked();
// checkReleased();
final String componentId = getIdProvider().getNextPid();
final StaxParser sp = new StaxParser();
// find out the creator of the component
// add Handler to the StaxParser to split the xml stream
// in to data streams and modify these datastreams
final List<DefaultHandler> handlerChain = new ArrayList<DefaultHandler>();
// TODO Einkommentieren
// OptimisticLockingHandler lockingHandler = new
// OptimisticLockingHandler(id, sp);
// handlerChain.add(lockingHandler);
final OneComponentPropertiesHandler componentPropertiesHandler = new OneComponentPropertiesHandler(sp);
handlerChain.add(componentPropertiesHandler);
final OneComponentContentHandler contentHandler = new OneComponentContentHandler(sp);
handlerChain.add(contentHandler);
final OneComponentTitleHandler titleHandler = new OneComponentTitleHandler(sp);
handlerChain.add(titleHandler);
final ComponentMetadataHandler cmh = new ComponentMetadataHandler(sp, "/component");
final List<String> pids = new ArrayList<String>();
pids.add(componentId);
cmh.setObjids(pids);
handlerChain.add(cmh);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
extractPathes.put("/component/content", null);
extractPathes.put("/component/md-records/md-record", "name");
final List<String> componentPid = new ArrayList<String>();
componentPid.add(componentId);
final MultipleExtractor me = new MultipleExtractor(extractPathes, sp);
me.setPids(componentPid);
handlerChain.add(me);
sp.setHandlerChain(handlerChain);
try {
sp.parse(xmlData);
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e);
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final ReadonlyElementViolationException e) {
throw e;
}
catch (final ReadonlyAttributeViolationException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final MissingContentException e) {
throw e;
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
// reset StaxParser
sp.clearHandlerChain();
final Map<String, String> componentBinary = contentHandler.getComponentBinary();
// get modified data streams
final Map streams = me.getOutputStreams();
final Map<String, String> properties = componentPropertiesHandler.getProperties();
properties.put(TripleStoreUtility.PROP_CREATED_BY_ID, getUtility().getCurrentUserId());
properties.put(TripleStoreUtility.PROP_CREATED_BY_TITLE, getUtility().getCurrentUserRealName());
final Map components = (Map) streams.get("components");
final Map componentStreams = (Map) components.get(componentId);
final Map<String, Map<String, String>> componentMdAttributes = cmh.getMetadataAttributes().get(componentId);
final String escidocMdNsUri = cmh.getNamespacesMap().get(componentId);
if (componentBinary.get("storage") == null) {
throw new InvalidContentException("The attribute 'storage' of the element " + "'content' is missing.");
}
if (componentBinary.get(DATASTREAM_CONTENT) != null
&& (componentBinary.get("storage").equals(
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_URL) || componentBinary
.get("storage").equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED))) {
throw new InvalidContentException(
"The component section 'content' with the attribute 'storage' set to 'external-url' "
+ "or 'external-managed' may not have an inline content.");
}
handleComponent(componentId, properties, componentBinary, componentStreams, componentMdAttributes,
escidocMdNsUri);
final AddNewSubTreesToDatastream addNewEntriesHandler = new AddNewSubTreesToDatastream("/RDF", sp);
final StartElement pointer = new StartElement();
pointer.setLocalName("Description");
pointer.setPrefix(Constants.RDF_NAMESPACE_PREFIX);
pointer.setNamespace(Constants.RDF_NAMESPACE_URI);
addNewEntriesHandler.setPointerElement(pointer);
final StartElementWithChildElements newComponentIdElement = new StartElementWithChildElements();
newComponentIdElement.setLocalName("component");
newComponentIdElement.setPrefix(Constants.STRUCTURAL_RELATIONS_NS_PREFIX);
newComponentIdElement.setNamespace(Constants.STRUCTURAL_RELATIONS_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX, "info:fedora/"
+ componentId);
newComponentIdElement.addAttribute(resource);
newComponentIdElement.setChildrenElements(null);
final List<StartElementWithChildElements> elements = new ArrayList<StartElementWithChildElements>();
elements.add(newComponentIdElement);
addNewEntriesHandler.setSubtreeToInsert(elements);
sp.addHandler(addNewEntriesHandler);
try {
sp.parse(getItem().getRelsExt().getStream());
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e.getMessage(), e);
}
catch (final Exception e) {
throw new WebserverSystemException(e);
}
sp.clearHandlerChain();
final ByteArrayOutputStream relsExtNew = addNewEntriesHandler.getOutputStreams();
getItem().setRelsExt(relsExtNew);
this.getFedoraServiceClient().sync();
try {
this.getTripleStoreUtility().reinitialize();
}
catch (TripleStoreSystemException e) {
throw new FedoraSystemException("Error on reinitializing triple store.", e);
}
final String component;
try {
final Component c = new Component(componentId, getItem().getId(), null);
getItem().addComponent(c);
- component = renderComponent(componentId, false);
+ component = renderComponent(componentId, true);
}
catch (final ResourceNotFoundException e) {
throw new IntegritySystemException("Component not found.", e);
}
return component;
}
/**
* Create a new Component.
* <p/>
* ATTENTION: Object is created but sync is not called!
*
* @param xmlData eSciDoc XML representation of Component.
* @return objid of the new Component
*/
public String createComponent(final String xmlData) throws SystemException, FileNotFoundException,
MissingElementValueException, ReadonlyElementViolationException, ReadonlyAttributeViolationException,
InvalidContentException, MissingContentException, XmlParserSystemException, WebserverSystemException {
final StaxParser sp = new StaxParser();
// find out the creator of the component
final List<DefaultHandler> handlerChain = new ArrayList<DefaultHandler>();
final OneComponentPropertiesHandler componentPropertiesHandler = new OneComponentPropertiesHandler(sp);
handlerChain.add(componentPropertiesHandler);
final OneComponentContentHandler contentHandler = new OneComponentContentHandler(sp);
handlerChain.add(contentHandler);
final OneComponentTitleHandler titleHandler = new OneComponentTitleHandler(sp);
handlerChain.add(titleHandler);
final ComponentMetadataHandler cmh = new ComponentMetadataHandler(sp, "/component");
final List<String> pids = new ArrayList<String>();
final String componentId = getIdProvider().getNextPid();
pids.add(componentId);
cmh.setObjids(pids);
handlerChain.add(cmh);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
// extractPathes.put("/component/properties", null);
extractPathes.put("/component/content", null);
extractPathes.put("/component/md-records/md-record", "name");
final List<String> componentIds = new ArrayList<String>();
componentIds.add(componentId);
final MultipleExtractor me = new MultipleExtractor(extractPathes, sp);
me.setPids(componentIds);
handlerChain.add(me);
sp.setHandlerChain(handlerChain);
try {
sp.parse(xmlData);
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e);
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final ReadonlyElementViolationException e) {
throw e;
}
catch (final ReadonlyAttributeViolationException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final MissingContentException e) {
throw e;
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
// reset StaxParser
sp.clearHandlerChain();
final Map<String, String> componentBinary = contentHandler.getComponentBinary();
// get modified data streams
final Map<String, Object> streams = me.getOutputStreams();
final Map<String, String> properties = componentPropertiesHandler.getProperties();
properties.put(TripleStoreUtility.PROP_CREATED_BY_ID, getUtility().getCurrentUserId());
properties.put(TripleStoreUtility.PROP_CREATED_BY_TITLE, getUtility().getCurrentUserRealName());
final Map components = (Map) streams.get("components");
final Map componentStreams = (Map) components.get(componentId);
final Map<String, Map<String, String>> componentMdAttributes = cmh.getMetadataAttributes().get(componentId);
final String escidocMdNsUri = cmh.getNamespacesMap().get(componentId);
if (componentBinary.get("storage") == null) {
throw new InvalidContentException("The attribute 'storage' of the element " + "'content' is missing.");
}
if (componentBinary.get(DATASTREAM_CONTENT) != null
&& (componentBinary.get("storage").equals(
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_URL) || componentBinary
.get("storage").equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED))) {
throw new InvalidContentException(
"The component section 'content' with the attribute 'storage' set to 'external-url' "
+ "or 'external-managed' may not have an inline content.");
}
handleComponent(componentId, properties, componentBinary, componentStreams, componentMdAttributes,
escidocMdNsUri);
return componentId;
}
/**
* The method prepares datastreams for a fedora object which will represent a component. - it calls a jhof service
* to get a technical metadata about a binary data of the component. - in case that a binary data is an inline
* binary stream, the method uploads this binary stream in to a staging area using a staging component in order to
* get an access url. - then it calls the method buildComponentFoxml() with following parameter: provided
* componentStreams, an access url to a binary content and a component title - store retrieved component FOXML in to
* Fedora.
*
* @param componentId component id
* @param properties Property Map
* @param binaryContent data of the binary data stream
* @param datastreams HashMap with component data streams
* @param mdRecordAttributes Attributes of eSciDoc XML md-record element.
* @param nsUri Name space URI
* @throws IntegritySystemException If the integrity of the repository is violated.
* @throws EncodingSystemException If encoding fails.
* @throws WebserverSystemException In case of an internal error.
* @throws FileNotFoundException If binary content can not be retrieved.
*/
protected void handleComponent(
final String componentId, final Map<String, String> properties, final Map<String, String> binaryContent,
final Map datastreams, final Map<String, Map<String, String>> mdRecordAttributes, final String nsUri)
throws FileNotFoundException, WebserverSystemException, IntegritySystemException, FedoraSystemException {
if (datastreams.containsKey(DATASTREAM_CONTENT)) {
datastreams.remove(DATASTREAM_CONTENT);
}
String mimeType = properties.get(TripleStoreUtility.PROP_MIME_TYPE);
if (mimeType == null || mimeType.length() == 0) {
mimeType = FoXmlProvider.MIME_TYPE_APPLICATION_OCTET_STREAM;
}
datastreams.put(Datastream.RELS_EXT_DATASTREAM, getComponentRelsExtWithVelocity(componentId, properties, true));
if (datastreams.get(FoXmlProvider.DATASTREAM_MD_RECORDS) == null) {
datastreams.put(FoXmlProvider.DATASTREAM_MD_RECORDS, new HashMap());
}
String uploadUrl = binaryContent.get(FoXmlProvider.DATASTREAM_UPLOAD_URL);
if (binaryContent.get(DATASTREAM_CONTENT) != null) {
final String fileName = "component " + componentId;
uploadUrl = uploadBase64EncodedContent(binaryContent.get(DATASTREAM_CONTENT), fileName, mimeType);
}
datastreams.put(FoXmlProvider.DATASTREAM_UPLOAD_URL, uploadUrl);
try {
final String componentFoxml =
getComponentFoxmlWithVelocity(componentId, mimeType, datastreams, mdRecordAttributes, nsUri,
binaryContent.get(FoXmlProvider.DATASTREAM_STORAGE_ATTRIBUTE));
final IngestPathParam path = new IngestPathParam();
final IngestQueryParam query = new IngestQueryParam();
this.getFedoraServiceClient().ingest(path, query, componentFoxml);
}
catch (final Exception e) {
final Matcher invalidFoxml = PATTERN_INVALID_FOXML.matcher(e.getCause().getMessage());
if (invalidFoxml.find()) {
throw new IntegritySystemException(e);
}
handleFedoraUploadError(uploadUrl, e);
}
}
}
| true | true | public String addComponent(final String xmlData) throws SystemException, FileNotFoundException,
MissingElementValueException, ReadonlyElementViolationException, ReadonlyAttributeViolationException,
InvalidContentException, MissingContentException, XmlParserSystemException, WebserverSystemException {
// TODO move all precondition checks to service method
// checkLocked();
// checkReleased();
final String componentId = getIdProvider().getNextPid();
final StaxParser sp = new StaxParser();
// find out the creator of the component
// add Handler to the StaxParser to split the xml stream
// in to data streams and modify these datastreams
final List<DefaultHandler> handlerChain = new ArrayList<DefaultHandler>();
// TODO Einkommentieren
// OptimisticLockingHandler lockingHandler = new
// OptimisticLockingHandler(id, sp);
// handlerChain.add(lockingHandler);
final OneComponentPropertiesHandler componentPropertiesHandler = new OneComponentPropertiesHandler(sp);
handlerChain.add(componentPropertiesHandler);
final OneComponentContentHandler contentHandler = new OneComponentContentHandler(sp);
handlerChain.add(contentHandler);
final OneComponentTitleHandler titleHandler = new OneComponentTitleHandler(sp);
handlerChain.add(titleHandler);
final ComponentMetadataHandler cmh = new ComponentMetadataHandler(sp, "/component");
final List<String> pids = new ArrayList<String>();
pids.add(componentId);
cmh.setObjids(pids);
handlerChain.add(cmh);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
extractPathes.put("/component/content", null);
extractPathes.put("/component/md-records/md-record", "name");
final List<String> componentPid = new ArrayList<String>();
componentPid.add(componentId);
final MultipleExtractor me = new MultipleExtractor(extractPathes, sp);
me.setPids(componentPid);
handlerChain.add(me);
sp.setHandlerChain(handlerChain);
try {
sp.parse(xmlData);
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e);
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final ReadonlyElementViolationException e) {
throw e;
}
catch (final ReadonlyAttributeViolationException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final MissingContentException e) {
throw e;
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
// reset StaxParser
sp.clearHandlerChain();
final Map<String, String> componentBinary = contentHandler.getComponentBinary();
// get modified data streams
final Map streams = me.getOutputStreams();
final Map<String, String> properties = componentPropertiesHandler.getProperties();
properties.put(TripleStoreUtility.PROP_CREATED_BY_ID, getUtility().getCurrentUserId());
properties.put(TripleStoreUtility.PROP_CREATED_BY_TITLE, getUtility().getCurrentUserRealName());
final Map components = (Map) streams.get("components");
final Map componentStreams = (Map) components.get(componentId);
final Map<String, Map<String, String>> componentMdAttributes = cmh.getMetadataAttributes().get(componentId);
final String escidocMdNsUri = cmh.getNamespacesMap().get(componentId);
if (componentBinary.get("storage") == null) {
throw new InvalidContentException("The attribute 'storage' of the element " + "'content' is missing.");
}
if (componentBinary.get(DATASTREAM_CONTENT) != null
&& (componentBinary.get("storage").equals(
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_URL) || componentBinary
.get("storage").equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED))) {
throw new InvalidContentException(
"The component section 'content' with the attribute 'storage' set to 'external-url' "
+ "or 'external-managed' may not have an inline content.");
}
handleComponent(componentId, properties, componentBinary, componentStreams, componentMdAttributes,
escidocMdNsUri);
final AddNewSubTreesToDatastream addNewEntriesHandler = new AddNewSubTreesToDatastream("/RDF", sp);
final StartElement pointer = new StartElement();
pointer.setLocalName("Description");
pointer.setPrefix(Constants.RDF_NAMESPACE_PREFIX);
pointer.setNamespace(Constants.RDF_NAMESPACE_URI);
addNewEntriesHandler.setPointerElement(pointer);
final StartElementWithChildElements newComponentIdElement = new StartElementWithChildElements();
newComponentIdElement.setLocalName("component");
newComponentIdElement.setPrefix(Constants.STRUCTURAL_RELATIONS_NS_PREFIX);
newComponentIdElement.setNamespace(Constants.STRUCTURAL_RELATIONS_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX, "info:fedora/"
+ componentId);
newComponentIdElement.addAttribute(resource);
newComponentIdElement.setChildrenElements(null);
final List<StartElementWithChildElements> elements = new ArrayList<StartElementWithChildElements>();
elements.add(newComponentIdElement);
addNewEntriesHandler.setSubtreeToInsert(elements);
sp.addHandler(addNewEntriesHandler);
try {
sp.parse(getItem().getRelsExt().getStream());
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e.getMessage(), e);
}
catch (final Exception e) {
throw new WebserverSystemException(e);
}
sp.clearHandlerChain();
final ByteArrayOutputStream relsExtNew = addNewEntriesHandler.getOutputStreams();
getItem().setRelsExt(relsExtNew);
this.getFedoraServiceClient().sync();
try {
this.getTripleStoreUtility().reinitialize();
}
catch (TripleStoreSystemException e) {
throw new FedoraSystemException("Error on reinitializing triple store.", e);
}
final String component;
try {
final Component c = new Component(componentId, getItem().getId(), null);
getItem().addComponent(c);
component = renderComponent(componentId, false);
}
catch (final ResourceNotFoundException e) {
throw new IntegritySystemException("Component not found.", e);
}
return component;
}
| public String addComponent(final String xmlData) throws SystemException, FileNotFoundException,
MissingElementValueException, ReadonlyElementViolationException, ReadonlyAttributeViolationException,
InvalidContentException, MissingContentException, XmlParserSystemException, WebserverSystemException {
// TODO move all precondition checks to service method
// checkLocked();
// checkReleased();
final String componentId = getIdProvider().getNextPid();
final StaxParser sp = new StaxParser();
// find out the creator of the component
// add Handler to the StaxParser to split the xml stream
// in to data streams and modify these datastreams
final List<DefaultHandler> handlerChain = new ArrayList<DefaultHandler>();
// TODO Einkommentieren
// OptimisticLockingHandler lockingHandler = new
// OptimisticLockingHandler(id, sp);
// handlerChain.add(lockingHandler);
final OneComponentPropertiesHandler componentPropertiesHandler = new OneComponentPropertiesHandler(sp);
handlerChain.add(componentPropertiesHandler);
final OneComponentContentHandler contentHandler = new OneComponentContentHandler(sp);
handlerChain.add(contentHandler);
final OneComponentTitleHandler titleHandler = new OneComponentTitleHandler(sp);
handlerChain.add(titleHandler);
final ComponentMetadataHandler cmh = new ComponentMetadataHandler(sp, "/component");
final List<String> pids = new ArrayList<String>();
pids.add(componentId);
cmh.setObjids(pids);
handlerChain.add(cmh);
final HashMap<String, String> extractPathes = new HashMap<String, String>();
extractPathes.put("/component/content", null);
extractPathes.put("/component/md-records/md-record", "name");
final List<String> componentPid = new ArrayList<String>();
componentPid.add(componentId);
final MultipleExtractor me = new MultipleExtractor(extractPathes, sp);
me.setPids(componentPid);
handlerChain.add(me);
sp.setHandlerChain(handlerChain);
try {
sp.parse(xmlData);
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e);
}
catch (final MissingElementValueException e) {
throw e;
}
catch (final ReadonlyElementViolationException e) {
throw e;
}
catch (final ReadonlyAttributeViolationException e) {
throw e;
}
catch (final InvalidContentException e) {
throw e;
}
catch (final MissingContentException e) {
throw e;
}
catch (final WebserverSystemException e) {
throw e;
}
catch (final Exception e) {
XmlUtility.handleUnexpectedStaxParserException("", e);
}
// reset StaxParser
sp.clearHandlerChain();
final Map<String, String> componentBinary = contentHandler.getComponentBinary();
// get modified data streams
final Map streams = me.getOutputStreams();
final Map<String, String> properties = componentPropertiesHandler.getProperties();
properties.put(TripleStoreUtility.PROP_CREATED_BY_ID, getUtility().getCurrentUserId());
properties.put(TripleStoreUtility.PROP_CREATED_BY_TITLE, getUtility().getCurrentUserRealName());
final Map components = (Map) streams.get("components");
final Map componentStreams = (Map) components.get(componentId);
final Map<String, Map<String, String>> componentMdAttributes = cmh.getMetadataAttributes().get(componentId);
final String escidocMdNsUri = cmh.getNamespacesMap().get(componentId);
if (componentBinary.get("storage") == null) {
throw new InvalidContentException("The attribute 'storage' of the element " + "'content' is missing.");
}
if (componentBinary.get(DATASTREAM_CONTENT) != null
&& (componentBinary.get("storage").equals(
de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_URL) || componentBinary
.get("storage").equals(de.escidoc.core.common.business.fedora.Constants.STORAGE_EXTERNAL_MANAGED))) {
throw new InvalidContentException(
"The component section 'content' with the attribute 'storage' set to 'external-url' "
+ "or 'external-managed' may not have an inline content.");
}
handleComponent(componentId, properties, componentBinary, componentStreams, componentMdAttributes,
escidocMdNsUri);
final AddNewSubTreesToDatastream addNewEntriesHandler = new AddNewSubTreesToDatastream("/RDF", sp);
final StartElement pointer = new StartElement();
pointer.setLocalName("Description");
pointer.setPrefix(Constants.RDF_NAMESPACE_PREFIX);
pointer.setNamespace(Constants.RDF_NAMESPACE_URI);
addNewEntriesHandler.setPointerElement(pointer);
final StartElementWithChildElements newComponentIdElement = new StartElementWithChildElements();
newComponentIdElement.setLocalName("component");
newComponentIdElement.setPrefix(Constants.STRUCTURAL_RELATIONS_NS_PREFIX);
newComponentIdElement.setNamespace(Constants.STRUCTURAL_RELATIONS_NS_URI);
final Attribute resource =
new Attribute("resource", Constants.RDF_NAMESPACE_URI, Constants.RDF_NAMESPACE_PREFIX, "info:fedora/"
+ componentId);
newComponentIdElement.addAttribute(resource);
newComponentIdElement.setChildrenElements(null);
final List<StartElementWithChildElements> elements = new ArrayList<StartElementWithChildElements>();
elements.add(newComponentIdElement);
addNewEntriesHandler.setSubtreeToInsert(elements);
sp.addHandler(addNewEntriesHandler);
try {
sp.parse(getItem().getRelsExt().getStream());
}
catch (final XMLStreamException e) {
throw new XmlParserSystemException(e.getMessage(), e);
}
catch (final Exception e) {
throw new WebserverSystemException(e);
}
sp.clearHandlerChain();
final ByteArrayOutputStream relsExtNew = addNewEntriesHandler.getOutputStreams();
getItem().setRelsExt(relsExtNew);
this.getFedoraServiceClient().sync();
try {
this.getTripleStoreUtility().reinitialize();
}
catch (TripleStoreSystemException e) {
throw new FedoraSystemException("Error on reinitializing triple store.", e);
}
final String component;
try {
final Component c = new Component(componentId, getItem().getId(), null);
getItem().addComponent(c);
component = renderComponent(componentId, true);
}
catch (final ResourceNotFoundException e) {
throw new IntegritySystemException("Component not found.", e);
}
return component;
}
|
diff --git a/src/jmxsh/GetCmd.java b/src/jmxsh/GetCmd.java
index 98c1494..0c0db10 100755
--- a/src/jmxsh/GetCmd.java
+++ b/src/jmxsh/GetCmd.java
@@ -1,175 +1,175 @@
/*
* $URL$
*
* $Revision$
*
* $LastChangedDate$
*
* $LastChangedBy$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package jmxsh;
import org.apache.commons.cli.*;
//import org.apache.log4j.Logger;
import tcl.lang.*;
class GetCmd implements Command {
private final static GetCmd instance = new GetCmd();
//private final static Logger logger = Logger.getLogger(GetCmd.class);
private String server;
//private String domain;
private String mbean;
private String attrop;
private Options opts;
static GetCmd getInstance() {
return instance;
}
private GetCmd() {
this.opts = new Options();
this.opts.addOption(
OptionBuilder.withLongOpt("server")
.withDescription("Server containing mbean.")
.withArgName("SERVER")
.hasArg()
.create("s")
);
this.opts.addOption(
OptionBuilder.withLongOpt("mbean")
.withDescription("MBean containing attribute.")
.withArgName("MBEAN")
.hasArg()
.create("m")
);
this.opts.addOption(
OptionBuilder.withLongOpt("noconvert")
.withDescription("Do not auto-convert the result to a Tcl string, instead create a java object reference.")
.hasArg(false)
.create("n")
);
this.opts.addOption(
OptionBuilder.withLongOpt("help")
.withDescription("Display usage help.")
.hasArg(false)
.create("?")
);
}
private CommandLine parseCommandLine(TclObject argv[])
throws ParseException {
String[] args = new String[argv.length - 1];
for(int i = 0; i < argv.length - 1; i++)
args[i] = argv[i + 1].toString();
CommandLine cl = (new PosixParser()).parse(this.opts, args);
return cl;
}
private void getDefaults(Interp interp) {
this.server = null;
//domain = null;
this.mbean = null;
this.attrop = null;
try {
this.server = interp.getVar("SERVER", TCL.GLOBAL_ONLY).toString();
//domain = interp.getVar("DOMAIN", TCL.GLOBAL_ONLY).toString();
this.mbean = interp.getVar("MBEAN", TCL.GLOBAL_ONLY).toString();
this.attrop = interp.getVar("ATTROP", TCL.GLOBAL_ONLY).toString();
}
catch (TclException e) {
/* If one doesn't exist, it will just be null. */
}
}
public void cmdProc(Interp interp, TclObject argv[])
throws TclException {
try {
CommandLine cl = parseCommandLine(argv);
String args[] = cl.getArgs();
String attribute = null;
if (cl.hasOption("help")) {
new HelpFormatter().printHelp (
"jmx_get [-?] [-n] [-s server] [-m mbean] [ATTRIBUTE]",
"======================================================================",
this.opts,
"======================================================================",
false
);
System.out.println("jmx_get retrieves the current value of the given attribute.");
System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the");
System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,");
System.out.println("respectively, will be used.");
System.out.println("");
System.out.println("If you specify -n, then the return will be a Java/Tcl java");
System.out.println("object reference. See the Java/Tcl documentation on the");
System.out.println("internet for more details.");
return;
}
getDefaults(interp);
this.server = cl.getOptionValue("server", this.server);
this.mbean = cl.getOptionValue("mbean", this.mbean);
this.attrop = cl.getOptionValue("attrop", this.attrop);
if (args.length > 0) {
attribute = args[0];
}
else {
attribute = this.attrop;
}
if (this.server == null) {
throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR);
}
if (this.mbean == null) {
throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR);
}
- if (this.attrop == null) {
+ if (attribute == null) {
throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR);
}
if (cl.hasOption("noconvert")) {
String result = Utils.java2tcl(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute));
interp.setResult(result);
} else {
interp.setResult(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute).toString());
}
}
catch(ParseException e) {
throw new TclException(interp, e.getMessage(), 1);
}
catch(RuntimeException e) {
throw new TclException(interp, "Cannot convert result to a string.", 1);
}
}
}
| true | true | public void cmdProc(Interp interp, TclObject argv[])
throws TclException {
try {
CommandLine cl = parseCommandLine(argv);
String args[] = cl.getArgs();
String attribute = null;
if (cl.hasOption("help")) {
new HelpFormatter().printHelp (
"jmx_get [-?] [-n] [-s server] [-m mbean] [ATTRIBUTE]",
"======================================================================",
this.opts,
"======================================================================",
false
);
System.out.println("jmx_get retrieves the current value of the given attribute.");
System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the");
System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,");
System.out.println("respectively, will be used.");
System.out.println("");
System.out.println("If you specify -n, then the return will be a Java/Tcl java");
System.out.println("object reference. See the Java/Tcl documentation on the");
System.out.println("internet for more details.");
return;
}
getDefaults(interp);
this.server = cl.getOptionValue("server", this.server);
this.mbean = cl.getOptionValue("mbean", this.mbean);
this.attrop = cl.getOptionValue("attrop", this.attrop);
if (args.length > 0) {
attribute = args[0];
}
else {
attribute = this.attrop;
}
if (this.server == null) {
throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR);
}
if (this.mbean == null) {
throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR);
}
if (this.attrop == null) {
throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR);
}
if (cl.hasOption("noconvert")) {
String result = Utils.java2tcl(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute));
interp.setResult(result);
} else {
interp.setResult(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute).toString());
}
}
catch(ParseException e) {
throw new TclException(interp, e.getMessage(), 1);
}
catch(RuntimeException e) {
throw new TclException(interp, "Cannot convert result to a string.", 1);
}
}
| public void cmdProc(Interp interp, TclObject argv[])
throws TclException {
try {
CommandLine cl = parseCommandLine(argv);
String args[] = cl.getArgs();
String attribute = null;
if (cl.hasOption("help")) {
new HelpFormatter().printHelp (
"jmx_get [-?] [-n] [-s server] [-m mbean] [ATTRIBUTE]",
"======================================================================",
this.opts,
"======================================================================",
false
);
System.out.println("jmx_get retrieves the current value of the given attribute.");
System.out.println("If you do not specify server, mbean, or ATTRIBUTE, then the");
System.out.println("values in the global variables SERVER, MBEAN, and ATTROP,");
System.out.println("respectively, will be used.");
System.out.println("");
System.out.println("If you specify -n, then the return will be a Java/Tcl java");
System.out.println("object reference. See the Java/Tcl documentation on the");
System.out.println("internet for more details.");
return;
}
getDefaults(interp);
this.server = cl.getOptionValue("server", this.server);
this.mbean = cl.getOptionValue("mbean", this.mbean);
this.attrop = cl.getOptionValue("attrop", this.attrop);
if (args.length > 0) {
attribute = args[0];
}
else {
attribute = this.attrop;
}
if (this.server == null) {
throw new TclException(interp, "No server specified; please set SERVER variable or use -s option.", TCL.ERROR);
}
if (this.mbean == null) {
throw new TclException(interp, "No mbean specified; please set MBEAN variable or use -m option.", TCL.ERROR);
}
if (attribute == null) {
throw new TclException(interp, "No attribute specified; please set ATTROP variable or add it to the command line.", TCL.ERROR);
}
if (cl.hasOption("noconvert")) {
String result = Utils.java2tcl(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute));
interp.setResult(result);
} else {
interp.setResult(Jmx.getInstance().getAttribute(this.server, this.mbean, attribute).toString());
}
}
catch(ParseException e) {
throw new TclException(interp, e.getMessage(), 1);
}
catch(RuntimeException e) {
throw new TclException(interp, "Cannot convert result to a string.", 1);
}
}
|
diff --git a/src/org/openstreetmap/osmosis/core/apidb/v0_6/impl/EntityDao.java b/src/org/openstreetmap/osmosis/core/apidb/v0_6/impl/EntityDao.java
index 0797af83..c67f4e03 100644
--- a/src/org/openstreetmap/osmosis/core/apidb/v0_6/impl/EntityDao.java
+++ b/src/org/openstreetmap/osmosis/core/apidb/v0_6/impl/EntityDao.java
@@ -1,490 +1,490 @@
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.apidb.v0_6.impl;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openstreetmap.osmosis.core.container.v0_6.ChangeContainer;
import org.openstreetmap.osmosis.core.container.v0_6.EntityContainer;
import org.openstreetmap.osmosis.core.container.v0_6.EntityContainerFactory;
import org.openstreetmap.osmosis.core.domain.v0_6.CommonEntityData;
import org.openstreetmap.osmosis.core.domain.v0_6.Entity;
import org.openstreetmap.osmosis.core.domain.v0_6.Tag;
import org.openstreetmap.osmosis.core.lifecycle.ReleasableContainer;
import org.openstreetmap.osmosis.core.lifecycle.ReleasableIterator;
import org.openstreetmap.osmosis.core.store.SimpleObjectStore;
import org.openstreetmap.osmosis.core.store.SingleClassObjectSerializationFactory;
import org.openstreetmap.osmosis.core.store.StoreReleasingIterator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
/**
* Provides functionality common to all top level entity daos.
*
* @param <T>
* The entity type to be supported.
*/
public abstract class EntityDao<T extends Entity> {
private static final Logger LOG = Logger.getLogger(EntityDao.class.getName());
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedParamJdbcTemplate;
private String entityName;
/**
* Creates a new instance.
*
* @param jdbcTemplate
* Used to access the database.
* @param entityName
* The name of the entity. Used for building dynamic sql queries.
*/
protected EntityDao(JdbcTemplate jdbcTemplate, String entityName) {
this.jdbcTemplate = jdbcTemplate;
this.namedParamJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
this.entityName = entityName;
}
/**
* Provides access to the named parameter jdbc template.
*
* @return The jdbc template.
*/
protected NamedParameterJdbcTemplate getNamedParamJdbcTemplate() {
return namedParamJdbcTemplate;
}
/**
* Produces an array of additional column names specific to this entity type to be returned by
* entity queries.
*
* @return The column names.
*/
protected abstract String[] getTypeSpecificFieldNames();
/**
* Creates a row mapper that receives common entity data objects and produces full entity
* objects.
*
* @param entityListener
* The full entity object listener.
* @return The full entity row mapper.
*/
protected abstract RowMapperListener<CommonEntityData> getEntityRowMapper(RowMapperListener<T> entityListener);
/**
* Gets the entity container factory for the entity type.
*
* @return The factory.
*/
protected abstract EntityContainerFactory<T> getContainerFactory();
/**
* Gets the history feature populators for the entity type.
*
* @param selectedEntityTableName
* The name of the table containing the id and version pairs of entity records
* selected.
* @return The history feature populators.
*/
protected abstract List<FeatureHistoryPopulator<T, ?>> getFeatureHistoryPopulators(String selectedEntityTableName);
private ReleasableIterator<EntityHistory<T>> getEntityHistory(String sql, SqlParameterSource parameterSource) {
SimpleObjectStore<EntityHistory<T>> store = new SimpleObjectStore<EntityHistory<T>>(
new SingleClassObjectSerializationFactory(EntityHistory.class), "his", true);
try {
ObjectStoreRowMapperListener<EntityHistory<T>> storeListener;
EntityHistoryRowMapper<T> entityHistoryRowMapper;
RowMapperListener<CommonEntityData> entityRowMapper;
EntityDataRowMapper entityDataRowMapper;
ReleasableIterator<EntityHistory<T>> resultIterator;
// Sends all received data into the object store.
storeListener = new ObjectStoreRowMapperListener<EntityHistory<T>>(store);
// Retrieves the visible attribute allowing modifies to be distinguished
// from deletes.
entityHistoryRowMapper = new EntityHistoryRowMapper<T>(storeListener);
// Retrieves the entity type specific columns and builds the entity objects.
entityRowMapper = getEntityRowMapper(entityHistoryRowMapper);
// Retrieves the common entity information.
entityDataRowMapper = new EntityDataRowMapper(entityRowMapper, true);
// Perform the query passing the row mapper chain to process rows in a streamy fashion.
namedParamJdbcTemplate.query(sql, parameterSource, entityDataRowMapper);
// Open a iterator on the store that will release the store upon completion.
resultIterator = new StoreReleasingIterator<EntityHistory<T>>(store.iterate(), store);
// The store itself shouldn't be released now that it has been attached to the iterator.
store = null;
return resultIterator;
} finally {
if (store != null) {
store.release();
}
}
}
private ReleasableIterator<EntityHistory<T>> getRawEntityHistory(String selectedEntityTableName) {
StringBuilder sql;
MapSqlParameterSource parameterSource;
sql = new StringBuilder();
sql.append("SELECT e.id, e.version, e.timestamp, e.visible, u.data_public,");
sql.append(" u.id AS user_id, u.display_name, e.changeset_id");
for (String fieldName : getTypeSpecificFieldNames()) {
sql.append(", e.");
sql.append(fieldName);
}
sql.append(" FROM ");
sql.append(entityName);
sql.append("s e");
sql.append(" INNER JOIN ");
sql.append(selectedEntityTableName);
sql.append(" t ON e.id = t.id AND e.version = t.version");
sql.append(" INNER JOIN changesets c ON e.changeset_id = c.id INNER JOIN users u ON c.user_id = u.id");
sql.append(" ORDER BY e.id, e.version");
LOG.log(Level.FINER, "Entity history query: " + sql);
parameterSource = new MapSqlParameterSource();
return getEntityHistory(sql.toString(), parameterSource);
}
private ReleasableIterator<DbFeatureHistory<DbFeature<Tag>>> getTagHistory(String sql,
SqlParameterSource parameterSource) {
SimpleObjectStore<DbFeatureHistory<DbFeature<Tag>>> store =
new SimpleObjectStore<DbFeatureHistory<DbFeature<Tag>>>(
new SingleClassObjectSerializationFactory(DbFeatureHistory.class), "tag", true);
try {
ObjectStoreRowMapperListener<DbFeatureHistory<DbFeature<Tag>>> storeListener;
DbFeatureHistoryRowMapper<DbFeature<Tag>> dbFeatureHistoryRowMapper;
DbFeatureRowMapper<Tag> dbFeatureRowMapper;
TagRowMapper tagRowMapper;
ReleasableIterator<DbFeatureHistory<DbFeature<Tag>>> resultIterator;
// Sends all received data into the object store.
storeListener = new ObjectStoreRowMapperListener<DbFeatureHistory<DbFeature<Tag>>>(store);
// Retrieves the version information associated with the tag.
dbFeatureHistoryRowMapper = new DbFeatureHistoryRowMapper<DbFeature<Tag>>(storeListener);
// Retrieves the entity information associated with the tag.
dbFeatureRowMapper = new DbFeatureRowMapper<Tag>(dbFeatureHistoryRowMapper);
// Retrieves the basic tag information.
tagRowMapper = new TagRowMapper(dbFeatureRowMapper);
// Perform the query passing the row mapper chain to process rows in a streamy fashion.
namedParamJdbcTemplate.query(sql, parameterSource, tagRowMapper);
// Open a iterator on the store that will release the store upon completion.
resultIterator = new StoreReleasingIterator<DbFeatureHistory<DbFeature<Tag>>>(store.iterate(), store);
// The store itself shouldn't be released now that it has been attached to the iterator.
store = null;
return resultIterator;
} finally {
if (store != null) {
store.release();
}
}
}
private ReleasableIterator<DbFeatureHistory<DbFeature<Tag>>> getTagHistory(String selectedEntityTableName) {
StringBuilder sql;
MapSqlParameterSource parameterSource;
sql = new StringBuilder();
sql.append("SELECT et.id, et.k, et.v, et.version");
sql.append(" FROM ");
sql.append(entityName);
sql.append("_tags et");
sql.append(" INNER JOIN ");
sql.append(selectedEntityTableName);
sql.append(" t ON et.id = t.id AND et.version = t.version");
sql.append(" ORDER BY et.id, et.version");
LOG.log(Level.FINER, "Tag history query: " + sql);
parameterSource = new MapSqlParameterSource();
return getTagHistory(sql.toString(), parameterSource);
}
private ReleasableIterator<EntityHistory<T>> getEntityHistory(String selectedEntityTableName) {
ReleasableContainer releasableContainer;
releasableContainer = new ReleasableContainer();
try {
ReleasableIterator<EntityHistory<T>> entityIterator;
ReleasableIterator<DbFeatureHistory<DbFeature<Tag>>> tagIterator;
List<FeatureHistoryPopulator<T, ?>> featurePopulators;
EntityHistoryReader<T> entityHistoryReader;
entityIterator = releasableContainer.add(getRawEntityHistory(selectedEntityTableName));
tagIterator = releasableContainer.add(getTagHistory(selectedEntityTableName));
featurePopulators = getFeatureHistoryPopulators(selectedEntityTableName);
for (FeatureHistoryPopulator<T, ?> featurePopulator : featurePopulators) {
releasableContainer.add(featurePopulator);
}
entityHistoryReader = new EntityHistoryReader<T>(entityIterator, tagIterator, featurePopulators);
// The sources are now all attached to the history reader so we don't want to release
// them in the finally block.
releasableContainer.clear();
return entityHistoryReader;
} finally {
releasableContainer.release();
}
}
private ReleasableIterator<ChangeContainer> getChangeHistory(String selectedEntityTableName) {
return new ChangeReader<T>(getEntityHistory(selectedEntityTableName), getContainerFactory());
}
private List<Integer> buildTransactionRanges(long bottomTransactionId, long topTransactionId) {
List<Integer> rangeValues;
int topTransactionIdInt;
int currentXid;
// We need the top transaction id in int form so that we can tell if it will be treated as a
// negative number.
topTransactionIdInt = (int) topTransactionId;
// Begin building the values to use in the WHERE clause transaction ranges. Each pair of ids
// in this list will become a range selection.
rangeValues = new ArrayList<Integer>();
// The bottom id is the last one read, so we begin reading from the next transaction.
currentXid = ((int) bottomTransactionId) + 1;
rangeValues.add(currentXid);
// We only have data to process if the two transaction ids are not equal.
- if (bottomTransactionId != topTransactionId) {
+ if (currentXid != topTransactionId) {
// Process until we have enough ranges to reach the top transaction id.
while (currentXid != topTransactionIdInt) {
// Determine how to terminate the current transaction range.
if (currentXid <= 2 && topTransactionId >= 0) {
// The range overlaps special ids 0-2 which should never be queried on.
// Terminate the current range before the special values.
rangeValues.add(-1);
// Begin the new range after the special values.
rangeValues.add(3);
currentXid = 3;
} else if (topTransactionIdInt < currentXid) {
// The range crosses the integer overflow point. Only do this check once we are
// past 2 because the xid special values 0-2 may need to be crossed first.
// Terminate the current range at the maximum int value.
rangeValues.add(Integer.MAX_VALUE);
// Begin a new range at the minimum int value.
rangeValues.add(Integer.MIN_VALUE);
currentXid = Integer.MIN_VALUE;
} else {
// There are no problematic transaction id values between the current value and
// the top transaction id so terminate the current range at the top transaction
// id.
rangeValues.add(topTransactionIdInt);
currentXid = topTransactionIdInt;
}
}
} else {
// Terminate the range at the top transaction id. The start of the range is one higher
// therefore no data will be selected.
rangeValues.add(topTransactionIdInt);
}
return rangeValues;
}
private void buildTransactionRangeWhereClause(StringBuilder sql, MapSqlParameterSource parameters,
long bottomTransactionId, long topTransactionId) {
List<Integer> rangeValues;
// Determine the transaction ranges required to select all transactions between the bottom
// and top values. This takes into account transaction id wrapping issues and reserved ids.
rangeValues = buildTransactionRanges(bottomTransactionId, topTransactionId);
// Create a range clause for each range pair.
for (int i = 0; i < rangeValues.size(); i = i + 2) {
if (i > 0) {
sql.append(" OR ");
}
sql.append("(");
sql.append("xid_to_int4(xmin) >= :rangeValue").append(i);
sql.append(" AND ");
sql.append("xid_to_int4(xmin) <= :rangeValue").append(i + 1);
sql.append(")");
parameters.addValue("rangeValue" + i, rangeValues.get(i), Types.INTEGER);
parameters.addValue("rangeValue" + (i + 1), rangeValues.get(i + 1), Types.INTEGER);
}
}
private void buildTransactionIdListWhereClause(StringBuilder sql, List<Long> transactionIdList) {
for (int i = 0; i < transactionIdList.size(); i++) {
if (i > 0) {
sql.append(",");
}
// Must cast to int to allow the integer based xmin index to be used correctly.
sql.append((int) transactionIdList.get(i).longValue());
}
}
/**
* Retrieves the changes that have were made by a set of transactions.
*
* @param predicates
* Contains the predicates defining the transactions to be queried.
* @return An iterator pointing at the identified records.
*/
public ReleasableIterator<ChangeContainer> getHistory(ReplicationQueryPredicates predicates) {
String selectedEntityTableName;
StringBuilder sql;
MapSqlParameterSource parameterSource;
parameterSource = new MapSqlParameterSource();
selectedEntityTableName = "tmp_" + entityName + "s";
sql = new StringBuilder();
sql.append("CREATE TEMPORARY TABLE ");
sql.append(selectedEntityTableName);
sql.append(" ON COMMIT DROP");
sql.append(" AS SELECT id, version FROM ");
sql.append(entityName);
sql.append("s WHERE ((");
// Add the main transaction ranges to the where clause.
buildTransactionRangeWhereClause(sql, parameterSource, predicates.getBottomTransactionId(), predicates
.getTopTransactionId());
sql.append(")");
// If previously active transactions have become ready since the last invocation we include those as well.
if (predicates.getReadyList().size() > 0) {
sql.append(" OR xid_to_int4(xmin) IN [");
buildTransactionIdListWhereClause(sql, predicates.getReadyList());
sql.append("]");
}
sql.append(")");
// Any active transactions must be explicitly excluded.
if (predicates.getActiveList().size() > 0) {
sql.append(" AND xid_to_int4(xmin) NOT IN [");
buildTransactionIdListWhereClause(sql, predicates.getActiveList());
sql.append("]");
}
LOG.log(Level.FINER, "Entity identification query: " + sql);
namedParamJdbcTemplate.update(sql.toString(), parameterSource);
if (LOG.isLoggable(Level.FINER)) {
LOG.log(Level.FINER,
jdbcTemplate.queryForInt("SELECT Count(id) FROM " + selectedEntityTableName) + " "
+ entityName + " records located.");
}
return getChangeHistory(selectedEntityTableName);
}
/**
* Retrieves the changes that have were made between two points in time.
*
* @param intervalBegin
* Marks the beginning (inclusive) of the time interval to be checked.
* @param intervalEnd
* Marks the end (exclusive) of the time interval to be checked.
* @return An iterator pointing at the identified records.
*/
public ReleasableIterator<ChangeContainer> getHistory(Date intervalBegin, Date intervalEnd) {
String selectedEntityTableName;
StringBuilder sql;
MapSqlParameterSource parameterSource;
selectedEntityTableName = "tmp_" + entityName + "s";
sql = new StringBuilder();
sql.append("CREATE TEMPORARY TABLE ");
sql.append(selectedEntityTableName);
sql.append(" ON COMMIT DROP");
sql.append(" AS SELECT id, version FROM ");
sql.append(entityName);
sql.append("s WHERE timestamp > :intervalBegin AND timestamp <= :intervalEnd");
LOG.log(Level.FINER, "Entity identification query: " + sql);
parameterSource = new MapSqlParameterSource();
parameterSource.addValue("intervalBegin", intervalBegin, Types.TIMESTAMP);
parameterSource.addValue("intervalEnd", intervalEnd, Types.TIMESTAMP);
namedParamJdbcTemplate.update(sql.toString(), parameterSource);
return getChangeHistory(selectedEntityTableName);
}
/**
* Retrieves all changes in the database.
*
* @return An iterator pointing at the identified records.
*/
public ReleasableIterator<ChangeContainer> getHistory() {
// Join the entity table to itself which will return all records.
return getChangeHistory(entityName + "s");
}
/**
* Retrieves all current data in the database.
*
* @return An iterator pointing at the current records.
*/
public ReleasableIterator<EntityContainer> getCurrent() {
// Join the entity table to the current version of itself which will return all current
// records.
return new EntityContainerReader<T>(getEntityHistory("(SELECT id, version FROM current_" + entityName
+ "s WHERE visible = TRUE)"), getContainerFactory());
}
}
| true | true | private List<Integer> buildTransactionRanges(long bottomTransactionId, long topTransactionId) {
List<Integer> rangeValues;
int topTransactionIdInt;
int currentXid;
// We need the top transaction id in int form so that we can tell if it will be treated as a
// negative number.
topTransactionIdInt = (int) topTransactionId;
// Begin building the values to use in the WHERE clause transaction ranges. Each pair of ids
// in this list will become a range selection.
rangeValues = new ArrayList<Integer>();
// The bottom id is the last one read, so we begin reading from the next transaction.
currentXid = ((int) bottomTransactionId) + 1;
rangeValues.add(currentXid);
// We only have data to process if the two transaction ids are not equal.
if (bottomTransactionId != topTransactionId) {
// Process until we have enough ranges to reach the top transaction id.
while (currentXid != topTransactionIdInt) {
// Determine how to terminate the current transaction range.
if (currentXid <= 2 && topTransactionId >= 0) {
// The range overlaps special ids 0-2 which should never be queried on.
// Terminate the current range before the special values.
rangeValues.add(-1);
// Begin the new range after the special values.
rangeValues.add(3);
currentXid = 3;
} else if (topTransactionIdInt < currentXid) {
// The range crosses the integer overflow point. Only do this check once we are
// past 2 because the xid special values 0-2 may need to be crossed first.
// Terminate the current range at the maximum int value.
rangeValues.add(Integer.MAX_VALUE);
// Begin a new range at the minimum int value.
rangeValues.add(Integer.MIN_VALUE);
currentXid = Integer.MIN_VALUE;
} else {
// There are no problematic transaction id values between the current value and
// the top transaction id so terminate the current range at the top transaction
// id.
rangeValues.add(topTransactionIdInt);
currentXid = topTransactionIdInt;
}
}
} else {
// Terminate the range at the top transaction id. The start of the range is one higher
// therefore no data will be selected.
rangeValues.add(topTransactionIdInt);
}
return rangeValues;
}
| private List<Integer> buildTransactionRanges(long bottomTransactionId, long topTransactionId) {
List<Integer> rangeValues;
int topTransactionIdInt;
int currentXid;
// We need the top transaction id in int form so that we can tell if it will be treated as a
// negative number.
topTransactionIdInt = (int) topTransactionId;
// Begin building the values to use in the WHERE clause transaction ranges. Each pair of ids
// in this list will become a range selection.
rangeValues = new ArrayList<Integer>();
// The bottom id is the last one read, so we begin reading from the next transaction.
currentXid = ((int) bottomTransactionId) + 1;
rangeValues.add(currentXid);
// We only have data to process if the two transaction ids are not equal.
if (currentXid != topTransactionId) {
// Process until we have enough ranges to reach the top transaction id.
while (currentXid != topTransactionIdInt) {
// Determine how to terminate the current transaction range.
if (currentXid <= 2 && topTransactionId >= 0) {
// The range overlaps special ids 0-2 which should never be queried on.
// Terminate the current range before the special values.
rangeValues.add(-1);
// Begin the new range after the special values.
rangeValues.add(3);
currentXid = 3;
} else if (topTransactionIdInt < currentXid) {
// The range crosses the integer overflow point. Only do this check once we are
// past 2 because the xid special values 0-2 may need to be crossed first.
// Terminate the current range at the maximum int value.
rangeValues.add(Integer.MAX_VALUE);
// Begin a new range at the minimum int value.
rangeValues.add(Integer.MIN_VALUE);
currentXid = Integer.MIN_VALUE;
} else {
// There are no problematic transaction id values between the current value and
// the top transaction id so terminate the current range at the top transaction
// id.
rangeValues.add(topTransactionIdInt);
currentXid = topTransactionIdInt;
}
}
} else {
// Terminate the range at the top transaction id. The start of the range is one higher
// therefore no data will be selected.
rangeValues.add(topTransactionIdInt);
}
return rangeValues;
}
|
diff --git a/org.eclipse.b3.backend/src/org/eclipse/b3/backend/evaluator/b3backend/impl/B3FunctionImpl.java b/org.eclipse.b3.backend/src/org/eclipse/b3/backend/evaluator/b3backend/impl/B3FunctionImpl.java
index 5e0435c3..6cb9bd53 100644
--- a/org.eclipse.b3.backend/src/org/eclipse/b3/backend/evaluator/b3backend/impl/B3FunctionImpl.java
+++ b/org.eclipse.b3.backend/src/org/eclipse/b3/backend/evaluator/b3backend/impl/B3FunctionImpl.java
@@ -1,241 +1,241 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.b3.backend.evaluator.b3backend.impl;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.b3.backend.core.B3IncompatibleTypeException;
import org.eclipse.b3.backend.evaluator.b3backend.B3Function;
import org.eclipse.b3.backend.evaluator.b3backend.B3backendPackage;
import org.eclipse.b3.backend.evaluator.b3backend.BExecutionContext;
import org.eclipse.b3.backend.evaluator.b3backend.BExpression;
import org.eclipse.b3.backend.evaluator.typesystem.B3ParameterizedType;
import org.eclipse.b3.backend.evaluator.typesystem.TypeUtils;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>B3 Function</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.b3.backend.evaluator.b3backend.impl.B3FunctionImpl#getFuncExpr <em>Func Expr</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class B3FunctionImpl extends BFunctionImpl implements B3Function {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String copyright = "Copyright (c) 2009, Cloudsmith Inc and others.\nAll rights reserved. This program and the accompanying materials\nare made available under the terms of the Eclipse Public License v1.0\nwhich accompanies this distribution, and is available at\nhttp://www.eclipse.org/legal/epl-v10.html\n\rContributors:\n- Cloudsmith Inc - initial API and implementation.\r";
/**
* The cached value of the '{@link #getFuncExpr() <em>Func Expr</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFuncExpr()
* @generated
* @ordered
*/
protected BExpression funcExpr;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected B3FunctionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return B3backendPackage.Literals.B3_FUNCTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BExpression getFuncExpr() {
return funcExpr;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetFuncExpr(BExpression newFuncExpr, NotificationChain msgs) {
BExpression oldFuncExpr = funcExpr;
funcExpr = newFuncExpr;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, B3backendPackage.B3_FUNCTION__FUNC_EXPR, oldFuncExpr, newFuncExpr);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFuncExpr(BExpression newFuncExpr) {
if (newFuncExpr != funcExpr) {
NotificationChain msgs = null;
if (funcExpr != null)
msgs = ((InternalEObject)funcExpr).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - B3backendPackage.B3_FUNCTION__FUNC_EXPR, null, msgs);
if (newFuncExpr != null)
msgs = ((InternalEObject)newFuncExpr).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - B3backendPackage.B3_FUNCTION__FUNC_EXPR, null, msgs);
msgs = basicSetFuncExpr(newFuncExpr, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, B3backendPackage.B3_FUNCTION__FUNC_EXPR, newFuncExpr, newFuncExpr));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case B3backendPackage.B3_FUNCTION__FUNC_EXPR:
return basicSetFuncExpr(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case B3backendPackage.B3_FUNCTION__FUNC_EXPR:
return getFuncExpr();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case B3backendPackage.B3_FUNCTION__FUNC_EXPR:
setFuncExpr((BExpression)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case B3backendPackage.B3_FUNCTION__FUNC_EXPR:
setFuncExpr((BExpression)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case B3backendPackage.B3_FUNCTION__FUNC_EXPR:
return funcExpr != null;
}
return super.eIsSet(featureID);
}
/**
* Calls the B3 Defined function using the context passed as the context for the function.
* Function starts by binding the parameters to declared parameter names.
* Function body is then evaluated and returned.
*/
@SuppressWarnings("unchecked")
@Override
public Object internalCall(BExecutionContext octx, Object[] parameters, Type[] types) throws Throwable {
computeParameters();
if(parameterTypes.length > 0) { // if function takes no parameters, there is no binding to be done
int limit = parameterTypes.length -1; // bind all but the last defined parameter
if(parameters.length < limit)
throw new IllegalArgumentException("B3 Function called with too few arguments");
for(int i = 0; i < limit; i++) {
// check type compatibility
- if(!((Class)parameterTypes[i]).isAssignableFrom(parameters[i].getClass()))
+ if(!(TypeUtils.getRaw(parameterTypes[i]).isAssignableFrom(parameters[i].getClass())))
throw new B3IncompatibleTypeException(parameterNames[i],
parameterTypes[i].getClass(), parameters[i].getClass());
// ok, define it
octx.defineVariableValue(parameterNames[i], parameters[i], parameterTypes[i]);
}
if(!isVarArgs()) { // if not varargs, bind the last defined parameter
if(parameters.length < parameterTypes.length)
throw new IllegalArgumentException("B3 Function called with too few arguments. Expected: "+parameterTypes.length +" but got: "+parameters.length);
// check type compatibility
if(!(TypeUtils.getRaw(parameterTypes[limit])).isAssignableFrom(parameters[limit].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
parameterTypes[limit].getClass(), parameters[limit].getClass());
// ok
octx.defineVariableValue(parameterNames[limit], parameters[limit], parameterTypes[limit]);
} else {
// varargs call, create a list and stuff any remaining parameters there
List<Object> varargs = new ArrayList<Object>();
Class varargsType = parameterTypes[limit].getClass();
for(int i = limit; i < parameters.length; i++) {
if(!varargsType.isAssignableFrom(parameters[i].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
varargsType, parameters[i].getClass());
varargs.add(parameters[i]);
}
// bind the varargs to a List of the declared type (possibly an empty list).
octx.defineVariableValue(parameterNames[limit], varargs,
new B3ParameterizedType(List.class, new Type[] { parameterTypes[limit] }));
}
}
// all set up - fire away
return funcExpr.evaluate(octx);
}
} //B3FunctionImpl
| true | true | public Object internalCall(BExecutionContext octx, Object[] parameters, Type[] types) throws Throwable {
computeParameters();
if(parameterTypes.length > 0) { // if function takes no parameters, there is no binding to be done
int limit = parameterTypes.length -1; // bind all but the last defined parameter
if(parameters.length < limit)
throw new IllegalArgumentException("B3 Function called with too few arguments");
for(int i = 0; i < limit; i++) {
// check type compatibility
if(!((Class)parameterTypes[i]).isAssignableFrom(parameters[i].getClass()))
throw new B3IncompatibleTypeException(parameterNames[i],
parameterTypes[i].getClass(), parameters[i].getClass());
// ok, define it
octx.defineVariableValue(parameterNames[i], parameters[i], parameterTypes[i]);
}
if(!isVarArgs()) { // if not varargs, bind the last defined parameter
if(parameters.length < parameterTypes.length)
throw new IllegalArgumentException("B3 Function called with too few arguments. Expected: "+parameterTypes.length +" but got: "+parameters.length);
// check type compatibility
if(!(TypeUtils.getRaw(parameterTypes[limit])).isAssignableFrom(parameters[limit].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
parameterTypes[limit].getClass(), parameters[limit].getClass());
// ok
octx.defineVariableValue(parameterNames[limit], parameters[limit], parameterTypes[limit]);
} else {
// varargs call, create a list and stuff any remaining parameters there
List<Object> varargs = new ArrayList<Object>();
Class varargsType = parameterTypes[limit].getClass();
for(int i = limit; i < parameters.length; i++) {
if(!varargsType.isAssignableFrom(parameters[i].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
varargsType, parameters[i].getClass());
varargs.add(parameters[i]);
}
// bind the varargs to a List of the declared type (possibly an empty list).
octx.defineVariableValue(parameterNames[limit], varargs,
new B3ParameterizedType(List.class, new Type[] { parameterTypes[limit] }));
}
}
// all set up - fire away
return funcExpr.evaluate(octx);
}
| public Object internalCall(BExecutionContext octx, Object[] parameters, Type[] types) throws Throwable {
computeParameters();
if(parameterTypes.length > 0) { // if function takes no parameters, there is no binding to be done
int limit = parameterTypes.length -1; // bind all but the last defined parameter
if(parameters.length < limit)
throw new IllegalArgumentException("B3 Function called with too few arguments");
for(int i = 0; i < limit; i++) {
// check type compatibility
if(!(TypeUtils.getRaw(parameterTypes[i]).isAssignableFrom(parameters[i].getClass())))
throw new B3IncompatibleTypeException(parameterNames[i],
parameterTypes[i].getClass(), parameters[i].getClass());
// ok, define it
octx.defineVariableValue(parameterNames[i], parameters[i], parameterTypes[i]);
}
if(!isVarArgs()) { // if not varargs, bind the last defined parameter
if(parameters.length < parameterTypes.length)
throw new IllegalArgumentException("B3 Function called with too few arguments. Expected: "+parameterTypes.length +" but got: "+parameters.length);
// check type compatibility
if(!(TypeUtils.getRaw(parameterTypes[limit])).isAssignableFrom(parameters[limit].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
parameterTypes[limit].getClass(), parameters[limit].getClass());
// ok
octx.defineVariableValue(parameterNames[limit], parameters[limit], parameterTypes[limit]);
} else {
// varargs call, create a list and stuff any remaining parameters there
List<Object> varargs = new ArrayList<Object>();
Class varargsType = parameterTypes[limit].getClass();
for(int i = limit; i < parameters.length; i++) {
if(!varargsType.isAssignableFrom(parameters[i].getClass()))
throw new B3IncompatibleTypeException(parameterNames[limit],
varargsType, parameters[i].getClass());
varargs.add(parameters[i]);
}
// bind the varargs to a List of the declared type (possibly an empty list).
octx.defineVariableValue(parameterNames[limit], varargs,
new B3ParameterizedType(List.class, new Type[] { parameterTypes[limit] }));
}
}
// all set up - fire away
return funcExpr.evaluate(octx);
}
|
diff --git a/com.ibm.wala.core/src/com/ibm/wala/ipa/callgraph/propagation/SSAPropagationCallGraphBuilder.java b/com.ibm.wala.core/src/com/ibm/wala/ipa/callgraph/propagation/SSAPropagationCallGraphBuilder.java
index baae60c10..6c7c800b1 100644
--- a/com.ibm.wala.core/src/com/ibm/wala/ipa/callgraph/propagation/SSAPropagationCallGraphBuilder.java
+++ b/com.ibm.wala.core/src/com/ibm/wala/ipa/callgraph/propagation/SSAPropagationCallGraphBuilder.java
@@ -1,2092 +1,2095 @@
/*******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.ipa.callgraph.propagation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.ibm.wala.analysis.reflection.CloneInterpreter;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.ProgramCounter;
import com.ibm.wala.fixedpoint.impl.UnaryOperator;
import com.ibm.wala.fixpoint.IntSetVariable;
import com.ibm.wala.ipa.callgraph.AnalysisCache;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.callgraph.impl.FakeWorldClinitMethod;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrikeBT.ConditionalBranchInstruction;
import com.ibm.wala.shrikeBT.IInstruction;
import com.ibm.wala.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractThrowInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadClassInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.ssa.SSACFG.BasicBlock;
import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.ref.ReferenceCleanser;
import com.ibm.wala.util.warnings.Warning;
import com.ibm.wala.util.warnings.Warnings;
/**
* This abstract base class provides the general algorithm for a call graph builder that relies on propagation through
* an iterative dataflow solver, and constraints generated by statements in SSA form.
*
* TODO: This implementation currently keeps all points to sets live ... even those for local variables that do not span
* interprocedural boundaries. This may be too space-inefficient .. we can consider recomputing local sets on demand.
*
* @author sfink
* @author adonovan
*/
public abstract class SSAPropagationCallGraphBuilder extends PropagationCallGraphBuilder implements HeapModel {
private final static boolean DEBUG = false;
private final static boolean DEBUG_MULTINEWARRAY = DEBUG | false;
/**
* Should we periodically clear out soft reference caches in an attempt to help the GC?
*/
public final static boolean PERIODIC_WIPE_SOFT_CACHES = true;
/**
* Interval which defines the period to clear soft reference caches
*/
public final static int WIPE_SOFT_CACHE_INTERVAL = 2500;
/**
* Counter for wiping soft caches
*/
private static int wipeCount = 0;
/**
* use type inference to avoid unnecessary filter constraints?
*/
// private final static boolean OPTIMIZE_WITH_TYPE_INFERENCE = true;
/**
* An optimization: if we can locally determine the final solution for a points-to set, then don't actually create the
* points-to set, but instead short circuit by propagating the final solution to all such uses.
*
* String constants are ALWAYS considered invariant, regardless of the value of this flag.
*
* However, if this flag is set, then the solver is more aggressive identifying invariants.
*
* Doesn't play well with pre-transitive solver; turning off for now.
*/
private final static boolean SHORT_CIRCUIT_INVARIANT_SETS = true;
/**
* An optimization: if we can locally determine that a particular pointer p has exactly one use, then we don't
* actually create the points-to-set for p, but instead short-circuit by propagating the final solution to the unique
* use.
*
* Doesn't play well with pre-transitive solver; turning off for now.
*/
protected final static boolean SHORT_CIRCUIT_SINGLE_USES = true;
/**
* Should we change calls to clone() to assignments?
*/
private final boolean clone2Assign = false;
/**
* Cache for efficiency
*/
private final static Selector cloneSelector = CloneInterpreter.CLONE.getSelector();
/**
* set of class whose clinits have already been processed
*/
private final Set<IClass> clinitVisited = HashSetFactory.make();
/**
* Should we use the pre-transitive solver?
*/
private final boolean usePreTransitiveSolver;
protected SSAPropagationCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, AnalysisCache cache,
PointerKeyFactory pointerKeyFactory) {
super(cha, options, cache, pointerKeyFactory);
this.usePreTransitiveSolver = options.usePreTransitiveSolver();
}
public SSAContextInterpreter getCFAContextInterpreter() {
return (SSAContextInterpreter) getContextInterpreter();
}
/**
* @param node
* @param x
* @param type
* @return the instance key that represents the exception of type _type_ thrown by a particular PEI.
* @throws IllegalArgumentException if ikFactory is null
*/
public static InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter x, TypeReference type, InstanceKeyFactory ikFactory) {
if (ikFactory == null) {
throw new IllegalArgumentException("ikFactory is null");
}
return ikFactory.getInstanceKeyForPEI(node, x, type);
}
/**
* Visit all instructions in a node, and add dataflow constraints induced by each statement in the SSA form.
*
* @see com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder#addConstraintsFromNode(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
protected boolean addConstraintsFromNode(CGNode node) {
if (haveAlreadyVisited(node)) {
return false;
} else {
markAlreadyVisited(node);
}
return unconditionallyAddConstraintsFromNode(node);
}
@Override
protected boolean unconditionallyAddConstraintsFromNode(CGNode node) {
if (PERIODIC_WIPE_SOFT_CACHES) {
wipeCount++;
if (wipeCount >= WIPE_SOFT_CACHE_INTERVAL) {
wipeCount = 0;
ReferenceCleanser.clearSoftCaches();
}
}
if (DEBUG) {
System.err.println("\n\nAdd constraints from node " + node);
}
IR ir = getCFAContextInterpreter().getIR(node);
if (DEBUG) {
if (ir == null) {
System.err.println("\n No statements\n");
} else {
try {
System.err.println(ir.toString());
} catch (Error e) {
e.printStackTrace();
}
}
}
if (ir == null) {
return false;
}
addNodeInstructionConstraints(node);
DefUse du = getCFAContextInterpreter().getDU(node);
addNodePassthruExceptionConstraints(node, ir, du);
// conservatively assume something changed
return true;
}
/**
* @return a visitor to examine instructions in the ir
*/
protected ConstraintVisitor makeVisitor(ExplicitCallGraph.ExplicitNode node) {
return new ConstraintVisitor(this, node);
}
/**
* Add pointer flow constraints based on instructions in a given node
*/
protected void addNodeInstructionConstraints(CGNode node) {
ConstraintVisitor v = makeVisitor((ExplicitCallGraph.ExplicitNode) node);
IR ir = getCFAContextInterpreter().getIR(node);
ControlFlowGraph<ISSABasicBlock> cfg = ir.getControlFlowGraph();
for (Iterator<ISSABasicBlock> x = cfg.iterator(); x.hasNext();) {
BasicBlock b = (BasicBlock) x.next();
addBlockInstructionConstraints(node, cfg, b, v);
if (wasChanged(node)) {
return;
}
}
}
/**
* Add constraints for a particular basic block.
*/
protected void addBlockInstructionConstraints(CGNode node, ControlFlowGraph<ISSABasicBlock> cfg, BasicBlock b, ConstraintVisitor v) {
v.setBasicBlock(b);
// visit each instruction in the basic block.
for (Iterator<IInstruction> it = b.iterator(); it.hasNext();) {
SSAInstruction s = (SSAInstruction) it.next();
if (s != null) {
s.visit(v);
if (wasChanged(node)) {
return;
}
}
}
addPhiConstraints(node, cfg, b, v);
}
private void addPhiConstraints(CGNode node, ControlFlowGraph<ISSABasicBlock> cfg, BasicBlock b, ConstraintVisitor v) {
// visit each phi instruction in each successor block
for (Iterator sbs = cfg.getSuccNodes(b); sbs.hasNext();) {
BasicBlock sb = (BasicBlock) sbs.next();
if (!sb.hasPhi()) {
continue;
}
int n = 0;
for (Iterator<? extends IBasicBlock> back = cfg.getPredNodes(sb); back.hasNext(); n++) {
if (back.next() == b) {
break;
}
}
if (DEBUG && Assertions.verifyAssertions) {
Assertions._assert(n < cfg.getPredNodeCount(sb));
}
for (Iterator<? extends SSAInstruction> phis = sb.iteratePhis(); phis.hasNext();) {
SSAPhiInstruction phi = (SSAPhiInstruction) phis.next();
if (phi == null) {
continue;
}
PointerKey def = getPointerKeyForLocal(node, phi.getDef());
if (hasNoInterestingUses(node, phi.getDef(), v.du)) {
system.recordImplicitPointsToSet(def);
} else {
// the following test restricts the constraints to reachable
// paths, according to verification constraints
if (phi.getUse(n) > 0) {
PointerKey use = getPointerKeyForLocal(node, phi.getUse(n));
if (contentsAreInvariant(v.symbolTable, v.du, phi.getUse(n))) {
system.recordImplicitPointsToSet(use);
InstanceKey[] ik = getInvariantContents(v.symbolTable, v.du, node, phi.getUse(n), this);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(def, ik[i]);
}
} else {
system.newConstraint(def, assignOperator, use);
}
}
}
}
}
}
/**
* Add constraints to represent the flow of exceptions to the exceptional return value for this node
*
* @param node
* @param ir
*/
protected void addNodePassthruExceptionConstraints(CGNode node, IR ir, DefUse du) {
// add constraints relating to thrown exceptions that reach the exit block.
List<ProgramCounter> peis = getIncomingPEIs(ir, ir.getExitBlock());
PointerKey exception = getPointerKeyForExceptionalReturnValue(node);
TypeReference throwableType =
node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getThrowableType();
IClass c = node.getClassHierarchy().lookupClass(throwableType);
addExceptionDefConstraints(ir, du, node, peis, exception, Collections.singleton(c));
}
/**
* Generate constraints which assign exception values into an exception pointer
*
* @param node governing node
* @param peis list of PEI instructions
* @param exceptionVar PointerKey representing a pointer to an exception value
* @param catchClasses the types "caught" by the exceptionVar
*/
private void addExceptionDefConstraints(IR ir, DefUse du, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar,
Set<IClass> catchClasses) {
if (DEBUG) {
System.err.println("Add exception def constraints for node " + node);
}
for (Iterator<ProgramCounter> it = peis.iterator(); it.hasNext();) {
ProgramCounter peiLoc = it.next();
if (DEBUG) {
System.err.println("peiLoc: " + peiLoc);
}
SSAInstruction pei = ir.getPEI(peiLoc);
if (DEBUG) {
System.err.println("Add exceptions from pei " + pei);
}
if (pei instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (!SHORT_CIRCUIT_SINGLE_USES || !hasUniqueCatchBlock(s, ir)) {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}// else {
// System.err.println("SKIPPING ASSIGNMENTS TO " + exceptionVar + " FROM " +
// e);
// }
} else if (pei instanceof SSAAbstractThrowInstruction) {
SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (contentsAreInvariant(ir.getSymbolTable(), du, s.getException())) {
InstanceKey[] ik = getInvariantContents(ir.getSymbolTable(), du, node, s.getException(), this);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
assignInstanceToCatch(exceptionVar, catchClasses, ik[i]);
}
} else {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}
}
// Account for those exceptions for which we do not actually have a
// points-to set for
// the pei, but just instance keys
Collection<TypeReference> types = pei.getExceptionTypes();
if (types != null) {
for (Iterator<TypeReference> it2 = types.iterator(); it2.hasNext();) {
TypeReference type = it2.next();
if (type != null) {
InstanceKey ik = getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory);
if (ik == null) {
continue;
}
if (Assertions.verifyAssertions) {
if (!(ik instanceof ConcreteTypeKey)) {
Assertions._assert(ik instanceof ConcreteTypeKey,
"uh oh: need to implement getCaughtException constraints for instance " + ik);
}
}
ConcreteTypeKey ck = (ConcreteTypeKey) ik;
IClass klass = ck.getType();
if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) {
system.newConstraint(exceptionVar, getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory));
}
}
}
}
}
}
/**
* @return true iff there's a unique catch block which catches all exceptions thrown by a certain call site.
*/
protected static boolean hasUniqueCatchBlock(SSAAbstractInvokeInstruction call, IR ir) {
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (bb.length == 1) {
Iterator it = ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator();
// check that there's exactly one element in the iterator
if (it.hasNext()) {
it.next();
return (!it.hasNext());
}
}
return false;
}
/**
* precondition: hasUniqueCatchBlock(call,node,cg)
*
* @return the unique pointer key which catches the exceptions thrown by a call
* @throws IllegalArgumentException if ir == null
* @throws IllegalArgumentException if call == null
*/
public PointerKey getUniqueCatchKey(SSAAbstractInvokeInstruction call, IR ir, CGNode node) throws IllegalArgumentException,
IllegalArgumentException {
if (call == null) {
throw new IllegalArgumentException("call == null");
}
if (ir == null) {
throw new IllegalArgumentException("ir == null");
}
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (Assertions.verifyAssertions) {
Assertions._assert(bb.length == 1);
}
SSACFG.BasicBlock cb = (BasicBlock) ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator().next();
if (cb.isExitBlock()) {
return getPointerKeyForExceptionalReturnValue(node);
} else {
SSACFG.ExceptionHandlerBasicBlock ehbb = (ExceptionHandlerBasicBlock) cb;
SSAGetCaughtExceptionInstruction ci = ehbb.getCatchInstruction();
return getPointerKeyForLocal(node, ci.getDef());
}
}
/**
* @return a List of Instructions that may transfer control to bb via an exceptional edge
* @throws IllegalArgumentException if ir is null
*/
public static List<ProgramCounter> getIncomingPEIs(IR ir, ISSABasicBlock bb) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (DEBUG) {
System.err.println("getIncomingPEIs " + bb);
}
ControlFlowGraph<ISSABasicBlock> g = ir.getControlFlowGraph();
List<ProgramCounter> result = new ArrayList<ProgramCounter>(g.getPredNodeCount(bb));
for (Iterator it = g.getPredNodes(bb); it.hasNext();) {
BasicBlock pred = (BasicBlock) it.next();
if (DEBUG) {
System.err.println("pred: " + pred);
}
if (pred.isEntryBlock())
continue;
int index = pred.getLastInstructionIndex();
SSAInstruction pei = ir.getInstructions()[index];
// Note: pei might be null if pred is unreachable.
// TODO: consider pruning CFG for unreachable blocks.
if (pei != null && pei.isPEI()) {
if (DEBUG) {
System.err.println("PEI: " + pei + " index " + index + " PC " + g.getProgramCounter(index));
}
result.add(new ProgramCounter(g.getProgramCounter(index)));
}
}
return result;
}
/**
* A visitor that generates constraints based on statements in SSA form.
*/
protected static class ConstraintVisitor extends SSAInstruction.Visitor {
/**
* The governing call graph builder. This field is used instead of an inner class in order to allow more flexible
* reuse of this visitor in subclasses
*/
protected final SSAPropagationCallGraphBuilder builder;
/**
* The node whose statements we are currently traversing
*/
protected final ExplicitCallGraph.ExplicitNode node;
/**
* The governing call graph.
*/
private final ExplicitCallGraph callGraph;
/**
* The governing IR
*/
protected final IR ir;
/**
* The governing propagation system, into which constraints are added
*/
protected final PropagationSystem system;
/**
* The basic block currently being processed
*/
private ISSABasicBlock basicBlock;
/**
* Governing symbol table
*/
protected final SymbolTable symbolTable;
/**
* Def-use information
*/
protected final DefUse du;
public ConstraintVisitor(SSAPropagationCallGraphBuilder builder, ExplicitCallGraph.ExplicitNode node) {
this.builder = builder;
this.node = node;
this.callGraph = builder.getCallGraph();
this.system = builder.getPropagationSystem();
this.ir = builder.getCFAContextInterpreter().getIR(node);
this.symbolTable = this.ir.getSymbolTable();
this.du = builder.getCFAContextInterpreter().getDU(node);
if (Assertions.verifyAssertions) {
Assertions._assert(symbolTable != null);
}
}
protected SSAPropagationCallGraphBuilder getBuilder() {
return builder;
}
protected AnalysisOptions getOptions() {
return builder.options;
}
protected AnalysisCache getAnalysisCache() {
return builder.getAnalysisCache();
}
public PointerKey getPointerKeyForLocal(int valueNumber) {
return getBuilder().getPointerKeyForLocal(node, valueNumber);
}
public FilteredPointerKey getFilteredPointerKeyForLocal(int valueNumber, FilteredPointerKey.TypeFilter filter) {
return getBuilder().getFilteredPointerKeyForLocal(node, valueNumber, filter);
}
public PointerKey getPointerKeyForReturnValue() {
return getBuilder().getPointerKeyForReturnValue(node);
}
public PointerKey getPointerKeyForExceptionalReturnValue() {
return getBuilder().getPointerKeyForExceptionalReturnValue(node);
}
public PointerKey getPointerKeyForStaticField(IField f) {
return getBuilder().getPointerKeyForStaticField(f);
}
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) {
return getBuilder().getPointerKeyForInstanceField(I, f);
}
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
return getBuilder().getPointerKeyForArrayContents(I);
}
public InstanceKey getInstanceKeyForAllocation(NewSiteReference allocation) {
return getBuilder().getInstanceKeyForAllocation(node, allocation);
}
public InstanceKey getInstanceKeyForMultiNewArray(NewSiteReference allocation, int dim) {
return getBuilder().getInstanceKeyForMultiNewArray(node, allocation, dim);
}
public <T> InstanceKey getInstanceKeyForConstant(T S) {
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
return getBuilder().getInstanceKeyForConstant(type, S);
}
public InstanceKey getInstanceKeyForPEI(ProgramCounter instr, TypeReference type) {
return getBuilder().getInstanceKeyForPEI(node, instr, type);
}
public InstanceKey getInstanceKeyForClassObject(TypeReference type) {
return getBuilder().getInstanceKeyForClassObject(type);
}
public CGNode getTargetForCall(CGNode caller, CallSiteReference site, InstanceKey iKey) {
return getBuilder().getTargetForCall(caller, site, iKey);
}
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
return getBuilder().contentsAreInvariant(symbolTable, du, valueNumber);
}
protected InstanceKey[] getInvariantContents(int valueNumber) {
return getInvariantContents(ir.getSymbolTable(), du, node, valueNumber);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber) {
return getBuilder().getInvariantContents(symbolTable, du, node, valueNumber, getBuilder());
}
protected IClassHierarchy getClassHierarchy() {
return getBuilder().getClassHierarchy();
}
protected boolean hasNoInterestingUses(int vn) {
return getBuilder().hasNoInterestingUses(node, vn, du);
}
protected boolean isRootType(IClass klass) {
return getBuilder().isRootType(klass);
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayLoad(com.ibm.wala.ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayLoad(instruction.getDef(), instruction.getArrayRef());
}
protected void doVisitArrayLoad(int def, int arrayRef) {
PointerKey result = getPointerKeyForLocal(def);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
if (hasNoInterestingUses(def)) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
if (p == null) {
} else {
system.newConstraint(result, assignOperator, p);
}
}
}
} else {
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(result));
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new ArrayLoadOperator(system.findOrCreatePointsToSet(result)), arrayRefPtrKey);
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction)
*/
public void doVisitArrayStore(int arrayRef, int value) {
// (requires the creation of assign constraints as
// the set points-to(a[]) grows.)
PointerKey valuePtrKey = getPointerKeyForLocal(value);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getArrayRef())) {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
IClass contents = ((ArrayClass) ik[i].getConcreteType()).getElementClass();
if (p == null) {
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] vk = getInvariantContents(value);
for (int j = 0; j < vk.length; j++) {
system.findOrCreateIndexForInstanceKey(vk[j]);
if (vk[j].getConcreteType() != null) {
if (getClassHierarchy().isAssignableFrom(contents, vk[j].getConcreteType())) {
system.newConstraint(p, vk[j]);
}
}
}
} else {
if (isRootType(contents)) {
system.newConstraint(p, assignOperator, valuePtrKey);
} else {
system.newConstraint(p, getBuilder().filterOperator, valuePtrKey);
}
}
}
}
}
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] ik = getInvariantContents(value);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new InstanceArrayStoreOperator(ik[i]), arrayRefPtrKey);
}
} else {
system.newSideEffect(getBuilder().new ArrayStoreOperator(system.findOrCreatePointsToSet(valuePtrKey)), arrayRefPtrKey);
}
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayStore(instruction.getArrayRef(), instruction.getValue());
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitCheckCast(com.ibm.wala.ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
IClass cls = getClassHierarchy().lookupClass(instruction.getDeclaredResultType());
PointerKey result = null;
if (cls == null) {
Warnings.add(CheckcastFailure.create(instruction.getDeclaredResultType()));
// we failed to find the type.
// conservatively it would make sense to ignore the filter and be
// conservative, assuming
// java.lang.Object.
// however, this breaks the invariants downstream that assume every
// variable is
// strongly typed ... we can't have bad types flowing around.
// since things are broken anyway, just give up.
// result = getPointerKeyForLocal(node, instruction.getResult());
return;
} else {
result = getFilteredPointerKeyForLocal(instruction.getResult(), new FilteredPointerKey.SingleClassFilter(cls));
}
PointerKey value = getPointerKeyForLocal(instruction.getVal());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, instruction.getVal())) {
system.recordImplicitPointsToSet(value);
InstanceKey[] ik = getInvariantContents(instruction.getVal());
if (cls.isInterface()) {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().implementsInterface(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().isSubclassOf(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
}
} else {
if (isRootType(cls)) {
system.newConstraint(result, assignOperator, value);
} else {
system.newConstraint(result, getBuilder().filterOperator, value);
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitReturn(com.ibm.wala.ssa.SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {
// skip returns of primitive type
if (instruction.returnsPrimitiveType() || instruction.returnsVoid()) {
return;
}
if (DEBUG) {
System.err.println("visitReturn: " + instruction);
}
PointerKey returnValue = getPointerKeyForReturnValue();
PointerKey result = getPointerKeyForLocal(instruction.getResult());
if (contentsAreInvariant(symbolTable, du, instruction.getResult())) {
system.recordImplicitPointsToSet(result);
InstanceKey[] ik = getInvariantContents(instruction.getResult());
for (int i = 0; i < ik.length; i++) {
if (DEBUG) {
System.err.println("invariant contents: " + returnValue + " " + ik[i]);
}
system.newConstraint(returnValue, ik[i]);
}
} else {
system.newConstraint(returnValue, assignOperator, result);
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitGet(com.ibm.wala.ssa.SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
visitGetInternal(instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitGet " + field);
}
// skip getfields of primitive type (optimisation)
if (field.getFieldType().isPrimitiveType()) {
return;
}
PointerKey def = getPointerKeyForLocal(lval);
if (Assertions.verifyAssertions) {
Assertions._assert(def != null);
}
IField f = getClassHierarchy().resolveField(field);
if (f == null && callGraph.getFakeRootNode().getMethod().getDeclaringClass().getReference().equals(field.getDeclaringClass())) {
f = callGraph.getFakeRootNode().getMethod().getDeclaringClass().getField(field.getName());
}
if (f == null) {
return;
}
if (hasNoInterestingUses(lval)) {
system.recordImplicitPointsToSet(def);
} else {
if (isStatic) {
PointerKey fKey = getPointerKeyForStaticField(f);
system.newConstraint(def, assignOperator, fKey);
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
} else {
// side effect of getstatic: may call class initializer
if (DEBUG) {
System.err.println("getstatic call class init " + klass);
}
processClassInitializer(klass);
}
} else {
PointerKey refKey = getPointerKeyForLocal(ref);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(ref)) {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] ik = getInvariantContents(ref);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForInstanceField(ik[i], f);
system.newConstraint(def, assignOperator, p);
}
}
} else {
system.newSideEffect(getBuilder().new GetFieldOperator(f, system.findOrCreatePointsToSet(def)), refKey);
}
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitPut(com.ibm.wala.ssa.PutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
visitPutInternal(instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitPut " + field);
}
// skip putfields of primitive type
if (field.getFieldType().isPrimitiveType()) {
return;
}
IField f = getClassHierarchy().resolveField(field);
if (f == null) {
if (DEBUG) {
System.err.println("Could not resolve field " + field);
}
Warnings.add(FieldResolutionFailure.create(field));
return;
}
if (Assertions.verifyAssertions) {
Assertions._assert(isStatic || !symbolTable.isStringConstant(ref), "put to string constant shouldn't be allowed?");
}
if (isStatic) {
processPutStatic(rval, field, f);
} else {
processPutField(rval, ref, f);
}
}
private void processPutField(int rval, int ref, IField f) {
if (Assertions.verifyAssertions) {
Assertions._assert(!f.getFieldTypeReference().isPrimitiveType());
}
PointerKey refKey = getPointerKeyForLocal(ref);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(p, ik[i]);
}
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
system.newSideEffect(getBuilder().new InstancePutFieldOperator(f, ik[i]), refKey);
}
}
} else {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
system.newConstraint(p, assignOperator, rvalKey);
}
}
} else {
if (DEBUG) {
System.err.println("adding side effect " + f);
}
system.newSideEffect(getBuilder().new PutFieldOperator(f, system.findOrCreatePointsToSet(rvalKey)), refKey);
}
}
}
private void processPutStatic(int rval, FieldReference field, IField f) {
PointerKey fKey = getPointerKeyForStaticField(f);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(fKey, ik[i]);
}
} else {
system.newConstraint(fKey, assignOperator, rvalKey);
}
if (DEBUG) {
System.err.println("visitPut class init " + field.getDeclaringClass() + " " + field);
}
// side effect of putstatic: may call class initializer
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
Warnings.add(FieldResolutionFailure.create(field));
} else {
processClassInitializer(klass);
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitInvoke(com.ibm.wala.ssa.InvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
visitInvokeInternal(instruction);
}
protected void visitInvokeInternal(SSAAbstractInvokeInstruction instruction) {
if (DEBUG) {
System.err.println("visitInvoke: " + instruction);
}
PointerKey uniqueCatch = null;
if (hasUniqueCatchBlock(instruction, ir)) {
uniqueCatch = getBuilder().getUniqueCatchKey(instruction, ir, node);
}
if (instruction.getCallSite().isStatic()) {
CGNode n = getTargetForCall(node, instruction.getCallSite(), (InstanceKey) null);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
if (DEBUG) {
System.err.println("visitInvoke class init " + n);
}
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
} else {
// Add a side effect that will fire when we determine a value
// for the receiver. This side effect will create a new node
// and new constraints based on the new callee context.
// NOTE: This will not be adequate for CPA-style context selectors,
// where the callee context may depend on state other than the
// receiver. TODO: rectify this when needed.
PointerKey receiver = getPointerKeyForLocal(instruction.getReceiver());
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getReceiver())) {
if (contentsAreInvariant(symbolTable, du, instruction.getReceiver())) {
system.recordImplicitPointsToSet(receiver);
InstanceKey[] ik = getInvariantContents(instruction.getReceiver());
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
CGNode n = getTargetForCall(node, instruction.getCallSite(), ik[i]);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
}
} else {
if (DEBUG) {
System.err.println("Add side effect, dispatch to " + instruction + ", receiver " + receiver);
}
DispatchOperator dispatchOperator = getBuilder().new DispatchOperator(instruction, node,
computeInvariantParameters(instruction), uniqueCatch);
system.newSideEffect(dispatchOperator, receiver);
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitNew(com.ibm.wala.ssa.NewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {
InstanceKey iKey = getInstanceKeyForAllocation(instruction.getNewSite());
if (iKey == null) {
// something went wrong. I hope someone raised a warning.
return;
}
PointerKey def = getPointerKeyForLocal(instruction.getDef());
IClass klass = iKey.getConcreteType();
if (DEBUG) {
System.err.println("visitNew: " + instruction + " " + iKey + " " + system.findOrCreateIndexForInstanceKey(iKey));
}
if (klass == null) {
if (DEBUG) {
System.err.println("Resolution failure: " + instruction);
}
return;
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
// side effect of new: may call class initializer
if (DEBUG) {
System.err.println("visitNew call clinit: " + klass);
}
processClassInitializer(klass);
// add instance keys and pointer keys for array contents
int dim = 0;
InstanceKey lastInstance = iKey;
while (klass != null && klass.isArrayClass()) {
klass = ((ArrayClass) klass).getElementClass();
// klass == null means it's a primitive
if (klass != null && klass.isArrayClass()) {
if (instruction.getNumberOfUses() <= (dim + 1)) {
break;
}
int sv = instruction.getUse(dim + 1);
if (ir.getSymbolTable().isIntegerConstant(sv)) {
Integer c = (Integer) ir.getSymbolTable().getConstantValue(sv);
if (c.intValue() == 0) {
break;
}
}
InstanceKey ik = getInstanceKeyForMultiNewArray(instruction.getNewSite(), dim);
PointerKey pk = getPointerKeyForArrayContents(lastInstance);
if (DEBUG_MULTINEWARRAY) {
System.err.println("multinewarray constraint: ");
System.err.println(" pk: " + pk);
System.err.println(" ik: " + system.findOrCreateIndexForInstanceKey(ik) + " concrete type " + ik.getConcreteType()
+ " is " + ik);
System.err.println(" klass:" + klass);
}
system.newConstraint(pk, ik);
lastInstance = ik;
dim++;
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitThrow(com.ibm.wala.ssa.ThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
// don't do anything: we handle exceptional edges
// in a separate pass
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitGetCaughtException(com.ibm.wala.ssa.GetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
List<ProgramCounter> peis = getIncomingPEIs(ir, getBasicBlock());
PointerKey def = getPointerKeyForLocal(instruction.getDef());
// SJF: we don't optimize based on dead catch blocks yet ... it's a little
// tricky due interaction with the SINGLE_USE optimization which directly
// shoves exceptional return values from calls into exception vars.
// it may not be worth doing this.
// if (hasNoInterestingUses(instruction.getDef(), du)) {
// solver.recordImplicitPointsToSet(def);
// } else {
Set<IClass> types = getCaughtExceptionTypes(instruction, ir);
getBuilder().addExceptionDefConstraints(ir, du, node, peis, def, types);
// }
}
/**
* TODO: What is this doing? Document me!
*/
private int booleanConstantTest(SSAConditionalBranchInstruction c, int v) {
int result = 0;
// right for OPR_eq
if ((symbolTable.isZeroOrFalse(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isZeroOrFalse(c.getUse(1)) && c.getUse(0) == v)) {
result = -1;
} else if ((symbolTable.isOneOrTrue(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isOneOrTrue(c.getUse(1)) && c.getUse(0) == v)) {
result = 1;
}
if (c.getOperator() == ConditionalBranchInstruction.Operator.NE) {
result = -result;
}
return result;
}
private int nullConstantTest(SSAConditionalBranchInstruction c, int v) {
if ((symbolTable.isNullConstant(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isNullConstant(c.getUse(1)) && c.getUse(0) == v)) {
if (c.getOperator() == ConditionalBranchInstruction.Operator.EQ) {
return 1;
} else {
return -1;
}
} else {
return 0;
}
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
if (ir.getMethod() instanceof AbstractRootMethod) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(dst);
} else {
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
PointerKey use = getPointerKeyForLocal(instruction.getUse(i));
if (contentsAreInvariant(symbolTable, du, instruction.getUse(i))) {
system.recordImplicitPointsToSet(use);
InstanceKey[] ik = getInvariantContents(instruction.getUse(i));
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, use);
}
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitPi(com.ibm.wala.ssa.SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {
int dir;
if (hasNoInterestingUses(instruction.getDef())) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
system.recordImplicitPointsToSet(dst);
} else {
ControlFlowGraph<ISSABasicBlock> cfg = ir.getControlFlowGraph();
if (com.ibm.wala.cfg.Util.endsWithConditionalBranch(cfg, getBasicBlock()) && cfg.getSuccNodeCount(getBasicBlock()) == 2) {
SSAConditionalBranchInstruction cond = (SSAConditionalBranchInstruction) com.ibm.wala.cfg.Util.getLastInstruction(cfg,
getBasicBlock());
SSAInstruction cause = instruction.getCause();
BasicBlock target = (BasicBlock) cfg.getNode(instruction.getSuccessor());
if ((cause instanceof SSAInstanceofInstruction)) {
int direction = booleanConstantTest(cond, cause.getDef());
if (direction != 0) {
TypeReference type = ((SSAInstanceofInstruction) cause).getCheckedType();
IClass cls = getClassHierarchy().lookupClass(type);
if (cls == null) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
} else {
PointerKey dst = getFilteredPointerKeyForLocal(instruction.getDef(), new FilteredPointerKey.SingleClassFilter(cls));
PointerKey src = getPointerKeyForLocal(instruction.getVal());
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && direction == 1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && direction == -1)) {
system.newConstraint(dst, getBuilder().filterOperator, src);
} else {
system.newConstraint(dst, getBuilder().inverseFilterOperator, src);
}
}
}
} else if ((dir = nullConstantTest(cond, instruction.getVal())) != 0) {
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && dir == -1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && dir == 1)) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
}
}
/**
* Add a constraint to the system indicating that the contents of local src flows to dst, with no special type
* filter.
*/
private void addPiAssignment(PointerKey dst, int src) {
PointerKey srcKey = getPointerKeyForLocal(src);
if (contentsAreInvariant(symbolTable, du, src)) {
system.recordImplicitPointsToSet(srcKey);
InstanceKey[] ik = getInvariantContents(src);
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, srcKey);
}
}
public ISSABasicBlock getBasicBlock() {
return basicBlock;
}
/**
* The calling loop must call this in each iteration!
*/
public void setBasicBlock(ISSABasicBlock block) {
basicBlock = block;
}
/**
* Side effect: records invariant parameters as implicit points-to-sets.
*
* @return if non-null, then result[i] holds the set of instance keys which may be passed as the ith parameter.
* (which must be invariant)
*/
protected InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] constParams = null;
for (int i = 0; i < call.getNumberOfUses(); i++) {
// not sure how getUse(i) <= 0 .. dead code?
// TODO: investigate
if (call.getUse(i) > 0) {
if (contentsAreInvariant(symbolTable, du, call.getUse(i))) {
system.recordImplicitPointsToSet(getPointerKeyForLocal(call.getUse(i)));
if (constParams == null) {
constParams = new InstanceKey[call.getNumberOfUses()][];
}
constParams[i] = getInvariantContents(call.getUse(i));
for (int j = 0; j < constParams[i].length; j++) {
system.findOrCreateIndexForInstanceKey(constParams[i][j]);
}
}
}
}
return constParams;
}
@Override
public void visitLoadClass(SSALoadClassInstruction instruction) {
PointerKey def = getPointerKeyForLocal(instruction.getDef());
InstanceKey iKey = getInstanceKeyForClassObject(instruction.getLoadedClass());
IClass klass = getClassHierarchy().lookupClass(instruction.getLoadedClass());
if (klass != null) {
processClassInitializer(klass);
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
}
/**
* TODO: lift most of this logic to PropagationCallGraphBuilder
*
* Add a call to the class initializer from the root method.
*/
private void processClassInitializer(IClass klass) {
if (Assertions.verifyAssertions) {
Assertions._assert(klass != null);
}
if (getBuilder().clinitVisited.contains(klass)) {
return;
}
getBuilder().clinitVisited.add(klass);
if (klass.getClassInitializer() != null) {
if (DEBUG) {
System.err.println("process class initializer for " + klass);
}
// add an invocation from the fake root method to the <clinit>
FakeWorldClinitMethod fakeWorldClinitMethod = (FakeWorldClinitMethod) callGraph.getFakeWorldClinitNode().getMethod();
MethodReference m = klass.getClassInitializer().getReference();
CallSiteReference site = CallSiteReference.make(1, m, IInvokeInstruction.Dispatch.STATIC);
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(callGraph.getFakeRootNode(), site, null);
if (targetMethod != null) {
CGNode target = getTargetForCall(callGraph.getFakeRootNode(), site, (InstanceKey) null);
if (target != null && callGraph.getPredNodeCount(target) == 0) {
SSAAbstractInvokeInstruction s = fakeWorldClinitMethod.addInvocation(new int[0], site);
PointerKey uniqueCatch = getBuilder().getPointerKeyForExceptionalReturnValue(callGraph.getFakeRootNode());
getBuilder().processResolvedCall(callGraph.getFakeWorldClinitNode(), s, target, null, uniqueCatch);
}
}
}
try {
IClass sc = klass.getSuperclass();
if (sc != null) {
processClassInitializer(sc);
}
} catch (ClassHierarchyException e) {
Assertions.UNREACHABLE();
}
}
}
/**
* Add constraints for a call site after we have computed a reachable target for the dispatch
*
* Side effect: add edge to the call graph.
*
* @param instruction
* @param constParams if non-null, then constParams[i] holds the set of instance keys that are passed as param i, or
* null if param i is not invariant
* @param uniqueCatchKey if non-null, then this is the unique PointerKey that catches all exceptions from this call
* site.
*/
@SuppressWarnings("deprecation")
private void processResolvedCall(CGNode caller, SSAAbstractInvokeInstruction instruction, CGNode target,
InstanceKey[][] constParams, PointerKey uniqueCatchKey) {
if (DEBUG) {
System.err.println("processResolvedCall: " + caller + " ," + instruction + " , " + target);
}
if (DEBUG) {
System.err.println("addTarget: " + caller + " ," + instruction + " , " + target);
}
caller.addTarget(instruction.getCallSite(), target);
if (FakeRootMethod.isFakeRootMethod(caller.getMethod().getReference())) {
if (entrypointCallSites.contains(instruction.getCallSite())) {
callGraph.registerEntrypoint(target);
}
}
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
// TODO: i'd like to enable this optimization, but it's a little tricky
// to recover the implicit points-to sets with recursion. TODO: don't
// be lazy and code the recursive logic to enable this.
// if (hasNoInstructions(target)) {
// // record points-to sets for formals implicitly .. computed on
// // demand.
// // TODO: generalize this by using hasNoInterestingUses on parameters.
// // however .. have to be careful to cache results in that case ... don't
// // want
// // to recompute du each time we process a call to Object.<init> !
// for (int i = 0; i < instruction.getNumberOfUses(); i++) {
// // we rely on the invariant that the value number for the ith parameter
// // is i+1
// final int vn = i + 1;
// PointerKey formal = getPointerKeyForLocal(target, vn);
// if (target.getMethod().getParameterType(i).isReferenceType()) {
// system.recordImplicitPointsToSet(formal);
// }
// }
// } else {
// generate contraints from parameter passing
int nUses = instruction.getNumberOfParameters();
int nExpected = target.getMethod().getNumberOfParameters();
/*
* int nExpected = target.getMethod().getReference().getNumberOfParameters(); if (!target.getMethod().isStatic() &&
* !target.getMethod().isClinit()) { nExpected++; }
*/
if (nUses != nExpected) {
// some sort of unverifiable code mismatch. give up.
return;
}
boolean needsFilter = !instruction.getCallSite().isStatic() && needsFilterForReceiver(instruction, target);
// we're a little sloppy for now ... we don't filter calls to
// java.lang.Object.
// TODO: we need much more precise filters than cones in order to handle
// the various types of dispatch logic. We need a filter that expresses
// "the set of types s.t. x.foo resolves to y.foo."
for (int i = 0; i < instruction.getNumberOfParameters(); i++) {
// we rely on the invariant that the value number for the ith parameter
// is i+1
final int vn = i + 1;
if (target.getMethod().getParameterType(i).isReferenceType()) {
// if (constParams != null && constParams[i] != null &&
// !supportFullPointerFlowGraph) {
if (constParams != null && constParams[i] != null) {
InstanceKey[] ik = constParams[i];
for (int j = 0; j < ik.length; j++) {
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
PointerKey formal = null;
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
formal = getPointerKeyForLocal(target, vn);
} else {
formal = getFilteredPointerKeyForLocal(target, vn, C);
}
system.newConstraint(formal, ik[j]);
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, ik[j]);
}
}
} else {
if (Assertions.verifyAssertions) {
if (instruction.getUse(i) < 0) {
Assertions.UNREACHABLE("unexpected " + instruction + " in " + caller);
}
}
PointerKey actual = getPointerKeyForLocal(caller, instruction.getUse(i));
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
} else {
FilteredPointerKey formal = getFilteredPointerKeyForLocal(target, vn, C);
system.newConstraint(formal, filterOperator, actual);
}
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
}
}
}
}
// generate contraints from return value.
if (instruction.hasDef() && instruction.getDeclaredResultType().isReferenceType()) {
PointerKey result = getPointerKeyForLocal(caller, instruction.getDef());
PointerKey ret = getPointerKeyForReturnValue(target);
system.newConstraint(result, assignOperator, ret);
}
// generate constraints from exception return value.
PointerKey e = getPointerKeyForLocal(caller, instruction.getException());
PointerKey er = getPointerKeyForExceptionalReturnValue(target);
if (SHORT_CIRCUIT_SINGLE_USES && uniqueCatchKey != null) {
// e has exactly one use. so, represent e implicitly
system.newConstraint(uniqueCatchKey, assignOperator, er);
} else {
system.newConstraint(e, assignOperator, er);
}
// }
}
/**
* An operator to fire when we discover a potential new callee for a virtual or interface call site.
*
* This operator will create a new callee context and constraints if necessary.
*
* N.B: This implementation assumes that the calling context depends solely on the dataflow information computed for
* the receiver. TODO: generalize this to have other forms of context selection, such as CPA-style algorithms.
*/
final class DispatchOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator {
private final SSAAbstractInvokeInstruction call;
private final ExplicitCallGraph.ExplicitNode node;
private final InstanceKey[][] constParams;
private final PointerKey uniqueCatch;
/**
* @param call
* @param node
* @param constParams if non-null, then constParams[i] holds the String constant that is passed as param i, or null
* if param i is not a String constant
*/
DispatchOperator(SSAAbstractInvokeInstruction call, ExplicitCallGraph.ExplicitNode node, InstanceKey[][] constParams,
PointerKey uniqueCatch) {
this.call = call;
this.node = node;
this.constParams = constParams;
this.uniqueCatch = uniqueCatch;
}
/**
* The set of pointers that have already been processed.
*/
final private MutableIntSet previousReceivers = IntSetUtil.getDefaultIntSetFactory().make();
/*
* @see com.ibm.wala.dataflow.fixpoint.UnaryOperator#evaluate(com.ibm.wala.dataflow.fixpoint.IVariable,
* com.ibm.wala.dataflow.fixpoint.IVariable)
*/
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable receivers = rhs;
final MutableBoolean sideEffect = new MutableBoolean();
// compute the set of pointers that were not previously handled
IntSet value = receivers.getValue();
if (value == null) {
// this constraint was put on the work list, probably by
// initialization,
// even though the right-hand-side is empty.
// TODO: be more careful about what goes on the worklist to
// avoid this.
if (DEBUG) {
System.err.println("EVAL dispatch with value null");
}
return NOT_CHANGED;
}
if (DEBUG) {
System.err.println("EVAL dispatch to " + node + ":" + call);
System.err.println("receivers: " + value);
}
IntSetAction action = new IntSetAction() {
public void act(int ptr) {
if (DEBUG) {
System.err.println(" dispatch to ptr " + ptr);
}
InstanceKey iKey = system.getInstanceKey(ptr);
CGNode target;
if (clone2Assign) {
// for efficiency: assume that only call sites that reference
// clone() might dispatch to clone methods
if (call.getCallSite().getDeclaredTarget().getSelector().equals(cloneSelector)) {
IClass recv = (iKey != null) ? iKey.getConcreteType() : null;
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(node, call.getCallSite(), recv);
if (targetMethod != null && targetMethod.getReference().equals(CloneInterpreter.CLONE)) {
// treat this call to clone as an assignment
PointerKey result = getPointerKeyForLocal(node, call.getDef());
PointerKey receiver = getPointerKeyForLocal(node, call.getReceiver());
system.newConstraint(result, assignOperator, receiver);
return;
}
}
}
target = getTargetForCall(node, call.getCallSite(), iKey);
if (target == null) {
// This indicates an error; I sure hope getTargetForCall
// raised a warning about this!
if (DEBUG) {
System.err.println("Warning: null target for call " + call + " " + iKey);
}
} else {
IntSet targets = getCallGraph().getPossibleTargetNumbers(node, call.getCallSite());
if (targets != null && targets.contains(target.getGraphNodeId())) {
// do nothing; we've previously discovered and handled this
// receiver for this call site.
} else {
// process the newly discovered target for this call
sideEffect.b = true;
processResolvedCall(node, call, target, constParams, uniqueCatch);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
}
}
}
};
try {
value.foreachExcluding(previousReceivers, action);
} catch (Error e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
} catch (RuntimeException e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
}
// update the set of receivers previously considered
previousReceivers.copySet(value);
byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0;
return (byte) (NOT_CHANGED | sideEffectMask);
}
@Override
public String toString() {
return "Dispatch to " + call + " in node " + node;
}
@Override
public int hashCode() {
return node.hashCode() + 90289 * call.hashCode();
}
@Override
public boolean equals(Object o) {
// note that these are not necessarily canonical, since
// with synthetic factories we may regenerate constraints
// many times. TODO: change processing of synthetic factories
// so that we guarantee to insert each dispatch equation
// only once ... if this were true we could optimize this
// with reference equality
// instanceof is OK because this class is final
if (o instanceof DispatchOperator) {
DispatchOperator other = (DispatchOperator) o;
return node.equals(other.node) && call.equals(other.call);
} else {
return false;
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.IPointerOperator#isComplex()
*/
public boolean isComplex() {
return true;
}
}
public boolean hasNoInterestingUses(CGNode node, int vn, DefUse du) {
if (du == null) {
throw new IllegalArgumentException("du is null");
}
+ if (vn <= 0) {
+ throw new IllegalArgumentException("v is invalid: " + vn);
+ }
// todo: enhance this by solving a dead-code elimination
// problem.
InterestingVisitor v = makeInterestingVisitor(node, vn);
- for (Iterator it = du.getUses(vn); it.hasNext();) {
+ for (Iterator it = du.getUses(v.vn); it.hasNext();) {
SSAInstruction s = (SSAInstruction) it.next();
s.visit(v);
if (v.bingo) {
return false;
}
}
return true;
}
protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) {
return new InterestingVisitor(vn);
}
/**
* sets bingo to true when it visits an interesting instruction
*/
protected static class InterestingVisitor extends SSAInstruction.Visitor {
protected final int vn;
protected InterestingVisitor(int vn) {
this.vn = vn;
}
protected boolean bingo = false;
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
if (!instruction.typeIsPrimitive() && instruction.getArrayRef() == vn) {
bingo = true;
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
if (!instruction.typeIsPrimitive() && (instruction.getArrayRef() == vn || instruction.getValue() == vn)) {
bingo = true;
}
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
bingo = true;
}
@Override
public void visitGet(SSAGetInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
bingo = true;
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
bingo = true;
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
bingo = true;
}
@Override
public void visitPi(SSAPiInstruction instruction) {
bingo = true;
}
@Override
public void visitPut(SSAPutInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
bingo = true;
}
@Override
public void visitThrow(SSAThrowInstruction instruction) {
bingo = true;
}
}
/**
* TODO: enhance this logic using type inference
*
* @param instruction
* @return true if we need to filter the receiver type to account for virtual dispatch
*/
private boolean needsFilterForReceiver(SSAAbstractInvokeInstruction instruction, CGNode target) {
FilteredPointerKey.TypeFilter f = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (f != null) {
// the context selects a particular concrete type for the receiver.
// we need to filter, unless the declared receiver type implies the
// concrete type (TODO: need to implement this optimization)
return true;
}
// don't need to filter for invokestatic
if (instruction.getCallSite().isStatic() || instruction.getCallSite().isSpecial()) {
return false;
}
MethodReference declaredTarget = instruction.getDeclaredTarget();
IMethod resolvedTarget = getClassHierarchy().resolveMethod(declaredTarget);
if (resolvedTarget == null) {
// there's some problem that will be flagged as a warning
return true;
}
return true;
}
private boolean isRootType(IClass klass) {
return klass.getClassHierarchy().isRootClass(klass);
}
private boolean isRootType(FilteredPointerKey.TypeFilter filter) {
if (filter instanceof FilteredPointerKey.SingleClassFilter) {
return isRootType(((FilteredPointerKey.SingleClassFilter) filter).getConcreteType());
} else {
return false;
}
}
/**
* TODO: enhance this logic using type inference TODO!!!: enhance filtering to consider concrete types, not just
* cones. precondition: needs Filter
*
* @param target
* @return an IClass which represents
*/
private FilteredPointerKey.TypeFilter getFilter(CGNode target) {
FilteredPointerKey.TypeFilter filter = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (filter != null) {
return filter;
} else {
// the context does not select a particular concrete type for the
// receiver.
IClass C = getReceiverClass(target.getMethod());
return new FilteredPointerKey.SingleClassFilter(C);
}
}
/**
* @param method
* @return the receiver class for this method.
*/
private IClass getReceiverClass(IMethod method) {
TypeReference formalType = method.getParameterType(0);
IClass C = getClassHierarchy().lookupClass(formalType);
if (Assertions.verifyAssertions) {
if (method.isStatic()) {
Assertions.UNREACHABLE("asked for receiver of static method " + method);
}
if (C == null) {
Assertions.UNREACHABLE("no class found for " + formalType + " recv of " + method);
}
}
return C;
}
/**
* A value is "invariant" if we can figure out the instances it can ever point to locally, without resorting to
* propagation.
*
* @param valueNumber
* @return true iff the contents of the local with this value number can be deduced locally, without propagation
*/
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
if (isConstantRef(symbolTable, valueNumber)) {
return true;
} else if (SHORT_CIRCUIT_INVARIANT_SETS) {
SSAInstruction def = du.getDef(valueNumber);
if (def instanceof SSANewInstruction) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* precondition:contentsAreInvariant(valueNumber)
*
* @param valueNumber
* @return the complete set of instances that the local with vn=valueNumber may point to.
*/
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm) {
return getInvariantContents(symbolTable, du, node, valueNumber, hm, false);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm,
boolean ensureIndexes) {
InstanceKey[] result;
if (isConstantRef(symbolTable, valueNumber)) {
Object x = symbolTable.getConstantValue(valueNumber);
if (x instanceof String) {
// this is always the case in Java. use strong typing in the call to getInstanceKeyForConstant.
String S = (String) x;
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, S);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
} else {
// some non-built in type (e.g. Integer). give up on strong typing.
// language-specific subclasses (e.g. Javascript) should override this method to get strong typing
// with generics if desired.
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(x);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, x);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
}
} else {
SSANewInstruction def = (SSANewInstruction) du.getDef(valueNumber);
InstanceKey iKey = hm.getInstanceKeyForAllocation(node, def.getNewSite());
result = (iKey == null) ? new InstanceKey[0] : new InstanceKey[] { iKey };
}
if (ensureIndexes) {
for (int i = 0; i < result.length; i++) {
system.findOrCreateIndexForInstanceKey(result[i]);
}
}
return result;
}
protected boolean isConstantRef(SymbolTable symbolTable, int valueNumber) {
if (valueNumber == -1) {
return false;
}
if (symbolTable.isConstant(valueNumber)) {
Object v = symbolTable.getConstantValue(valueNumber);
return (!(v instanceof Number));
} else {
return false;
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a checkcast
*/
private static class CheckcastFailure extends Warning {
final TypeReference type;
CheckcastFailure(TypeReference type) {
super(Warning.SEVERE);
this.type = type;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + type;
}
public static CheckcastFailure create(TypeReference type) {
return new CheckcastFailure(type);
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a field
*/
private static class FieldResolutionFailure extends Warning {
final FieldReference field;
FieldResolutionFailure(FieldReference field) {
super(Warning.SEVERE);
this.field = field;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + field;
}
public static FieldResolutionFailure create(FieldReference field) {
return new FieldResolutionFailure(field);
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.HeapModel#iteratePointerKeys()
*/
public Iterator<PointerKey> iteratePointerKeys() {
return system.iteratePointerKeys();
}
public static Set<IClass> getCaughtExceptionTypes(SSAGetCaughtExceptionInstruction instruction, IR ir) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (instruction == null) {
throw new IllegalArgumentException("instruction is null");
}
Iterator<TypeReference> exceptionTypes = ((ExceptionHandlerBasicBlock) ir.getControlFlowGraph().getNode(
instruction.getBasicBlockNumber())).getCaughtExceptionTypes();
HashSet<IClass> types = HashSetFactory.make(10);
for (; exceptionTypes.hasNext();) {
IClass c = ir.getMethod().getClassHierarchy().lookupClass(exceptionTypes.next());
if (c != null) {
types.add(c);
}
}
return types;
}
public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) {
return getInstanceKeyForPEI(node, instr, type, instanceKeyFactory);
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder#makeSolver()
*/
@Override
protected IPointsToSolver makeSolver() {
return usePreTransitiveSolver ? (IPointsToSolver) new PreTransitiveSolver(system, this) : new StandardSolver(system, this);
// return true ? (IPointsToSolver)new PreTransitiveSolver(system,this) : new
// StandardSolver(system,this);
}
}
| false | true | private void addExceptionDefConstraints(IR ir, DefUse du, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar,
Set<IClass> catchClasses) {
if (DEBUG) {
System.err.println("Add exception def constraints for node " + node);
}
for (Iterator<ProgramCounter> it = peis.iterator(); it.hasNext();) {
ProgramCounter peiLoc = it.next();
if (DEBUG) {
System.err.println("peiLoc: " + peiLoc);
}
SSAInstruction pei = ir.getPEI(peiLoc);
if (DEBUG) {
System.err.println("Add exceptions from pei " + pei);
}
if (pei instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (!SHORT_CIRCUIT_SINGLE_USES || !hasUniqueCatchBlock(s, ir)) {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}// else {
// System.err.println("SKIPPING ASSIGNMENTS TO " + exceptionVar + " FROM " +
// e);
// }
} else if (pei instanceof SSAAbstractThrowInstruction) {
SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (contentsAreInvariant(ir.getSymbolTable(), du, s.getException())) {
InstanceKey[] ik = getInvariantContents(ir.getSymbolTable(), du, node, s.getException(), this);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
assignInstanceToCatch(exceptionVar, catchClasses, ik[i]);
}
} else {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}
}
// Account for those exceptions for which we do not actually have a
// points-to set for
// the pei, but just instance keys
Collection<TypeReference> types = pei.getExceptionTypes();
if (types != null) {
for (Iterator<TypeReference> it2 = types.iterator(); it2.hasNext();) {
TypeReference type = it2.next();
if (type != null) {
InstanceKey ik = getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory);
if (ik == null) {
continue;
}
if (Assertions.verifyAssertions) {
if (!(ik instanceof ConcreteTypeKey)) {
Assertions._assert(ik instanceof ConcreteTypeKey,
"uh oh: need to implement getCaughtException constraints for instance " + ik);
}
}
ConcreteTypeKey ck = (ConcreteTypeKey) ik;
IClass klass = ck.getType();
if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) {
system.newConstraint(exceptionVar, getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory));
}
}
}
}
}
}
/**
* @return true iff there's a unique catch block which catches all exceptions thrown by a certain call site.
*/
protected static boolean hasUniqueCatchBlock(SSAAbstractInvokeInstruction call, IR ir) {
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (bb.length == 1) {
Iterator it = ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator();
// check that there's exactly one element in the iterator
if (it.hasNext()) {
it.next();
return (!it.hasNext());
}
}
return false;
}
/**
* precondition: hasUniqueCatchBlock(call,node,cg)
*
* @return the unique pointer key which catches the exceptions thrown by a call
* @throws IllegalArgumentException if ir == null
* @throws IllegalArgumentException if call == null
*/
public PointerKey getUniqueCatchKey(SSAAbstractInvokeInstruction call, IR ir, CGNode node) throws IllegalArgumentException,
IllegalArgumentException {
if (call == null) {
throw new IllegalArgumentException("call == null");
}
if (ir == null) {
throw new IllegalArgumentException("ir == null");
}
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (Assertions.verifyAssertions) {
Assertions._assert(bb.length == 1);
}
SSACFG.BasicBlock cb = (BasicBlock) ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator().next();
if (cb.isExitBlock()) {
return getPointerKeyForExceptionalReturnValue(node);
} else {
SSACFG.ExceptionHandlerBasicBlock ehbb = (ExceptionHandlerBasicBlock) cb;
SSAGetCaughtExceptionInstruction ci = ehbb.getCatchInstruction();
return getPointerKeyForLocal(node, ci.getDef());
}
}
/**
* @return a List of Instructions that may transfer control to bb via an exceptional edge
* @throws IllegalArgumentException if ir is null
*/
public static List<ProgramCounter> getIncomingPEIs(IR ir, ISSABasicBlock bb) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (DEBUG) {
System.err.println("getIncomingPEIs " + bb);
}
ControlFlowGraph<ISSABasicBlock> g = ir.getControlFlowGraph();
List<ProgramCounter> result = new ArrayList<ProgramCounter>(g.getPredNodeCount(bb));
for (Iterator it = g.getPredNodes(bb); it.hasNext();) {
BasicBlock pred = (BasicBlock) it.next();
if (DEBUG) {
System.err.println("pred: " + pred);
}
if (pred.isEntryBlock())
continue;
int index = pred.getLastInstructionIndex();
SSAInstruction pei = ir.getInstructions()[index];
// Note: pei might be null if pred is unreachable.
// TODO: consider pruning CFG for unreachable blocks.
if (pei != null && pei.isPEI()) {
if (DEBUG) {
System.err.println("PEI: " + pei + " index " + index + " PC " + g.getProgramCounter(index));
}
result.add(new ProgramCounter(g.getProgramCounter(index)));
}
}
return result;
}
/**
* A visitor that generates constraints based on statements in SSA form.
*/
protected static class ConstraintVisitor extends SSAInstruction.Visitor {
/**
* The governing call graph builder. This field is used instead of an inner class in order to allow more flexible
* reuse of this visitor in subclasses
*/
protected final SSAPropagationCallGraphBuilder builder;
/**
* The node whose statements we are currently traversing
*/
protected final ExplicitCallGraph.ExplicitNode node;
/**
* The governing call graph.
*/
private final ExplicitCallGraph callGraph;
/**
* The governing IR
*/
protected final IR ir;
/**
* The governing propagation system, into which constraints are added
*/
protected final PropagationSystem system;
/**
* The basic block currently being processed
*/
private ISSABasicBlock basicBlock;
/**
* Governing symbol table
*/
protected final SymbolTable symbolTable;
/**
* Def-use information
*/
protected final DefUse du;
public ConstraintVisitor(SSAPropagationCallGraphBuilder builder, ExplicitCallGraph.ExplicitNode node) {
this.builder = builder;
this.node = node;
this.callGraph = builder.getCallGraph();
this.system = builder.getPropagationSystem();
this.ir = builder.getCFAContextInterpreter().getIR(node);
this.symbolTable = this.ir.getSymbolTable();
this.du = builder.getCFAContextInterpreter().getDU(node);
if (Assertions.verifyAssertions) {
Assertions._assert(symbolTable != null);
}
}
protected SSAPropagationCallGraphBuilder getBuilder() {
return builder;
}
protected AnalysisOptions getOptions() {
return builder.options;
}
protected AnalysisCache getAnalysisCache() {
return builder.getAnalysisCache();
}
public PointerKey getPointerKeyForLocal(int valueNumber) {
return getBuilder().getPointerKeyForLocal(node, valueNumber);
}
public FilteredPointerKey getFilteredPointerKeyForLocal(int valueNumber, FilteredPointerKey.TypeFilter filter) {
return getBuilder().getFilteredPointerKeyForLocal(node, valueNumber, filter);
}
public PointerKey getPointerKeyForReturnValue() {
return getBuilder().getPointerKeyForReturnValue(node);
}
public PointerKey getPointerKeyForExceptionalReturnValue() {
return getBuilder().getPointerKeyForExceptionalReturnValue(node);
}
public PointerKey getPointerKeyForStaticField(IField f) {
return getBuilder().getPointerKeyForStaticField(f);
}
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) {
return getBuilder().getPointerKeyForInstanceField(I, f);
}
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
return getBuilder().getPointerKeyForArrayContents(I);
}
public InstanceKey getInstanceKeyForAllocation(NewSiteReference allocation) {
return getBuilder().getInstanceKeyForAllocation(node, allocation);
}
public InstanceKey getInstanceKeyForMultiNewArray(NewSiteReference allocation, int dim) {
return getBuilder().getInstanceKeyForMultiNewArray(node, allocation, dim);
}
public <T> InstanceKey getInstanceKeyForConstant(T S) {
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
return getBuilder().getInstanceKeyForConstant(type, S);
}
public InstanceKey getInstanceKeyForPEI(ProgramCounter instr, TypeReference type) {
return getBuilder().getInstanceKeyForPEI(node, instr, type);
}
public InstanceKey getInstanceKeyForClassObject(TypeReference type) {
return getBuilder().getInstanceKeyForClassObject(type);
}
public CGNode getTargetForCall(CGNode caller, CallSiteReference site, InstanceKey iKey) {
return getBuilder().getTargetForCall(caller, site, iKey);
}
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
return getBuilder().contentsAreInvariant(symbolTable, du, valueNumber);
}
protected InstanceKey[] getInvariantContents(int valueNumber) {
return getInvariantContents(ir.getSymbolTable(), du, node, valueNumber);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber) {
return getBuilder().getInvariantContents(symbolTable, du, node, valueNumber, getBuilder());
}
protected IClassHierarchy getClassHierarchy() {
return getBuilder().getClassHierarchy();
}
protected boolean hasNoInterestingUses(int vn) {
return getBuilder().hasNoInterestingUses(node, vn, du);
}
protected boolean isRootType(IClass klass) {
return getBuilder().isRootType(klass);
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayLoad(com.ibm.wala.ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayLoad(instruction.getDef(), instruction.getArrayRef());
}
protected void doVisitArrayLoad(int def, int arrayRef) {
PointerKey result = getPointerKeyForLocal(def);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
if (hasNoInterestingUses(def)) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
if (p == null) {
} else {
system.newConstraint(result, assignOperator, p);
}
}
}
} else {
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(result));
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new ArrayLoadOperator(system.findOrCreatePointsToSet(result)), arrayRefPtrKey);
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction)
*/
public void doVisitArrayStore(int arrayRef, int value) {
// (requires the creation of assign constraints as
// the set points-to(a[]) grows.)
PointerKey valuePtrKey = getPointerKeyForLocal(value);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getArrayRef())) {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
IClass contents = ((ArrayClass) ik[i].getConcreteType()).getElementClass();
if (p == null) {
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] vk = getInvariantContents(value);
for (int j = 0; j < vk.length; j++) {
system.findOrCreateIndexForInstanceKey(vk[j]);
if (vk[j].getConcreteType() != null) {
if (getClassHierarchy().isAssignableFrom(contents, vk[j].getConcreteType())) {
system.newConstraint(p, vk[j]);
}
}
}
} else {
if (isRootType(contents)) {
system.newConstraint(p, assignOperator, valuePtrKey);
} else {
system.newConstraint(p, getBuilder().filterOperator, valuePtrKey);
}
}
}
}
}
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] ik = getInvariantContents(value);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new InstanceArrayStoreOperator(ik[i]), arrayRefPtrKey);
}
} else {
system.newSideEffect(getBuilder().new ArrayStoreOperator(system.findOrCreatePointsToSet(valuePtrKey)), arrayRefPtrKey);
}
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayStore(instruction.getArrayRef(), instruction.getValue());
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitCheckCast(com.ibm.wala.ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
IClass cls = getClassHierarchy().lookupClass(instruction.getDeclaredResultType());
PointerKey result = null;
if (cls == null) {
Warnings.add(CheckcastFailure.create(instruction.getDeclaredResultType()));
// we failed to find the type.
// conservatively it would make sense to ignore the filter and be
// conservative, assuming
// java.lang.Object.
// however, this breaks the invariants downstream that assume every
// variable is
// strongly typed ... we can't have bad types flowing around.
// since things are broken anyway, just give up.
// result = getPointerKeyForLocal(node, instruction.getResult());
return;
} else {
result = getFilteredPointerKeyForLocal(instruction.getResult(), new FilteredPointerKey.SingleClassFilter(cls));
}
PointerKey value = getPointerKeyForLocal(instruction.getVal());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, instruction.getVal())) {
system.recordImplicitPointsToSet(value);
InstanceKey[] ik = getInvariantContents(instruction.getVal());
if (cls.isInterface()) {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().implementsInterface(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().isSubclassOf(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
}
} else {
if (isRootType(cls)) {
system.newConstraint(result, assignOperator, value);
} else {
system.newConstraint(result, getBuilder().filterOperator, value);
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitReturn(com.ibm.wala.ssa.SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {
// skip returns of primitive type
if (instruction.returnsPrimitiveType() || instruction.returnsVoid()) {
return;
}
if (DEBUG) {
System.err.println("visitReturn: " + instruction);
}
PointerKey returnValue = getPointerKeyForReturnValue();
PointerKey result = getPointerKeyForLocal(instruction.getResult());
if (contentsAreInvariant(symbolTable, du, instruction.getResult())) {
system.recordImplicitPointsToSet(result);
InstanceKey[] ik = getInvariantContents(instruction.getResult());
for (int i = 0; i < ik.length; i++) {
if (DEBUG) {
System.err.println("invariant contents: " + returnValue + " " + ik[i]);
}
system.newConstraint(returnValue, ik[i]);
}
} else {
system.newConstraint(returnValue, assignOperator, result);
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitGet(com.ibm.wala.ssa.SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
visitGetInternal(instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitGet " + field);
}
// skip getfields of primitive type (optimisation)
if (field.getFieldType().isPrimitiveType()) {
return;
}
PointerKey def = getPointerKeyForLocal(lval);
if (Assertions.verifyAssertions) {
Assertions._assert(def != null);
}
IField f = getClassHierarchy().resolveField(field);
if (f == null && callGraph.getFakeRootNode().getMethod().getDeclaringClass().getReference().equals(field.getDeclaringClass())) {
f = callGraph.getFakeRootNode().getMethod().getDeclaringClass().getField(field.getName());
}
if (f == null) {
return;
}
if (hasNoInterestingUses(lval)) {
system.recordImplicitPointsToSet(def);
} else {
if (isStatic) {
PointerKey fKey = getPointerKeyForStaticField(f);
system.newConstraint(def, assignOperator, fKey);
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
} else {
// side effect of getstatic: may call class initializer
if (DEBUG) {
System.err.println("getstatic call class init " + klass);
}
processClassInitializer(klass);
}
} else {
PointerKey refKey = getPointerKeyForLocal(ref);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(ref)) {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] ik = getInvariantContents(ref);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForInstanceField(ik[i], f);
system.newConstraint(def, assignOperator, p);
}
}
} else {
system.newSideEffect(getBuilder().new GetFieldOperator(f, system.findOrCreatePointsToSet(def)), refKey);
}
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitPut(com.ibm.wala.ssa.PutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
visitPutInternal(instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitPut " + field);
}
// skip putfields of primitive type
if (field.getFieldType().isPrimitiveType()) {
return;
}
IField f = getClassHierarchy().resolveField(field);
if (f == null) {
if (DEBUG) {
System.err.println("Could not resolve field " + field);
}
Warnings.add(FieldResolutionFailure.create(field));
return;
}
if (Assertions.verifyAssertions) {
Assertions._assert(isStatic || !symbolTable.isStringConstant(ref), "put to string constant shouldn't be allowed?");
}
if (isStatic) {
processPutStatic(rval, field, f);
} else {
processPutField(rval, ref, f);
}
}
private void processPutField(int rval, int ref, IField f) {
if (Assertions.verifyAssertions) {
Assertions._assert(!f.getFieldTypeReference().isPrimitiveType());
}
PointerKey refKey = getPointerKeyForLocal(ref);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(p, ik[i]);
}
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
system.newSideEffect(getBuilder().new InstancePutFieldOperator(f, ik[i]), refKey);
}
}
} else {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
system.newConstraint(p, assignOperator, rvalKey);
}
}
} else {
if (DEBUG) {
System.err.println("adding side effect " + f);
}
system.newSideEffect(getBuilder().new PutFieldOperator(f, system.findOrCreatePointsToSet(rvalKey)), refKey);
}
}
}
private void processPutStatic(int rval, FieldReference field, IField f) {
PointerKey fKey = getPointerKeyForStaticField(f);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(fKey, ik[i]);
}
} else {
system.newConstraint(fKey, assignOperator, rvalKey);
}
if (DEBUG) {
System.err.println("visitPut class init " + field.getDeclaringClass() + " " + field);
}
// side effect of putstatic: may call class initializer
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
Warnings.add(FieldResolutionFailure.create(field));
} else {
processClassInitializer(klass);
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitInvoke(com.ibm.wala.ssa.InvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
visitInvokeInternal(instruction);
}
protected void visitInvokeInternal(SSAAbstractInvokeInstruction instruction) {
if (DEBUG) {
System.err.println("visitInvoke: " + instruction);
}
PointerKey uniqueCatch = null;
if (hasUniqueCatchBlock(instruction, ir)) {
uniqueCatch = getBuilder().getUniqueCatchKey(instruction, ir, node);
}
if (instruction.getCallSite().isStatic()) {
CGNode n = getTargetForCall(node, instruction.getCallSite(), (InstanceKey) null);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
if (DEBUG) {
System.err.println("visitInvoke class init " + n);
}
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
} else {
// Add a side effect that will fire when we determine a value
// for the receiver. This side effect will create a new node
// and new constraints based on the new callee context.
// NOTE: This will not be adequate for CPA-style context selectors,
// where the callee context may depend on state other than the
// receiver. TODO: rectify this when needed.
PointerKey receiver = getPointerKeyForLocal(instruction.getReceiver());
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getReceiver())) {
if (contentsAreInvariant(symbolTable, du, instruction.getReceiver())) {
system.recordImplicitPointsToSet(receiver);
InstanceKey[] ik = getInvariantContents(instruction.getReceiver());
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
CGNode n = getTargetForCall(node, instruction.getCallSite(), ik[i]);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
}
} else {
if (DEBUG) {
System.err.println("Add side effect, dispatch to " + instruction + ", receiver " + receiver);
}
DispatchOperator dispatchOperator = getBuilder().new DispatchOperator(instruction, node,
computeInvariantParameters(instruction), uniqueCatch);
system.newSideEffect(dispatchOperator, receiver);
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitNew(com.ibm.wala.ssa.NewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {
InstanceKey iKey = getInstanceKeyForAllocation(instruction.getNewSite());
if (iKey == null) {
// something went wrong. I hope someone raised a warning.
return;
}
PointerKey def = getPointerKeyForLocal(instruction.getDef());
IClass klass = iKey.getConcreteType();
if (DEBUG) {
System.err.println("visitNew: " + instruction + " " + iKey + " " + system.findOrCreateIndexForInstanceKey(iKey));
}
if (klass == null) {
if (DEBUG) {
System.err.println("Resolution failure: " + instruction);
}
return;
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
// side effect of new: may call class initializer
if (DEBUG) {
System.err.println("visitNew call clinit: " + klass);
}
processClassInitializer(klass);
// add instance keys and pointer keys for array contents
int dim = 0;
InstanceKey lastInstance = iKey;
while (klass != null && klass.isArrayClass()) {
klass = ((ArrayClass) klass).getElementClass();
// klass == null means it's a primitive
if (klass != null && klass.isArrayClass()) {
if (instruction.getNumberOfUses() <= (dim + 1)) {
break;
}
int sv = instruction.getUse(dim + 1);
if (ir.getSymbolTable().isIntegerConstant(sv)) {
Integer c = (Integer) ir.getSymbolTable().getConstantValue(sv);
if (c.intValue() == 0) {
break;
}
}
InstanceKey ik = getInstanceKeyForMultiNewArray(instruction.getNewSite(), dim);
PointerKey pk = getPointerKeyForArrayContents(lastInstance);
if (DEBUG_MULTINEWARRAY) {
System.err.println("multinewarray constraint: ");
System.err.println(" pk: " + pk);
System.err.println(" ik: " + system.findOrCreateIndexForInstanceKey(ik) + " concrete type " + ik.getConcreteType()
+ " is " + ik);
System.err.println(" klass:" + klass);
}
system.newConstraint(pk, ik);
lastInstance = ik;
dim++;
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitThrow(com.ibm.wala.ssa.ThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
// don't do anything: we handle exceptional edges
// in a separate pass
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitGetCaughtException(com.ibm.wala.ssa.GetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
List<ProgramCounter> peis = getIncomingPEIs(ir, getBasicBlock());
PointerKey def = getPointerKeyForLocal(instruction.getDef());
// SJF: we don't optimize based on dead catch blocks yet ... it's a little
// tricky due interaction with the SINGLE_USE optimization which directly
// shoves exceptional return values from calls into exception vars.
// it may not be worth doing this.
// if (hasNoInterestingUses(instruction.getDef(), du)) {
// solver.recordImplicitPointsToSet(def);
// } else {
Set<IClass> types = getCaughtExceptionTypes(instruction, ir);
getBuilder().addExceptionDefConstraints(ir, du, node, peis, def, types);
// }
}
/**
* TODO: What is this doing? Document me!
*/
private int booleanConstantTest(SSAConditionalBranchInstruction c, int v) {
int result = 0;
// right for OPR_eq
if ((symbolTable.isZeroOrFalse(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isZeroOrFalse(c.getUse(1)) && c.getUse(0) == v)) {
result = -1;
} else if ((symbolTable.isOneOrTrue(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isOneOrTrue(c.getUse(1)) && c.getUse(0) == v)) {
result = 1;
}
if (c.getOperator() == ConditionalBranchInstruction.Operator.NE) {
result = -result;
}
return result;
}
private int nullConstantTest(SSAConditionalBranchInstruction c, int v) {
if ((symbolTable.isNullConstant(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isNullConstant(c.getUse(1)) && c.getUse(0) == v)) {
if (c.getOperator() == ConditionalBranchInstruction.Operator.EQ) {
return 1;
} else {
return -1;
}
} else {
return 0;
}
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
if (ir.getMethod() instanceof AbstractRootMethod) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(dst);
} else {
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
PointerKey use = getPointerKeyForLocal(instruction.getUse(i));
if (contentsAreInvariant(symbolTable, du, instruction.getUse(i))) {
system.recordImplicitPointsToSet(use);
InstanceKey[] ik = getInvariantContents(instruction.getUse(i));
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, use);
}
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitPi(com.ibm.wala.ssa.SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {
int dir;
if (hasNoInterestingUses(instruction.getDef())) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
system.recordImplicitPointsToSet(dst);
} else {
ControlFlowGraph<ISSABasicBlock> cfg = ir.getControlFlowGraph();
if (com.ibm.wala.cfg.Util.endsWithConditionalBranch(cfg, getBasicBlock()) && cfg.getSuccNodeCount(getBasicBlock()) == 2) {
SSAConditionalBranchInstruction cond = (SSAConditionalBranchInstruction) com.ibm.wala.cfg.Util.getLastInstruction(cfg,
getBasicBlock());
SSAInstruction cause = instruction.getCause();
BasicBlock target = (BasicBlock) cfg.getNode(instruction.getSuccessor());
if ((cause instanceof SSAInstanceofInstruction)) {
int direction = booleanConstantTest(cond, cause.getDef());
if (direction != 0) {
TypeReference type = ((SSAInstanceofInstruction) cause).getCheckedType();
IClass cls = getClassHierarchy().lookupClass(type);
if (cls == null) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
} else {
PointerKey dst = getFilteredPointerKeyForLocal(instruction.getDef(), new FilteredPointerKey.SingleClassFilter(cls));
PointerKey src = getPointerKeyForLocal(instruction.getVal());
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && direction == 1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && direction == -1)) {
system.newConstraint(dst, getBuilder().filterOperator, src);
} else {
system.newConstraint(dst, getBuilder().inverseFilterOperator, src);
}
}
}
} else if ((dir = nullConstantTest(cond, instruction.getVal())) != 0) {
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && dir == -1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && dir == 1)) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
}
}
/**
* Add a constraint to the system indicating that the contents of local src flows to dst, with no special type
* filter.
*/
private void addPiAssignment(PointerKey dst, int src) {
PointerKey srcKey = getPointerKeyForLocal(src);
if (contentsAreInvariant(symbolTable, du, src)) {
system.recordImplicitPointsToSet(srcKey);
InstanceKey[] ik = getInvariantContents(src);
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, srcKey);
}
}
public ISSABasicBlock getBasicBlock() {
return basicBlock;
}
/**
* The calling loop must call this in each iteration!
*/
public void setBasicBlock(ISSABasicBlock block) {
basicBlock = block;
}
/**
* Side effect: records invariant parameters as implicit points-to-sets.
*
* @return if non-null, then result[i] holds the set of instance keys which may be passed as the ith parameter.
* (which must be invariant)
*/
protected InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] constParams = null;
for (int i = 0; i < call.getNumberOfUses(); i++) {
// not sure how getUse(i) <= 0 .. dead code?
// TODO: investigate
if (call.getUse(i) > 0) {
if (contentsAreInvariant(symbolTable, du, call.getUse(i))) {
system.recordImplicitPointsToSet(getPointerKeyForLocal(call.getUse(i)));
if (constParams == null) {
constParams = new InstanceKey[call.getNumberOfUses()][];
}
constParams[i] = getInvariantContents(call.getUse(i));
for (int j = 0; j < constParams[i].length; j++) {
system.findOrCreateIndexForInstanceKey(constParams[i][j]);
}
}
}
}
return constParams;
}
@Override
public void visitLoadClass(SSALoadClassInstruction instruction) {
PointerKey def = getPointerKeyForLocal(instruction.getDef());
InstanceKey iKey = getInstanceKeyForClassObject(instruction.getLoadedClass());
IClass klass = getClassHierarchy().lookupClass(instruction.getLoadedClass());
if (klass != null) {
processClassInitializer(klass);
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
}
/**
* TODO: lift most of this logic to PropagationCallGraphBuilder
*
* Add a call to the class initializer from the root method.
*/
private void processClassInitializer(IClass klass) {
if (Assertions.verifyAssertions) {
Assertions._assert(klass != null);
}
if (getBuilder().clinitVisited.contains(klass)) {
return;
}
getBuilder().clinitVisited.add(klass);
if (klass.getClassInitializer() != null) {
if (DEBUG) {
System.err.println("process class initializer for " + klass);
}
// add an invocation from the fake root method to the <clinit>
FakeWorldClinitMethod fakeWorldClinitMethod = (FakeWorldClinitMethod) callGraph.getFakeWorldClinitNode().getMethod();
MethodReference m = klass.getClassInitializer().getReference();
CallSiteReference site = CallSiteReference.make(1, m, IInvokeInstruction.Dispatch.STATIC);
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(callGraph.getFakeRootNode(), site, null);
if (targetMethod != null) {
CGNode target = getTargetForCall(callGraph.getFakeRootNode(), site, (InstanceKey) null);
if (target != null && callGraph.getPredNodeCount(target) == 0) {
SSAAbstractInvokeInstruction s = fakeWorldClinitMethod.addInvocation(new int[0], site);
PointerKey uniqueCatch = getBuilder().getPointerKeyForExceptionalReturnValue(callGraph.getFakeRootNode());
getBuilder().processResolvedCall(callGraph.getFakeWorldClinitNode(), s, target, null, uniqueCatch);
}
}
}
try {
IClass sc = klass.getSuperclass();
if (sc != null) {
processClassInitializer(sc);
}
} catch (ClassHierarchyException e) {
Assertions.UNREACHABLE();
}
}
}
/**
* Add constraints for a call site after we have computed a reachable target for the dispatch
*
* Side effect: add edge to the call graph.
*
* @param instruction
* @param constParams if non-null, then constParams[i] holds the set of instance keys that are passed as param i, or
* null if param i is not invariant
* @param uniqueCatchKey if non-null, then this is the unique PointerKey that catches all exceptions from this call
* site.
*/
@SuppressWarnings("deprecation")
private void processResolvedCall(CGNode caller, SSAAbstractInvokeInstruction instruction, CGNode target,
InstanceKey[][] constParams, PointerKey uniqueCatchKey) {
if (DEBUG) {
System.err.println("processResolvedCall: " + caller + " ," + instruction + " , " + target);
}
if (DEBUG) {
System.err.println("addTarget: " + caller + " ," + instruction + " , " + target);
}
caller.addTarget(instruction.getCallSite(), target);
if (FakeRootMethod.isFakeRootMethod(caller.getMethod().getReference())) {
if (entrypointCallSites.contains(instruction.getCallSite())) {
callGraph.registerEntrypoint(target);
}
}
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
// TODO: i'd like to enable this optimization, but it's a little tricky
// to recover the implicit points-to sets with recursion. TODO: don't
// be lazy and code the recursive logic to enable this.
// if (hasNoInstructions(target)) {
// // record points-to sets for formals implicitly .. computed on
// // demand.
// // TODO: generalize this by using hasNoInterestingUses on parameters.
// // however .. have to be careful to cache results in that case ... don't
// // want
// // to recompute du each time we process a call to Object.<init> !
// for (int i = 0; i < instruction.getNumberOfUses(); i++) {
// // we rely on the invariant that the value number for the ith parameter
// // is i+1
// final int vn = i + 1;
// PointerKey formal = getPointerKeyForLocal(target, vn);
// if (target.getMethod().getParameterType(i).isReferenceType()) {
// system.recordImplicitPointsToSet(formal);
// }
// }
// } else {
// generate contraints from parameter passing
int nUses = instruction.getNumberOfParameters();
int nExpected = target.getMethod().getNumberOfParameters();
/*
* int nExpected = target.getMethod().getReference().getNumberOfParameters(); if (!target.getMethod().isStatic() &&
* !target.getMethod().isClinit()) { nExpected++; }
*/
if (nUses != nExpected) {
// some sort of unverifiable code mismatch. give up.
return;
}
boolean needsFilter = !instruction.getCallSite().isStatic() && needsFilterForReceiver(instruction, target);
// we're a little sloppy for now ... we don't filter calls to
// java.lang.Object.
// TODO: we need much more precise filters than cones in order to handle
// the various types of dispatch logic. We need a filter that expresses
// "the set of types s.t. x.foo resolves to y.foo."
for (int i = 0; i < instruction.getNumberOfParameters(); i++) {
// we rely on the invariant that the value number for the ith parameter
// is i+1
final int vn = i + 1;
if (target.getMethod().getParameterType(i).isReferenceType()) {
// if (constParams != null && constParams[i] != null &&
// !supportFullPointerFlowGraph) {
if (constParams != null && constParams[i] != null) {
InstanceKey[] ik = constParams[i];
for (int j = 0; j < ik.length; j++) {
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
PointerKey formal = null;
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
formal = getPointerKeyForLocal(target, vn);
} else {
formal = getFilteredPointerKeyForLocal(target, vn, C);
}
system.newConstraint(formal, ik[j]);
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, ik[j]);
}
}
} else {
if (Assertions.verifyAssertions) {
if (instruction.getUse(i) < 0) {
Assertions.UNREACHABLE("unexpected " + instruction + " in " + caller);
}
}
PointerKey actual = getPointerKeyForLocal(caller, instruction.getUse(i));
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
} else {
FilteredPointerKey formal = getFilteredPointerKeyForLocal(target, vn, C);
system.newConstraint(formal, filterOperator, actual);
}
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
}
}
}
}
// generate contraints from return value.
if (instruction.hasDef() && instruction.getDeclaredResultType().isReferenceType()) {
PointerKey result = getPointerKeyForLocal(caller, instruction.getDef());
PointerKey ret = getPointerKeyForReturnValue(target);
system.newConstraint(result, assignOperator, ret);
}
// generate constraints from exception return value.
PointerKey e = getPointerKeyForLocal(caller, instruction.getException());
PointerKey er = getPointerKeyForExceptionalReturnValue(target);
if (SHORT_CIRCUIT_SINGLE_USES && uniqueCatchKey != null) {
// e has exactly one use. so, represent e implicitly
system.newConstraint(uniqueCatchKey, assignOperator, er);
} else {
system.newConstraint(e, assignOperator, er);
}
// }
}
/**
* An operator to fire when we discover a potential new callee for a virtual or interface call site.
*
* This operator will create a new callee context and constraints if necessary.
*
* N.B: This implementation assumes that the calling context depends solely on the dataflow information computed for
* the receiver. TODO: generalize this to have other forms of context selection, such as CPA-style algorithms.
*/
final class DispatchOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator {
private final SSAAbstractInvokeInstruction call;
private final ExplicitCallGraph.ExplicitNode node;
private final InstanceKey[][] constParams;
private final PointerKey uniqueCatch;
/**
* @param call
* @param node
* @param constParams if non-null, then constParams[i] holds the String constant that is passed as param i, or null
* if param i is not a String constant
*/
DispatchOperator(SSAAbstractInvokeInstruction call, ExplicitCallGraph.ExplicitNode node, InstanceKey[][] constParams,
PointerKey uniqueCatch) {
this.call = call;
this.node = node;
this.constParams = constParams;
this.uniqueCatch = uniqueCatch;
}
/**
* The set of pointers that have already been processed.
*/
final private MutableIntSet previousReceivers = IntSetUtil.getDefaultIntSetFactory().make();
/*
* @see com.ibm.wala.dataflow.fixpoint.UnaryOperator#evaluate(com.ibm.wala.dataflow.fixpoint.IVariable,
* com.ibm.wala.dataflow.fixpoint.IVariable)
*/
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable receivers = rhs;
final MutableBoolean sideEffect = new MutableBoolean();
// compute the set of pointers that were not previously handled
IntSet value = receivers.getValue();
if (value == null) {
// this constraint was put on the work list, probably by
// initialization,
// even though the right-hand-side is empty.
// TODO: be more careful about what goes on the worklist to
// avoid this.
if (DEBUG) {
System.err.println("EVAL dispatch with value null");
}
return NOT_CHANGED;
}
if (DEBUG) {
System.err.println("EVAL dispatch to " + node + ":" + call);
System.err.println("receivers: " + value);
}
IntSetAction action = new IntSetAction() {
public void act(int ptr) {
if (DEBUG) {
System.err.println(" dispatch to ptr " + ptr);
}
InstanceKey iKey = system.getInstanceKey(ptr);
CGNode target;
if (clone2Assign) {
// for efficiency: assume that only call sites that reference
// clone() might dispatch to clone methods
if (call.getCallSite().getDeclaredTarget().getSelector().equals(cloneSelector)) {
IClass recv = (iKey != null) ? iKey.getConcreteType() : null;
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(node, call.getCallSite(), recv);
if (targetMethod != null && targetMethod.getReference().equals(CloneInterpreter.CLONE)) {
// treat this call to clone as an assignment
PointerKey result = getPointerKeyForLocal(node, call.getDef());
PointerKey receiver = getPointerKeyForLocal(node, call.getReceiver());
system.newConstraint(result, assignOperator, receiver);
return;
}
}
}
target = getTargetForCall(node, call.getCallSite(), iKey);
if (target == null) {
// This indicates an error; I sure hope getTargetForCall
// raised a warning about this!
if (DEBUG) {
System.err.println("Warning: null target for call " + call + " " + iKey);
}
} else {
IntSet targets = getCallGraph().getPossibleTargetNumbers(node, call.getCallSite());
if (targets != null && targets.contains(target.getGraphNodeId())) {
// do nothing; we've previously discovered and handled this
// receiver for this call site.
} else {
// process the newly discovered target for this call
sideEffect.b = true;
processResolvedCall(node, call, target, constParams, uniqueCatch);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
}
}
}
};
try {
value.foreachExcluding(previousReceivers, action);
} catch (Error e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
} catch (RuntimeException e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
}
// update the set of receivers previously considered
previousReceivers.copySet(value);
byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0;
return (byte) (NOT_CHANGED | sideEffectMask);
}
@Override
public String toString() {
return "Dispatch to " + call + " in node " + node;
}
@Override
public int hashCode() {
return node.hashCode() + 90289 * call.hashCode();
}
@Override
public boolean equals(Object o) {
// note that these are not necessarily canonical, since
// with synthetic factories we may regenerate constraints
// many times. TODO: change processing of synthetic factories
// so that we guarantee to insert each dispatch equation
// only once ... if this were true we could optimize this
// with reference equality
// instanceof is OK because this class is final
if (o instanceof DispatchOperator) {
DispatchOperator other = (DispatchOperator) o;
return node.equals(other.node) && call.equals(other.call);
} else {
return false;
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.IPointerOperator#isComplex()
*/
public boolean isComplex() {
return true;
}
}
public boolean hasNoInterestingUses(CGNode node, int vn, DefUse du) {
if (du == null) {
throw new IllegalArgumentException("du is null");
}
// todo: enhance this by solving a dead-code elimination
// problem.
InterestingVisitor v = makeInterestingVisitor(node, vn);
for (Iterator it = du.getUses(vn); it.hasNext();) {
SSAInstruction s = (SSAInstruction) it.next();
s.visit(v);
if (v.bingo) {
return false;
}
}
return true;
}
protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) {
return new InterestingVisitor(vn);
}
/**
* sets bingo to true when it visits an interesting instruction
*/
protected static class InterestingVisitor extends SSAInstruction.Visitor {
protected final int vn;
protected InterestingVisitor(int vn) {
this.vn = vn;
}
protected boolean bingo = false;
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
if (!instruction.typeIsPrimitive() && instruction.getArrayRef() == vn) {
bingo = true;
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
if (!instruction.typeIsPrimitive() && (instruction.getArrayRef() == vn || instruction.getValue() == vn)) {
bingo = true;
}
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
bingo = true;
}
@Override
public void visitGet(SSAGetInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
bingo = true;
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
bingo = true;
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
bingo = true;
}
@Override
public void visitPi(SSAPiInstruction instruction) {
bingo = true;
}
@Override
public void visitPut(SSAPutInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
bingo = true;
}
@Override
public void visitThrow(SSAThrowInstruction instruction) {
bingo = true;
}
}
/**
* TODO: enhance this logic using type inference
*
* @param instruction
* @return true if we need to filter the receiver type to account for virtual dispatch
*/
private boolean needsFilterForReceiver(SSAAbstractInvokeInstruction instruction, CGNode target) {
FilteredPointerKey.TypeFilter f = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (f != null) {
// the context selects a particular concrete type for the receiver.
// we need to filter, unless the declared receiver type implies the
// concrete type (TODO: need to implement this optimization)
return true;
}
// don't need to filter for invokestatic
if (instruction.getCallSite().isStatic() || instruction.getCallSite().isSpecial()) {
return false;
}
MethodReference declaredTarget = instruction.getDeclaredTarget();
IMethod resolvedTarget = getClassHierarchy().resolveMethod(declaredTarget);
if (resolvedTarget == null) {
// there's some problem that will be flagged as a warning
return true;
}
return true;
}
private boolean isRootType(IClass klass) {
return klass.getClassHierarchy().isRootClass(klass);
}
private boolean isRootType(FilteredPointerKey.TypeFilter filter) {
if (filter instanceof FilteredPointerKey.SingleClassFilter) {
return isRootType(((FilteredPointerKey.SingleClassFilter) filter).getConcreteType());
} else {
return false;
}
}
/**
* TODO: enhance this logic using type inference TODO!!!: enhance filtering to consider concrete types, not just
* cones. precondition: needs Filter
*
* @param target
* @return an IClass which represents
*/
private FilteredPointerKey.TypeFilter getFilter(CGNode target) {
FilteredPointerKey.TypeFilter filter = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (filter != null) {
return filter;
} else {
// the context does not select a particular concrete type for the
// receiver.
IClass C = getReceiverClass(target.getMethod());
return new FilteredPointerKey.SingleClassFilter(C);
}
}
/**
* @param method
* @return the receiver class for this method.
*/
private IClass getReceiverClass(IMethod method) {
TypeReference formalType = method.getParameterType(0);
IClass C = getClassHierarchy().lookupClass(formalType);
if (Assertions.verifyAssertions) {
if (method.isStatic()) {
Assertions.UNREACHABLE("asked for receiver of static method " + method);
}
if (C == null) {
Assertions.UNREACHABLE("no class found for " + formalType + " recv of " + method);
}
}
return C;
}
/**
* A value is "invariant" if we can figure out the instances it can ever point to locally, without resorting to
* propagation.
*
* @param valueNumber
* @return true iff the contents of the local with this value number can be deduced locally, without propagation
*/
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
if (isConstantRef(symbolTable, valueNumber)) {
return true;
} else if (SHORT_CIRCUIT_INVARIANT_SETS) {
SSAInstruction def = du.getDef(valueNumber);
if (def instanceof SSANewInstruction) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* precondition:contentsAreInvariant(valueNumber)
*
* @param valueNumber
* @return the complete set of instances that the local with vn=valueNumber may point to.
*/
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm) {
return getInvariantContents(symbolTable, du, node, valueNumber, hm, false);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm,
boolean ensureIndexes) {
InstanceKey[] result;
if (isConstantRef(symbolTable, valueNumber)) {
Object x = symbolTable.getConstantValue(valueNumber);
if (x instanceof String) {
// this is always the case in Java. use strong typing in the call to getInstanceKeyForConstant.
String S = (String) x;
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, S);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
} else {
// some non-built in type (e.g. Integer). give up on strong typing.
// language-specific subclasses (e.g. Javascript) should override this method to get strong typing
// with generics if desired.
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(x);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, x);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
}
} else {
SSANewInstruction def = (SSANewInstruction) du.getDef(valueNumber);
InstanceKey iKey = hm.getInstanceKeyForAllocation(node, def.getNewSite());
result = (iKey == null) ? new InstanceKey[0] : new InstanceKey[] { iKey };
}
if (ensureIndexes) {
for (int i = 0; i < result.length; i++) {
system.findOrCreateIndexForInstanceKey(result[i]);
}
}
return result;
}
protected boolean isConstantRef(SymbolTable symbolTable, int valueNumber) {
if (valueNumber == -1) {
return false;
}
if (symbolTable.isConstant(valueNumber)) {
Object v = symbolTable.getConstantValue(valueNumber);
return (!(v instanceof Number));
} else {
return false;
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a checkcast
*/
private static class CheckcastFailure extends Warning {
final TypeReference type;
CheckcastFailure(TypeReference type) {
super(Warning.SEVERE);
this.type = type;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + type;
}
public static CheckcastFailure create(TypeReference type) {
return new CheckcastFailure(type);
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a field
*/
private static class FieldResolutionFailure extends Warning {
final FieldReference field;
FieldResolutionFailure(FieldReference field) {
super(Warning.SEVERE);
this.field = field;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + field;
}
public static FieldResolutionFailure create(FieldReference field) {
return new FieldResolutionFailure(field);
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.HeapModel#iteratePointerKeys()
*/
public Iterator<PointerKey> iteratePointerKeys() {
return system.iteratePointerKeys();
}
public static Set<IClass> getCaughtExceptionTypes(SSAGetCaughtExceptionInstruction instruction, IR ir) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (instruction == null) {
throw new IllegalArgumentException("instruction is null");
}
Iterator<TypeReference> exceptionTypes = ((ExceptionHandlerBasicBlock) ir.getControlFlowGraph().getNode(
instruction.getBasicBlockNumber())).getCaughtExceptionTypes();
HashSet<IClass> types = HashSetFactory.make(10);
for (; exceptionTypes.hasNext();) {
IClass c = ir.getMethod().getClassHierarchy().lookupClass(exceptionTypes.next());
if (c != null) {
types.add(c);
}
}
return types;
}
public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) {
return getInstanceKeyForPEI(node, instr, type, instanceKeyFactory);
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder#makeSolver()
*/
@Override
protected IPointsToSolver makeSolver() {
return usePreTransitiveSolver ? (IPointsToSolver) new PreTransitiveSolver(system, this) : new StandardSolver(system, this);
// return true ? (IPointsToSolver)new PreTransitiveSolver(system,this) : new
// StandardSolver(system,this);
}
}
| private void addExceptionDefConstraints(IR ir, DefUse du, CGNode node, List<ProgramCounter> peis, PointerKey exceptionVar,
Set<IClass> catchClasses) {
if (DEBUG) {
System.err.println("Add exception def constraints for node " + node);
}
for (Iterator<ProgramCounter> it = peis.iterator(); it.hasNext();) {
ProgramCounter peiLoc = it.next();
if (DEBUG) {
System.err.println("peiLoc: " + peiLoc);
}
SSAInstruction pei = ir.getPEI(peiLoc);
if (DEBUG) {
System.err.println("Add exceptions from pei " + pei);
}
if (pei instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction s = (SSAAbstractInvokeInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (!SHORT_CIRCUIT_SINGLE_USES || !hasUniqueCatchBlock(s, ir)) {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}// else {
// System.err.println("SKIPPING ASSIGNMENTS TO " + exceptionVar + " FROM " +
// e);
// }
} else if (pei instanceof SSAAbstractThrowInstruction) {
SSAAbstractThrowInstruction s = (SSAAbstractThrowInstruction) pei;
PointerKey e = getPointerKeyForLocal(node, s.getException());
if (contentsAreInvariant(ir.getSymbolTable(), du, s.getException())) {
InstanceKey[] ik = getInvariantContents(ir.getSymbolTable(), du, node, s.getException(), this);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
assignInstanceToCatch(exceptionVar, catchClasses, ik[i]);
}
} else {
addAssignmentsForCatchPointerKey(exceptionVar, catchClasses, e);
}
}
// Account for those exceptions for which we do not actually have a
// points-to set for
// the pei, but just instance keys
Collection<TypeReference> types = pei.getExceptionTypes();
if (types != null) {
for (Iterator<TypeReference> it2 = types.iterator(); it2.hasNext();) {
TypeReference type = it2.next();
if (type != null) {
InstanceKey ik = getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory);
if (ik == null) {
continue;
}
if (Assertions.verifyAssertions) {
if (!(ik instanceof ConcreteTypeKey)) {
Assertions._assert(ik instanceof ConcreteTypeKey,
"uh oh: need to implement getCaughtException constraints for instance " + ik);
}
}
ConcreteTypeKey ck = (ConcreteTypeKey) ik;
IClass klass = ck.getType();
if (PropagationCallGraphBuilder.catches(catchClasses, klass, cha)) {
system.newConstraint(exceptionVar, getInstanceKeyForPEI(node, peiLoc, type, instanceKeyFactory));
}
}
}
}
}
}
/**
* @return true iff there's a unique catch block which catches all exceptions thrown by a certain call site.
*/
protected static boolean hasUniqueCatchBlock(SSAAbstractInvokeInstruction call, IR ir) {
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (bb.length == 1) {
Iterator it = ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator();
// check that there's exactly one element in the iterator
if (it.hasNext()) {
it.next();
return (!it.hasNext());
}
}
return false;
}
/**
* precondition: hasUniqueCatchBlock(call,node,cg)
*
* @return the unique pointer key which catches the exceptions thrown by a call
* @throws IllegalArgumentException if ir == null
* @throws IllegalArgumentException if call == null
*/
public PointerKey getUniqueCatchKey(SSAAbstractInvokeInstruction call, IR ir, CGNode node) throws IllegalArgumentException,
IllegalArgumentException {
if (call == null) {
throw new IllegalArgumentException("call == null");
}
if (ir == null) {
throw new IllegalArgumentException("ir == null");
}
ISSABasicBlock[] bb = ir.getBasicBlocksForCall(call.getCallSite());
if (Assertions.verifyAssertions) {
Assertions._assert(bb.length == 1);
}
SSACFG.BasicBlock cb = (BasicBlock) ir.getControlFlowGraph().getExceptionalSuccessors(bb[0]).iterator().next();
if (cb.isExitBlock()) {
return getPointerKeyForExceptionalReturnValue(node);
} else {
SSACFG.ExceptionHandlerBasicBlock ehbb = (ExceptionHandlerBasicBlock) cb;
SSAGetCaughtExceptionInstruction ci = ehbb.getCatchInstruction();
return getPointerKeyForLocal(node, ci.getDef());
}
}
/**
* @return a List of Instructions that may transfer control to bb via an exceptional edge
* @throws IllegalArgumentException if ir is null
*/
public static List<ProgramCounter> getIncomingPEIs(IR ir, ISSABasicBlock bb) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (DEBUG) {
System.err.println("getIncomingPEIs " + bb);
}
ControlFlowGraph<ISSABasicBlock> g = ir.getControlFlowGraph();
List<ProgramCounter> result = new ArrayList<ProgramCounter>(g.getPredNodeCount(bb));
for (Iterator it = g.getPredNodes(bb); it.hasNext();) {
BasicBlock pred = (BasicBlock) it.next();
if (DEBUG) {
System.err.println("pred: " + pred);
}
if (pred.isEntryBlock())
continue;
int index = pred.getLastInstructionIndex();
SSAInstruction pei = ir.getInstructions()[index];
// Note: pei might be null if pred is unreachable.
// TODO: consider pruning CFG for unreachable blocks.
if (pei != null && pei.isPEI()) {
if (DEBUG) {
System.err.println("PEI: " + pei + " index " + index + " PC " + g.getProgramCounter(index));
}
result.add(new ProgramCounter(g.getProgramCounter(index)));
}
}
return result;
}
/**
* A visitor that generates constraints based on statements in SSA form.
*/
protected static class ConstraintVisitor extends SSAInstruction.Visitor {
/**
* The governing call graph builder. This field is used instead of an inner class in order to allow more flexible
* reuse of this visitor in subclasses
*/
protected final SSAPropagationCallGraphBuilder builder;
/**
* The node whose statements we are currently traversing
*/
protected final ExplicitCallGraph.ExplicitNode node;
/**
* The governing call graph.
*/
private final ExplicitCallGraph callGraph;
/**
* The governing IR
*/
protected final IR ir;
/**
* The governing propagation system, into which constraints are added
*/
protected final PropagationSystem system;
/**
* The basic block currently being processed
*/
private ISSABasicBlock basicBlock;
/**
* Governing symbol table
*/
protected final SymbolTable symbolTable;
/**
* Def-use information
*/
protected final DefUse du;
public ConstraintVisitor(SSAPropagationCallGraphBuilder builder, ExplicitCallGraph.ExplicitNode node) {
this.builder = builder;
this.node = node;
this.callGraph = builder.getCallGraph();
this.system = builder.getPropagationSystem();
this.ir = builder.getCFAContextInterpreter().getIR(node);
this.symbolTable = this.ir.getSymbolTable();
this.du = builder.getCFAContextInterpreter().getDU(node);
if (Assertions.verifyAssertions) {
Assertions._assert(symbolTable != null);
}
}
protected SSAPropagationCallGraphBuilder getBuilder() {
return builder;
}
protected AnalysisOptions getOptions() {
return builder.options;
}
protected AnalysisCache getAnalysisCache() {
return builder.getAnalysisCache();
}
public PointerKey getPointerKeyForLocal(int valueNumber) {
return getBuilder().getPointerKeyForLocal(node, valueNumber);
}
public FilteredPointerKey getFilteredPointerKeyForLocal(int valueNumber, FilteredPointerKey.TypeFilter filter) {
return getBuilder().getFilteredPointerKeyForLocal(node, valueNumber, filter);
}
public PointerKey getPointerKeyForReturnValue() {
return getBuilder().getPointerKeyForReturnValue(node);
}
public PointerKey getPointerKeyForExceptionalReturnValue() {
return getBuilder().getPointerKeyForExceptionalReturnValue(node);
}
public PointerKey getPointerKeyForStaticField(IField f) {
return getBuilder().getPointerKeyForStaticField(f);
}
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) {
return getBuilder().getPointerKeyForInstanceField(I, f);
}
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
return getBuilder().getPointerKeyForArrayContents(I);
}
public InstanceKey getInstanceKeyForAllocation(NewSiteReference allocation) {
return getBuilder().getInstanceKeyForAllocation(node, allocation);
}
public InstanceKey getInstanceKeyForMultiNewArray(NewSiteReference allocation, int dim) {
return getBuilder().getInstanceKeyForMultiNewArray(node, allocation, dim);
}
public <T> InstanceKey getInstanceKeyForConstant(T S) {
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
return getBuilder().getInstanceKeyForConstant(type, S);
}
public InstanceKey getInstanceKeyForPEI(ProgramCounter instr, TypeReference type) {
return getBuilder().getInstanceKeyForPEI(node, instr, type);
}
public InstanceKey getInstanceKeyForClassObject(TypeReference type) {
return getBuilder().getInstanceKeyForClassObject(type);
}
public CGNode getTargetForCall(CGNode caller, CallSiteReference site, InstanceKey iKey) {
return getBuilder().getTargetForCall(caller, site, iKey);
}
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
return getBuilder().contentsAreInvariant(symbolTable, du, valueNumber);
}
protected InstanceKey[] getInvariantContents(int valueNumber) {
return getInvariantContents(ir.getSymbolTable(), du, node, valueNumber);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber) {
return getBuilder().getInvariantContents(symbolTable, du, node, valueNumber, getBuilder());
}
protected IClassHierarchy getClassHierarchy() {
return getBuilder().getClassHierarchy();
}
protected boolean hasNoInterestingUses(int vn) {
return getBuilder().hasNoInterestingUses(node, vn, du);
}
protected boolean isRootType(IClass klass) {
return getBuilder().isRootType(klass);
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayLoad(com.ibm.wala.ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayLoad(instruction.getDef(), instruction.getArrayRef());
}
protected void doVisitArrayLoad(int def, int arrayRef) {
PointerKey result = getPointerKeyForLocal(def);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
if (hasNoInterestingUses(def)) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
if (p == null) {
} else {
system.newConstraint(result, assignOperator, p);
}
}
}
} else {
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(result));
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new ArrayLoadOperator(system.findOrCreatePointsToSet(result)), arrayRefPtrKey);
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitArrayStore(com.ibm.wala.ssa.SSAArrayStoreInstruction)
*/
public void doVisitArrayStore(int arrayRef, int value) {
// (requires the creation of assign constraints as
// the set points-to(a[]) grows.)
PointerKey valuePtrKey = getPointerKeyForLocal(value);
PointerKey arrayRefPtrKey = getPointerKeyForLocal(arrayRef);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getArrayRef())) {
if (contentsAreInvariant(symbolTable, du, arrayRef)) {
system.recordImplicitPointsToSet(arrayRefPtrKey);
InstanceKey[] ik = getInvariantContents(arrayRef);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForArrayContents(ik[i]);
IClass contents = ((ArrayClass) ik[i].getConcreteType()).getElementClass();
if (p == null) {
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] vk = getInvariantContents(value);
for (int j = 0; j < vk.length; j++) {
system.findOrCreateIndexForInstanceKey(vk[j]);
if (vk[j].getConcreteType() != null) {
if (getClassHierarchy().isAssignableFrom(contents, vk[j].getConcreteType())) {
system.newConstraint(p, vk[j]);
}
}
}
} else {
if (isRootType(contents)) {
system.newConstraint(p, assignOperator, valuePtrKey);
} else {
system.newConstraint(p, getBuilder().filterOperator, valuePtrKey);
}
}
}
}
}
} else {
if (contentsAreInvariant(symbolTable, du, value)) {
system.recordImplicitPointsToSet(valuePtrKey);
InstanceKey[] ik = getInvariantContents(value);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (Assertions.verifyAssertions) {
Assertions._assert(!system.isUnified(arrayRefPtrKey));
}
system.newSideEffect(getBuilder().new InstanceArrayStoreOperator(ik[i]), arrayRefPtrKey);
}
} else {
system.newSideEffect(getBuilder().new ArrayStoreOperator(system.findOrCreatePointsToSet(valuePtrKey)), arrayRefPtrKey);
}
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
// skip arrays of primitive type
if (instruction.typeIsPrimitive()) {
return;
}
doVisitArrayStore(instruction.getArrayRef(), instruction.getValue());
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitCheckCast(com.ibm.wala.ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
IClass cls = getClassHierarchy().lookupClass(instruction.getDeclaredResultType());
PointerKey result = null;
if (cls == null) {
Warnings.add(CheckcastFailure.create(instruction.getDeclaredResultType()));
// we failed to find the type.
// conservatively it would make sense to ignore the filter and be
// conservative, assuming
// java.lang.Object.
// however, this breaks the invariants downstream that assume every
// variable is
// strongly typed ... we can't have bad types flowing around.
// since things are broken anyway, just give up.
// result = getPointerKeyForLocal(node, instruction.getResult());
return;
} else {
result = getFilteredPointerKeyForLocal(instruction.getResult(), new FilteredPointerKey.SingleClassFilter(cls));
}
PointerKey value = getPointerKeyForLocal(instruction.getVal());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(result);
} else {
if (contentsAreInvariant(symbolTable, du, instruction.getVal())) {
system.recordImplicitPointsToSet(value);
InstanceKey[] ik = getInvariantContents(instruction.getVal());
if (cls.isInterface()) {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().implementsInterface(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
if (getClassHierarchy().isSubclassOf(ik[i].getConcreteType(), cls)) {
system.newConstraint(result, ik[i]);
}
}
}
} else {
if (isRootType(cls)) {
system.newConstraint(result, assignOperator, value);
} else {
system.newConstraint(result, getBuilder().filterOperator, value);
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitReturn(com.ibm.wala.ssa.SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {
// skip returns of primitive type
if (instruction.returnsPrimitiveType() || instruction.returnsVoid()) {
return;
}
if (DEBUG) {
System.err.println("visitReturn: " + instruction);
}
PointerKey returnValue = getPointerKeyForReturnValue();
PointerKey result = getPointerKeyForLocal(instruction.getResult());
if (contentsAreInvariant(symbolTable, du, instruction.getResult())) {
system.recordImplicitPointsToSet(result);
InstanceKey[] ik = getInvariantContents(instruction.getResult());
for (int i = 0; i < ik.length; i++) {
if (DEBUG) {
System.err.println("invariant contents: " + returnValue + " " + ik[i]);
}
system.newConstraint(returnValue, ik[i]);
}
} else {
system.newConstraint(returnValue, assignOperator, result);
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitGet(com.ibm.wala.ssa.SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
visitGetInternal(instruction.getDef(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
protected void visitGetInternal(int lval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitGet " + field);
}
// skip getfields of primitive type (optimisation)
if (field.getFieldType().isPrimitiveType()) {
return;
}
PointerKey def = getPointerKeyForLocal(lval);
if (Assertions.verifyAssertions) {
Assertions._assert(def != null);
}
IField f = getClassHierarchy().resolveField(field);
if (f == null && callGraph.getFakeRootNode().getMethod().getDeclaringClass().getReference().equals(field.getDeclaringClass())) {
f = callGraph.getFakeRootNode().getMethod().getDeclaringClass().getField(field.getName());
}
if (f == null) {
return;
}
if (hasNoInterestingUses(lval)) {
system.recordImplicitPointsToSet(def);
} else {
if (isStatic) {
PointerKey fKey = getPointerKeyForStaticField(f);
system.newConstraint(def, assignOperator, fKey);
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
} else {
// side effect of getstatic: may call class initializer
if (DEBUG) {
System.err.println("getstatic call class init " + klass);
}
processClassInitializer(klass);
}
} else {
PointerKey refKey = getPointerKeyForLocal(ref);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(ref)) {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] ik = getInvariantContents(ref);
for (int i = 0; i < ik.length; i++) {
if (!representsNullType(ik[i])) {
system.findOrCreateIndexForInstanceKey(ik[i]);
PointerKey p = getPointerKeyForInstanceField(ik[i], f);
system.newConstraint(def, assignOperator, p);
}
}
} else {
system.newSideEffect(getBuilder().new GetFieldOperator(f, system.findOrCreatePointsToSet(def)), refKey);
}
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitPut(com.ibm.wala.ssa.PutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
visitPutInternal(instruction.getVal(), instruction.getRef(), instruction.isStatic(), instruction.getDeclaredField());
}
public void visitPutInternal(int rval, int ref, boolean isStatic, FieldReference field) {
if (DEBUG) {
System.err.println("visitPut " + field);
}
// skip putfields of primitive type
if (field.getFieldType().isPrimitiveType()) {
return;
}
IField f = getClassHierarchy().resolveField(field);
if (f == null) {
if (DEBUG) {
System.err.println("Could not resolve field " + field);
}
Warnings.add(FieldResolutionFailure.create(field));
return;
}
if (Assertions.verifyAssertions) {
Assertions._assert(isStatic || !symbolTable.isStringConstant(ref), "put to string constant shouldn't be allowed?");
}
if (isStatic) {
processPutStatic(rval, field, f);
} else {
processPutField(rval, ref, f);
}
}
private void processPutField(int rval, int ref, IField f) {
if (Assertions.verifyAssertions) {
Assertions._assert(!f.getFieldTypeReference().isPrimitiveType());
}
PointerKey refKey = getPointerKeyForLocal(ref);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(p, ik[i]);
}
}
}
} else {
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
system.newSideEffect(getBuilder().new InstancePutFieldOperator(f, ik[i]), refKey);
}
}
} else {
if (contentsAreInvariant(symbolTable, du, ref)) {
system.recordImplicitPointsToSet(refKey);
InstanceKey[] refk = getInvariantContents(ref);
for (int j = 0; j < refk.length; j++) {
if (!representsNullType(refk[j])) {
system.findOrCreateIndexForInstanceKey(refk[j]);
PointerKey p = getPointerKeyForInstanceField(refk[j], f);
system.newConstraint(p, assignOperator, rvalKey);
}
}
} else {
if (DEBUG) {
System.err.println("adding side effect " + f);
}
system.newSideEffect(getBuilder().new PutFieldOperator(f, system.findOrCreatePointsToSet(rvalKey)), refKey);
}
}
}
private void processPutStatic(int rval, FieldReference field, IField f) {
PointerKey fKey = getPointerKeyForStaticField(f);
PointerKey rvalKey = getPointerKeyForLocal(rval);
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(rval)) {
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(fKey, ik[i]);
}
} else {
system.newConstraint(fKey, assignOperator, rvalKey);
}
if (DEBUG) {
System.err.println("visitPut class init " + field.getDeclaringClass() + " " + field);
}
// side effect of putstatic: may call class initializer
IClass klass = getClassHierarchy().lookupClass(field.getDeclaringClass());
if (klass == null) {
Warnings.add(FieldResolutionFailure.create(field));
} else {
processClassInitializer(klass);
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitInvoke(com.ibm.wala.ssa.InvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
visitInvokeInternal(instruction);
}
protected void visitInvokeInternal(SSAAbstractInvokeInstruction instruction) {
if (DEBUG) {
System.err.println("visitInvoke: " + instruction);
}
PointerKey uniqueCatch = null;
if (hasUniqueCatchBlock(instruction, ir)) {
uniqueCatch = getBuilder().getUniqueCatchKey(instruction, ir, node);
}
if (instruction.getCallSite().isStatic()) {
CGNode n = getTargetForCall(node, instruction.getCallSite(), (InstanceKey) null);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
if (DEBUG) {
System.err.println("visitInvoke class init " + n);
}
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
} else {
// Add a side effect that will fire when we determine a value
// for the receiver. This side effect will create a new node
// and new constraints based on the new callee context.
// NOTE: This will not be adequate for CPA-style context selectors,
// where the callee context may depend on state other than the
// receiver. TODO: rectify this when needed.
PointerKey receiver = getPointerKeyForLocal(instruction.getReceiver());
// if (!supportFullPointerFlowGraph &&
// contentsAreInvariant(instruction.getReceiver())) {
if (contentsAreInvariant(symbolTable, du, instruction.getReceiver())) {
system.recordImplicitPointsToSet(receiver);
InstanceKey[] ik = getInvariantContents(instruction.getReceiver());
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
CGNode n = getTargetForCall(node, instruction.getCallSite(), ik[i]);
if (n == null) {
} else {
getBuilder().processResolvedCall(node, instruction, n, computeInvariantParameters(instruction), uniqueCatch);
// side effect of invoke: may call class initializer
processClassInitializer(n.getMethod().getDeclaringClass());
}
}
} else {
if (DEBUG) {
System.err.println("Add side effect, dispatch to " + instruction + ", receiver " + receiver);
}
DispatchOperator dispatchOperator = getBuilder().new DispatchOperator(instruction, node,
computeInvariantParameters(instruction), uniqueCatch);
system.newSideEffect(dispatchOperator, receiver);
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitNew(com.ibm.wala.ssa.NewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {
InstanceKey iKey = getInstanceKeyForAllocation(instruction.getNewSite());
if (iKey == null) {
// something went wrong. I hope someone raised a warning.
return;
}
PointerKey def = getPointerKeyForLocal(instruction.getDef());
IClass klass = iKey.getConcreteType();
if (DEBUG) {
System.err.println("visitNew: " + instruction + " " + iKey + " " + system.findOrCreateIndexForInstanceKey(iKey));
}
if (klass == null) {
if (DEBUG) {
System.err.println("Resolution failure: " + instruction);
}
return;
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
// side effect of new: may call class initializer
if (DEBUG) {
System.err.println("visitNew call clinit: " + klass);
}
processClassInitializer(klass);
// add instance keys and pointer keys for array contents
int dim = 0;
InstanceKey lastInstance = iKey;
while (klass != null && klass.isArrayClass()) {
klass = ((ArrayClass) klass).getElementClass();
// klass == null means it's a primitive
if (klass != null && klass.isArrayClass()) {
if (instruction.getNumberOfUses() <= (dim + 1)) {
break;
}
int sv = instruction.getUse(dim + 1);
if (ir.getSymbolTable().isIntegerConstant(sv)) {
Integer c = (Integer) ir.getSymbolTable().getConstantValue(sv);
if (c.intValue() == 0) {
break;
}
}
InstanceKey ik = getInstanceKeyForMultiNewArray(instruction.getNewSite(), dim);
PointerKey pk = getPointerKeyForArrayContents(lastInstance);
if (DEBUG_MULTINEWARRAY) {
System.err.println("multinewarray constraint: ");
System.err.println(" pk: " + pk);
System.err.println(" ik: " + system.findOrCreateIndexForInstanceKey(ik) + " concrete type " + ik.getConcreteType()
+ " is " + ik);
System.err.println(" klass:" + klass);
}
system.newConstraint(pk, ik);
lastInstance = ik;
dim++;
}
}
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitThrow(com.ibm.wala.ssa.ThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
// don't do anything: we handle exceptional edges
// in a separate pass
}
/*
* @see com.ibm.wala.ssa.Instruction.Visitor#visitGetCaughtException(com.ibm.wala.ssa.GetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
List<ProgramCounter> peis = getIncomingPEIs(ir, getBasicBlock());
PointerKey def = getPointerKeyForLocal(instruction.getDef());
// SJF: we don't optimize based on dead catch blocks yet ... it's a little
// tricky due interaction with the SINGLE_USE optimization which directly
// shoves exceptional return values from calls into exception vars.
// it may not be worth doing this.
// if (hasNoInterestingUses(instruction.getDef(), du)) {
// solver.recordImplicitPointsToSet(def);
// } else {
Set<IClass> types = getCaughtExceptionTypes(instruction, ir);
getBuilder().addExceptionDefConstraints(ir, du, node, peis, def, types);
// }
}
/**
* TODO: What is this doing? Document me!
*/
private int booleanConstantTest(SSAConditionalBranchInstruction c, int v) {
int result = 0;
// right for OPR_eq
if ((symbolTable.isZeroOrFalse(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isZeroOrFalse(c.getUse(1)) && c.getUse(0) == v)) {
result = -1;
} else if ((symbolTable.isOneOrTrue(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isOneOrTrue(c.getUse(1)) && c.getUse(0) == v)) {
result = 1;
}
if (c.getOperator() == ConditionalBranchInstruction.Operator.NE) {
result = -result;
}
return result;
}
private int nullConstantTest(SSAConditionalBranchInstruction c, int v) {
if ((symbolTable.isNullConstant(c.getUse(0)) && c.getUse(1) == v)
|| (symbolTable.isNullConstant(c.getUse(1)) && c.getUse(0) == v)) {
if (c.getOperator() == ConditionalBranchInstruction.Operator.EQ) {
return 1;
} else {
return -1;
}
} else {
return 0;
}
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
if (ir.getMethod() instanceof AbstractRootMethod) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
if (hasNoInterestingUses(instruction.getDef())) {
system.recordImplicitPointsToSet(dst);
} else {
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
PointerKey use = getPointerKeyForLocal(instruction.getUse(i));
if (contentsAreInvariant(symbolTable, du, instruction.getUse(i))) {
system.recordImplicitPointsToSet(use);
InstanceKey[] ik = getInvariantContents(instruction.getUse(i));
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, use);
}
}
}
}
}
/*
* @see com.ibm.wala.ssa.SSAInstruction.Visitor#visitPi(com.ibm.wala.ssa.SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {
int dir;
if (hasNoInterestingUses(instruction.getDef())) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
system.recordImplicitPointsToSet(dst);
} else {
ControlFlowGraph<ISSABasicBlock> cfg = ir.getControlFlowGraph();
if (com.ibm.wala.cfg.Util.endsWithConditionalBranch(cfg, getBasicBlock()) && cfg.getSuccNodeCount(getBasicBlock()) == 2) {
SSAConditionalBranchInstruction cond = (SSAConditionalBranchInstruction) com.ibm.wala.cfg.Util.getLastInstruction(cfg,
getBasicBlock());
SSAInstruction cause = instruction.getCause();
BasicBlock target = (BasicBlock) cfg.getNode(instruction.getSuccessor());
if ((cause instanceof SSAInstanceofInstruction)) {
int direction = booleanConstantTest(cond, cause.getDef());
if (direction != 0) {
TypeReference type = ((SSAInstanceofInstruction) cause).getCheckedType();
IClass cls = getClassHierarchy().lookupClass(type);
if (cls == null) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
} else {
PointerKey dst = getFilteredPointerKeyForLocal(instruction.getDef(), new FilteredPointerKey.SingleClassFilter(cls));
PointerKey src = getPointerKeyForLocal(instruction.getVal());
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && direction == 1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && direction == -1)) {
system.newConstraint(dst, getBuilder().filterOperator, src);
} else {
system.newConstraint(dst, getBuilder().inverseFilterOperator, src);
}
}
}
} else if ((dir = nullConstantTest(cond, instruction.getVal())) != 0) {
if ((target == com.ibm.wala.cfg.Util.getTakenSuccessor(cfg, getBasicBlock()) && dir == -1)
|| (target == com.ibm.wala.cfg.Util.getNotTakenSuccessor(cfg, getBasicBlock()) && dir == 1)) {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
} else {
PointerKey dst = getPointerKeyForLocal(instruction.getDef());
addPiAssignment(dst, instruction.getVal());
}
}
}
/**
* Add a constraint to the system indicating that the contents of local src flows to dst, with no special type
* filter.
*/
private void addPiAssignment(PointerKey dst, int src) {
PointerKey srcKey = getPointerKeyForLocal(src);
if (contentsAreInvariant(symbolTable, du, src)) {
system.recordImplicitPointsToSet(srcKey);
InstanceKey[] ik = getInvariantContents(src);
for (int j = 0; j < ik.length; j++) {
system.newConstraint(dst, ik[j]);
}
} else {
system.newConstraint(dst, assignOperator, srcKey);
}
}
public ISSABasicBlock getBasicBlock() {
return basicBlock;
}
/**
* The calling loop must call this in each iteration!
*/
public void setBasicBlock(ISSABasicBlock block) {
basicBlock = block;
}
/**
* Side effect: records invariant parameters as implicit points-to-sets.
*
* @return if non-null, then result[i] holds the set of instance keys which may be passed as the ith parameter.
* (which must be invariant)
*/
protected InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] constParams = null;
for (int i = 0; i < call.getNumberOfUses(); i++) {
// not sure how getUse(i) <= 0 .. dead code?
// TODO: investigate
if (call.getUse(i) > 0) {
if (contentsAreInvariant(symbolTable, du, call.getUse(i))) {
system.recordImplicitPointsToSet(getPointerKeyForLocal(call.getUse(i)));
if (constParams == null) {
constParams = new InstanceKey[call.getNumberOfUses()][];
}
constParams[i] = getInvariantContents(call.getUse(i));
for (int j = 0; j < constParams[i].length; j++) {
system.findOrCreateIndexForInstanceKey(constParams[i][j]);
}
}
}
}
return constParams;
}
@Override
public void visitLoadClass(SSALoadClassInstruction instruction) {
PointerKey def = getPointerKeyForLocal(instruction.getDef());
InstanceKey iKey = getInstanceKeyForClassObject(instruction.getLoadedClass());
IClass klass = getClassHierarchy().lookupClass(instruction.getLoadedClass());
if (klass != null) {
processClassInitializer(klass);
}
if (!contentsAreInvariant(symbolTable, du, instruction.getDef())) {
system.newConstraint(def, iKey);
} else {
system.findOrCreateIndexForInstanceKey(iKey);
system.recordImplicitPointsToSet(def);
}
}
/**
* TODO: lift most of this logic to PropagationCallGraphBuilder
*
* Add a call to the class initializer from the root method.
*/
private void processClassInitializer(IClass klass) {
if (Assertions.verifyAssertions) {
Assertions._assert(klass != null);
}
if (getBuilder().clinitVisited.contains(klass)) {
return;
}
getBuilder().clinitVisited.add(klass);
if (klass.getClassInitializer() != null) {
if (DEBUG) {
System.err.println("process class initializer for " + klass);
}
// add an invocation from the fake root method to the <clinit>
FakeWorldClinitMethod fakeWorldClinitMethod = (FakeWorldClinitMethod) callGraph.getFakeWorldClinitNode().getMethod();
MethodReference m = klass.getClassInitializer().getReference();
CallSiteReference site = CallSiteReference.make(1, m, IInvokeInstruction.Dispatch.STATIC);
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(callGraph.getFakeRootNode(), site, null);
if (targetMethod != null) {
CGNode target = getTargetForCall(callGraph.getFakeRootNode(), site, (InstanceKey) null);
if (target != null && callGraph.getPredNodeCount(target) == 0) {
SSAAbstractInvokeInstruction s = fakeWorldClinitMethod.addInvocation(new int[0], site);
PointerKey uniqueCatch = getBuilder().getPointerKeyForExceptionalReturnValue(callGraph.getFakeRootNode());
getBuilder().processResolvedCall(callGraph.getFakeWorldClinitNode(), s, target, null, uniqueCatch);
}
}
}
try {
IClass sc = klass.getSuperclass();
if (sc != null) {
processClassInitializer(sc);
}
} catch (ClassHierarchyException e) {
Assertions.UNREACHABLE();
}
}
}
/**
* Add constraints for a call site after we have computed a reachable target for the dispatch
*
* Side effect: add edge to the call graph.
*
* @param instruction
* @param constParams if non-null, then constParams[i] holds the set of instance keys that are passed as param i, or
* null if param i is not invariant
* @param uniqueCatchKey if non-null, then this is the unique PointerKey that catches all exceptions from this call
* site.
*/
@SuppressWarnings("deprecation")
private void processResolvedCall(CGNode caller, SSAAbstractInvokeInstruction instruction, CGNode target,
InstanceKey[][] constParams, PointerKey uniqueCatchKey) {
if (DEBUG) {
System.err.println("processResolvedCall: " + caller + " ," + instruction + " , " + target);
}
if (DEBUG) {
System.err.println("addTarget: " + caller + " ," + instruction + " , " + target);
}
caller.addTarget(instruction.getCallSite(), target);
if (FakeRootMethod.isFakeRootMethod(caller.getMethod().getReference())) {
if (entrypointCallSites.contains(instruction.getCallSite())) {
callGraph.registerEntrypoint(target);
}
}
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
// TODO: i'd like to enable this optimization, but it's a little tricky
// to recover the implicit points-to sets with recursion. TODO: don't
// be lazy and code the recursive logic to enable this.
// if (hasNoInstructions(target)) {
// // record points-to sets for formals implicitly .. computed on
// // demand.
// // TODO: generalize this by using hasNoInterestingUses on parameters.
// // however .. have to be careful to cache results in that case ... don't
// // want
// // to recompute du each time we process a call to Object.<init> !
// for (int i = 0; i < instruction.getNumberOfUses(); i++) {
// // we rely on the invariant that the value number for the ith parameter
// // is i+1
// final int vn = i + 1;
// PointerKey formal = getPointerKeyForLocal(target, vn);
// if (target.getMethod().getParameterType(i).isReferenceType()) {
// system.recordImplicitPointsToSet(formal);
// }
// }
// } else {
// generate contraints from parameter passing
int nUses = instruction.getNumberOfParameters();
int nExpected = target.getMethod().getNumberOfParameters();
/*
* int nExpected = target.getMethod().getReference().getNumberOfParameters(); if (!target.getMethod().isStatic() &&
* !target.getMethod().isClinit()) { nExpected++; }
*/
if (nUses != nExpected) {
// some sort of unverifiable code mismatch. give up.
return;
}
boolean needsFilter = !instruction.getCallSite().isStatic() && needsFilterForReceiver(instruction, target);
// we're a little sloppy for now ... we don't filter calls to
// java.lang.Object.
// TODO: we need much more precise filters than cones in order to handle
// the various types of dispatch logic. We need a filter that expresses
// "the set of types s.t. x.foo resolves to y.foo."
for (int i = 0; i < instruction.getNumberOfParameters(); i++) {
// we rely on the invariant that the value number for the ith parameter
// is i+1
final int vn = i + 1;
if (target.getMethod().getParameterType(i).isReferenceType()) {
// if (constParams != null && constParams[i] != null &&
// !supportFullPointerFlowGraph) {
if (constParams != null && constParams[i] != null) {
InstanceKey[] ik = constParams[i];
for (int j = 0; j < ik.length; j++) {
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
PointerKey formal = null;
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
formal = getPointerKeyForLocal(target, vn);
} else {
formal = getFilteredPointerKeyForLocal(target, vn, C);
}
system.newConstraint(formal, ik[j]);
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, ik[j]);
}
}
} else {
if (Assertions.verifyAssertions) {
if (instruction.getUse(i) < 0) {
Assertions.UNREACHABLE("unexpected " + instruction + " in " + caller);
}
}
PointerKey actual = getPointerKeyForLocal(caller, instruction.getUse(i));
if (needsFilter && (i == 0)) {
FilteredPointerKey.TypeFilter C = getFilter(target);
if (isRootType(C)) {
// TODO: we need much better filtering here ... see comments
// above.
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
} else {
FilteredPointerKey formal = getFilteredPointerKeyForLocal(target, vn, C);
system.newConstraint(formal, filterOperator, actual);
}
} else {
PointerKey formal = getPointerKeyForLocal(target, vn);
system.newConstraint(formal, assignOperator, actual);
}
}
}
}
// generate contraints from return value.
if (instruction.hasDef() && instruction.getDeclaredResultType().isReferenceType()) {
PointerKey result = getPointerKeyForLocal(caller, instruction.getDef());
PointerKey ret = getPointerKeyForReturnValue(target);
system.newConstraint(result, assignOperator, ret);
}
// generate constraints from exception return value.
PointerKey e = getPointerKeyForLocal(caller, instruction.getException());
PointerKey er = getPointerKeyForExceptionalReturnValue(target);
if (SHORT_CIRCUIT_SINGLE_USES && uniqueCatchKey != null) {
// e has exactly one use. so, represent e implicitly
system.newConstraint(uniqueCatchKey, assignOperator, er);
} else {
system.newConstraint(e, assignOperator, er);
}
// }
}
/**
* An operator to fire when we discover a potential new callee for a virtual or interface call site.
*
* This operator will create a new callee context and constraints if necessary.
*
* N.B: This implementation assumes that the calling context depends solely on the dataflow information computed for
* the receiver. TODO: generalize this to have other forms of context selection, such as CPA-style algorithms.
*/
final class DispatchOperator extends UnaryOperator<PointsToSetVariable> implements IPointerOperator {
private final SSAAbstractInvokeInstruction call;
private final ExplicitCallGraph.ExplicitNode node;
private final InstanceKey[][] constParams;
private final PointerKey uniqueCatch;
/**
* @param call
* @param node
* @param constParams if non-null, then constParams[i] holds the String constant that is passed as param i, or null
* if param i is not a String constant
*/
DispatchOperator(SSAAbstractInvokeInstruction call, ExplicitCallGraph.ExplicitNode node, InstanceKey[][] constParams,
PointerKey uniqueCatch) {
this.call = call;
this.node = node;
this.constParams = constParams;
this.uniqueCatch = uniqueCatch;
}
/**
* The set of pointers that have already been processed.
*/
final private MutableIntSet previousReceivers = IntSetUtil.getDefaultIntSetFactory().make();
/*
* @see com.ibm.wala.dataflow.fixpoint.UnaryOperator#evaluate(com.ibm.wala.dataflow.fixpoint.IVariable,
* com.ibm.wala.dataflow.fixpoint.IVariable)
*/
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable receivers = rhs;
final MutableBoolean sideEffect = new MutableBoolean();
// compute the set of pointers that were not previously handled
IntSet value = receivers.getValue();
if (value == null) {
// this constraint was put on the work list, probably by
// initialization,
// even though the right-hand-side is empty.
// TODO: be more careful about what goes on the worklist to
// avoid this.
if (DEBUG) {
System.err.println("EVAL dispatch with value null");
}
return NOT_CHANGED;
}
if (DEBUG) {
System.err.println("EVAL dispatch to " + node + ":" + call);
System.err.println("receivers: " + value);
}
IntSetAction action = new IntSetAction() {
public void act(int ptr) {
if (DEBUG) {
System.err.println(" dispatch to ptr " + ptr);
}
InstanceKey iKey = system.getInstanceKey(ptr);
CGNode target;
if (clone2Assign) {
// for efficiency: assume that only call sites that reference
// clone() might dispatch to clone methods
if (call.getCallSite().getDeclaredTarget().getSelector().equals(cloneSelector)) {
IClass recv = (iKey != null) ? iKey.getConcreteType() : null;
IMethod targetMethod = getOptions().getMethodTargetSelector().getCalleeTarget(node, call.getCallSite(), recv);
if (targetMethod != null && targetMethod.getReference().equals(CloneInterpreter.CLONE)) {
// treat this call to clone as an assignment
PointerKey result = getPointerKeyForLocal(node, call.getDef());
PointerKey receiver = getPointerKeyForLocal(node, call.getReceiver());
system.newConstraint(result, assignOperator, receiver);
return;
}
}
}
target = getTargetForCall(node, call.getCallSite(), iKey);
if (target == null) {
// This indicates an error; I sure hope getTargetForCall
// raised a warning about this!
if (DEBUG) {
System.err.println("Warning: null target for call " + call + " " + iKey);
}
} else {
IntSet targets = getCallGraph().getPossibleTargetNumbers(node, call.getCallSite());
if (targets != null && targets.contains(target.getGraphNodeId())) {
// do nothing; we've previously discovered and handled this
// receiver for this call site.
} else {
// process the newly discovered target for this call
sideEffect.b = true;
processResolvedCall(node, call, target, constParams, uniqueCatch);
if (!haveAlreadyVisited(target)) {
markDiscovered(target);
}
}
}
}
};
try {
value.foreachExcluding(previousReceivers, action);
} catch (Error e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
} catch (RuntimeException e) {
System.err.println("error in " + call + " on " + receivers + " of types " + value + " for " + node);
throw e;
}
// update the set of receivers previously considered
previousReceivers.copySet(value);
byte sideEffectMask = sideEffect.b ? (byte) SIDE_EFFECT_MASK : 0;
return (byte) (NOT_CHANGED | sideEffectMask);
}
@Override
public String toString() {
return "Dispatch to " + call + " in node " + node;
}
@Override
public int hashCode() {
return node.hashCode() + 90289 * call.hashCode();
}
@Override
public boolean equals(Object o) {
// note that these are not necessarily canonical, since
// with synthetic factories we may regenerate constraints
// many times. TODO: change processing of synthetic factories
// so that we guarantee to insert each dispatch equation
// only once ... if this were true we could optimize this
// with reference equality
// instanceof is OK because this class is final
if (o instanceof DispatchOperator) {
DispatchOperator other = (DispatchOperator) o;
return node.equals(other.node) && call.equals(other.call);
} else {
return false;
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.IPointerOperator#isComplex()
*/
public boolean isComplex() {
return true;
}
}
public boolean hasNoInterestingUses(CGNode node, int vn, DefUse du) {
if (du == null) {
throw new IllegalArgumentException("du is null");
}
if (vn <= 0) {
throw new IllegalArgumentException("v is invalid: " + vn);
}
// todo: enhance this by solving a dead-code elimination
// problem.
InterestingVisitor v = makeInterestingVisitor(node, vn);
for (Iterator it = du.getUses(v.vn); it.hasNext();) {
SSAInstruction s = (SSAInstruction) it.next();
s.visit(v);
if (v.bingo) {
return false;
}
}
return true;
}
protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) {
return new InterestingVisitor(vn);
}
/**
* sets bingo to true when it visits an interesting instruction
*/
protected static class InterestingVisitor extends SSAInstruction.Visitor {
protected final int vn;
protected InterestingVisitor(int vn) {
this.vn = vn;
}
protected boolean bingo = false;
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
if (!instruction.typeIsPrimitive() && instruction.getArrayRef() == vn) {
bingo = true;
}
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
if (!instruction.typeIsPrimitive() && (instruction.getArrayRef() == vn || instruction.getValue() == vn)) {
bingo = true;
}
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
bingo = true;
}
@Override
public void visitGet(SSAGetInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
bingo = true;
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
bingo = true;
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
bingo = true;
}
@Override
public void visitPi(SSAPiInstruction instruction) {
bingo = true;
}
@Override
public void visitPut(SSAPutInstruction instruction) {
FieldReference field = instruction.getDeclaredField();
if (!field.getFieldType().isPrimitiveType()) {
bingo = true;
}
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
bingo = true;
}
@Override
public void visitThrow(SSAThrowInstruction instruction) {
bingo = true;
}
}
/**
* TODO: enhance this logic using type inference
*
* @param instruction
* @return true if we need to filter the receiver type to account for virtual dispatch
*/
private boolean needsFilterForReceiver(SSAAbstractInvokeInstruction instruction, CGNode target) {
FilteredPointerKey.TypeFilter f = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (f != null) {
// the context selects a particular concrete type for the receiver.
// we need to filter, unless the declared receiver type implies the
// concrete type (TODO: need to implement this optimization)
return true;
}
// don't need to filter for invokestatic
if (instruction.getCallSite().isStatic() || instruction.getCallSite().isSpecial()) {
return false;
}
MethodReference declaredTarget = instruction.getDeclaredTarget();
IMethod resolvedTarget = getClassHierarchy().resolveMethod(declaredTarget);
if (resolvedTarget == null) {
// there's some problem that will be flagged as a warning
return true;
}
return true;
}
private boolean isRootType(IClass klass) {
return klass.getClassHierarchy().isRootClass(klass);
}
private boolean isRootType(FilteredPointerKey.TypeFilter filter) {
if (filter instanceof FilteredPointerKey.SingleClassFilter) {
return isRootType(((FilteredPointerKey.SingleClassFilter) filter).getConcreteType());
} else {
return false;
}
}
/**
* TODO: enhance this logic using type inference TODO!!!: enhance filtering to consider concrete types, not just
* cones. precondition: needs Filter
*
* @param target
* @return an IClass which represents
*/
private FilteredPointerKey.TypeFilter getFilter(CGNode target) {
FilteredPointerKey.TypeFilter filter = (FilteredPointerKey.TypeFilter) target.getContext().get(ContextKey.FILTER);
if (filter != null) {
return filter;
} else {
// the context does not select a particular concrete type for the
// receiver.
IClass C = getReceiverClass(target.getMethod());
return new FilteredPointerKey.SingleClassFilter(C);
}
}
/**
* @param method
* @return the receiver class for this method.
*/
private IClass getReceiverClass(IMethod method) {
TypeReference formalType = method.getParameterType(0);
IClass C = getClassHierarchy().lookupClass(formalType);
if (Assertions.verifyAssertions) {
if (method.isStatic()) {
Assertions.UNREACHABLE("asked for receiver of static method " + method);
}
if (C == null) {
Assertions.UNREACHABLE("no class found for " + formalType + " recv of " + method);
}
}
return C;
}
/**
* A value is "invariant" if we can figure out the instances it can ever point to locally, without resorting to
* propagation.
*
* @param valueNumber
* @return true iff the contents of the local with this value number can be deduced locally, without propagation
*/
protected boolean contentsAreInvariant(SymbolTable symbolTable, DefUse du, int valueNumber) {
if (isConstantRef(symbolTable, valueNumber)) {
return true;
} else if (SHORT_CIRCUIT_INVARIANT_SETS) {
SSAInstruction def = du.getDef(valueNumber);
if (def instanceof SSANewInstruction) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* precondition:contentsAreInvariant(valueNumber)
*
* @param valueNumber
* @return the complete set of instances that the local with vn=valueNumber may point to.
*/
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm) {
return getInvariantContents(symbolTable, du, node, valueNumber, hm, false);
}
protected InstanceKey[] getInvariantContents(SymbolTable symbolTable, DefUse du, CGNode node, int valueNumber, HeapModel hm,
boolean ensureIndexes) {
InstanceKey[] result;
if (isConstantRef(symbolTable, valueNumber)) {
Object x = symbolTable.getConstantValue(valueNumber);
if (x instanceof String) {
// this is always the case in Java. use strong typing in the call to getInstanceKeyForConstant.
String S = (String) x;
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(S);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, S);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
} else {
// some non-built in type (e.g. Integer). give up on strong typing.
// language-specific subclasses (e.g. Javascript) should override this method to get strong typing
// with generics if desired.
TypeReference type = node.getMethod().getDeclaringClass().getClassLoader().getLanguage().getConstantType(x);
if (type == null) {
return new InstanceKey[0];
}
InstanceKey ik = hm.getInstanceKeyForConstant(type, x);
if (ik != null) {
result = new InstanceKey[] { ik };
} else {
result = new InstanceKey[0];
}
}
} else {
SSANewInstruction def = (SSANewInstruction) du.getDef(valueNumber);
InstanceKey iKey = hm.getInstanceKeyForAllocation(node, def.getNewSite());
result = (iKey == null) ? new InstanceKey[0] : new InstanceKey[] { iKey };
}
if (ensureIndexes) {
for (int i = 0; i < result.length; i++) {
system.findOrCreateIndexForInstanceKey(result[i]);
}
}
return result;
}
protected boolean isConstantRef(SymbolTable symbolTable, int valueNumber) {
if (valueNumber == -1) {
return false;
}
if (symbolTable.isConstant(valueNumber)) {
Object v = symbolTable.getConstantValue(valueNumber);
return (!(v instanceof Number));
} else {
return false;
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a checkcast
*/
private static class CheckcastFailure extends Warning {
final TypeReference type;
CheckcastFailure(TypeReference type) {
super(Warning.SEVERE);
this.type = type;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + type;
}
public static CheckcastFailure create(TypeReference type) {
return new CheckcastFailure(type);
}
}
/**
* @author sfink
*
* A warning for when we fail to resolve the type for a field
*/
private static class FieldResolutionFailure extends Warning {
final FieldReference field;
FieldResolutionFailure(FieldReference field) {
super(Warning.SEVERE);
this.field = field;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + field;
}
public static FieldResolutionFailure create(FieldReference field) {
return new FieldResolutionFailure(field);
}
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.HeapModel#iteratePointerKeys()
*/
public Iterator<PointerKey> iteratePointerKeys() {
return system.iteratePointerKeys();
}
public static Set<IClass> getCaughtExceptionTypes(SSAGetCaughtExceptionInstruction instruction, IR ir) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
if (instruction == null) {
throw new IllegalArgumentException("instruction is null");
}
Iterator<TypeReference> exceptionTypes = ((ExceptionHandlerBasicBlock) ir.getControlFlowGraph().getNode(
instruction.getBasicBlockNumber())).getCaughtExceptionTypes();
HashSet<IClass> types = HashSetFactory.make(10);
for (; exceptionTypes.hasNext();) {
IClass c = ir.getMethod().getClassHierarchy().lookupClass(exceptionTypes.next());
if (c != null) {
types.add(c);
}
}
return types;
}
public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) {
return getInstanceKeyForPEI(node, instr, type, instanceKeyFactory);
}
/*
* @see com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder#makeSolver()
*/
@Override
protected IPointsToSolver makeSolver() {
return usePreTransitiveSolver ? (IPointsToSolver) new PreTransitiveSolver(system, this) : new StandardSolver(system, this);
// return true ? (IPointsToSolver)new PreTransitiveSolver(system,this) : new
// StandardSolver(system,this);
}
}
|
diff --git a/src/com/designs_1393/asana/DatabaseAdapter.java b/src/com/designs_1393/asana/DatabaseAdapter.java
index 5bacb87..d9f45fa 100644
--- a/src/com/designs_1393/asana/DatabaseAdapter.java
+++ b/src/com/designs_1393/asana/DatabaseAdapter.java
@@ -1,268 +1,269 @@
package com.designs_1393.asana;
import com.designs_1393.asana.workspace.*;
import com.designs_1393.asana.project.*;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import java.lang.Long;
import android.util.Log;
// SQL stuff
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseAdapter
{
/* Database Attribute Declarations */
public static final String WORKSPACES_TABLE_NAME = "workspaces";
public static final String WORKSPACES_COL_ID = "_id";
public static final String WORKSPACES_COL_ASANA_ID = "workspace_id";
public static final String WORKSPACES_COL_NAME = "workspace_name";
public static final String PROJECTS_TABLE_NAME = "projects";
public static final String PROJECTS_COL_ID = "_id";
public static final String PROJECTS_COL_ASANA_ID = "project_id";
public static final String PROJECTS_COL_ARCHIVED = "archived";
public static final String PROJECTS_COL_CREATED_AT = "created_at";
public static final String PROJECTS_COL_FOLLOWERS = "followers";
public static final String PROJECTS_COL_MODIFIED_AT = "modified_at";
public static final String PROJECTS_COL_NAME = "project_name";
public static final String PROJECTS_COL_NOTES = "project_notes";
public static final String PROJECTS_COL_WORKSPACE = "workspace_id";
public static final String DATABASE_NAME = "asana_data";
public static final int DATABASE_VERSION = 1;
/* Table CREATE Commands */
private static final String WORKSPACES_TABLE_CREATE =
"CREATE TABLE " +WORKSPACES_TABLE_NAME +" ("
+WORKSPACES_COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "
+WORKSPACES_COL_ASANA_ID +" INTEGER NOT NULL, "
+WORKSPACES_COL_NAME +" TEXT NOT NULL);";
private static final String PROJECTS_TABLE_CREATE =
"CREATE TABLE " +PROJECTS_TABLE_NAME +" ("
+PROJECTS_COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "
+PROJECTS_COL_ASANA_ID +" INTEGER NOT NULL, "
+PROJECTS_COL_ARCHIVED +" INTEGER NOT NULL, "
+PROJECTS_COL_CREATED_AT +" TEXT NOT NULL, "
+PROJECTS_COL_FOLLOWERS +" TEXT NOT NULL, "
+PROJECTS_COL_MODIFIED_AT +" TEXT NOT NULL, "
+PROJECTS_COL_NAME +" TEXT NOT NULL, "
+PROJECTS_COL_NOTES +" TEXT NOT NULL, "
+PROJECTS_COL_WORKSPACE +" INTEGER NOT NULL);";
/* Class Member Objects */
private static final String TAG = "Asana: DatabaseAdapter";
private DatabaseHelper DBhelper;
private SQLiteDatabase DB;
private final Context context;
/** Class constructor.
* Retains calling application's context, so that it can be used in
* additional functions.
* @param callingApplicationsContext Calling application's context
*/
public DatabaseAdapter( Context callingApplicationsContext )
{
this.context = callingApplicationsContext;
}
/* Inner class providing a databse upgrade process. */
private static class DatabaseHelper extends SQLiteOpenHelper
{
/** Class constructor.
* Retains calling application's context, so that it can be used in
* additional functions.
* @param context Calling application's context
*/
DatabaseHelper( Context context )
{
super( context, DATABASE_NAME, null, DATABASE_VERSION );
}
@Override
public void onCreate( SQLiteDatabase db )
{
db.execSQL( WORKSPACES_TABLE_CREATE );
db.execSQL( PROJECTS_TABLE_CREATE );
}
@Override
public void onUpgrade( SQLiteDatabase db,
int oldVersion,
int newVersion )
{
// nothing required here yet
}
}
/**
* Opens the database helper for writing and returns the database adapter.
* @return Database adapter associated with the database.
*/
public DatabaseAdapter open() throws SQLException
{
DBhelper = new DatabaseHelper( this.context );
DB = DBhelper.getWritableDatabase();
return this;
}
/** Closes the database helper
*/
public void close()
{
DBhelper.close();
}
/** Returns a cursor containing every element of the "workspaces" table,
* sorted either alphabetically or in the order they're in on the website.
* @param sortAlphabetically Whether to return the workspaces in
* alphabetical order or in the order they
* appear on asana.com
*
* @return Cursor containing the row ID, short name,
* and Asana workspace ID for each workspace in
* the table.
*/
public Cursor getWorkspaces( boolean sortAlphabetically )
{
String sorter = WORKSPACES_COL_ASANA_ID;
if( sortAlphabetically )
sorter = WORKSPACES_COL_NAME;
return DB.query( WORKSPACES_TABLE_NAME,
new String[] {WORKSPACES_COL_ID,
WORKSPACES_COL_ASANA_ID,
WORKSPACES_COL_NAME},
null, null, null, null, sorter );
}
/** Sets the "workspaces" table to the data in the WorkspaceSet.
* This should be used primarily to inject the WorkspaceSet parsed from
* {@link AsanaAPI.getWorkspaces()}. Note that this method deletes the
* entire contents of the "workspaces" table first, and then replaces them
* with the data in "workspaces".
* @param workspaces WorkspaceSet parsed from Asana's list of workspaces.
* @return true if the operation was successful, flase otherwise.
*/
public boolean setWorkspaces( WorkspaceSet workspaces )
{
// TODO: Handle rollback if "insert" fails? Maybe this is possible
// with some a conflict clause?
// delete contents
DB.delete( WORKSPACES_TABLE_NAME, null, null );
ContentValues values;
// Get array of workspaces from WorkspaceSet
Workspace[] workspaceArray = workspaces.getData();
long insertResult = 0;
for( int i = 0; i < workspaceArray.length; i++ )
{
values = new ContentValues();
values.put( WORKSPACES_COL_ASANA_ID, workspaceArray[i].getID() );
values.put( WORKSPACES_COL_NAME, workspaceArray[i].getName() );
insertResult = DB.insert( WORKSPACES_TABLE_NAME, null, values );
if( insertResult == -1 )
return false;
}
return true;
}
/**
* Returns a cursor containing all elements of the "projects" table, from a
* specific workspace, sorted either alphabetically or in the order they're
* list in on the website.
* @param archived Whether to return archived projects or not.
* @param sortAlphabetically Whether to return the projects in
* alphabetical order or not.
* @return Cursor containing the row ID, and name for
* all projects in the workspace that qualify.
*/
public Cursor getProjects( long workspaceID, boolean sortAlphabetically )
{
String sorter = PROJECTS_COL_ID;
if( sortAlphabetically )
sorter = PROJECTS_COL_NAME;
String[] cols = new String[]
{ PROJECTS_COL_ASANA_ID,
PROJECTS_COL_ID,
PROJECTS_COL_NAME,
PROJECTS_COL_WORKSPACE };
String selection = PROJECTS_COL_WORKSPACE +" = " +workspaceID;
Log.i( TAG, "id = " +workspaceID );
Log.i( TAG, "id as string = " +String.valueOf(workspaceID) );
return DB.query( PROJECTS_TABLE_NAME,
cols, selection, null, null, null, sorter );
}
/**
* Sets the "projects" table to the data in the ProjectSet.
* This should be used primarily to inject the ProjectSet parsed from
* {@link AsanaAPI.getProjects( long workspaceID )}. Note that this method
* deletes the entire contents of the "projects" table first, and then
* replaces them with the data in "projects".
* @param projects ProjectSet parsed from Asana's list of projects for a
* specific workspace.
* @return true if the operation was successful, false otherwise.
*/
public boolean setProjects( ProjectSet projects )
{
// TODO: Handle rollback if "insert" fails? Maybe this is possible
// with some a conflict clause?
// delete contents
DB.delete( PROJECTS_TABLE_NAME, null, null );
ContentValues values;
// Get array of projects from ProjectSet
Project[] projectArray = projects.getData();
long insertResult = 0;
for( Project p : projectArray )
{
//User[] followers = p.getFollowers.getData();
//String userIDs = "";
//for( User u : followers )
// userIDs += u.getID();
// build transaction values
values = new ContentValues();
values.put( PROJECTS_COL_ASANA_ID, p.getID() );
values.put( PROJECTS_COL_ARCHIVED, p.isArchived() ? 1 : 0 );
values.put( PROJECTS_COL_CREATED_AT, p.getCreatedAt() );
//values.put( PROJECTS_COL_FOLLOWERS, userIDs );
+ values.put( PROJECTS_COL_FOLLOWERS, "none" );
values.put( PROJECTS_COL_MODIFIED_AT, p.getModifiedAt() );
values.put( PROJECTS_COL_NAME, p.getName() );
values.put( PROJECTS_COL_NOTES, p.getNotes() );
values.put( PROJECTS_COL_WORKSPACE, p.getWorkspace().getID() );
insertResult = DB.insert( PROJECTS_TABLE_NAME, null, values );
if( insertResult == -1 )
return false;
}
return true;
}
}
| true | true | public boolean setProjects( ProjectSet projects )
{
// TODO: Handle rollback if "insert" fails? Maybe this is possible
// with some a conflict clause?
// delete contents
DB.delete( PROJECTS_TABLE_NAME, null, null );
ContentValues values;
// Get array of projects from ProjectSet
Project[] projectArray = projects.getData();
long insertResult = 0;
for( Project p : projectArray )
{
//User[] followers = p.getFollowers.getData();
//String userIDs = "";
//for( User u : followers )
// userIDs += u.getID();
// build transaction values
values = new ContentValues();
values.put( PROJECTS_COL_ASANA_ID, p.getID() );
values.put( PROJECTS_COL_ARCHIVED, p.isArchived() ? 1 : 0 );
values.put( PROJECTS_COL_CREATED_AT, p.getCreatedAt() );
//values.put( PROJECTS_COL_FOLLOWERS, userIDs );
values.put( PROJECTS_COL_MODIFIED_AT, p.getModifiedAt() );
values.put( PROJECTS_COL_NAME, p.getName() );
values.put( PROJECTS_COL_NOTES, p.getNotes() );
values.put( PROJECTS_COL_WORKSPACE, p.getWorkspace().getID() );
insertResult = DB.insert( PROJECTS_TABLE_NAME, null, values );
if( insertResult == -1 )
return false;
}
return true;
}
| public boolean setProjects( ProjectSet projects )
{
// TODO: Handle rollback if "insert" fails? Maybe this is possible
// with some a conflict clause?
// delete contents
DB.delete( PROJECTS_TABLE_NAME, null, null );
ContentValues values;
// Get array of projects from ProjectSet
Project[] projectArray = projects.getData();
long insertResult = 0;
for( Project p : projectArray )
{
//User[] followers = p.getFollowers.getData();
//String userIDs = "";
//for( User u : followers )
// userIDs += u.getID();
// build transaction values
values = new ContentValues();
values.put( PROJECTS_COL_ASANA_ID, p.getID() );
values.put( PROJECTS_COL_ARCHIVED, p.isArchived() ? 1 : 0 );
values.put( PROJECTS_COL_CREATED_AT, p.getCreatedAt() );
//values.put( PROJECTS_COL_FOLLOWERS, userIDs );
values.put( PROJECTS_COL_FOLLOWERS, "none" );
values.put( PROJECTS_COL_MODIFIED_AT, p.getModifiedAt() );
values.put( PROJECTS_COL_NAME, p.getName() );
values.put( PROJECTS_COL_NOTES, p.getNotes() );
values.put( PROJECTS_COL_WORKSPACE, p.getWorkspace().getID() );
insertResult = DB.insert( PROJECTS_TABLE_NAME, null, values );
if( insertResult == -1 )
return false;
}
return true;
}
|
diff --git a/src/chalmers/dax021308/ecosystem/model/agent/PigAgent.java b/src/chalmers/dax021308/ecosystem/model/agent/PigAgent.java
index ef753a2..ed778e0 100644
--- a/src/chalmers/dax021308/ecosystem/model/agent/PigAgent.java
+++ b/src/chalmers/dax021308/ecosystem/model/agent/PigAgent.java
@@ -1,350 +1,343 @@
package chalmers.dax021308.ecosystem.model.agent;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import chalmers.dax021308.ecosystem.model.environment.obstacle.IObstacle;
import chalmers.dax021308.ecosystem.model.population.IPopulation;
import chalmers.dax021308.ecosystem.model.util.IShape;
import chalmers.dax021308.ecosystem.model.util.Log;
import chalmers.dax021308.ecosystem.model.util.Position;
import chalmers.dax021308.ecosystem.model.util.Vector;
/**
* Pig Agent.
*
* @author Group 8, path finding edits by Erik Ramqvist
*/
public class PigAgent extends AbstractAgent {
private static final int MAX_ENERGY = 1000;
private static final int MAX_LIFE_LENGTH = Integer.MAX_VALUE;
private boolean hungry = true;
private static final double REPRODUCTION_RATE = 0.1;
private boolean willFocusPreys = false;
private static final int DIGESTION_TIME = 10;
private int digesting = 0;
private double STOTTING_RANGE = 20;
private double STOTTING_LENGTH = 30;
private double STOTTING_COOLDOWN = 150;
private double stottingDuration = STOTTING_LENGTH;
private double stottingCoolDown = 0;
private boolean isAStottingDeer = true;
private boolean isStotting = false;
private Vector stottingVector = new Vector();
private boolean alone;
public PigAgent(String name, Position p, Color c, int width, int height,
Vector velocity, double maxSpeed, double maxAcceleration,
double visionRange, boolean groupBehaviour) {
super(name, p, c, width, height, velocity, maxSpeed, visionRange,
maxAcceleration);
this.energy = MAX_ENERGY;
this.groupBehaviour = groupBehaviour;
}
@Override
public List<IAgent> reproduce(IAgent agent, int populationSize,
List<IObstacle> obstacles, IShape shape, Dimension gridDimension) {
if (hungry)
return null;
else {
hungry = true;
List<IAgent> spawn = new ArrayList<IAgent>();
if (Math.random() < REPRODUCTION_RATE) {
Position pos;
do {
double xSign = Math.signum(-1 + 2 * Math.random());
double ySign = Math.signum(-1 + 2 * Math.random());
double newX = this.getPosition().getX() + xSign
* (0.001 + 0.001 * Math.random());
double newY = this.getPosition().getY() + ySign
* (0.001 + 0.001 * Math.random());
pos = new Position(newX, newY);
} while (!shape.isInside(gridDimension, pos));
IAgent child = new PigAgent(name, pos, color, width, height,
new Vector(velocity), maxSpeed, maxAcceleration,
visionRange, groupBehaviour);
spawn.add(child);
}
return spawn;
}
}
/**
* Calculates the next position of the agent depending on the forces that
* affects it. Note: The next position is not set until updatePosition() is
* called.
*
* @author Sebbe
*/
@Override
public void calculateNextPosition(List<IPopulation> predators,
List<IPopulation> preys, List<IPopulation> neutral,
Dimension gridDimension, IShape shape, List<IObstacle> obstacles) {
updateNeighbourList(neutral, preys, predators);
Vector predatorForce = getPredatorForce();
if (digesting > 0 && alone) {
digesting--;
} else {
Vector mutualInteractionForce = new Vector();
Vector forwardThrust = new Vector();
Vector arrayalForce = new Vector();
if (groupBehaviour) {
mutualInteractionForce = mutualInteractionForce(
neutralNeighbours, position);
forwardThrust = forwardThrust(velocity);
arrayalForce = arrayalForce(velocity, neutralNeighbours, position);
}
Vector environmentForce = getEnvironmentForce(gridDimension, shape,
position);
Vector obstacleForce = getObstacleForce(obstacles, position);
/*
* Sum the forces from walls, predators and neutral to form the
* acceleration force. If the acceleration exceeds maximum
* acceleration --> scale it to maxAcceleration, but keep the
* correct direction of the acceleration.
*/
Vector acceleration;
if (isAStottingDeer && isStotting) {
acceleration = predatorForce;
} else {
acceleration = predatorForce.multiply(5)
.add(mutualInteractionForce).add(forwardThrust)
.add(arrayalForce);
// if (alone) {
Vector preyForce = getPreyForce(shape, gridDimension);
acceleration.add(preyForce.multiply(5 * (1 - energy
/ MAX_ENERGY)));
}
// }
double accelerationNorm = acceleration.getNorm();
if (accelerationNorm > maxAcceleration) {
acceleration.multiply(maxAcceleration / accelerationNorm);
}
acceleration.add(environmentForce).add(obstacleForce);
/*
* The new velocity is then just: v(t+dt) = (v(t)+a(t+1)*dt)*decay,
* where dt = 1 in this case. There is a decay that says if they are
* not affected by any force, they will eventually stop. If speed
* exceeds maxSpeed --> scale it to maxSpeed, but keep the correct
* direction.
*/
Vector newVelocity = Vector.addVectors(this.getVelocity(),
acceleration);
newVelocity.multiply(VELOCITY_DECAY);
double speed = newVelocity.getNorm();
if (speed > maxSpeed) {
newVelocity.multiply(maxSpeed / speed);
}
// if (alone) {
// newVelocity.multiply(0.9);
// }
this.setVelocity(newVelocity);
/* Reusing the same position object, for less heap allocations. */
// if (reUsedPosition == null) {
nextPosition = Position.positionPlusVector(position, velocity);
// } else {
// nextPosition.setPosition(reUsedPosition.setPosition(position.getX()
// + velocity.x, position.getY() + velocity.y));
// }
}
}
/**
* @return returns The force the preys attracts the agent with
* @author Sebastian/Henrik
*/
private Vector getPreyForce(IShape shape, Dimension dim) {
if (willFocusPreys && focusedPrey != null && focusedPrey.isAlive()) {
Position p = focusedPrey.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= EATING_RANGE) {
if (focusedPrey.tryConsumeAgent()) {
focusedPrey = null;
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else {
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
//Focused prey cant be reached. Change target.
focusedPrey = null;
} else {
return new Vector(pathToTarget.get(0), position);
}
}
}
Vector preyForce = new Vector(0, 0);
IAgent closestFocusPrey = null;
int preySize = preyNeighbours.size();
for (int i = 0; i < preySize; i++) {
IAgent a = preyNeighbours.get(i);
Position p = a.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= visionRange) {
if (distance <= EATING_RANGE) {
if (a.tryConsumeAgent()) {
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else if (willFocusPreys && distance <= FOCUS_RANGE) {
if (closestFocusPrey != null && a.isAlive()) {
if (closestFocusPrey.getPosition().getDistance(
this.position) > a.getPosition().getDistance(
this.position)) {
closestFocusPrey = a;
}
} else {
closestFocusPrey = a;
}
} else if (closestFocusPrey == null) {
/*
* Create a vector that points towards the prey.
*/
- Vector newForce = null;
- List<Position> pathToTarget = Position.getShortestPath(position, p, obstacles, shape, dim);
- if(pathToTarget == null || pathToTarget.size() == 0) {
- //Focused prey cant be reached. Change target.
- newForce = Vector.emptyVector();
- } else {
- newForce = new Vector(pathToTarget.get(0), position);
- }
+ Vector newForce = new Vector(p, position);
/*
* Add this vector to the prey force, with proportion to how
* close the prey is. Closer preys will affect the force
* more than those far away.
*/
double norm = newForce.getNorm();
preyForce.add(newForce.multiply(1 / (norm * distance)));
}
}
}
double norm = preyForce.getNorm();
if (norm != 0) {
preyForce.multiply(maxAcceleration / norm);
}
if (willFocusPreys && closestFocusPrey != null) {
focusedPrey = closestFocusPrey;
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
return Vector.emptyVector();
} else {
return new Vector(pathToTarget.get(0), position);
}
}
return preyForce;
}
/**
* "Predator Force" is defined as the sum of the vectors pointing away from
* all the predators in vision, weighted by the inverse of the distance to
* the predators, then normalized to have unit norm. Can be interpreted as
* the average sum of forces that the agent feels, weighted by how close the
* source of the force is.
*
* @author Sebbe
*/
private Vector getPredatorForce() {
Vector predatorForce = new Vector(0, 0);
if (isAStottingDeer && isStotting) {
stottingDuration--;
if (stottingDuration <= 0) {
isStotting = false;
}
return stottingVector;
} else {
boolean predatorClose = false;
int predSize = predNeighbours.size();
IAgent predator;
for (int i = 0; i < predSize; i++) {
predator = predNeighbours.get(i);
Position p = predator.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= visionRange) { // If predator is in vision range
// for prey
/*
* Create a vector that points away from the predator.
*/
Vector newForce = new Vector(this.getPosition(), p);
if (isAStottingDeer && distance <= STOTTING_RANGE) {
predatorClose = true;
}
/*
* Add this vector to the predator force, with proportion to
* how close the predator is. Closer predators will affect
* the force more than those far away.
*/
double norm = newForce.getNorm();
predatorForce.add(newForce.multiply(1 / (norm * distance)));
}
}
double norm = predatorForce.getNorm();
if (norm <= 0) { // No predators near --> Be unaffected
alone = true;
} else { // Else set the force depending on visible predators and
// normalize it to maxAcceleration.
predatorForce.multiply(maxAcceleration / norm);
alone = false;
}
if (isAStottingDeer && stottingCoolDown <= 0 && predatorClose) {
isStotting = true;
stottingCoolDown = STOTTING_COOLDOWN;
stottingDuration = STOTTING_LENGTH;
double newX = 0;
double newY = 0;
if (Math.random() < 0.5) {
newX = 1;
newY = -predatorForce.getX() / predatorForce.getY();
} else {
newY = 1;
newX = -predatorForce.getY() / predatorForce.getX();
}
stottingVector.setVector(newX, newY);
stottingVector.multiply(predatorForce.getNorm()
/ stottingVector.getNorm());
stottingVector.add(predatorForce.multiply(-0.5));
return stottingVector;
}
}
return predatorForce;
}
/**
* This also decreases the deer's energy.
*/
@Override
public void updatePosition() {
super.updatePosition();
this.energy--;
stottingCoolDown--;
if (energy == 0 || lifeLength > MAX_LIFE_LENGTH)
isAlive = false;
}
}
| true | true | private Vector getPreyForce(IShape shape, Dimension dim) {
if (willFocusPreys && focusedPrey != null && focusedPrey.isAlive()) {
Position p = focusedPrey.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= EATING_RANGE) {
if (focusedPrey.tryConsumeAgent()) {
focusedPrey = null;
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else {
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
//Focused prey cant be reached. Change target.
focusedPrey = null;
} else {
return new Vector(pathToTarget.get(0), position);
}
}
}
Vector preyForce = new Vector(0, 0);
IAgent closestFocusPrey = null;
int preySize = preyNeighbours.size();
for (int i = 0; i < preySize; i++) {
IAgent a = preyNeighbours.get(i);
Position p = a.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= visionRange) {
if (distance <= EATING_RANGE) {
if (a.tryConsumeAgent()) {
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else if (willFocusPreys && distance <= FOCUS_RANGE) {
if (closestFocusPrey != null && a.isAlive()) {
if (closestFocusPrey.getPosition().getDistance(
this.position) > a.getPosition().getDistance(
this.position)) {
closestFocusPrey = a;
}
} else {
closestFocusPrey = a;
}
} else if (closestFocusPrey == null) {
/*
* Create a vector that points towards the prey.
*/
Vector newForce = null;
List<Position> pathToTarget = Position.getShortestPath(position, p, obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
//Focused prey cant be reached. Change target.
newForce = Vector.emptyVector();
} else {
newForce = new Vector(pathToTarget.get(0), position);
}
/*
* Add this vector to the prey force, with proportion to how
* close the prey is. Closer preys will affect the force
* more than those far away.
*/
double norm = newForce.getNorm();
preyForce.add(newForce.multiply(1 / (norm * distance)));
}
}
}
double norm = preyForce.getNorm();
if (norm != 0) {
preyForce.multiply(maxAcceleration / norm);
}
if (willFocusPreys && closestFocusPrey != null) {
focusedPrey = closestFocusPrey;
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
return Vector.emptyVector();
} else {
return new Vector(pathToTarget.get(0), position);
}
}
return preyForce;
}
| private Vector getPreyForce(IShape shape, Dimension dim) {
if (willFocusPreys && focusedPrey != null && focusedPrey.isAlive()) {
Position p = focusedPrey.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= EATING_RANGE) {
if (focusedPrey.tryConsumeAgent()) {
focusedPrey = null;
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else {
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
//Focused prey cant be reached. Change target.
focusedPrey = null;
} else {
return new Vector(pathToTarget.get(0), position);
}
}
}
Vector preyForce = new Vector(0, 0);
IAgent closestFocusPrey = null;
int preySize = preyNeighbours.size();
for (int i = 0; i < preySize; i++) {
IAgent a = preyNeighbours.get(i);
Position p = a.getPosition();
double distance = getPosition().getDistance(p);
if (distance <= visionRange) {
if (distance <= EATING_RANGE) {
if (a.tryConsumeAgent()) {
hungry = false;
energy = MAX_ENERGY;
digesting = DIGESTION_TIME;
}
} else if (willFocusPreys && distance <= FOCUS_RANGE) {
if (closestFocusPrey != null && a.isAlive()) {
if (closestFocusPrey.getPosition().getDistance(
this.position) > a.getPosition().getDistance(
this.position)) {
closestFocusPrey = a;
}
} else {
closestFocusPrey = a;
}
} else if (closestFocusPrey == null) {
/*
* Create a vector that points towards the prey.
*/
Vector newForce = new Vector(p, position);
/*
* Add this vector to the prey force, with proportion to how
* close the prey is. Closer preys will affect the force
* more than those far away.
*/
double norm = newForce.getNorm();
preyForce.add(newForce.multiply(1 / (norm * distance)));
}
}
}
double norm = preyForce.getNorm();
if (norm != 0) {
preyForce.multiply(maxAcceleration / norm);
}
if (willFocusPreys && closestFocusPrey != null) {
focusedPrey = closestFocusPrey;
List<Position> pathToTarget = Position.getShortestPath(position, focusedPrey.getPosition(), obstacles, shape, dim);
if(pathToTarget == null || pathToTarget.size() == 0) {
return Vector.emptyVector();
} else {
return new Vector(pathToTarget.get(0), position);
}
}
return preyForce;
}
|
diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/client/APVS.java b/apvs/src/main/java/ch/cern/atlas/apvs/client/APVS.java
index 3acdce73..639d56e6 100644
--- a/apvs/src/main/java/ch/cern/atlas/apvs/client/APVS.java
+++ b/apvs/src/main/java/ch/cern/atlas/apvs/client/APVS.java
@@ -1,447 +1,445 @@
package ch.cern.atlas.apvs.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.cern.atlas.apvs.client.domain.Ternary;
import ch.cern.atlas.apvs.client.event.ConnectionStatusChangedRemoteEvent;
import ch.cern.atlas.apvs.client.event.ConnectionStatusChangedRemoteEvent.ConnectionType;
import ch.cern.atlas.apvs.client.event.SelectPtuEvent;
import ch.cern.atlas.apvs.client.settings.SettingsPersister;
import ch.cern.atlas.apvs.client.tablet.AppBundle;
import ch.cern.atlas.apvs.client.tablet.HomePlace;
import ch.cern.atlas.apvs.client.tablet.LocalStorage;
import ch.cern.atlas.apvs.client.tablet.TabletHistoryObserver;
import ch.cern.atlas.apvs.client.tablet.TabletMenuActivityMapper;
import ch.cern.atlas.apvs.client.tablet.TabletMenuAnimationMapper;
import ch.cern.atlas.apvs.client.tablet.TabletPanelActivityMapper;
import ch.cern.atlas.apvs.client.tablet.TabletPanelAnimationMapper;
import ch.cern.atlas.apvs.client.tablet.TabletPlaceHistoryMapper;
import ch.cern.atlas.apvs.client.ui.AlarmView;
import ch.cern.atlas.apvs.client.ui.Arguments;
import ch.cern.atlas.apvs.client.ui.AudioSummary;
import ch.cern.atlas.apvs.client.ui.AudioSupervisorSettingsView;
import ch.cern.atlas.apvs.client.ui.AudioView;
import ch.cern.atlas.apvs.client.ui.CameraTable;
import ch.cern.atlas.apvs.client.ui.CameraView;
import ch.cern.atlas.apvs.client.ui.EventView;
import ch.cern.atlas.apvs.client.ui.GeneralInfoView;
import ch.cern.atlas.apvs.client.ui.InterventionView;
import ch.cern.atlas.apvs.client.ui.MeasurementTable;
import ch.cern.atlas.apvs.client.ui.MeasurementView;
import ch.cern.atlas.apvs.client.ui.Module;
import ch.cern.atlas.apvs.client.ui.PlaceView;
import ch.cern.atlas.apvs.client.ui.ProcedureControls;
import ch.cern.atlas.apvs.client.ui.ProcedureView;
import ch.cern.atlas.apvs.client.ui.PtuSettingsView;
import ch.cern.atlas.apvs.client.ui.PtuTabSelector;
import ch.cern.atlas.apvs.client.ui.PtuView;
import ch.cern.atlas.apvs.client.ui.ServerSettingsView;
import ch.cern.atlas.apvs.client.ui.Tab;
import ch.cern.atlas.apvs.client.ui.TimeView;
import ch.cern.atlas.apvs.client.widget.DialogResultEvent;
import ch.cern.atlas.apvs.client.widget.DialogResultHandler;
import ch.cern.atlas.apvs.client.widget.PasswordDialog;
import ch.cern.atlas.apvs.eventbus.shared.RemoteEventBus;
import ch.cern.atlas.apvs.eventbus.shared.RequestRemoteEvent;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.StyleInjector;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.googlecode.mgwt.mvp.client.AnimatableDisplay;
import com.googlecode.mgwt.mvp.client.AnimatingActivityManager;
import com.googlecode.mgwt.mvp.client.AnimationMapper;
import com.googlecode.mgwt.mvp.client.history.MGWTPlaceHistoryHandler;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.MGWTSettings;
import com.googlecode.mgwt.ui.client.MGWTSettings.ViewPort;
import com.googlecode.mgwt.ui.client.MGWTSettings.ViewPort.DENSITY;
import com.googlecode.mgwt.ui.client.dialog.TabletPortraitOverlay;
import com.googlecode.mgwt.ui.client.layout.MasterRegionHandler;
import com.googlecode.mgwt.ui.client.layout.OrientationRegionHandler;
/**
* @author Mark Donszelmann
*/
public class APVS implements EntryPoint {
private Logger log = LoggerFactory.getLogger(getClass().getName());
@SuppressWarnings("unused")
private Window screen;
private RemoteEventBus remoteEventBus;
@SuppressWarnings("unused")
private PlaceController placeController;
@SuppressWarnings("unused")
private SettingsPersister settingsPersister;
private String defaultPtuId = "PTUdemo";
private ClientFactory clientFactory;
private Ternary alive = Ternary.Unknown;
@Override
public void onModuleLoad() {
GWT.setUncaughtExceptionHandler(new APVSUncaughtExceptionHandler());
Build build = GWT.create(Build.class);
log.info("Starting APVS Version: " + build.version() + " - "
+ build.build());
clientFactory = GWT.create(ClientFactory.class);
String pwd = LocalStorage.getInstance()
.get(LocalStorage.SUPERVISOR_PWD);
if (pwd != null) {
login(pwd);
} else {
prompt();
}
}
private void login(final String pwd) {
clientFactory.getServerService().isReady(pwd,
new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean supervisor) {
clientFactory.setSupervisor(supervisor);
log.info("Server ready, user is "
+ (supervisor ? "SUPERVISOR" : "OBSERVER"));
LocalStorage.getInstance().put(LocalStorage.SUPERVISOR_PWD, supervisor ? pwd : null);
start();
}
@Override
public void onFailure(Throwable caught) {
Window.alert("Server not ready. reload webpage "
+ caught);
}
});
}
private void prompt() {
final PasswordDialog pwdDialog = new PasswordDialog();
pwdDialog.addDialogResultHandler(new DialogResultHandler() {
@Override
public void onDialogResult(DialogResultEvent event) {
login(event.getResult());
}
});
pwdDialog.setModal(true);
pwdDialog.setGlassEnabled(true);
pwdDialog.setPopupPositionAndShow(new PositionCallback() {
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
// center
pwdDialog.setPopupPosition(
(Window.getClientWidth() - offsetWidth) / 3,
(Window.getClientHeight() - offsetHeight) / 3);
}
});
}
private void start() {
remoteEventBus = clientFactory.getRemoteEventBus();
placeController = clientFactory.getPlaceController();
settingsPersister = new SettingsPersister(remoteEventBus);
// get first div element
NodeList<Element> divs = Document.get().getElementsByTagName("div");
if (divs.getLength() == 0) {
Window.alert("Please define a <div> element with the class set to your view you want to show.");
return;
}
boolean layoutOnlyMode = Window.Location.getQueryString().indexOf(
"layout=true") >= 0;
if (layoutOnlyMode) {
log.info("Running in layoutOnly mode");
return;
}
boolean newCode = false;
for (int i = 0; i < divs.getLength(); i++) {
Element element = divs.getItem(i);
String id = element.getId();
if (id.equals("footer")) {
Label supervisor = new Label(
clientFactory.isSupervisor() ? "Supervisor"
: "Observer");
supervisor.addStyleName("footer-left");
RootPanel.get(id).insert(supervisor, 0);
continue;
}
String[] parts = id.split("\\(", 2);
if (parts.length == 2) {
String className = parts[0];
if ((parts[1].length() > 0) && !parts[1].endsWith(")")) {
log.warn("Missing closing parenthesis on '" + id + "'");
parts[1] += ")";
}
Arguments args = new Arguments(
parts[1].length() > 0 ? parts[1].substring(0,
parts[1].length() - 1) : null);
log.info("Creating " + className + " with args (" + args + ")");
Module module = null;
// FIXME handle generically
if (id.startsWith("MeasurementView")) {
module = new MeasurementView();
} else if (id.startsWith("MeasurementTable")) {
module = new MeasurementTable();
} else if (id.startsWith("AlarmView")) {
module = new AlarmView();
} else if (id.startsWith("AudioSummary")) {
module = new AudioSummary();
} else if (id.startsWith("AudioView")) {
module = new AudioView();
} else if (id.startsWith("AudioSupervisorSettingsView")) {
module = new AudioSupervisorSettingsView();
} else if (id.startsWith("CameraTable")) {
module = new CameraTable();
} else if (id.startsWith("CameraView")) {
module = new CameraView();
} else if (id.startsWith("EventView")) {
module = new EventView();
} else if (id.startsWith("GeneralInfoView")) {
module = new GeneralInfoView();
} else if (id.startsWith("InterventionView")) {
module = new InterventionView();
} else if (id.startsWith("PlaceView")) {
module = new PlaceView();
} else if (id.startsWith("ProcedureControls")) {
module = new ProcedureControls();
} else if (id.startsWith("ProcedureView")) {
module = new ProcedureView();
} else if (id.startsWith("PtuSettingsView")) {
module = new PtuSettingsView();
} else if (id.startsWith("PtuTabSelector")) {
module = new PtuTabSelector();
} else if (id.startsWith("PtuView")) {
module = new PtuView();
} else if (id.startsWith("ServerSettingsView")) {
module = new ServerSettingsView();
} else if (id.startsWith("Tab")) {
module = new Tab();
} else if (id.startsWith("TimeView")) {
module = new TimeView();
}
if (module != null) {
boolean add = module
.configure(element, clientFactory, args);
if (add && module instanceof IsWidget) {
RootPanel.get(id).add((IsWidget) module);
}
newCode = true;
}
}
}
// FIXME create tab buttons for each, select default one
clientFactory.getEventBus("ptu").fireEvent(
new SelectPtuEvent(defaultPtuId));
// Server ALIVE status
RequestRemoteEvent.register(remoteEventBus, new RequestRemoteEvent.Handler() {
@Override
public void onRequestEvent(RequestRemoteEvent event) {
String type = event.getRequestedClassName();
if (type.equals(ConnectionStatusChangedRemoteEvent.class
.getName())) {
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus,
ConnectionType.server, alive);
}
}
});
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
@Override
public boolean execute() {
RequestBuilder request = PingServiceAsync.Util.getInstance().ping(new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
- Window.alert("Sucess");
if (!alive.isTrue()) {
alive = Ternary.True;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
@Override
public void onFailure(Throwable caught) {
- Window.alert("Failure "+caught);
if (!alive.isFalse()) {
alive = Ternary.False;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
});
request.setTimeoutMillis(10000);
try {
request.send();
} catch (RequestException e) {
}
Window.alert("Sent");
- return false;
+ return true;
}
}, 20000);
if (newCode)
return;
startWorker();
return;
}
private void startWorker() {
// MGWTColorScheme.setBaseColor("#56a60D");
// MGWTColorScheme.setFontColor("#eee");
//
// MGWTStyle.setDefaultBundle((MGWTClientBundle)
// GWT.create(MGWTStandardBundle.class));
// MGWTStyle.getDefaultClientBundle().getMainCss().ensureInjected();
ViewPort viewPort = new MGWTSettings.ViewPort();
viewPort.setTargetDensity(DENSITY.MEDIUM);
viewPort.setUserScaleAble(false).setMinimumScale(1.0)
.setMinimumScale(1.0).setMaximumScale(1.0);
MGWTSettings settings = new MGWTSettings();
settings.setViewPort(viewPort);
// settings.setIconUrl("logo.png");
// settings.setAddGlosToIcon(true);
settings.setFullscreen(true);
settings.setPreventScrolling(true);
MGWT.applySettings(settings);
final ClientFactory clientFactory = new APVSClientFactory();
// Start PlaceHistoryHandler with our PlaceHistoryMapper
TabletPlaceHistoryMapper historyMapper = GWT
.create(TabletPlaceHistoryMapper.class);
if (MGWT.getOsDetection().isTablet()) {
// very nasty workaround because GWT does not corretly support
// @media
StyleInjector.inject(AppBundle.INSTANCE.css().getText());
createTabletDisplay(clientFactory);
} else {
createTabletDisplay(clientFactory);
// createPhoneDisplay(clientFactory);
}
TabletHistoryObserver historyObserver = new TabletHistoryObserver();
MGWTPlaceHistoryHandler historyHandler = new MGWTPlaceHistoryHandler(
historyMapper, historyObserver);
historyHandler.register(clientFactory.getPlaceController(),
clientFactory.getRemoteEventBus(), new HomePlace());
historyHandler.handleCurrentHistory();
}
/*
* private void createPhoneDisplay(ClientFactory clientFactory) {
* AnimatableDisplay display = GWT.create(AnimatableDisplay.class);
*
* PhoneActivityMapper appActivityMapper = new PhoneActivityMapper(
* clientFactory);
*
* PhoneAnimationMapper appAnimationMapper = new PhoneAnimationMapper();
*
* AnimatingActivityManager activityManager = new AnimatingActivityManager(
* appActivityMapper, appAnimationMapper, clientFactory.getEventBus());
*
* activityManager.setDisplay(display);
*
* RootPanel.get().add(display);
*
* }
*/
private void createTabletDisplay(ClientFactory clientFactory) {
SimplePanel navContainer = new SimplePanel();
navContainer.getElement().setId("nav");
navContainer.getElement().addClassName("landscapeonly");
AnimatableDisplay navDisplay = GWT.create(AnimatableDisplay.class);
final TabletPortraitOverlay tabletPortraitOverlay = new TabletPortraitOverlay();
new OrientationRegionHandler(navContainer, tabletPortraitOverlay,
navDisplay);
new MasterRegionHandler(clientFactory.getRemoteEventBus(), "nav",
tabletPortraitOverlay);
ActivityMapper navActivityMapper = new TabletMenuActivityMapper(
clientFactory);
AnimationMapper navAnimationMapper = new TabletMenuAnimationMapper();
AnimatingActivityManager navActivityManager = new AnimatingActivityManager(
navActivityMapper, navAnimationMapper,
clientFactory.getRemoteEventBus());
navActivityManager.setDisplay(navDisplay);
RootPanel.get().add(navContainer);
SimplePanel mainContainer = new SimplePanel();
mainContainer.getElement().setId("main");
AnimatableDisplay mainDisplay = GWT.create(AnimatableDisplay.class);
TabletPanelActivityMapper tabletMainActivityMapper = new TabletPanelActivityMapper(
clientFactory);
AnimationMapper tabletMainAnimationMapper = new TabletPanelAnimationMapper();
AnimatingActivityManager mainActivityManager = new AnimatingActivityManager(
tabletMainActivityMapper, tabletMainAnimationMapper,
clientFactory.getRemoteEventBus());
mainActivityManager.setDisplay(mainDisplay);
mainContainer.setWidget(mainDisplay);
RootPanel.get().add(mainContainer);
}
}
| false | true | private void start() {
remoteEventBus = clientFactory.getRemoteEventBus();
placeController = clientFactory.getPlaceController();
settingsPersister = new SettingsPersister(remoteEventBus);
// get first div element
NodeList<Element> divs = Document.get().getElementsByTagName("div");
if (divs.getLength() == 0) {
Window.alert("Please define a <div> element with the class set to your view you want to show.");
return;
}
boolean layoutOnlyMode = Window.Location.getQueryString().indexOf(
"layout=true") >= 0;
if (layoutOnlyMode) {
log.info("Running in layoutOnly mode");
return;
}
boolean newCode = false;
for (int i = 0; i < divs.getLength(); i++) {
Element element = divs.getItem(i);
String id = element.getId();
if (id.equals("footer")) {
Label supervisor = new Label(
clientFactory.isSupervisor() ? "Supervisor"
: "Observer");
supervisor.addStyleName("footer-left");
RootPanel.get(id).insert(supervisor, 0);
continue;
}
String[] parts = id.split("\\(", 2);
if (parts.length == 2) {
String className = parts[0];
if ((parts[1].length() > 0) && !parts[1].endsWith(")")) {
log.warn("Missing closing parenthesis on '" + id + "'");
parts[1] += ")";
}
Arguments args = new Arguments(
parts[1].length() > 0 ? parts[1].substring(0,
parts[1].length() - 1) : null);
log.info("Creating " + className + " with args (" + args + ")");
Module module = null;
// FIXME handle generically
if (id.startsWith("MeasurementView")) {
module = new MeasurementView();
} else if (id.startsWith("MeasurementTable")) {
module = new MeasurementTable();
} else if (id.startsWith("AlarmView")) {
module = new AlarmView();
} else if (id.startsWith("AudioSummary")) {
module = new AudioSummary();
} else if (id.startsWith("AudioView")) {
module = new AudioView();
} else if (id.startsWith("AudioSupervisorSettingsView")) {
module = new AudioSupervisorSettingsView();
} else if (id.startsWith("CameraTable")) {
module = new CameraTable();
} else if (id.startsWith("CameraView")) {
module = new CameraView();
} else if (id.startsWith("EventView")) {
module = new EventView();
} else if (id.startsWith("GeneralInfoView")) {
module = new GeneralInfoView();
} else if (id.startsWith("InterventionView")) {
module = new InterventionView();
} else if (id.startsWith("PlaceView")) {
module = new PlaceView();
} else if (id.startsWith("ProcedureControls")) {
module = new ProcedureControls();
} else if (id.startsWith("ProcedureView")) {
module = new ProcedureView();
} else if (id.startsWith("PtuSettingsView")) {
module = new PtuSettingsView();
} else if (id.startsWith("PtuTabSelector")) {
module = new PtuTabSelector();
} else if (id.startsWith("PtuView")) {
module = new PtuView();
} else if (id.startsWith("ServerSettingsView")) {
module = new ServerSettingsView();
} else if (id.startsWith("Tab")) {
module = new Tab();
} else if (id.startsWith("TimeView")) {
module = new TimeView();
}
if (module != null) {
boolean add = module
.configure(element, clientFactory, args);
if (add && module instanceof IsWidget) {
RootPanel.get(id).add((IsWidget) module);
}
newCode = true;
}
}
}
// FIXME create tab buttons for each, select default one
clientFactory.getEventBus("ptu").fireEvent(
new SelectPtuEvent(defaultPtuId));
// Server ALIVE status
RequestRemoteEvent.register(remoteEventBus, new RequestRemoteEvent.Handler() {
@Override
public void onRequestEvent(RequestRemoteEvent event) {
String type = event.getRequestedClassName();
if (type.equals(ConnectionStatusChangedRemoteEvent.class
.getName())) {
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus,
ConnectionType.server, alive);
}
}
});
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
@Override
public boolean execute() {
RequestBuilder request = PingServiceAsync.Util.getInstance().ping(new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
Window.alert("Sucess");
if (!alive.isTrue()) {
alive = Ternary.True;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
@Override
public void onFailure(Throwable caught) {
Window.alert("Failure "+caught);
if (!alive.isFalse()) {
alive = Ternary.False;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
});
request.setTimeoutMillis(10000);
try {
request.send();
} catch (RequestException e) {
}
Window.alert("Sent");
return false;
}
}, 20000);
if (newCode)
return;
startWorker();
return;
}
| private void start() {
remoteEventBus = clientFactory.getRemoteEventBus();
placeController = clientFactory.getPlaceController();
settingsPersister = new SettingsPersister(remoteEventBus);
// get first div element
NodeList<Element> divs = Document.get().getElementsByTagName("div");
if (divs.getLength() == 0) {
Window.alert("Please define a <div> element with the class set to your view you want to show.");
return;
}
boolean layoutOnlyMode = Window.Location.getQueryString().indexOf(
"layout=true") >= 0;
if (layoutOnlyMode) {
log.info("Running in layoutOnly mode");
return;
}
boolean newCode = false;
for (int i = 0; i < divs.getLength(); i++) {
Element element = divs.getItem(i);
String id = element.getId();
if (id.equals("footer")) {
Label supervisor = new Label(
clientFactory.isSupervisor() ? "Supervisor"
: "Observer");
supervisor.addStyleName("footer-left");
RootPanel.get(id).insert(supervisor, 0);
continue;
}
String[] parts = id.split("\\(", 2);
if (parts.length == 2) {
String className = parts[0];
if ((parts[1].length() > 0) && !parts[1].endsWith(")")) {
log.warn("Missing closing parenthesis on '" + id + "'");
parts[1] += ")";
}
Arguments args = new Arguments(
parts[1].length() > 0 ? parts[1].substring(0,
parts[1].length() - 1) : null);
log.info("Creating " + className + " with args (" + args + ")");
Module module = null;
// FIXME handle generically
if (id.startsWith("MeasurementView")) {
module = new MeasurementView();
} else if (id.startsWith("MeasurementTable")) {
module = new MeasurementTable();
} else if (id.startsWith("AlarmView")) {
module = new AlarmView();
} else if (id.startsWith("AudioSummary")) {
module = new AudioSummary();
} else if (id.startsWith("AudioView")) {
module = new AudioView();
} else if (id.startsWith("AudioSupervisorSettingsView")) {
module = new AudioSupervisorSettingsView();
} else if (id.startsWith("CameraTable")) {
module = new CameraTable();
} else if (id.startsWith("CameraView")) {
module = new CameraView();
} else if (id.startsWith("EventView")) {
module = new EventView();
} else if (id.startsWith("GeneralInfoView")) {
module = new GeneralInfoView();
} else if (id.startsWith("InterventionView")) {
module = new InterventionView();
} else if (id.startsWith("PlaceView")) {
module = new PlaceView();
} else if (id.startsWith("ProcedureControls")) {
module = new ProcedureControls();
} else if (id.startsWith("ProcedureView")) {
module = new ProcedureView();
} else if (id.startsWith("PtuSettingsView")) {
module = new PtuSettingsView();
} else if (id.startsWith("PtuTabSelector")) {
module = new PtuTabSelector();
} else if (id.startsWith("PtuView")) {
module = new PtuView();
} else if (id.startsWith("ServerSettingsView")) {
module = new ServerSettingsView();
} else if (id.startsWith("Tab")) {
module = new Tab();
} else if (id.startsWith("TimeView")) {
module = new TimeView();
}
if (module != null) {
boolean add = module
.configure(element, clientFactory, args);
if (add && module instanceof IsWidget) {
RootPanel.get(id).add((IsWidget) module);
}
newCode = true;
}
}
}
// FIXME create tab buttons for each, select default one
clientFactory.getEventBus("ptu").fireEvent(
new SelectPtuEvent(defaultPtuId));
// Server ALIVE status
RequestRemoteEvent.register(remoteEventBus, new RequestRemoteEvent.Handler() {
@Override
public void onRequestEvent(RequestRemoteEvent event) {
String type = event.getRequestedClassName();
if (type.equals(ConnectionStatusChangedRemoteEvent.class
.getName())) {
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus,
ConnectionType.server, alive);
}
}
});
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
@Override
public boolean execute() {
RequestBuilder request = PingServiceAsync.Util.getInstance().ping(new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
if (!alive.isTrue()) {
alive = Ternary.True;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
@Override
public void onFailure(Throwable caught) {
if (!alive.isFalse()) {
alive = Ternary.False;
ConnectionStatusChangedRemoteEvent.fire(remoteEventBus, ConnectionType.server, alive);
}
}
});
request.setTimeoutMillis(10000);
try {
request.send();
} catch (RequestException e) {
}
Window.alert("Sent");
return true;
}
}, 20000);
if (newCode)
return;
startWorker();
return;
}
|
diff --git a/tooling/exam/regression/src/test/java/org/apache/karaf/tooling/exam/regression/BootClasspathLibraryOptionTest.java b/tooling/exam/regression/src/test/java/org/apache/karaf/tooling/exam/regression/BootClasspathLibraryOptionTest.java
index 199407f0a..3b1984de9 100644
--- a/tooling/exam/regression/src/test/java/org/apache/karaf/tooling/exam/regression/BootClasspathLibraryOptionTest.java
+++ b/tooling/exam/regression/src/test/java/org/apache/karaf/tooling/exam/regression/BootClasspathLibraryOptionTest.java
@@ -1,61 +1,61 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.karaf.tooling.exam.regression;
import static junit.framework.Assert.assertEquals;
import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.CoreOptions.bootClasspathLibrary;
import static org.ops4j.pax.exam.CoreOptions.maven;
import java.io.File;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.ExamReactorStrategy;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory;
@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(AllConfinedStagedReactorFactory.class)
public class BootClasspathLibraryOptionTest {
@Configuration
public Option[] config() {
return new Option[]{
karafDistributionConfiguration().frameworkUrl(
maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("zip")
.versionAsInProject()),
bootClasspathLibrary("mvn:commons-naming/commons-naming-core/20031116.223527") };
}
@Test
public void test() throws Exception {
File file = new File("lib");
File[] files = file.listFiles();
int foundJarFiles = 0;
for (File libFile : files) {
if (libFile.getName().endsWith("jar")) {
foundJarFiles++;
}
}
- assertEquals(3, foundJarFiles);
+ assertEquals(5, foundJarFiles);
}
}
| true | true | public void test() throws Exception {
File file = new File("lib");
File[] files = file.listFiles();
int foundJarFiles = 0;
for (File libFile : files) {
if (libFile.getName().endsWith("jar")) {
foundJarFiles++;
}
}
assertEquals(3, foundJarFiles);
}
| public void test() throws Exception {
File file = new File("lib");
File[] files = file.listFiles();
int foundJarFiles = 0;
for (File libFile : files) {
if (libFile.getName().endsWith("jar")) {
foundJarFiles++;
}
}
assertEquals(5, foundJarFiles);
}
|
diff --git a/src/com/sbezboro/standardplugin/model/StandardPlayer.java b/src/com/sbezboro/standardplugin/model/StandardPlayer.java
index 89d6c9c..0ee08a7 100644
--- a/src/com/sbezboro/standardplugin/model/StandardPlayer.java
+++ b/src/com/sbezboro/standardplugin/model/StandardPlayer.java
@@ -1,320 +1,320 @@
package com.sbezboro.standardplugin.model;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import com.sbezboro.standardplugin.StandardPlugin;
import com.sbezboro.standardplugin.integrations.EssentialsIntegration;
import com.sbezboro.standardplugin.persistence.PersistedList;
import com.sbezboro.standardplugin.persistence.PersistedProperty;
import com.sbezboro.standardplugin.persistence.PlayerStorage;
import com.sbezboro.standardplugin.persistence.TitleStorage;
import com.sbezboro.standardplugin.persistence.persistables.PersistableLocation;
import com.sbezboro.standardplugin.util.AnsiConverter;
import com.sbezboro.standardplugin.util.MiscUtil;
public class StandardPlayer extends PlayerDelegate {
private static final String FORUM_MUTED_PROPERTY = "forum-muted";
private static final String PVP_PROTECTION_PROPERTY = "pvp-protection";
private static final String BED_LOCATION_PROPERTY = "bed";
private static final String TITLES_PROPERTY = "titles";
private PersistedProperty<Boolean> forumMuted;
private PersistedProperty<Boolean> pvpProtection;
private PersistedProperty<PersistableLocation> bedLocation;
private PersistedList<String> titleNames;
private ArrayList<Title> titles;
private int timeSpent;
private int rank;
private int newbieAttacks;
public StandardPlayer(final Player player, final PlayerStorage storage) {
super(player, storage);
}
public StandardPlayer(final OfflinePlayer player, final PlayerStorage storage) {
super(player, storage);
}
@Override
public void loadProperties() {
titles = new ArrayList<Title>();
forumMuted = loadProperty(Boolean.class, FORUM_MUTED_PROPERTY);
pvpProtection = loadProperty(Boolean.class, PVP_PROTECTION_PROPERTY);
bedLocation = loadProperty(PersistableLocation.class, BED_LOCATION_PROPERTY);
titleNames = loadList(String.class, TITLES_PROPERTY);
TitleStorage titleStorage = StandardPlugin.getPlugin().getTitleStorage();
for (String name : titleNames) {
Title title = titleStorage.getTitle(name);
if (title == null) {
StandardPlugin.getPlugin().getLogger().severe("Player has title non-existant title \"" + name + "\"!");
} else {
titles.add(title);
}
}
}
// ------
// Persisted property mutators
// ------
public Boolean isForumMuted() {
return forumMuted.getValue();
}
public void setForumMuted(boolean forumMuted) {
this.forumMuted.setValue(forumMuted);
}
public boolean toggleForumMute() {
setForumMuted(!isForumMuted());
return isForumMuted();
}
public boolean isHungerProtected() {
return timeSpent <= StandardPlugin.getPlugin().getHungerProtectionTime();
}
public Boolean isPvpProtected() {
return pvpProtection.getValue();
}
public void setPvpProtection(boolean pvpProtection) {
this.pvpProtection.setValue(pvpProtection);
}
public int getPvpProtectionTimeRemaining() {
return Math.max(StandardPlugin.getPlugin().getPvpProtectionTime() - timeSpent, 0);
}
public void saveBedLocation(Location location) {
bedLocation.setValue(new PersistableLocation(location));
}
public Location getBedLocation() {
return bedLocation.getValue().getLocation();
}
public void addTitle(Title title) {
if (!titles.contains(title)) {
titles.add(title);
titleNames.add(title.getName());
}
}
public Title addTitle(String name) {
Title title = StandardPlugin.getPlugin().getTitleStorage().getTitle(name);
addTitle(title);
return title;
}
public void removeTitle(String name) {
Title title = StandardPlugin.getPlugin().getTitleStorage().getTitle(name);
titles.remove(title);
titleNames.remove(name);
}
// ------
// Non-persisted property mutators
// ------
public int getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(int timeSpent) {
this.timeSpent = timeSpent;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int getNewbieAttacks() {
return newbieAttacks;
}
public int incrementNewbieAttacks() {
return newbieAttacks++;
}
public ArrayList<Title> getTitles() {
return titles;
}
public boolean hasTitle(String name) {
for (Title title : titles) {
if (title.getName().equals(name)) {
return true;
}
}
return false;
}
public boolean isNewbieStalker() {
return hasTitle(Title.NEWBIE_STALKER);
}
public boolean isTop10Veteran() {
return hasTitle(Title.TOP10_VETERAN);
}
public boolean isTop40Veteran() {
return hasTitle(Title.TOP40_VETERAN);
}
public boolean isVeteran() {
return hasTitle(Title.VETERAN);
}
public void onLeaveServer() {
player = null;
}
public String getRankDescription(boolean self, int rank) {
String message = "";
Title broadcastedTitle = null;
for (Title title : getTitles()) {
if (title.isBroadcast()) {
broadcastedTitle = title;
break;
}
}
if (broadcastedTitle == null) {
for (Title title : getTitles()) {
if (title.getName().equals(Title.TOP10_VETERAN) ||
title.getName().equals(Title.TOP40_VETERAN) ||
title.getName().equals(Title.VETERAN)) {
broadcastedTitle = title;
break;
}
}
}
if (self) {
message = "You ";
if (broadcastedTitle != null) {
message += "are a " + ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE + " and ";
}
message += "are ranked " + ChatColor.AQUA + MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
} else {
if (broadcastedTitle != null) {
- message += ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE + " and ";
+ message += ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE;
}
message += ChatColor.AQUA + getDisplayName() + ChatColor.WHITE + " is ranked " + ChatColor.AQUA
+ MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
}
return message;
}
public String getTimePlayedDescription(boolean self, String time) {
if (self) {
return "You have played here " + ChatColor.AQUA + time + ChatColor.WHITE + ".";
} else {
return getName() + " has played here " + ChatColor.AQUA + time + ChatColor.WHITE + ".";
}
}
public String[] getTitleDescription(boolean self) {
ArrayList<String> messages = new ArrayList<String>();
String name = self ? "You" + ChatColor.RESET + " have" : getDisplayName(false) + ChatColor.RESET + " has";
if (titles.size() == 0) {
messages.add(ChatColor.AQUA + name + " no titles.");
} else {
messages.add(ChatColor.AQUA + name + " the following titles:");
for (Title title : titles) {
messages.add(ChatColor.DARK_AQUA + title.getDisplayName());
}
}
return messages.toArray(new String[messages.size()]);
}
public HashMap<String, Object> getInfo() {
HashMap<String, Object> info = new HashMap<String, Object>();
info.put("username", getName());
info.put("address", getAddress().getAddress().getHostAddress());
if (hasNickname()) {
String nicknameAnsi = AnsiConverter.toAnsi(player.getDisplayName());
String nickname = getDisplayName(false);
info.put("nickname_ansi", nicknameAnsi);
info.put("nickname", nickname);
}
info.put("rank", getRank());
info.put("time_spent", getTimeSpent());
info.put("is_pvp_protected", isPvpProtected());
info.put("is_hunger_protected", isHungerProtected());
info.put("world", getLocation().getWorld().getName());
info.put("x", getLocation().getBlockX());
info.put("y", getLocation().getBlockY());
info.put("z", getLocation().getBlockZ());
info.put("health", getHealth());
ArrayList<HashMap<String, String>> titleInfos = new ArrayList<HashMap<String, String>>();
for (Title title : titles) {
HashMap<String, String> titleInfo = new HashMap<String, String>();
titleInfo.put("name", title.getName());
titleInfo.put("display_name", title.getDisplayName());
titleInfos.add(titleInfo);
}
info.put("titles", titleInfos);
return info;
}
public boolean hasNickname() {
return EssentialsIntegration.hasNickname(getName());
}
public String getDisplayName(boolean colored) {
if (hasNickname()) {
String name = EssentialsIntegration.getNickname(getName());
if (!colored) {
return ChatColor.stripColor(name);
}
return name;
}
return getName();
}
@Override
public String getDisplayName() {
return getDisplayName(true);
}
}
| true | true | public String getRankDescription(boolean self, int rank) {
String message = "";
Title broadcastedTitle = null;
for (Title title : getTitles()) {
if (title.isBroadcast()) {
broadcastedTitle = title;
break;
}
}
if (broadcastedTitle == null) {
for (Title title : getTitles()) {
if (title.getName().equals(Title.TOP10_VETERAN) ||
title.getName().equals(Title.TOP40_VETERAN) ||
title.getName().equals(Title.VETERAN)) {
broadcastedTitle = title;
break;
}
}
}
if (self) {
message = "You ";
if (broadcastedTitle != null) {
message += "are a " + ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE + " and ";
}
message += "are ranked " + ChatColor.AQUA + MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
} else {
if (broadcastedTitle != null) {
message += ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE + " and ";
}
message += ChatColor.AQUA + getDisplayName() + ChatColor.WHITE + " is ranked " + ChatColor.AQUA
+ MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
}
return message;
}
| public String getRankDescription(boolean self, int rank) {
String message = "";
Title broadcastedTitle = null;
for (Title title : getTitles()) {
if (title.isBroadcast()) {
broadcastedTitle = title;
break;
}
}
if (broadcastedTitle == null) {
for (Title title : getTitles()) {
if (title.getName().equals(Title.TOP10_VETERAN) ||
title.getName().equals(Title.TOP40_VETERAN) ||
title.getName().equals(Title.VETERAN)) {
broadcastedTitle = title;
break;
}
}
}
if (self) {
message = "You ";
if (broadcastedTitle != null) {
message += "are a " + ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE + " and ";
}
message += "are ranked " + ChatColor.AQUA + MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
} else {
if (broadcastedTitle != null) {
message += ChatColor.GOLD + broadcastedTitle.getDisplayName() + ChatColor.WHITE;
}
message += ChatColor.AQUA + getDisplayName() + ChatColor.WHITE + " is ranked " + ChatColor.AQUA
+ MiscUtil.getRankString(rank) + ChatColor.WHITE + " on the server!";
}
return message;
}
|
diff --git a/src/com/jpii/navalbattle/pavo/grid/EntityManager.java b/src/com/jpii/navalbattle/pavo/grid/EntityManager.java
index ca19926a..b57755b7 100644
--- a/src/com/jpii/navalbattle/pavo/grid/EntityManager.java
+++ b/src/com/jpii/navalbattle/pavo/grid/EntityManager.java
@@ -1,345 +1,345 @@
/*
* Copyright (C) 2012 JPII and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jpii.navalbattle.pavo.grid;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
import com.jpii.navalbattle.pavo.Chunk;
import com.jpii.navalbattle.pavo.Game;
import com.jpii.navalbattle.pavo.PavoHelper;
import com.jpii.navalbattle.pavo.World;
import com.jpii.navalbattle.pavo.io.PavoImage;
public class EntityManager implements Serializable {
private static final long serialVersionUID = 1L;
private byte[][] tileAccessor;
private transient World w;
private ArrayList<Integer> entityRegister;
private ArrayList<Entity> entities;
public GridedEntityTileOrientation battleShipId;
public GridedEntityTileOrientation acarrierId;
public GridedEntityTileOrientation submarineId;
public GridedEntityTileOrientation submarineUId;
int counter = 0;
/**
* Creates a new entity manager for the desired world.
* @param w The world to create the entity manager.
*/
public EntityManager(World w) {
this.w = w;
tileAccessor = new byte[PavoHelper.getGameWidth(w.getWorldSize())*2][PavoHelper.getGameHeight(w.getWorldSize())*2];
entities = new ArrayList<Entity>();
PavoImage grid = new PavoImage(50,50,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = PavoHelper.createGraphics(grid);
g.setColor(Game.Settings.GridColor);
g.drawRect(1,1,49,49);
try {
IndexableImage.populateStore(0, grid);
}
catch (Exception ex) {}
g.dispose();
entityRegister = new ArrayList<Integer>();
entityRegister.add(0);
}
public boolean isReadyForGen() {
if (tileAccessor == null)
return false;
return true;
}
public void update(long ticksPassed) {
}
public Entity getEntity(int index) {
return entities.get(index);
}
public void removeEntity(Entity e) {
entities.remove(e);
}
public void removeEntity(int index) {
entities.remove(index);
}
/**
* DO NOT CALL INDIVIDUALLY
* @param e The entity.
*/
public void addEntity(Entity e) {
if (e == null)
return;
entities.add(e);
}
public int getTotalEntities() {
return entities.size();
}
/**
* Gets the chunk associated with the given entity location.
* @param r The row of the entity.
* @param c The column of the entity.
* @return The chunk. Will return null if the desired location is out of bounds.
*/
public Chunk getAssociatedChunk(int r, int c) {
if (c >= PavoHelper.getGameWidth(w.getWorldSize())*2 ||
r >= PavoHelper.getGameHeight(w.getWorldSize())*2 || c < 0 || r < 0)
return null;
return w.getChunk(c/2,r/2);
}
public Chunk getAssociatedChunk(Location loc) {
if (loc.getCol() >= PavoHelper.getGameWidth(w.getWorldSize())*2 ||
loc.getRow() >= PavoHelper.getGameHeight(w.getWorldSize())*2 || loc.getCol() < 0 || loc.getRow() < 0)
return null;
return w.getChunk(loc.getCol()/2,loc.getRow()/2);
}
/**
* Sets the entity at the desired location.
* @param <T>
* @param r The row the entity should be at.
* @param c The column the entity should be at.
* @param e The entity to replace it with.
*/
public void setTile(int r, int c, Tile<Entity> t) {
if (c >= PavoHelper.getGameWidth(w.getWorldSize())*2 ||
r >= PavoHelper.getGameHeight(w.getWorldSize())*2 || c < 0 || r < 0)
return;
int x = c/2;
int z = r/2;
Chunk chunk = w.getChunk(x, z);
int rx = c % 2;
int rz = r % 2;
if (rx == 0 && rz == 0)
chunk.Tile00 = t;
else if (rx != 0 && rz == 0)
chunk.Tile10 = t;
else if (rx == 0 && rz != 0)
chunk.Tile01 = t;
else if (rx != 0 && rz != 0)
chunk.Tile11 = t;
chunk.writeBuffer();
}
public void setTileOverlay(int r, int c, byte color) {
if (c >= PavoHelper.getGameWidth(w.getWorldSize())*2 ||
r >= PavoHelper.getGameHeight(w.getWorldSize())*2 || c < 0 || r < 0)
return;
int x = c/2;
int z = r/2;
Chunk chunk = w.getChunk(x, z);
int rx = c % 2;
int rz = r % 2;
if (rx == 0 && rz == 0)
chunk.Overlay00 = color;
else if (rx != 0 && rz == 0)
chunk.Overlay10 = color;
else if (rx == 0 && rz != 0)
chunk.Overlay01 = color;
else if (rx != 0 && rz != 0)
chunk.Overlay11 = color;
chunk.writeBuffer();
}
public Entity findEntity(int r, int c) {
if (r >= 0 && c >= 0 && c < PavoHelper.getGameWidth(getWorld().getWorldSize()) * 2
&& r < PavoHelper.getGameHeight(getWorld().getWorldSize()) * 2) {
Chunk chuck = PavoHelper.convertGridLocationToChunk(getWorld(), new Location(r,c));
if (chuck == null)
return null;
// if (chuck.Tile00 != null && chuck.Tile00.parent != null)
// return chuck.Tile00.parent;
// else if (chuck.Tile10 != null && chuck.Tile10.parent != null)
// return chuck.Tile10.parent;
// else if (chuck.Tile01 != null && chuck.Tile01.parent != null)
// return chuck.Tile01.parent;
// else if (chuck.Tile11 != null && chuck.Tile11.parent != null)
// return chuck.Tile11.parent;
// else {
// return null;
// }
int rrr = r % 2;
int rrc = c % 2;
- if (rrr == 0 && rrc == 0)
+ if (rrr == 0 && rrc == 0 && chuck.Tile00 != null)
return chuck.Tile00.parent;
- else if (rrr == 0 && rrc != 0)
+ else if (rrr == 0 && rrc != 0 && chuck.Tile10 != null)
return chuck.Tile10.parent;
- else if (rrr != 0 && rrc == 0)
+ else if (rrr != 0 && rrc == 0 && chuck.Tile01 != null)
return chuck.Tile01.parent;
- else if (rrc != 0 && rrr != 0)
+ else if (rrc != 0 && rrr != 0 && chuck.Tile11 != null)
return chuck.Tile11.parent;
else
return null;
}
return null;
}
public <T> void setTile(Location loc, Tile<Entity> t) {
setTile(loc.getRow(),loc.getCol(),t);
}
public Tile<Entity> getTile(Location loc) {
return getTile(loc.getRow(),loc.getCol());
}
public Tile<Entity> getTile(int r, int c) {
if (c >= PavoHelper.getGameWidth(w.getWorldSize())*2 ||
r >= PavoHelper.getGameHeight(w.getWorldSize())*2 || c < 0 || r < 0)
return null;
int x = c/2;
int z = r/2;
Chunk chunk = w.getChunk(x, z);
if (chunk == null)
return null;
int rx = c % 2;
int rz = r % 2;
if (c == 0)
rx = 0;
if (c == 1)
rx = 1;
if (r == 0)
rz = 0;
if (r == 1)
rz = 1;
if (rx == 0 && rz == 0)
return chunk.Tile00;
else if (rx != 0 && rz == 0)
return chunk.Tile10;
else if (rx == 0 && rz != 0)
return chunk.Tile01;
else if (rx != 0 && rz != 0)
return chunk.Tile11;
return null;
}
/**
* Determines whether the selected tile is filled with water.
* @param r The row of the tile.
* @param c The column of the tile.
* @return
*/
public boolean isTileFilledWithWater(int r, int c) {
if (r < 0 || r >= PavoHelper.getGameHeight(w.getWorldSize())*2 || c < 0 || c >= PavoHelper.getGameWidth(w.getWorldSize())*2)
return false;
return tileAccessor[c][r] <= Game.Settings.waterThresholdBarrier;
}
/**
* Gets the amount of land in the given tile.
* @param r The row of the tile.
* @param c The column of the tile.
* @return
*/
public int getTilePercentLand(int r, int c) {
if (r < 0 || c < 0 || r >= PavoHelper.getGameHeight(getWorld().getWorldSize())*2
|| c >= PavoHelper.getGameWidth(getWorld().getWorldSize())*2)
return 0;
return tileAccessor[c][r];
}
public static int lastid = 0;
public <T> int registerEntity(BufferedImage horizontalImage,byte orientation) {
int swap = lastid + 1;
if (orientation == GridedEntityTileOrientation.ORIENTATION_LEFTTORIGHT) {
for (int w = 0; w < horizontalImage.getWidth() / 50; w++) {
BufferedImage ab = PavoHelper.imgUtilFastCrop(horizontalImage, w * 50, 0, 50, 50);
IndexableImage.populateStore(new Id(swap,w).getMutexId(), ab);
}
}
else if (orientation == GridedEntityTileOrientation.ORIENTATION_TOPTOBOTTOM) {
for (int h = 0; h < horizontalImage.getHeight() / 50; h++) {
BufferedImage ab = PavoHelper.imgUtilFastCrop(horizontalImage,0, h * 50, 50, 50);
IndexableImage.populateStore(new Id(swap,h).getMutexId(), ab);
}
}
lastid = swap;
return lastid;
}
/**
* Finds all non-null entities of a particular type.
* Use it like:
* <code>
* BattleShip[] bs = getEntityManager().<BattleShip>findEntities();
* </code>
* @return
*/
public <T> T[] findEntities() {
ArrayList<T> ern = new ArrayList<T>();
for (int c = 0; c < getTotalEntities(); c++) {
Entity ef = getEntity(c);
if (ef != null) {
T tcast = null;
try {
tcast = (T)ef;
}
catch (Throwable t) {
}
if (tcast != null)
ern.add(tcast);
}
}
return (T[])ern.toArray();
}
public Entity findEntity(String tag) {
for (int c = 0; c < getTotalEntities(); c++) {
Entity ef = getEntity(c);
if (ef != null && ef.getTag().equals(tag)) {
return ef;
}
}
return null;
}
public Entity[] findEntities(int id) {
ArrayList<Entity> ferns = new ArrayList<Entity>();
for (int c = 0; c < getTotalEntities(); c++) {
Entity ef = getEntity(c);
if (ef != null && ef.getCurrentId() == id) {
ferns.add(ef);
}
}
return (Entity[])ferns.toArray();
}
public final BufferedImage getImage(Tile<Entity> tile) {
if (tile == null)
return IndexableImage.getImage(0);
return IndexableImage.getImage(tile.getId().getMutexId());
}
public void gameDoneGenerating() {
}
/**
* Don't play with this.
* @param snJMkqmd Don't play with this.
* @param cKQK91nm38910JNFEWo Don't play with this.
* @param traKQ91 Don't play with this.
*/
public void AQms03KampOQ9103nmJMs(int snJMkqmd, int cKQK91nm38910JNFEWo, int traKQ91) {
byte b = (byte)((traKQ91 * 100)/272);
if (b > 100)
b = 100;
if (b < 0)
b = 0;
if (b == 94)
b = 100;
if (tileAccessor == null)
tileAccessor = new byte[PavoHelper.getGameWidth(w.getWorldSize())*2][PavoHelper.getGameHeight(w.getWorldSize())*2];
tileAccessor[cKQK91nm38910JNFEWo][snJMkqmd] = b;
}
/**
* Get the world instance for the Entity Manager.
* @return
*/
public World getWorld() {
return w;
}
}
| false | true | public Entity findEntity(int r, int c) {
if (r >= 0 && c >= 0 && c < PavoHelper.getGameWidth(getWorld().getWorldSize()) * 2
&& r < PavoHelper.getGameHeight(getWorld().getWorldSize()) * 2) {
Chunk chuck = PavoHelper.convertGridLocationToChunk(getWorld(), new Location(r,c));
if (chuck == null)
return null;
// if (chuck.Tile00 != null && chuck.Tile00.parent != null)
// return chuck.Tile00.parent;
// else if (chuck.Tile10 != null && chuck.Tile10.parent != null)
// return chuck.Tile10.parent;
// else if (chuck.Tile01 != null && chuck.Tile01.parent != null)
// return chuck.Tile01.parent;
// else if (chuck.Tile11 != null && chuck.Tile11.parent != null)
// return chuck.Tile11.parent;
// else {
// return null;
// }
int rrr = r % 2;
int rrc = c % 2;
if (rrr == 0 && rrc == 0)
return chuck.Tile00.parent;
else if (rrr == 0 && rrc != 0)
return chuck.Tile10.parent;
else if (rrr != 0 && rrc == 0)
return chuck.Tile01.parent;
else if (rrc != 0 && rrr != 0)
return chuck.Tile11.parent;
else
return null;
}
return null;
}
| public Entity findEntity(int r, int c) {
if (r >= 0 && c >= 0 && c < PavoHelper.getGameWidth(getWorld().getWorldSize()) * 2
&& r < PavoHelper.getGameHeight(getWorld().getWorldSize()) * 2) {
Chunk chuck = PavoHelper.convertGridLocationToChunk(getWorld(), new Location(r,c));
if (chuck == null)
return null;
// if (chuck.Tile00 != null && chuck.Tile00.parent != null)
// return chuck.Tile00.parent;
// else if (chuck.Tile10 != null && chuck.Tile10.parent != null)
// return chuck.Tile10.parent;
// else if (chuck.Tile01 != null && chuck.Tile01.parent != null)
// return chuck.Tile01.parent;
// else if (chuck.Tile11 != null && chuck.Tile11.parent != null)
// return chuck.Tile11.parent;
// else {
// return null;
// }
int rrr = r % 2;
int rrc = c % 2;
if (rrr == 0 && rrc == 0 && chuck.Tile00 != null)
return chuck.Tile00.parent;
else if (rrr == 0 && rrc != 0 && chuck.Tile10 != null)
return chuck.Tile10.parent;
else if (rrr != 0 && rrc == 0 && chuck.Tile01 != null)
return chuck.Tile01.parent;
else if (rrc != 0 && rrr != 0 && chuck.Tile11 != null)
return chuck.Tile11.parent;
else
return null;
}
return null;
}
|
diff --git a/app/controllers/Checkins.java b/app/controllers/Checkins.java
index 037a445..b6a754b 100644
--- a/app/controllers/Checkins.java
+++ b/app/controllers/Checkins.java
@@ -1,58 +1,58 @@
package controllers;
import java.lang.reflect.Constructor;
import java.util.Calendar;
import java.util.List;
import models.BorrowItem;
import models.Item;
import models.ItemStatus;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import utils.Globals;
import controllers.CRUD.ObjectType;
import flexjson.JSONSerializer;
public class Checkins extends CRUD{
public static void blank() throws Exception {
render("Checkins/scanItem.html");
}
public static void checkin(String[] itemBarcodeScanned) throws Exception {
}
public static void scanItem(String barcode) throws Exception {
//
//TODO: Lookup the barcode from the borrowed material.
List<BorrowItem> items = BorrowItem.find("item.barcode = ?", barcode).fetch();
int numberFound = items.size();
if (numberFound==1) { /* found the exact item */
BorrowItem borrowItem = items.get(0);
//Save the returned date
borrowItem.returnedDate = Calendar.getInstance().getTime();
borrowItem.save();
Item item = borrowItem.item;
String info = toJson(item);
//Change the status of the Item
ItemStatus shelfStatus = ItemStatus.find("code = ?", Globals.ItemStatus_Shelf).first();
item.itemStatus = shelfStatus;
item.save();
renderJSON(info);
} else if (numberFound==0) { /* found nothing */
- response.status = 700;
+ response.status = Globals.Error_Item_FoundNothing;
} else { /* more than one items found */
- response.status = 710;
+ response.status = Globals.Error_Item_FoundMoreThanOne;
}
}
private static String toJson(Item item) {
JSONSerializer borrowedItemSerializer = new JSONSerializer().include("barcode", "name").exclude("*");
String json = borrowedItemSerializer.serialize(item);
return json;
}
}
| false | true | public static void scanItem(String barcode) throws Exception {
//
//TODO: Lookup the barcode from the borrowed material.
List<BorrowItem> items = BorrowItem.find("item.barcode = ?", barcode).fetch();
int numberFound = items.size();
if (numberFound==1) { /* found the exact item */
BorrowItem borrowItem = items.get(0);
//Save the returned date
borrowItem.returnedDate = Calendar.getInstance().getTime();
borrowItem.save();
Item item = borrowItem.item;
String info = toJson(item);
//Change the status of the Item
ItemStatus shelfStatus = ItemStatus.find("code = ?", Globals.ItemStatus_Shelf).first();
item.itemStatus = shelfStatus;
item.save();
renderJSON(info);
} else if (numberFound==0) { /* found nothing */
response.status = 700;
} else { /* more than one items found */
response.status = 710;
}
}
| public static void scanItem(String barcode) throws Exception {
//
//TODO: Lookup the barcode from the borrowed material.
List<BorrowItem> items = BorrowItem.find("item.barcode = ?", barcode).fetch();
int numberFound = items.size();
if (numberFound==1) { /* found the exact item */
BorrowItem borrowItem = items.get(0);
//Save the returned date
borrowItem.returnedDate = Calendar.getInstance().getTime();
borrowItem.save();
Item item = borrowItem.item;
String info = toJson(item);
//Change the status of the Item
ItemStatus shelfStatus = ItemStatus.find("code = ?", Globals.ItemStatus_Shelf).first();
item.itemStatus = shelfStatus;
item.save();
renderJSON(info);
} else if (numberFound==0) { /* found nothing */
response.status = Globals.Error_Item_FoundNothing;
} else { /* more than one items found */
response.status = Globals.Error_Item_FoundMoreThanOne;
}
}
|
diff --git a/src/ru/yaal/project/hhapi/dictionary/DictionaryException.java b/src/ru/yaal/project/hhapi/dictionary/DictionaryException.java
index fd67212..a21b9b2 100644
--- a/src/ru/yaal/project/hhapi/dictionary/DictionaryException.java
+++ b/src/ru/yaal/project/hhapi/dictionary/DictionaryException.java
@@ -1,15 +1,15 @@
package ru.yaal.project.hhapi.dictionary;
import static java.lang.String.format;
public class DictionaryException extends Exception {
private static final long serialVersionUID = -8329654964740843540L;
public DictionaryException(Exception e) {
- super(e);
+ super(e.getMessage(), e);
}
public DictionaryException(String message, Object... args) {
super(format(message, args));
}
}
| true | true | public DictionaryException(Exception e) {
super(e);
}
| public DictionaryException(Exception e) {
super(e.getMessage(), e);
}
|
diff --git a/src/main/java/org/testng/reporters/TextReporter.java b/src/main/java/org/testng/reporters/TextReporter.java
index 805cc7f1..7d14fba5 100644
--- a/src/main/java/org/testng/reporters/TextReporter.java
+++ b/src/main/java/org/testng/reporters/TextReporter.java
@@ -1,180 +1,180 @@
package org.testng.reporters;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.internal.Utils;
import java.util.List;
/**
* A simple reporter that collects the results and prints them on standard out.
*
* @author <a href="mailto:[email protected]">Cedric Beust</a>
* @author <a href='mailto:[email protected]'>Alexandru Popescu</a>
*/
public class TextReporter extends TestListenerAdapter {
private int m_verbose = 0;
private String m_testName = null;
public TextReporter(String testName, int verbose) {
m_testName = testName;
m_verbose = verbose;
}
@Override
public void onFinish(ITestContext context) {
if (m_verbose >= 2) {
logResults();
}
}
private ITestNGMethod[] resultsToMethods(List<ITestResult> results) {
ITestNGMethod[] result = new ITestNGMethod[results.size()];
int i = 0;
for (ITestResult tr : results) {
result[i++] = tr.getMethod();
}
return result;
}
private void logResults() {
//
// Log Text
//
for(Object o : getConfigurationFailures()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
stackTrace,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getConfigurationSkips()) {
ITestResult tr = (ITestResult) o;
logResult("SKIPPED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
null,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getPassedTests()) {
ITestResult tr = (ITestResult) o;
logResult("PASSED", tr, null);
}
for(Object o : getFailedTests()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED", tr, stackTrace);
}
for(Object o : getSkippedTests()) {
ITestResult tr = (ITestResult) o;
- logResult("SKIPPED", tr, null);
+ logResult("SKIPPED", tr, Utils.stackTrace(tr.getThrowable(), false)[0]);
}
ITestNGMethod[] ft = resultsToMethods(getFailedTests());
StringBuffer logBuf= new StringBuffer("\n===============================================\n");
logBuf.append(" ").append(m_testName).append("\n");
logBuf.append(" Tests run: ").append(Utils.calculateInvokedMethodCount(getAllTestMethods()))
.append(", Failures: ").append(Utils.calculateInvokedMethodCount(ft))
.append(", Skips: ").append(Utils.calculateInvokedMethodCount(resultsToMethods(getSkippedTests())));
int confFailures= getConfigurationFailures().size();
int confSkips= getConfigurationSkips().size();
if(confFailures > 0 || confSkips > 0) {
logBuf.append("\n").append(" Configuration Failures: ").append(confFailures)
.append(", Skips: ").append(confSkips);
}
logBuf.append("\n===============================================\n");
logResult("", logBuf.toString());
}
private String getName() {
return m_testName;
}
private void logResult(String status, ITestResult tr, String stackTrace) {
logResult(status, tr.getName(), tr.getMethod().getDescription(), stackTrace,
tr.getParameters(), tr.getMethod().getMethod().getParameterTypes());
}
private void logResult(String status, String message) {
StringBuffer buf= new StringBuffer();
if(!"".equals(status)) {
buf.append(status).append(": ");
}
buf.append(message);
System.out.println(buf);
}
private void logResult(String status, String name,
String description, String stackTrace,
Object[] params, Class[] paramTypes) {
StringBuffer msg= new StringBuffer(name);
if(null != params && params.length > 0) {
msg.append("(");
// The error might be a data provider parameter mismatch, so make
// a special case here
if (params.length != paramTypes.length) {
msg.append(name + ": Wrong number of arguments were passed by " +
"the Data Provider: found " + params.length + " but " +
"expected " + paramTypes.length
+ ")");
}
else {
for(int i= 0; i < params.length; i++) {
if(i > 0) {
msg.append(", ");
}
msg.append(Utils.toString(params[i], paramTypes[i]));
}
msg.append(")");
}
}
if (! Utils.isStringEmpty(description)) {
msg.append("\n");
for (int i = 0; i < status.length() + 2; i++) {
msg.append(" ");
}
msg.append(description);
}
if ( ! Utils.isStringEmpty(stackTrace)) {
msg.append("\n").append(stackTrace);
}
logResult(status, msg.toString());
}
public void ppp(String s) {
System.out.println("[TextReporter " + getName() + "] " + s);
}
}
| true | true | private void logResults() {
//
// Log Text
//
for(Object o : getConfigurationFailures()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
stackTrace,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getConfigurationSkips()) {
ITestResult tr = (ITestResult) o;
logResult("SKIPPED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
null,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getPassedTests()) {
ITestResult tr = (ITestResult) o;
logResult("PASSED", tr, null);
}
for(Object o : getFailedTests()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED", tr, stackTrace);
}
for(Object o : getSkippedTests()) {
ITestResult tr = (ITestResult) o;
logResult("SKIPPED", tr, null);
}
ITestNGMethod[] ft = resultsToMethods(getFailedTests());
StringBuffer logBuf= new StringBuffer("\n===============================================\n");
logBuf.append(" ").append(m_testName).append("\n");
logBuf.append(" Tests run: ").append(Utils.calculateInvokedMethodCount(getAllTestMethods()))
.append(", Failures: ").append(Utils.calculateInvokedMethodCount(ft))
.append(", Skips: ").append(Utils.calculateInvokedMethodCount(resultsToMethods(getSkippedTests())));
int confFailures= getConfigurationFailures().size();
int confSkips= getConfigurationSkips().size();
if(confFailures > 0 || confSkips > 0) {
logBuf.append("\n").append(" Configuration Failures: ").append(confFailures)
.append(", Skips: ").append(confSkips);
}
logBuf.append("\n===============================================\n");
logResult("", logBuf.toString());
}
| private void logResults() {
//
// Log Text
//
for(Object o : getConfigurationFailures()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
stackTrace,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getConfigurationSkips()) {
ITestResult tr = (ITestResult) o;
logResult("SKIPPED CONFIGURATION",
Utils.detailedMethodName(tr.getMethod(), false),
tr.getMethod().getDescription(),
null,
tr.getParameters(),
tr.getMethod().getMethod().getParameterTypes()
);
}
for(Object o : getPassedTests()) {
ITestResult tr = (ITestResult) o;
logResult("PASSED", tr, null);
}
for(Object o : getFailedTests()) {
ITestResult tr = (ITestResult) o;
Throwable ex = tr.getThrowable();
String stackTrace= "";
if (ex != null) {
if (m_verbose >= 2) {
stackTrace= Utils.stackTrace(ex, false)[0];
}
}
logResult("FAILED", tr, stackTrace);
}
for(Object o : getSkippedTests()) {
ITestResult tr = (ITestResult) o;
logResult("SKIPPED", tr, Utils.stackTrace(tr.getThrowable(), false)[0]);
}
ITestNGMethod[] ft = resultsToMethods(getFailedTests());
StringBuffer logBuf= new StringBuffer("\n===============================================\n");
logBuf.append(" ").append(m_testName).append("\n");
logBuf.append(" Tests run: ").append(Utils.calculateInvokedMethodCount(getAllTestMethods()))
.append(", Failures: ").append(Utils.calculateInvokedMethodCount(ft))
.append(", Skips: ").append(Utils.calculateInvokedMethodCount(resultsToMethods(getSkippedTests())));
int confFailures= getConfigurationFailures().size();
int confSkips= getConfigurationSkips().size();
if(confFailures > 0 || confSkips > 0) {
logBuf.append("\n").append(" Configuration Failures: ").append(confFailures)
.append(", Skips: ").append(confSkips);
}
logBuf.append("\n===============================================\n");
logResult("", logBuf.toString());
}
|
diff --git a/src/de/uni_koblenz/jgralab/utilities/tg2dot/greql2/funlib/OmegaIncidenceNumber.java b/src/de/uni_koblenz/jgralab/utilities/tg2dot/greql2/funlib/OmegaIncidenceNumber.java
index 0a1908058..7ad3d02f6 100644
--- a/src/de/uni_koblenz/jgralab/utilities/tg2dot/greql2/funlib/OmegaIncidenceNumber.java
+++ b/src/de/uni_koblenz/jgralab/utilities/tg2dot/greql2/funlib/OmegaIncidenceNumber.java
@@ -1,58 +1,58 @@
/*
* JGraLab - The Java Graph Laboratory
*
* Copyright (C) 2006-2011 Institute for Software Technology
* University of Koblenz-Landau, Germany
* [email protected]
*
* For bug reports, documentation and further information, visit
*
* http://jgralab.uni-koblenz.de
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with Eclipse (or a modified version of that program or an Eclipse
* plugin), containing parts covered by the terms of the Eclipse Public
* License (EPL), the licensors of this Program grant you additional
* permission to convey the resulting work. Corresponding Source for a
* non-source form of such a combination shall include the source code for
* the parts of JGraLab used as well as that of the covered work.
*/
package de.uni_koblenz.jgralab.utilities.tg2dot.greql2.funlib;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.greql2.funlib.Function;
public class OmegaIncidenceNumber extends Function {
public OmegaIncidenceNumber() {
super(
"Returns the omega incidence number of the given edge starting with 1.",
2, 1, 1.0, Category.GRAPH);
}
public Integer evaluate(Edge edge) {
int num = 1;
for (Edge incidence : edge.getOmega().incidences()) {
- if (incidence.getNormalEdge() == edge) {
+ if (incidence.getReversedEdge() == edge) {
return num;
}
num++;
}
return null;
}
}
| true | true | public Integer evaluate(Edge edge) {
int num = 1;
for (Edge incidence : edge.getOmega().incidences()) {
if (incidence.getNormalEdge() == edge) {
return num;
}
num++;
}
return null;
}
| public Integer evaluate(Edge edge) {
int num = 1;
for (Edge incidence : edge.getOmega().incidences()) {
if (incidence.getReversedEdge() == edge) {
return num;
}
num++;
}
return null;
}
|
diff --git a/src/main/java/pt/ua/tm/neji/writer/JSONWriter.java b/src/main/java/pt/ua/tm/neji/writer/JSONWriter.java
index 3bb55b4..c628da0 100644
--- a/src/main/java/pt/ua/tm/neji/writer/JSONWriter.java
+++ b/src/main/java/pt/ua/tm/neji/writer/JSONWriter.java
@@ -1,163 +1,163 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.ua.tm.neji.writer;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import monq.jfa.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pt.ua.tm.gimli.corpus.AnnotationID;
import pt.ua.tm.gimli.corpus.Corpus;
import pt.ua.tm.gimli.corpus.Sentence;
import pt.ua.tm.gimli.exception.GimliException;
import pt.ua.tm.gimli.tree.TreeNode;
import pt.ua.tm.neji.core.Tagger;
import pt.ua.tm.neji.global.Char;
import pt.ua.tm.neji.writer.json.JSONEntry;
import pt.ua.tm.neji.writer.json.JSONSentence;
import pt.ua.tm.neji.writer.json.JSONTerm;
/**
*
* @author david
*/
public class JSONWriter extends Tagger {
/**
* {@link Logger} to be used in the class.
*/
private static Logger logger = LoggerFactory.getLogger(JSONWriter.class);
private Corpus corpus;
private int sentenceCounter;
private int offset;
private List<JSONSentence> json;
public JSONWriter(final Corpus corpus) throws GimliException {
super();
this.corpus = corpus;
this.sentenceCounter = 0;
this.offset = 0;
this.json = new ArrayList<JSONSentence>();
try {
Nfa nfa = new Nfa(Nfa.NOTHING);
nfa.or(Xml.GoofedElement("s"), end_sentence);
this.dfa = nfa.compile(DfaRun.UNMATCHED_COPY, eof);
} catch (CompileDfaException ex) {
throw new GimliException("There was a problem compiling the Dfa to process the document.", ex);
} catch (ReSyntaxException ex) {
throw new GimliException("There is a syntax problem with the document.", ex);
}
}
private AbstractFaAction eof = new AbstractFaAction() {
@Override
public void invoke(StringBuffer yytext, int start, DfaRun runner) {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String jsonText = gson.toJson(json);
String jsonText = new Gson().toJson(json);
yytext.replace(0, yytext.length(), jsonText);
runner.collect = false;
}
};
private AbstractFaAction end_sentence = new AbstractFaAction() {
@Override
public void invoke(StringBuffer yytext, int start, DfaRun runner) {
// Get start and end of sentence
int startSentence = yytext.indexOf("<s id=");
int endSentence = yytext.lastIndexOf("</s>") + 4;
int realStart = yytext.indexOf(">", startSentence) + 1;
int realEnd = endSentence - 4;
// Get sentence with XML tags
String sentence = yytext.substring(realStart, realEnd);
// Get respective sentence from corpus
Sentence s = corpus.getSentence(sentenceCounter);
//Remove sentence tags and escape XML
- sentence = sentence.replaceAll("\\<.*?>", "");
+// sentence = sentence.replaceAll("\\<.*?>", "");
//sentence = StringEscapeUtils.escapeXml(sentence);
yytext.replace(startSentence, endSentence, sentence);
// Get final start and end of sentence
int startChar = offset + yytext.indexOf(sentence);
int endChar = startChar + sentence.length();
// Generate sentence on stand-off format
JSONSentence js = new JSONSentence(sentenceCounter + 1,
startChar, endChar - 1,
sentence);
getAnnotations(s, sentence, js, startChar);
json.add(js);
// Remove processed input from input
yytext.replace(0, endSentence, "");
// Change state variables
sentenceCounter++;
offset = endChar;
runner.collect = true;
}
};
private void getAnnotations(Sentence s, String source, JSONSentence js, int offset) {
getAnnotations(s.getAnnotationsTree().getRoot(), source, js, 0, 0, 1, offset);
}
private void getAnnotations(TreeNode<AnnotationID> node, String source, JSONEntry j, int level, int counter, int subcounter, int offset) {
JSONEntry je;
if (level != 0) {
// Add result to StringBuilder
int id;
if (level <= 1) {
id = counter;
} else {
id = subcounter;
}
AnnotationID data = node.getData();
Sentence s = data.getSentence();
int startAnnotationInSentence = s.getToken(data.getStartIndex()).getStartSource();
int endAnnotationInSentence = s.getToken(data.getEndIndex()).getEndSource() + 1;
int startChar = offset + startAnnotationInSentence;
int endChar = offset + endAnnotationInSentence;
JSONTerm jt = new JSONTerm(id, startChar,
endChar, source.substring(startAnnotationInSentence, endAnnotationInSentence).trim(),
data.getStringIDs());
j.addTerm(jt);
je = jt;
} else {
je = j;
}
int i = 0;
for (TreeNode<AnnotationID> child : node.getChildren()) {
getAnnotations(child, source, je, level + 1, ++counter, ++i, offset);
}
}
}
| true | true | public void invoke(StringBuffer yytext, int start, DfaRun runner) {
// Get start and end of sentence
int startSentence = yytext.indexOf("<s id=");
int endSentence = yytext.lastIndexOf("</s>") + 4;
int realStart = yytext.indexOf(">", startSentence) + 1;
int realEnd = endSentence - 4;
// Get sentence with XML tags
String sentence = yytext.substring(realStart, realEnd);
// Get respective sentence from corpus
Sentence s = corpus.getSentence(sentenceCounter);
//Remove sentence tags and escape XML
sentence = sentence.replaceAll("\\<.*?>", "");
//sentence = StringEscapeUtils.escapeXml(sentence);
yytext.replace(startSentence, endSentence, sentence);
// Get final start and end of sentence
int startChar = offset + yytext.indexOf(sentence);
int endChar = startChar + sentence.length();
// Generate sentence on stand-off format
JSONSentence js = new JSONSentence(sentenceCounter + 1,
startChar, endChar - 1,
sentence);
getAnnotations(s, sentence, js, startChar);
json.add(js);
// Remove processed input from input
yytext.replace(0, endSentence, "");
// Change state variables
sentenceCounter++;
offset = endChar;
runner.collect = true;
}
| public void invoke(StringBuffer yytext, int start, DfaRun runner) {
// Get start and end of sentence
int startSentence = yytext.indexOf("<s id=");
int endSentence = yytext.lastIndexOf("</s>") + 4;
int realStart = yytext.indexOf(">", startSentence) + 1;
int realEnd = endSentence - 4;
// Get sentence with XML tags
String sentence = yytext.substring(realStart, realEnd);
// Get respective sentence from corpus
Sentence s = corpus.getSentence(sentenceCounter);
//Remove sentence tags and escape XML
// sentence = sentence.replaceAll("\\<.*?>", "");
//sentence = StringEscapeUtils.escapeXml(sentence);
yytext.replace(startSentence, endSentence, sentence);
// Get final start and end of sentence
int startChar = offset + yytext.indexOf(sentence);
int endChar = startChar + sentence.length();
// Generate sentence on stand-off format
JSONSentence js = new JSONSentence(sentenceCounter + 1,
startChar, endChar - 1,
sentence);
getAnnotations(s, sentence, js, startChar);
json.add(js);
// Remove processed input from input
yytext.replace(0, endSentence, "");
// Change state variables
sentenceCounter++;
offset = endChar;
runner.collect = true;
}
|
diff --git a/modules/spigot-core/src/main/java/org/fluttercode/spigot/provider/file/CommaDelimitedProvider.java b/modules/spigot-core/src/main/java/org/fluttercode/spigot/provider/file/CommaDelimitedProvider.java
index bc3beb3..f1a305a 100644
--- a/modules/spigot-core/src/main/java/org/fluttercode/spigot/provider/file/CommaDelimitedProvider.java
+++ b/modules/spigot-core/src/main/java/org/fluttercode/spigot/provider/file/CommaDelimitedProvider.java
@@ -1,124 +1,127 @@
/*
* Copyright 2010, Andrew M Gibson
*
* www.andygibson.net
*
* This file is part of Spigot.
*
* Spigot is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Spigot is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
*
* You should have received a copy of the GNU Lesser General Public License
* along with Spigot. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.fluttercode.spigot.provider.file;
import java.util.Arrays;
import java.util.Collections;
/**
* Provider that returns data from a comma delimited file using a
* {@link ColumnarRowMapper} instance to convert an array of string values into
* an object.
*
* @author Andy Gibson
*
*/
public class CommaDelimitedProvider<T> extends TextFileProvider<T> {
private static final long serialVersionUID = 1L;
private int paddingLength = 0;
private ColumnarRowMapper<T> rowMapper;
public CommaDelimitedProvider(String filename,
ColumnarRowMapper<T> rowMapper) {
super(filename);
this.rowMapper = rowMapper;
}
public CommaDelimitedProvider(String filename) {
this(filename, null);
}
@Override
protected T createObjectFromLine(String line) {
String[] columns = padToLength(line.split(","));
return createObjectFromColumns(columns);
}
/**
* Creates a new instance of a data object and populates it with the data
* from the columns array.
*
* @param columns
* List of column values
* @return new instance of data object built from the columns values
*/
private T createObjectFromColumns(String[] columns) {
T result = doCreateObjectFromColumns(columns);
+ if (result != null) {
+ return result;
+ }
if (rowMapper == null) {
throw new NullPointerException(
"Rowmapper in comma delimited provider is unassigned");
- }
+ }
return rowMapper.mapRow(columns);
}
/**
* Method to create an instance of data from the column array of string.
* Default implementation returns null but this method can be overriden in
* subclasses to allow for extension using inheritance as opposed to
* extendision using the {@link CommaDelimitedProvider#rowMapper} attribute.
*
* @param columns
* Array of columns
* @return an instance of T built from the columnar data. If null is
* returned, then the rowmapper is used to create the entity.
*/
protected T doCreateObjectFromColumns(String[] columns) {
return null;
}
/**
* Takes an array of columns and pads it with nulls until it has a certain
* length.
*
* @param split
* array of columns
* @return padded array of columns
*/
private String[] padToLength(String[] split) {
if (paddingLength < split.length) {
return split;
}
return Arrays.copyOf(split, paddingLength);
}
public void setPaddingLength(int paddingLength) {
this.paddingLength = paddingLength;
}
public int getPaddingLength() {
return paddingLength;
}
public ColumnarRowMapper<T> getRowMapper() {
return rowMapper;
}
public void setRowMapper(ColumnarRowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
}
}
| false | true | private T createObjectFromColumns(String[] columns) {
T result = doCreateObjectFromColumns(columns);
if (rowMapper == null) {
throw new NullPointerException(
"Rowmapper in comma delimited provider is unassigned");
}
return rowMapper.mapRow(columns);
}
| private T createObjectFromColumns(String[] columns) {
T result = doCreateObjectFromColumns(columns);
if (result != null) {
return result;
}
if (rowMapper == null) {
throw new NullPointerException(
"Rowmapper in comma delimited provider is unassigned");
}
return rowMapper.mapRow(columns);
}
|
diff --git a/src/main/java/de/tudarmstadt/ukp/teaching/uima/nounDecompounding/evaluation/RankingEvaluation.java b/src/main/java/de/tudarmstadt/ukp/teaching/uima/nounDecompounding/evaluation/RankingEvaluation.java
index 10eb90e..c778fb2 100644
--- a/src/main/java/de/tudarmstadt/ukp/teaching/uima/nounDecompounding/evaluation/RankingEvaluation.java
+++ b/src/main/java/de/tudarmstadt/ukp/teaching/uima/nounDecompounding/evaluation/RankingEvaluation.java
@@ -1,304 +1,304 @@
/**
* Copyright (c) 2010 Jens Haase <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.tudarmstadt.ukp.teaching.uima.nounDecompounding.evaluation;
import java.io.IOException;
import java.util.List;
import de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.IRankList;
import de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.IRankListAndTree;
import de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.IRankTree;
import de.tudarmstadt.ukp.teaching.uima.nounDecompounding.splitter.ISplitAlgorithm;
import de.tudarmstadt.ukp.teaching.uima.nounDecompounding.splitter.Split;
/**
* Evaluation class for ranking algorithms
* @author Jens Haase <[email protected]>
*/
public class RankingEvaluation {
private CcorpusReader reader;
/**
* Stores the result of a evaluation
* @author Jens Haase <[email protected]>
*/
public class Result {
public float recall;
public float recallWithoutMorpheme;
public float recallAt2;
public float recallAt2WithoutMorpheme;
public float recallAt3;
public float recallAt3WithoutMorpheme;
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("Result:\n");
buf.append("\tCorrect: "+recall+" (without Morpheme: " +recallWithoutMorpheme+")\n");
buf.append("\tCorrect@2: "+recallAt2+" (without Morpheme: " +recallAt2WithoutMorpheme+")\n");
buf.append("\tCorrect@3: "+recallAt3+" (without Morpheme: " +recallAt3WithoutMorpheme+")");
return buf.toString();
}
}
public RankingEvaluation(CcorpusReader aReader) {
this.reader = aReader;
}
/**
* Evaluates a IRankList algorithm, with a given split algorithm
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @param limit How many splits should be evaluated
* @return
*/
public Result evaluateList(ISplitAlgorithm splitter, IRankList ranker, int limit) {
int total = 0, correct = 0, correctWithoutMorpheme = 0,
correctAt2 = 0, correctAt2WithoutMorpheme = 0,
correctAt3 = 0, correctAt3WithoutMorpheme = 0;
try {
Split split;
List<Split> result;
while ((split = reader.readSplit()) != null && total < limit) {
result = ranker.rank(splitter.split(split.getWord()).getAllSplits());
if (!result.get(0).equals(split)) {
System.out.println(total + ": " + split + " -> " + result.get(0) + " " + this.getResultList(result));
}
if (result.get(0).equals(split)) {
correct++; correctAt2++; correctAt3++;
} else if (result.size() > 2 && result.get(1).equals(split)) {
correctAt2++; correctAt3++;
} else if (result.size() > 3 && result.get(2).equals(split)) {
correctAt3++;
}
if (result.get(0).equalWithoutMorpheme(split)) {
correctWithoutMorpheme++; correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (result.size() > 2 && result.get(1).equalWithoutMorpheme(split)) {
correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (result.size() > 3 && result.get(2).equalWithoutMorpheme(split)) {
correctAt3WithoutMorpheme++;
}
total++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result r = new Result();
r.recall = (float) correct / (float) total;
r.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
r.recallAt2 = (float) correctAt2 / (float) total;
r.recallAt2WithoutMorpheme = (float) correctAt2WithoutMorpheme / (float) total;
r.recallAt3 = (float) correctAt3 / (float) total;
r.recallAt3WithoutMorpheme = (float) correctAt3WithoutMorpheme / (float) total;
return r;
}
/**
* Evaluates a IRankTree algorithm
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @param limit How many splits should be evaluated
* @return
*/
public Result evaluateTree(ISplitAlgorithm splitter, IRankTree ranker, int limit) {
int total = 0, correct = 0, correctWithoutMorpheme = 0;
try {
Split split, result;
while ((split = reader.readSplit()) != null && total < limit) {
result = ranker.highestRank((splitter.split(split.getWord())));
if (result.equals(split)) {
correct++;
} else {
System.out.println(total + ": " + split + " -> " + result);
}
if (result.equalWithoutMorpheme(split)) {
correctWithoutMorpheme++;
}
total++;
}
} catch (IOException e) {
e.printStackTrace();
}
Result r = new Result();
r.recall = (float) correct / (float) total;
r.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
return r;
}
/**
* Evaluates a IRankListAndTree algorithm, with a given split algorithm
*
* This is mostly the same as evaluteList and evaluteTree. But each
* word is evaluted directly by both method. This has the advantage
* that the cache contains the result and calculation is faster.
*
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @param limit How many splits should be evaluated
* @return A array of result with size 2. The first entry is the result for the list, second for the tree
*/
public Result[] evaluateListAndTree(ISplitAlgorithm splitter, IRankListAndTree ranker, int limit) {
int total = 0, correct = 0, correctWithoutMorpheme = 0,
correctAt2 = 0, correctAt2WithoutMorpheme = 0,
correctAt3 = 0, correctAt3WithoutMorpheme = 0;
int correctTree = 0, correctTreeWithoutMorpheme = 0;
try {
Split split;
List<Split> resultList;
Split resultTree;
while ((split = reader.readSplit()) != null && total < limit) {
resultList = ranker.rank(splitter.split(split.getWord()).getAllSplits());
// Evaluate List
if (!resultList.get(0).equals(split)) {
System.out.println(total + ": " + split + " -> " + resultList.get(0) + " " + this.getResultList(resultList));
}
if (resultList.get(0).equals(split)) {
correct++; correctAt2++; correctAt3++;
} else if (resultList.size() > 2 && resultList.get(1).equals(split)) {
correctAt2++; correctAt3++;
} else if (resultList.size() > 3 && resultList.get(2).equals(split)) {
correctAt3++;
}
if (resultList.get(0).equalWithoutMorpheme(split)) {
correctWithoutMorpheme++; correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 2 && resultList.get(1).equalWithoutMorpheme(split)) {
correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 3 && resultList.get(2).equalWithoutMorpheme(split)) {
correctAt3WithoutMorpheme++;
}
// Evaluate Tree
resultTree = ranker.highestRank((splitter.split(split.getWord())));
if (resultTree.equals(split)) {
correctTree++;
} else {
System.out.println(total + ": " + split + " -> " + resultTree);
}
if (resultTree.equalWithoutMorpheme(split)) {
correctTreeWithoutMorpheme++;
}
total++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result resultList = new Result();
resultList.recall = (float) correct / (float) total;
resultList.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
resultList.recallAt2 = (float) correctAt2 / (float) total;
resultList.recallAt2WithoutMorpheme = (float) correctAt2WithoutMorpheme / (float) total;
resultList.recallAt3 = (float) correctAt3 / (float) total;
resultList.recallAt3WithoutMorpheme = (float) correctAt3WithoutMorpheme / (float) total;
Result resultTree = new Result();
- resultTree.recall = (float) correct / (float) total;
- resultTree.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
+ resultTree.recall = (float) correctTree / (float) total;
+ resultTree.recallWithoutMorpheme = (float) correctTreeWithoutMorpheme / (float) total;
return new Result[]{resultList, resultTree};
}
/**
* Used to output a list of splits
* @param splits
* @return
*/
private String getResultList(List<Split> splits) {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for (int i = 0; i < splits.size(); i++) {
buffer.append(splits.get(i).toString());
buffer.append(":");
buffer.append(splits.get(i).getWeight());
if (i < splits.size()-1) {
buffer.append(", ");
}
}
buffer.append("]");
return buffer.toString();
}
/**
* Evaluates a IRankList algorithm, with a given split algorithm
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @return
*/
public Result evaluateList(ISplitAlgorithm splitter, IRankList ranker) {
return this.evaluateList(splitter, ranker, Integer.MAX_VALUE);
}
/**
* Evaluates a IRankTree algorithm, with a given split algorithm
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @return
*/
public Result evaluateTree(ISplitAlgorithm splitter, IRankTree ranker) {
return this.evaluateTree(splitter, ranker, Integer.MAX_VALUE);
}
/**
* Evaluates a IRankListAndTree algorithm, with a given split algorithm
*
* This is mostly the same as evaluteList and evaluteTree. But each
* word is evaluted directly by both method. This has the advantage
* that the cache contains the result and calculation is faster.
*
* @param splitter The splitting algorithm
* @param ranker The ranking algorithm
* @return A array of result with size 2. The first entry is the result for the list, second for the tree
*/
public Result[] evaluateListAndTree(ISplitAlgorithm splitter, IRankListAndTree ranker) {
return this.evaluateListAndTree(splitter, ranker, Integer.MAX_VALUE);
}
}
| true | true | public Result[] evaluateListAndTree(ISplitAlgorithm splitter, IRankListAndTree ranker, int limit) {
int total = 0, correct = 0, correctWithoutMorpheme = 0,
correctAt2 = 0, correctAt2WithoutMorpheme = 0,
correctAt3 = 0, correctAt3WithoutMorpheme = 0;
int correctTree = 0, correctTreeWithoutMorpheme = 0;
try {
Split split;
List<Split> resultList;
Split resultTree;
while ((split = reader.readSplit()) != null && total < limit) {
resultList = ranker.rank(splitter.split(split.getWord()).getAllSplits());
// Evaluate List
if (!resultList.get(0).equals(split)) {
System.out.println(total + ": " + split + " -> " + resultList.get(0) + " " + this.getResultList(resultList));
}
if (resultList.get(0).equals(split)) {
correct++; correctAt2++; correctAt3++;
} else if (resultList.size() > 2 && resultList.get(1).equals(split)) {
correctAt2++; correctAt3++;
} else if (resultList.size() > 3 && resultList.get(2).equals(split)) {
correctAt3++;
}
if (resultList.get(0).equalWithoutMorpheme(split)) {
correctWithoutMorpheme++; correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 2 && resultList.get(1).equalWithoutMorpheme(split)) {
correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 3 && resultList.get(2).equalWithoutMorpheme(split)) {
correctAt3WithoutMorpheme++;
}
// Evaluate Tree
resultTree = ranker.highestRank((splitter.split(split.getWord())));
if (resultTree.equals(split)) {
correctTree++;
} else {
System.out.println(total + ": " + split + " -> " + resultTree);
}
if (resultTree.equalWithoutMorpheme(split)) {
correctTreeWithoutMorpheme++;
}
total++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result resultList = new Result();
resultList.recall = (float) correct / (float) total;
resultList.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
resultList.recallAt2 = (float) correctAt2 / (float) total;
resultList.recallAt2WithoutMorpheme = (float) correctAt2WithoutMorpheme / (float) total;
resultList.recallAt3 = (float) correctAt3 / (float) total;
resultList.recallAt3WithoutMorpheme = (float) correctAt3WithoutMorpheme / (float) total;
Result resultTree = new Result();
resultTree.recall = (float) correct / (float) total;
resultTree.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
return new Result[]{resultList, resultTree};
}
| public Result[] evaluateListAndTree(ISplitAlgorithm splitter, IRankListAndTree ranker, int limit) {
int total = 0, correct = 0, correctWithoutMorpheme = 0,
correctAt2 = 0, correctAt2WithoutMorpheme = 0,
correctAt3 = 0, correctAt3WithoutMorpheme = 0;
int correctTree = 0, correctTreeWithoutMorpheme = 0;
try {
Split split;
List<Split> resultList;
Split resultTree;
while ((split = reader.readSplit()) != null && total < limit) {
resultList = ranker.rank(splitter.split(split.getWord()).getAllSplits());
// Evaluate List
if (!resultList.get(0).equals(split)) {
System.out.println(total + ": " + split + " -> " + resultList.get(0) + " " + this.getResultList(resultList));
}
if (resultList.get(0).equals(split)) {
correct++; correctAt2++; correctAt3++;
} else if (resultList.size() > 2 && resultList.get(1).equals(split)) {
correctAt2++; correctAt3++;
} else if (resultList.size() > 3 && resultList.get(2).equals(split)) {
correctAt3++;
}
if (resultList.get(0).equalWithoutMorpheme(split)) {
correctWithoutMorpheme++; correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 2 && resultList.get(1).equalWithoutMorpheme(split)) {
correctAt2WithoutMorpheme++; correctAt3WithoutMorpheme++;
} else if (resultList.size() > 3 && resultList.get(2).equalWithoutMorpheme(split)) {
correctAt3WithoutMorpheme++;
}
// Evaluate Tree
resultTree = ranker.highestRank((splitter.split(split.getWord())));
if (resultTree.equals(split)) {
correctTree++;
} else {
System.out.println(total + ": " + split + " -> " + resultTree);
}
if (resultTree.equalWithoutMorpheme(split)) {
correctTreeWithoutMorpheme++;
}
total++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Result resultList = new Result();
resultList.recall = (float) correct / (float) total;
resultList.recallWithoutMorpheme = (float) correctWithoutMorpheme / (float) total;
resultList.recallAt2 = (float) correctAt2 / (float) total;
resultList.recallAt2WithoutMorpheme = (float) correctAt2WithoutMorpheme / (float) total;
resultList.recallAt3 = (float) correctAt3 / (float) total;
resultList.recallAt3WithoutMorpheme = (float) correctAt3WithoutMorpheme / (float) total;
Result resultTree = new Result();
resultTree.recall = (float) correctTree / (float) total;
resultTree.recallWithoutMorpheme = (float) correctTreeWithoutMorpheme / (float) total;
return new Result[]{resultList, resultTree};
}
|
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestNativeSeqGenerator.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestNativeSeqGenerator.java
index f58194b3f..349a681b4 100644
--- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestNativeSeqGenerator.java
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/generationtype/TestNativeSeqGenerator.java
@@ -1,65 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.persistence.generationtype;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.jdbc.sql.DBDictionary;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.test.SQLListenerTestCase;
public class TestNativeSeqGenerator extends SQLListenerTestCase {
OpenJPAEntityManager em;
JDBCConfiguration conf;
DBDictionary dict;
boolean supportsNativeSequence = false;
EntityE2 entityE2;
@Override
public void setUp() throws Exception {
super.setUp(EntityE2.class,DROP_TABLES);
assertNotNull(emf);
conf = (JDBCConfiguration) emf.getConfiguration();
dict = conf.getDBDictionaryInstance();
supportsNativeSequence = dict.nextSequenceQuery != null;
if (supportsNativeSequence) {
em = emf.createEntityManager();
assertNotNull(em);
}
}
public void createEntityE2() {
entityE2 = new EntityE2("e name");
}
public void testGetIdGeneratorSeqGen() {
if (!supportsNativeSequence) {
System.out.println("Does not support native sequence");
return;
}
createEntityE2();
em.getTransaction().begin();
em.persist(entityE2);
em.getTransaction().commit();
int genId = entityE2.getId();
int nextId = (int)((Long)em.getIdGenerator(EntityE2.class).next()).longValue();
- assertTrue("Next value should depend on previous genid", nextId == genId + 1);
+ assertTrue("Next value should depend on previous genid", nextId >= genId + 1);
em.close();
}
}
| true | true | public void testGetIdGeneratorSeqGen() {
if (!supportsNativeSequence) {
System.out.println("Does not support native sequence");
return;
}
createEntityE2();
em.getTransaction().begin();
em.persist(entityE2);
em.getTransaction().commit();
int genId = entityE2.getId();
int nextId = (int)((Long)em.getIdGenerator(EntityE2.class).next()).longValue();
assertTrue("Next value should depend on previous genid", nextId == genId + 1);
em.close();
}
| public void testGetIdGeneratorSeqGen() {
if (!supportsNativeSequence) {
System.out.println("Does not support native sequence");
return;
}
createEntityE2();
em.getTransaction().begin();
em.persist(entityE2);
em.getTransaction().commit();
int genId = entityE2.getId();
int nextId = (int)((Long)em.getIdGenerator(EntityE2.class).next()).longValue();
assertTrue("Next value should depend on previous genid", nextId >= genId + 1);
em.close();
}
|
diff --git a/wflow-form/src/main/java/org/joget/form/model/dao/DynamicFormDao.java b/wflow-form/src/main/java/org/joget/form/model/dao/DynamicFormDao.java
index 415a350..ad70c56 100644
--- a/wflow-form/src/main/java/org/joget/form/model/dao/DynamicFormDao.java
+++ b/wflow-form/src/main/java/org/joget/form/model/dao/DynamicFormDao.java
@@ -1,332 +1,332 @@
package org.joget.form.model.dao;
import org.joget.form.model.Form;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.joget.form.model.FormMetaData;
import org.springframework.orm.hibernate3.HibernateCallback;
public class DynamicFormDao extends DynamicFormDaoSupport {
public static int STATUS_RUNNING_AND_COMPLETED = 0;
public static int STATUS_RUNNING = 1;
public static int VIEW_PERMISSION_PERSONAL = 0;
public static int VIEW_PERMISSION_ASSIGNED = 1;
public static int VIEW_PERMISSION_ALL = 2;
public Serializable save(Form form) {
String tableName = form.getTableName();
return getHibernateTemplate(tableName, form).save(FORM_ID_PREFIX + tableName, form);
}
public void saveOrUpdateMetaData(FormMetaData formMetaData, String tableName) {
getHibernateTemplate(tableName).saveOrUpdate(FORM_METADATA_ID_PREFIX + tableName, formMetaData);
}
public void saveOrUpdate(Form form) {
String tableName = form.getTableName();
getHibernateTemplate(tableName, form).saveOrUpdate(FORM_ID_PREFIX + tableName, form);
}
public List<Form> loadAllDynamicForm(final String tableName) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_ID_PREFIX + tableName + " e ";
Query q = session.createQuery(query);
return q.list();
}
});
return result;
}
public Form load(String tableName, String id) {
return (Form) getHibernateTemplate(tableName).load(FORM_ID_PREFIX + tableName, id);
}
public List<Form> getAllDynamicFormByFormId(final String formId, final String tableName, final boolean includeDraft) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String condition = "WHERE e.customProperties.formId = ? ";
if (!includeDraft) {
condition += "AND e.customProperties.draft <> 1";
}
String query = "SELECT e FROM " + FORM_ID_PREFIX + tableName + " e " + condition;
Query q = session.createQuery(query);
q.setParameter(0, formId);
return q.list();
}
});
return result;
}
public Form loadDynamicFormByProcessId(final String tableName, final String processId) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_ID_PREFIX + tableName + " e WHERE e.customProperties.processId = ? AND e.customProperties.draft <> ?";
Query q = session.createQuery(query);
q.setParameter(0, processId);
q.setParameter(1, "1");
return q.list();
}
});
if (result.size() > 0) {
return (Form) result.get(0);
} else {
return null;
}
}
public FormMetaData loadDynamicFormMetaDataByActivityId(final String tableName, final String activityId) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_METADATA_ID_PREFIX + tableName + " e WHERE e.activityId = ?";
Query q = session.createQuery(query);
q.setParameter(0, activityId);
return q.list();
}
});
if (result.size() > 0) {
return (FormMetaData) result.get(0);
} else {
return null;
}
}
public FormMetaData loadDynamicFormMetaData(final String tableName, final String id) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_METADATA_ID_PREFIX + tableName + " e WHERE e.id = ?";
Query q = session.createQuery(query);
q.setParameter(0, id);
return q.list();
}
});
if (result.size() > 0) {
return (FormMetaData) result.get(0);
} else {
return null;
}
}
public Form loadDraft(final String tableName, final String processId, final String activityId) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_ID_PREFIX + tableName + " e WHERE e.customProperties.processId = ? AND e.customProperties.activityId = ? AND e.customProperties.draft = ?";
Query q = session.createQuery(query);
q.setParameter(0, processId);
q.setParameter(1, activityId);
q.setParameter(2, "1");
return q.list();
}
});
if (result.size() > 0) {
return (Form) result.get(0);
} else {
return null;
}
}
public void delete(String tableName, Form form) {
getHibernateTemplate(tableName).delete(FORM_ID_PREFIX + tableName, form);
}
public int getMaxValue(final String columnName, final String tableName) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT max(e.customProperties." + columnName + ") FROM " + FORM_ID_PREFIX + tableName + " e";
Query q = session.createQuery(query);
return q.list();
}
});
if (result != null && result.size() > 0) {
return (result.get(0) == null) ? 0 : (Integer) result.get(0);
} else {
return 0;
}
}
public String getActivityIdByDefId(final String tableName, final String dynamicFormId, final String activityDefId){
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT activityId FROM " + FORM_METADATA_ID_PREFIX + tableName + " e WHERE e.dynamicFormId = ? AND e.activityDefId = ? order by e.latest desc";
Query q = session.createQuery(query);
q.setParameter(0, dynamicFormId);
q.setParameter(1, activityDefId);
return q.list();
}
});
if (result != null && result.size() > 0) {
return (result.get(0) == null) ? null : (String) result.get(0);
} else {
return null;
}
}
public List<FormMetaData> loadDynamicFormDataByActivityDefId(final String tableName, final String activityDefId, final String filter, final Collection<String> filterTypes, final int status, final int permType, final String currentUsername, final String sort, final Boolean desc, final Integer start, final Integer rows) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_METADATA_ID_PREFIX + tableName + " e ";
query += "WHERE e.dynamicFormId IS NOT NULL AND e.activityDefId = :activityDefId ";
if (status == STATUS_RUNNING) {
query += "AND e.latest=:status ";
}
if (permType == VIEW_PERMISSION_PERSONAL) {
query += "AND (e.pendingUsers LIKE :pendingUsers OR e.username=:currentUsername) ";
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
query += "AND e.pendingUsers LIKE :pendingUsers ";
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
query += "AND ";
if(filterTypes.size() > 1){
query += "(";
}
for (Iterator<String> i = filterTypes.iterator(); i.hasNext();){
query += "e." + i.next() + " LIKE :filter ";
if(i.hasNext()){
query += "OR ";
}
}
if(filterTypes.size() > 1){
query += ") ";
}
}
if (sort != null && !sort.equals("")) {
- query += "ORDER BY e." + sort;
+ query += "ORDER BY cast(e." + sort + " as string)";
if (desc) {
query += " DESC";
}
}
Query q = session.createQuery(query);
q.setString("activityDefId", activityDefId);
if (status == STATUS_RUNNING) {
q.setInteger("status", status);
}
if (permType == VIEW_PERMISSION_PERSONAL) {
q.setString("currentUsername", currentUsername);
q.setString("pendingUsers", "%," + currentUsername + ",%");
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
q.setString("pendingUsers", "%," + currentUsername + ",%");
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
q.setString("filter", "%" + filter + "%");
}
int s = (start == null) ? 0 : start;
q.setFirstResult(s);
if (rows != null && rows > 0) {
q.setMaxResults(rows);
}
return q.list();
}
});
return result;
}
public Long loadDynamicFormDataByActivityDefIdSize(final String tableName, final String activityDefId, final String filter, final Collection<String> filterTypes, final int status, final int permType, final String currentUsername){
Long count = (Long) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT COUNT(*) FROM " + FORM_METADATA_ID_PREFIX + tableName + " e ";
query += "WHERE e.dynamicFormId IS NOT NULL AND e.activityDefId = :activityDefId ";
if (status == STATUS_RUNNING) {
query += "AND e.latest=:status ";
}
if (permType == VIEW_PERMISSION_PERSONAL) {
query += "AND (e.pendingUsers LIKE :pendingUsers OR e.username=:currentUsername) ";
} else if (permType == VIEW_PERMISSION_ASSIGNED) {
query += "AND e.pendingUsers LIKE :pendingUsers ";
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
query += "AND ";
if(filterTypes.size() > 1){
query += "(";
}
for (Iterator<String> i = filterTypes.iterator(); i.hasNext();){
query += "e." + i.next() + " LIKE :filter ";
if(i.hasNext()){
query += "OR ";
}
}
if(filterTypes.size() > 1){
query += ")";
}
}
Query q = session.createQuery(query);
q.setString("activityDefId", activityDefId);
if (status == STATUS_RUNNING) {
q.setInteger("status", status);
}
if (permType == VIEW_PERMISSION_PERSONAL) {
q.setString("currentUsername", currentUsername);
q.setString("pendingUsers", "%," + currentUsername + ",%");
} else if (permType == VIEW_PERMISSION_ASSIGNED) {
q.setString("pendingUsers", "%," + currentUsername + ",%");
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
q.setString("filter", "%" + filter + "%");
}
return ((Long) q.iterate().next()).longValue();
}
});
return count;
}
}
| true | true | public List<FormMetaData> loadDynamicFormDataByActivityDefId(final String tableName, final String activityDefId, final String filter, final Collection<String> filterTypes, final int status, final int permType, final String currentUsername, final String sort, final Boolean desc, final Integer start, final Integer rows) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_METADATA_ID_PREFIX + tableName + " e ";
query += "WHERE e.dynamicFormId IS NOT NULL AND e.activityDefId = :activityDefId ";
if (status == STATUS_RUNNING) {
query += "AND e.latest=:status ";
}
if (permType == VIEW_PERMISSION_PERSONAL) {
query += "AND (e.pendingUsers LIKE :pendingUsers OR e.username=:currentUsername) ";
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
query += "AND e.pendingUsers LIKE :pendingUsers ";
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
query += "AND ";
if(filterTypes.size() > 1){
query += "(";
}
for (Iterator<String> i = filterTypes.iterator(); i.hasNext();){
query += "e." + i.next() + " LIKE :filter ";
if(i.hasNext()){
query += "OR ";
}
}
if(filterTypes.size() > 1){
query += ") ";
}
}
if (sort != null && !sort.equals("")) {
query += "ORDER BY e." + sort;
if (desc) {
query += " DESC";
}
}
Query q = session.createQuery(query);
q.setString("activityDefId", activityDefId);
if (status == STATUS_RUNNING) {
q.setInteger("status", status);
}
if (permType == VIEW_PERMISSION_PERSONAL) {
q.setString("currentUsername", currentUsername);
q.setString("pendingUsers", "%," + currentUsername + ",%");
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
q.setString("pendingUsers", "%," + currentUsername + ",%");
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
q.setString("filter", "%" + filter + "%");
}
int s = (start == null) ? 0 : start;
q.setFirstResult(s);
if (rows != null && rows > 0) {
q.setMaxResults(rows);
}
return q.list();
}
});
return result;
}
| public List<FormMetaData> loadDynamicFormDataByActivityDefId(final String tableName, final String activityDefId, final String filter, final Collection<String> filterTypes, final int status, final int permType, final String currentUsername, final String sort, final Boolean desc, final Integer start, final Integer rows) {
List result = (List) this.getHibernateTemplate(tableName).execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
String query = "SELECT e FROM " + FORM_METADATA_ID_PREFIX + tableName + " e ";
query += "WHERE e.dynamicFormId IS NOT NULL AND e.activityDefId = :activityDefId ";
if (status == STATUS_RUNNING) {
query += "AND e.latest=:status ";
}
if (permType == VIEW_PERMISSION_PERSONAL) {
query += "AND (e.pendingUsers LIKE :pendingUsers OR e.username=:currentUsername) ";
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
query += "AND e.pendingUsers LIKE :pendingUsers ";
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
query += "AND ";
if(filterTypes.size() > 1){
query += "(";
}
for (Iterator<String> i = filterTypes.iterator(); i.hasNext();){
query += "e." + i.next() + " LIKE :filter ";
if(i.hasNext()){
query += "OR ";
}
}
if(filterTypes.size() > 1){
query += ") ";
}
}
if (sort != null && !sort.equals("")) {
query += "ORDER BY cast(e." + sort + " as string)";
if (desc) {
query += " DESC";
}
}
Query q = session.createQuery(query);
q.setString("activityDefId", activityDefId);
if (status == STATUS_RUNNING) {
q.setInteger("status", status);
}
if (permType == VIEW_PERMISSION_PERSONAL) {
q.setString("currentUsername", currentUsername);
q.setString("pendingUsers", "%," + currentUsername + ",%");
}else if (permType == VIEW_PERMISSION_ASSIGNED) {
q.setString("pendingUsers", "%," + currentUsername + ",%");
}
if(filter != null && filter.trim().length() > 0 && filterTypes != null && filterTypes.size() > 0){
q.setString("filter", "%" + filter + "%");
}
int s = (start == null) ? 0 : start;
q.setFirstResult(s);
if (rows != null && rows > 0) {
q.setMaxResults(rows);
}
return q.list();
}
});
return result;
}
|
diff --git a/src/com/jme/scene/SharedMesh.java b/src/com/jme/scene/SharedMesh.java
index 638c28566..599fadf72 100755
--- a/src/com/jme/scene/SharedMesh.java
+++ b/src/com/jme/scene/SharedMesh.java
@@ -1,585 +1,586 @@
/*
* Copyright (c) 2003-2006 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.scene;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.logging.Level;
import com.jme.math.Ray;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.batch.GeomBatch;
import com.jme.scene.batch.SharedBatch;
import com.jme.scene.state.RenderState;
import com.jme.util.LoggingSystem;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
/**
* <code>SharedMesh</code> allows the sharing of data between multiple nodes.
* A provided TriMesh is used as the model for this node. This allows the user
* to place multiple copies of the same object throughout the scene without
* having to duplicate data. It should be known that any change to the provided
* target mesh will affect the appearance of this mesh, including animations.
* Secondly, the SharedMesh is read only. Any attempt to write to the mesh data
* via set* methods, will result in a warning being logged and nothing else. Any
* changes to the mesh should happened to the target mesh being shared.
* <br>
* If you plan to use collisions with a <code>SharedMesh</code> it is
* recommended that you disable the passing of <code>updateCollisionTree</code>
* calls to the target mesh. This is to prevent multiple calls to the target's
* <code>updateCollisionTree</code> method, from different shared meshes.
* Instead of this method being called from the scenegraph, you can now invoke it
* directly on the target mesh, thus ensuring it will only be invoked once.
* <br>
* <b>Important:</b> It is highly recommended that the Target mesh is NOT
* placed into the scenegraph, as its translation, rotation and scale are
* replaced by the shared meshes using it before they are rendered. <br>
* <b>Note:</b> Special thanks to Kevin Glass.
*
* @author Mark Powell
* @version $id$
*/
public class SharedMesh extends TriMesh {
private static final long serialVersionUID = 1L;
private TriMesh target;
private boolean updatesCollisionTree;
public SharedMesh() {
super();
}
@Override
protected void setupBatchList() {
batchList = new ArrayList<GeomBatch>();
batchCount = 0;
}
/**
* Constructor creates a new <code>SharedMesh</code> object.
*
* @param name
* the name of this shared mesh.
* @param target
* the TriMesh to share the data.
*/
public SharedMesh(String name, TriMesh target) {
this(name, target, true);
}
/**
* Constructor creates a new <code>SharedMesh</code> object.
*
* @param name
* the name of this shared mesh.
* @param target
* the TriMesh to share the data.
* @param updatesCollisionTree
* Sets wether calls to <code>updateCollisionTree</code> of this
* </code>SharedMesh</code> will be passed to the target Mesh.
*/
public SharedMesh(String name, TriMesh target, boolean updatesCollisionTree) {
super(name);
setUpdatesCollisionTree(updatesCollisionTree);
if((target.getType() & SceneElement.SHARED_MESH) != 0) {
setTarget(((SharedMesh)target).getTarget());
} else {
setTarget(target);
}
this.localRotation.set(target.getLocalRotation());
this.localScale.set(target.getLocalScale());
this.localTranslation.set(target.getLocalTranslation());
}
public int getType() {
return (SceneElement.GEOMETRY | SceneElement.TRIMESH | SceneElement.SHARED_MESH);
}
/**
* <code>setTarget</code> sets the shared data mesh.
*
* @param target
* the TriMesh to share the data.
*/
public void setTarget(TriMesh target) {
this.target = target;
for (int i = 0; i < RenderState.RS_MAX_STATE; i++) {
RenderState renderState = this.target.getRenderState( i );
if (renderState != null) {
setRenderState(renderState );
}
}
+ batchList.clear();
for (int x = 0; x < target.batchCount; x++) {
SharedBatch batch = new SharedBatch(target.getBatch(x));
batch.setParentGeom(this);
batchList.add(batch);
}
batchCount = batchList.size();
setCullMode(target.cullMode);
setLightCombineMode(target.lightCombineMode);
setRenderQueueMode(target.renderQueueMode);
setTextureCombineMode(target.textureCombineMode);
setZOrder(target.getZOrder());
}
/**
* <code>getTarget</code> returns the mesh that is being shared by
* this object.
* @return the mesh being shared.
*/
public TriMesh getTarget() {
return target;
}
/**
* <code>reconstruct</code> is not supported in SharedMesh.
*
* @param vertices
* the new vertices to use.
* @param normals
* the new normals to use.
* @param colors
* the new colors to use.
* @param textureCoords
* the new texture coordinates to use (position 0).
*/
public void reconstruct(FloatBuffer vertices, FloatBuffer normals,
FloatBuffer colors, FloatBuffer textureCoords) {
LoggingSystem.getLogger().log(Level.INFO, "SharedMesh will ignore reconstruct.");
}
/**
* <code>setVBOInfo</code> is not supported in SharedMesh.
*/
public void setVBOInfo(VBOInfo info) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
public void setVBOInfo(int batchIndex, VBOInfo info) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>getVBOInfo</code> returns the target mesh's vbo info.
*/
public VBOInfo getVBOInfo(int batchIndex) {
return target.getBatch(batchIndex).getVBOInfo();
}
/**
*
* <code>setSolidColor</code> is not supported by SharedMesh.
*
* @param color
* the color to set.
*/
public void setSolidColor(ColorRGBA color) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>setRandomColors</code> is not supported by SharedMesh.
*/
public void setRandomColors() {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>getVertexBuffer</code> returns the float buffer that
* contains the target geometry's vertex information.
*
* @return the float buffer that contains the target geometry's vertex
* information.
*/
public FloatBuffer getVertexBuffer(int batchIndex) {
return target.getVertexBuffer(batchIndex);
}
/**
* <code>setVertexBuffer</code> is not supported by SharedMesh.
*
* @param buff
* the new vertex buffer.
*/
public void setVertexBuffer(int batchIndex, FloatBuffer buff) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* Returns the number of vertexes defined in the target's Geometry object.
*
* @return The number of vertexes in the target Geometry object.
*/
public int getTotalVertices() {
return target.getTotalVertices();
}
/**
* <code>getNormalBuffer</code> retrieves the target geometry's normal
* information as a float buffer.
*
* @return the float buffer containing the target geometry information.
*/
public FloatBuffer getNormalBuffer(int batchIndex) {
return target.getNormalBuffer(batchIndex);
}
/**
* <code>setNormalBuffer</code> is not supported by SharedMesh.
*
* @param buff
* the new normal buffer.
*/
public void setNormalBuffer(int batchIndex, FloatBuffer buff) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>getColorBuffer</code> retrieves the float buffer that
* contains the target geometry's color information.
*
* @return the buffer that contains the target geometry's color information.
*/
public FloatBuffer getColorBuffer(int batchIndex) {
return target.getColorBuffer(batchIndex);
}
/**
* <code>setColorBuffer</code> is not supported by SharedMesh.
*
* @param buff
* the new color buffer.
*/
public void setColorBuffer(int batchIndex, FloatBuffer buff) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
*
* <code>getIndexAsBuffer</code> retrieves the target's indices array as an
* <code>IntBuffer</code>.
*
* @return the indices array as an <code>IntBuffer</code>.
*/
public IntBuffer getIndexBuffer(int batchIndex) {
return target.getIndexBuffer(batchIndex);
}
/**
*
* <code>setIndexBuffer</code> is not supported by SharedMesh.
*
* @param indices
* the index array as an IntBuffer.
*/
public void setIndexBuffer(int batchIndex, IntBuffer indices) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* Stores in the <code>storage</code> array the indices of triangle
* <code>i</code>. If <code>i</code> is an invalid index, or if
* <code>storage.length<3</code>, then nothing happens
*
* @param i
* The index of the triangle to get.
* @param storage
* The array that will hold the i's indexes.
*/
public void getTriangle(int i, int[] storage) {
target.getTriangle(i, storage);
}
public void getTriangle(int batchIndex, int i, int[] storage) {
target.getTriangle(batchIndex, i, storage);
}
/**
* Stores in the <code>vertices</code> array the vertex values of triangle
* <code>i</code>. If <code>i</code> is an invalid triangle index,
* nothing happens.
*
* @param i
* @param vertices
*/
public void getTriangle(int i, Vector3f[] vertices) {
target.getTriangle(i, vertices);
}
/**
* Returns the number of triangles the target TriMesh contains.
*
* @return The current number of triangles.
*/
public int getTotalTriangles() {
return target.getTotalTriangles();
}
/**
*
* <code>copyTextureCoords</code> is not supported by SharedMesh.
*
* @param fromIndex
* the coordinates to copy.
* @param toIndex
* the texture unit to set them to.
*/
public void copyTextureCoords(int batchIndex, int fromIndex, int toIndex) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>getTextureBuffers</code> retrieves the target geometry's texture
* information contained within a float buffer array.
*
* @return the float buffers that contain the target geometry's texture
* information.
*/
public FloatBuffer[] getTextureBuffers(int batchIndex) {
return target.getTextureBuffers(batchIndex);
}
/**
*
* <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a
* given texture unit.
*
* @param textureUnit
* the texture unit to check.
* @return the texture coordinates at the given texture unit.
*/
public FloatBuffer getTextureBuffer(int batchIndex, int textureUnit) {
return target.getTextureBuffer(batchIndex, textureUnit);
}
/**
* retrieves the mesh as triangle vertices of the target mesh.
*/
public Vector3f[] getMeshAsTrianglesVertices(int batchIndex, Vector3f[] verts) {
return target.getMeshAsTrianglesVertices(batchIndex, verts);
}
/**
* <code>setTextureBuffer</code> is not supported by SharedMesh.
*
* @param buff
* the new vertex buffer.
*/
public void setTextureBuffer(int batchIndex, FloatBuffer buff) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* <code>setTextureBuffer</code> not supported by SharedMesh
*
* @param buff
* the new vertex buffer.
*/
public void setTextureBuffer(int batchIndex, FloatBuffer buff, int position) {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* clearBuffers is not supported by SharedMesh
*/
public void clearBuffers() {
LoggingSystem.getLogger().log(Level.WARNING, "SharedMesh does not allow the manipulation" +
"of the the mesh data.");
}
/**
* generates the collision tree of the target mesh. It's recommended that you call
* updateCollisionTree on the original mesh directly.
*/
public void updateCollisionTree() {
if (updatesCollisionTree)
target.updateCollisionTree();
}
/**
* draw renders the target mesh, at the translation, rotation and scale of
* this shared mesh.
*
* @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer)
*/
public void draw(Renderer r) {
SharedBatch batch;
for (int i = 0, cSize = getBatchCount(); i < cSize; i++) {
batch = getBatch(i);
if (batch != null)
batch.onDraw(r);
}
}
public SharedBatch getBatch(int index) {
return (SharedBatch) batchList.get(index);
}
/**
* This function checks for intersection between the target trimesh and the given
* one. On the first intersection, true is returned.
*
* @param toCheck
* The intersection testing mesh.
* @return True if they intersect.
*/
public boolean hasTriangleCollision(TriMesh toCheck) {
target.setLocalTranslation(worldTranslation);
target.setLocalRotation(worldRotation);
target.setLocalScale(worldScale);
target.updateWorldBound();
return target.hasTriangleCollision(toCheck);
}
/**
* This function finds all intersections between this trimesh and the
* checking one. The intersections are stored as Integer objects of Triangle
* indexes in each of the parameters.
*
* @param toCheck
* The TriMesh to check.
* @param thisIndex
* The array of triangle indexes intersecting in this mesh.
* @param otherIndex
* The array of triangle indexes intersecting in the given mesh.
*/
public void findTriangleCollision(TriMesh toCheck, int batchIndex1, int batchIndex2, ArrayList<Integer> thisIndex,
ArrayList<Integer> otherIndex) {
target.setLocalTranslation(worldTranslation);
target.setLocalRotation(worldRotation);
target.setLocalScale(worldScale);
target.updateWorldBound();
target.findTriangleCollision(toCheck, batchIndex1, batchIndex2, thisIndex, otherIndex);
}
/**
*
* <code>findTrianglePick</code> determines the triangles of the target trimesh
* that are being touched by the ray. The indices of the triangles are
* stored in the provided ArrayList.
*
* @param toTest
* the ray to test.
* @param results
* the indices to the triangles.
*/
public void findTrianglePick(Ray toTest, ArrayList<Integer> results, int batchIndex) {
target.setLocalTranslation(worldTranslation);
target.setLocalRotation(worldRotation);
target.setLocalScale(worldScale);
target.updateWorldBound();
target.findTrianglePick(toTest, results, batchIndex);
}
/**
* <code>getUpdatesCollisionTree</code> returns wether calls to
* <code>updateCollisionTree</code> will be passed to the target mesh.
*
* @return true if these method calls are forwared.
*/
public boolean getUpdatesCollisionTree() {
return updatesCollisionTree;
}
/**
* code>setUpdatesCollisionTree</code> sets wether calls to
* <code>updateCollisionTree</code> are passed to the target mesh.
*
* @param updatesCollisionTree
* true to enable.
*/
public void setUpdatesCollisionTree(boolean updatesCollisionTree) {
this.updatesCollisionTree = updatesCollisionTree;
}
public void swapBatches(int index1, int index2) {
GeomBatch b2 = (GeomBatch) target.batchList.get(index2);
GeomBatch b1 = (GeomBatch) target.batchList.remove(index1);
target.batchList.add(index1, b2);
target.batchList.remove(index2);
target.batchList.add(index2, b1);
}
public void write(JMEExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(target, "target", null);
capsule.write(updatesCollisionTree, "updatesCollisionTree", false);
super.write(e);
}
public void read(JMEImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
target = (TriMesh)capsule.readSavable("target", null);
updatesCollisionTree = capsule.readBoolean("updatesCollisionTree", false);
super.read(e);
}
@Override
public void lockMeshes(Renderer r) {
target.lockMeshes(r);
}
/**
* @see Geometry#randomVertice(Vector3f)
*/
public Vector3f randomVertex(Vector3f fill) {
return target.randomVertex(fill);
}
}
| true | true | public void setTarget(TriMesh target) {
this.target = target;
for (int i = 0; i < RenderState.RS_MAX_STATE; i++) {
RenderState renderState = this.target.getRenderState( i );
if (renderState != null) {
setRenderState(renderState );
}
}
for (int x = 0; x < target.batchCount; x++) {
SharedBatch batch = new SharedBatch(target.getBatch(x));
batch.setParentGeom(this);
batchList.add(batch);
}
batchCount = batchList.size();
setCullMode(target.cullMode);
setLightCombineMode(target.lightCombineMode);
setRenderQueueMode(target.renderQueueMode);
setTextureCombineMode(target.textureCombineMode);
setZOrder(target.getZOrder());
}
| public void setTarget(TriMesh target) {
this.target = target;
for (int i = 0; i < RenderState.RS_MAX_STATE; i++) {
RenderState renderState = this.target.getRenderState( i );
if (renderState != null) {
setRenderState(renderState );
}
}
batchList.clear();
for (int x = 0; x < target.batchCount; x++) {
SharedBatch batch = new SharedBatch(target.getBatch(x));
batch.setParentGeom(this);
batchList.add(batch);
}
batchCount = batchList.size();
setCullMode(target.cullMode);
setLightCombineMode(target.lightCombineMode);
setRenderQueueMode(target.renderQueueMode);
setTextureCombineMode(target.textureCombineMode);
setZOrder(target.getZOrder());
}
|
diff --git a/modello-plugins/modello-plugin-plexus-registry/src/test/java/org/codehaus/modello/plugin/registry/AbstractRegistryGeneratorTestCase.java b/modello-plugins/modello-plugin-plexus-registry/src/test/java/org/codehaus/modello/plugin/registry/AbstractRegistryGeneratorTestCase.java
index 5a5a4f84..eddcf3db 100644
--- a/modello-plugins/modello-plugin-plexus-registry/src/test/java/org/codehaus/modello/plugin/registry/AbstractRegistryGeneratorTestCase.java
+++ b/modello-plugins/modello-plugin-plexus-registry/src/test/java/org/codehaus/modello/plugin/registry/AbstractRegistryGeneratorTestCase.java
@@ -1,91 +1,95 @@
package org.codehaus.modello.plugin.registry;
/*
* Copyright (c) 2007, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.AbstractModelloGeneratorTest;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloParameterConstants;
import org.codehaus.modello.core.ModelloCore;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelValidationException;
import org.codehaus.plexus.compiler.CompilerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.ReaderFactory;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
public abstract class AbstractRegistryGeneratorTestCase
extends AbstractModelloGeneratorTest
{
public AbstractRegistryGeneratorTestCase( String name )
{
super( name );
}
protected void prepareTest( String outputType )
throws ComponentLookupException, ModelloException, ModelValidationException, IOException, CompilerException
{
ModelloCore modello = (ModelloCore) container.lookup( ModelloCore.ROLE );
Model model = modello.loadModel( ReaderFactory.newXmlReader( getTestFile( "src/test/resources/model.mdo" ) ) );
File generatedSources = getTestFile( "target/" + outputType + "/sources" );
File classes = getTestFile( "target/" + outputType + "/classes" );
FileUtils.deleteDirectory( generatedSources );
FileUtils.deleteDirectory( classes );
generatedSources.mkdirs();
classes.mkdirs();
Properties parameters = new Properties();
parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, generatedSources.getAbsolutePath() );
parameters.setProperty( ModelloParameterConstants.VERSION, "1.0.0" );
parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( false ) );
modello.generate( model, "java", parameters );
modello.generate( model, outputType, parameters );
addDependency( "org.codehaus.modello", "modello-core", getModelloVersion() );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-api", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-commons", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus", "plexus-container-default", "1.0-alpha-30" );
addDependency( "commons-collections", "commons-collections", "3.1" );
addDependency( "commons-configuration", "commons-configuration", "1.3" );
addDependency( "commons-lang", "commons-lang", "2.1" );
addDependency( "commons-logging", "commons-logging-api", "1.0.4" );
- addDependency( "xerces", "xercesImpl", "2.9.1" );
+ if ( "1.5".compareTo( System.getProperty( "java.specification.version" ) ) <= 0 )
+ {
+ // causes a conflict with JDK 1.4 => add this dependency only with JDK 1.5+
+ addDependency( "xerces", "xercesImpl", "2.9.1" );
+ }
compile( generatedSources, classes );
}
}
| true | true | protected void prepareTest( String outputType )
throws ComponentLookupException, ModelloException, ModelValidationException, IOException, CompilerException
{
ModelloCore modello = (ModelloCore) container.lookup( ModelloCore.ROLE );
Model model = modello.loadModel( ReaderFactory.newXmlReader( getTestFile( "src/test/resources/model.mdo" ) ) );
File generatedSources = getTestFile( "target/" + outputType + "/sources" );
File classes = getTestFile( "target/" + outputType + "/classes" );
FileUtils.deleteDirectory( generatedSources );
FileUtils.deleteDirectory( classes );
generatedSources.mkdirs();
classes.mkdirs();
Properties parameters = new Properties();
parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, generatedSources.getAbsolutePath() );
parameters.setProperty( ModelloParameterConstants.VERSION, "1.0.0" );
parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( false ) );
modello.generate( model, "java", parameters );
modello.generate( model, outputType, parameters );
addDependency( "org.codehaus.modello", "modello-core", getModelloVersion() );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-api", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-commons", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus", "plexus-container-default", "1.0-alpha-30" );
addDependency( "commons-collections", "commons-collections", "3.1" );
addDependency( "commons-configuration", "commons-configuration", "1.3" );
addDependency( "commons-lang", "commons-lang", "2.1" );
addDependency( "commons-logging", "commons-logging-api", "1.0.4" );
addDependency( "xerces", "xercesImpl", "2.9.1" );
compile( generatedSources, classes );
}
| protected void prepareTest( String outputType )
throws ComponentLookupException, ModelloException, ModelValidationException, IOException, CompilerException
{
ModelloCore modello = (ModelloCore) container.lookup( ModelloCore.ROLE );
Model model = modello.loadModel( ReaderFactory.newXmlReader( getTestFile( "src/test/resources/model.mdo" ) ) );
File generatedSources = getTestFile( "target/" + outputType + "/sources" );
File classes = getTestFile( "target/" + outputType + "/classes" );
FileUtils.deleteDirectory( generatedSources );
FileUtils.deleteDirectory( classes );
generatedSources.mkdirs();
classes.mkdirs();
Properties parameters = new Properties();
parameters.setProperty( ModelloParameterConstants.OUTPUT_DIRECTORY, generatedSources.getAbsolutePath() );
parameters.setProperty( ModelloParameterConstants.VERSION, "1.0.0" );
parameters.setProperty( ModelloParameterConstants.PACKAGE_WITH_VERSION, Boolean.toString( false ) );
modello.generate( model, "java", parameters );
modello.generate( model, outputType, parameters );
addDependency( "org.codehaus.modello", "modello-core", getModelloVersion() );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-api", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus.registry", "plexus-registry-commons", "1.0-alpha-2" );
addDependency( "org.codehaus.plexus", "plexus-container-default", "1.0-alpha-30" );
addDependency( "commons-collections", "commons-collections", "3.1" );
addDependency( "commons-configuration", "commons-configuration", "1.3" );
addDependency( "commons-lang", "commons-lang", "2.1" );
addDependency( "commons-logging", "commons-logging-api", "1.0.4" );
if ( "1.5".compareTo( System.getProperty( "java.specification.version" ) ) <= 0 )
{
// causes a conflict with JDK 1.4 => add this dependency only with JDK 1.5+
addDependency( "xerces", "xercesImpl", "2.9.1" );
}
compile( generatedSources, classes );
}
|
diff --git a/org.knime.knip.imagej3d.base/src/org/knime/knip/imagej3d/ImageJ3DTableCellView.java b/org.knime.knip.imagej3d.base/src/org/knime/knip/imagej3d/ImageJ3DTableCellView.java
index 4bca959..48bd48b 100644
--- a/org.knime.knip.imagej3d.base/src/org/knime/knip/imagej3d/ImageJ3DTableCellView.java
+++ b/org.knime.knip.imagej3d.base/src/org/knime/knip/imagej3d/ImageJ3DTableCellView.java
@@ -1,487 +1,488 @@
/*
* ------------------------------------------------------------------------
*
* Copyright (C) 2003 - 2014
* University of Konstanz, Germany and
* KNIME GmbH, Konstanz, Germany
* Website: http://www.knime.org; Email: [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
* Hence, KNIME and ECLIPSE are both independent programs and are not
* derived from each other. Should, however, the interpretation of the
* GNU GPL Version 3 ("License") under any applicable laws result in
* KNIME and ECLIPSE being a combined program, KNIME GMBH herewith grants
* you the additional permission to use and propagate KNIME together with
* ECLIPSE with only the license terms in place for ECLIPSE applying to
* ECLIPSE and the GNU GPL Version 3 applying for KNIME, provided the
* license terms of ECLIPSE themselves allow for the respective use and
* propagation of ECLIPSE together with KNIME.
*
* Additional permission relating to nodes for KNIME that extend the Node
* Extension (and in particular that are based on subclasses of NodeModel,
* NodeDialog, and NodeView) and that only interoperate with KNIME through
* standard APIs ("Nodes"):
* Nodes are deemed to be separate and independent programs and to not be
* covered works. Notwithstanding anything to the contrary in the
* License, the License does not apply to Nodes, you are not required to
* license Nodes under the License, and you are granted a license to
* prepare and propagate Nodes, in each case even if such Nodes are
* propagated with or for interoperation with KNIME. The owner of a Node
* may freely choose the license terms applicable to such Node, including
* when such Node is propagated with or for interoperation with KNIME.
* --------------------------------------------------------------------- *
*
*/
package org.knime.knip.imagej3d;
import ij.ImagePlus;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij3d.Content;
import ij3d.ContentConstants;
import ij3d.Image3DUniverse;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingWorker;
import javax.swing.ToolTipManager;
import net.imglib2.converter.Converter;
import net.imglib2.meta.ImgPlus;
import net.imglib2.ops.operation.Operations;
import net.imglib2.ops.operation.iterableinterval.unary.MinMax;
import net.imglib2.ops.operation.real.unary.Normalize;
import net.imglib2.type.Type;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.ValuePair;
import org.knime.core.data.DataValue;
import org.knime.core.node.NodeLogger;
import org.knime.core.node.config.ConfigRO;
import org.knime.core.node.config.ConfigWO;
import org.knime.knip.base.data.img.ImgPlusValue;
import org.knime.knip.base.nodes.view.TableCellView;
import org.knime.knip.core.util.waitingindicator.WaitingIndicatorUtils;
import org.knime.knip.core.util.waitingindicator.libs.WaitIndicator;
import org.knime.knip.imagej2.core.util.ImageProcessorFactory;
import org.knime.knip.imagej2.core.util.ImgToIJ;
import view4d.Timeline;
import view4d.TimelineGUI;
/**
* Helper class for the ImageJ 3D Viewer, which provides the TableCellView.
*
* @author <a href="mailto:[email protected]">Gabriel Einsdorf</a>
*/
public class ImageJ3DTableCellView<T extends RealType<T>> implements
TableCellView {
private NodeLogger m_logger = NodeLogger
.getLogger(ImageJ3DTableCellView.class);
// Default rendering Type
private final int m_renderType = ContentConstants.VOLUME;
// 4D stuff
private Timeline m_timeline;
private TimelineGUI m_timelineGUI;
private JPanel m_panel4D = new JPanel();
// rendering Universe
private Image3DUniverse m_universe;
private Component m_universePanel;
// Container for the converted picture,
private ImagePlus m_ijImagePlus;
// ui containers
private JPanel m_rootPanel;
// Stores the Image that the viewer displays
private DataValue m_dataValue;
/**
*
* @return the immage the viewer is displaying
*/
public final DataValue getDataValue() {
return m_dataValue;
}
// Container for picture
private Content m_c;
// Creates a viewer which will be updated on "updateComponent"
@Override
public final Component getViewComponent() {
// Fixes Canvas covering menu
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
// Container for the viewComponent
m_rootPanel = new JPanel(new BorderLayout());
m_rootPanel.setVisible(true);
return m_rootPanel;
}
/**
* flushes the cache and updates the Component.
*
* @param valueToView
* TheImgPlus that is to be displayed by the viewer.
*/
protected final void fullReload(final DataValue valueToView) {
m_dataValue = null;
m_rootPanel.remove(m_universePanel);
updateComponent(valueToView);
}
/**
* updates the Component, called whenever a new picture is selected, or the
* view is reset.
*
* @param valueToView
* The ImgPlus that is to be displayed by the viewer.
*/
@SuppressWarnings("unchecked")
@Override
public final void updateComponent(final DataValue valueToView) {
if (m_dataValue == null || !(m_dataValue.equals(valueToView))) {
// reference to the current object so it can be reached in the
// worker.
final ImageJ3DTableCellView<T> context = this;
showError(m_rootPanel, null, false);
WaitingIndicatorUtils.setWaiting(m_rootPanel, true);
final SwingWorker<ImgPlus<T>, Integer> worker = new SwingWorker<ImgPlus<T>, Integer>() {
@Override
protected ImgPlus<T> doInBackground() throws Exception {
// universe for rendering the image
m_universe = new Image3DUniverse();
m_timeline = m_universe.getTimeline();
// Menubar
final ImageJ3DMenubar<T> ij3dbar = new ImageJ3DMenubar<T>(
m_universe, context);
// add menubar and 3Duniverse to the panel
m_rootPanel.add(ij3dbar, BorderLayout.NORTH);
// New image arrives
m_universe.resetView();
m_universe.removeAllContents(); // cleanup universe
m_dataValue = valueToView;
final ImgPlus<T> in = ((ImgPlusValue<T>) valueToView)
.getImgPlus();
// abort if input image has to few dimensions.
if (in.numDimensions() < 3) {
showError(
m_rootPanel,
new String[] {
"Only images with a minimum of three dimensions",
" are supported by the ImageJ 3D Viewer." },
true);
return null;
}
// abort if input image has to many dimensions.
if (in.numDimensions() > 5) {
showError(m_rootPanel, new String[] {
"Only images with up to five dimensions",
"are supported by the 3D Viewer." }, true);
return null;
}
// abort if unsuported type
if (in.firstElement() instanceof DoubleType) {
showError(
m_rootPanel,
new String[] {
"DoubleType images are not supported!",
" You have to convert your image to e.g. ByteType using the converter." },
true);
return null;
}
// validate if mapping can be inferred automatically
if (!ImgToIJ.validateMapping(in)) {
showError(
m_rootPanel,
new String[] { "Warning: The input image contains unknown dimensions. Currently we only support 'X','Y','Channel,'Z' and 'Time'!" },
true);
return null;
}
// here we create an converted ImagePlus
m_ijImagePlus = createImagePlus(in);
try {
// select the rendertype
switch (m_renderType) {
case ContentConstants.ORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
break;
case ContentConstants.MULTIORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
m_c.displayAs(ContentConstants.MULTIORTHO);
case ContentConstants.VOLUME:
m_c = m_universe.addVoltex(m_ijImagePlus);
break;
case ContentConstants.SURFACE:
m_c = m_universe.addMesh(m_ijImagePlus);
break;
case ContentConstants.SURFACE_PLOT2D:
m_c = m_universe.addSurfacePlot(m_ijImagePlus);
break;
default:
break;
}
} catch (final Exception e) {
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
showError(m_rootPanel, new String[] {
"error adding picture to universe:",
e.getClass().getSimpleName() }, true);
return null;
}
m_universe.updateTimeline();
return in;
}
/**
* @param firstElement
* @param imgPlus
* @param factor
*/
private ImagePlus createImagePlus(final ImgPlus<T> in) {
final double minValue = in.firstElement().getMinValue();
final double maxValue = in.firstElement().getMaxValue();
final ValuePair<T, T> oldMinMax = Operations.compute(
new MinMax<T>(), in);
final double factor = (((maxValue - minValue) / 255))
/ Normalize.normalizationFactor(
oldMinMax.a.getRealDouble(),
oldMinMax.b.getRealDouble(), minValue,
maxValue);
return ImgToIJ.wrap(in, new ImageProcessorFactory() {
@Override
public <V extends Type<V>> ImageProcessor createProcessor(
final int width, final int height, final V type) {
return new ByteProcessor(width, height);
}
}, new Converter<T, FloatType>() {
@Override
public void convert(final T input,
final FloatType output) {
output.setReal(((input.getRealDouble() - minValue) / factor));
}
});
}
@Override
protected void done() {
ImgPlus<T> imgPlus = null;
try {
imgPlus = get();
} catch (final Exception e) {
e.printStackTrace();
return;
}
// Error happend during rendering
if (imgPlus == null) {
return;
}
//
+ m_universe.init(new ImageWindow3D("abc", m_universe));
m_universePanel = m_universe.getCanvas(0);
try {
m_rootPanel.add(m_universePanel, BorderLayout.CENTER);
} catch (final IllegalArgumentException e) {
// TEMPORARY error handling: openen the 3D view
// on different monitors doesn't work so far, at
// least with linux
if (e.getLocalizedMessage()
.equals("adding a container to a container on a different GraphicsDevice")) {
m_rootPanel
.add(new JLabel(
"Opening the ImageJ 3D Viewer on different monitors doesn't work so far, sorry. We are working on it ...!"));
} else {
throw e;
}
}
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
// enables the timeline gui if picture has 4 or 5
// Dimensions
if (m_ijImagePlus.getNFrames() > 1) {
m_timelineGUI = new TimelineGUI(m_timeline);
m_panel4D = m_timelineGUI.getPanel();
m_universe.setTimelineGui(m_timelineGUI);
m_panel4D.setVisible(true);
m_rootPanel.add(m_panel4D, BorderLayout.SOUTH);
} else {
m_panel4D.setVisible(false);
}
}
};
worker.execute();
}
}
private class ImageJ3DErrorIndicator extends WaitIndicator {
private String[] m_errorText = { "Error" };
public ImageJ3DErrorIndicator(final JComponent target,
final String[] message) {
super(target);
getPainter().setCursor(
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
this.m_errorText = message;
}
@Override
public void paint(Graphics g) {
final Rectangle r = getDecorationBounds();
g = g.create();
g.setColor(new Color(211, 211, 211, 255));
g.fillRect(r.x, r.y, r.width, r.height);
if (m_errorText == null) {
m_errorText = new String[] { "unknown Error!" };
}
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// Title Warning
g.setColor(new Color(0, 0, 0));
g.setFont(new Font("Helvetica", Font.BOLD, 50));
g.drawString("ERROR", 10, 130);
// Error message
g.setFont(new Font("TimesRoman", Font.BOLD, 14));
final int newline = g.getFontMetrics().getHeight() + 5;
int y = 200;
for (final String s : m_errorText) {
g.drawString(s, 10, y += newline);
}
g.dispose();
}
}
@SuppressWarnings("unchecked")
private void showError(final JComponent jc, final String[] message,
final boolean on) {
ImageJ3DErrorIndicator w = (ImageJ3DErrorIndicator) jc
.getClientProperty("error");
if (w == null) {
if (on) {
String loggerMessage = "";
for (final String s : message) {
loggerMessage += " " + s;
}
m_logger.warn(loggerMessage);
w = new ImageJ3DErrorIndicator(jc, message);
}
} else if (!on) {
w.dispose();
w = null;
}
jc.putClientProperty("error", w);
}
@Override
public final void onClose() {
if (m_universe != null)
m_universe.cleanup();
m_dataValue = null;
m_ijImagePlus = null;
m_c = null;
m_panel4D = null;
m_universe = null;
m_timeline = null;
m_timelineGUI = null;
m_logger = null;
}
@Override
public final String getName() {
return "ImageJ 3D Viewer";
}
@Override
public final String getDescription() {
return "ImageJ 3D Viewer (see http://3dviewer.neurofly.de/)";
}
@Override
public void loadConfigurationFrom(final ConfigRO config) {
}
@Override
public void saveConfigurationTo(final ConfigWO config) {
}
@Override
public void onReset() {
}
}
| true | true | public final void updateComponent(final DataValue valueToView) {
if (m_dataValue == null || !(m_dataValue.equals(valueToView))) {
// reference to the current object so it can be reached in the
// worker.
final ImageJ3DTableCellView<T> context = this;
showError(m_rootPanel, null, false);
WaitingIndicatorUtils.setWaiting(m_rootPanel, true);
final SwingWorker<ImgPlus<T>, Integer> worker = new SwingWorker<ImgPlus<T>, Integer>() {
@Override
protected ImgPlus<T> doInBackground() throws Exception {
// universe for rendering the image
m_universe = new Image3DUniverse();
m_timeline = m_universe.getTimeline();
// Menubar
final ImageJ3DMenubar<T> ij3dbar = new ImageJ3DMenubar<T>(
m_universe, context);
// add menubar and 3Duniverse to the panel
m_rootPanel.add(ij3dbar, BorderLayout.NORTH);
// New image arrives
m_universe.resetView();
m_universe.removeAllContents(); // cleanup universe
m_dataValue = valueToView;
final ImgPlus<T> in = ((ImgPlusValue<T>) valueToView)
.getImgPlus();
// abort if input image has to few dimensions.
if (in.numDimensions() < 3) {
showError(
m_rootPanel,
new String[] {
"Only images with a minimum of three dimensions",
" are supported by the ImageJ 3D Viewer." },
true);
return null;
}
// abort if input image has to many dimensions.
if (in.numDimensions() > 5) {
showError(m_rootPanel, new String[] {
"Only images with up to five dimensions",
"are supported by the 3D Viewer." }, true);
return null;
}
// abort if unsuported type
if (in.firstElement() instanceof DoubleType) {
showError(
m_rootPanel,
new String[] {
"DoubleType images are not supported!",
" You have to convert your image to e.g. ByteType using the converter." },
true);
return null;
}
// validate if mapping can be inferred automatically
if (!ImgToIJ.validateMapping(in)) {
showError(
m_rootPanel,
new String[] { "Warning: The input image contains unknown dimensions. Currently we only support 'X','Y','Channel,'Z' and 'Time'!" },
true);
return null;
}
// here we create an converted ImagePlus
m_ijImagePlus = createImagePlus(in);
try {
// select the rendertype
switch (m_renderType) {
case ContentConstants.ORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
break;
case ContentConstants.MULTIORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
m_c.displayAs(ContentConstants.MULTIORTHO);
case ContentConstants.VOLUME:
m_c = m_universe.addVoltex(m_ijImagePlus);
break;
case ContentConstants.SURFACE:
m_c = m_universe.addMesh(m_ijImagePlus);
break;
case ContentConstants.SURFACE_PLOT2D:
m_c = m_universe.addSurfacePlot(m_ijImagePlus);
break;
default:
break;
}
} catch (final Exception e) {
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
showError(m_rootPanel, new String[] {
"error adding picture to universe:",
e.getClass().getSimpleName() }, true);
return null;
}
m_universe.updateTimeline();
return in;
}
/**
* @param firstElement
* @param imgPlus
* @param factor
*/
private ImagePlus createImagePlus(final ImgPlus<T> in) {
final double minValue = in.firstElement().getMinValue();
final double maxValue = in.firstElement().getMaxValue();
final ValuePair<T, T> oldMinMax = Operations.compute(
new MinMax<T>(), in);
final double factor = (((maxValue - minValue) / 255))
/ Normalize.normalizationFactor(
oldMinMax.a.getRealDouble(),
oldMinMax.b.getRealDouble(), minValue,
maxValue);
return ImgToIJ.wrap(in, new ImageProcessorFactory() {
@Override
public <V extends Type<V>> ImageProcessor createProcessor(
final int width, final int height, final V type) {
return new ByteProcessor(width, height);
}
}, new Converter<T, FloatType>() {
@Override
public void convert(final T input,
final FloatType output) {
output.setReal(((input.getRealDouble() - minValue) / factor));
}
});
}
@Override
protected void done() {
ImgPlus<T> imgPlus = null;
try {
imgPlus = get();
} catch (final Exception e) {
e.printStackTrace();
return;
}
// Error happend during rendering
if (imgPlus == null) {
return;
}
//
m_universePanel = m_universe.getCanvas(0);
try {
m_rootPanel.add(m_universePanel, BorderLayout.CENTER);
} catch (final IllegalArgumentException e) {
// TEMPORARY error handling: openen the 3D view
// on different monitors doesn't work so far, at
// least with linux
if (e.getLocalizedMessage()
.equals("adding a container to a container on a different GraphicsDevice")) {
m_rootPanel
.add(new JLabel(
"Opening the ImageJ 3D Viewer on different monitors doesn't work so far, sorry. We are working on it ...!"));
} else {
throw e;
}
}
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
// enables the timeline gui if picture has 4 or 5
// Dimensions
if (m_ijImagePlus.getNFrames() > 1) {
m_timelineGUI = new TimelineGUI(m_timeline);
m_panel4D = m_timelineGUI.getPanel();
m_universe.setTimelineGui(m_timelineGUI);
m_panel4D.setVisible(true);
m_rootPanel.add(m_panel4D, BorderLayout.SOUTH);
} else {
m_panel4D.setVisible(false);
}
}
};
worker.execute();
}
}
| public final void updateComponent(final DataValue valueToView) {
if (m_dataValue == null || !(m_dataValue.equals(valueToView))) {
// reference to the current object so it can be reached in the
// worker.
final ImageJ3DTableCellView<T> context = this;
showError(m_rootPanel, null, false);
WaitingIndicatorUtils.setWaiting(m_rootPanel, true);
final SwingWorker<ImgPlus<T>, Integer> worker = new SwingWorker<ImgPlus<T>, Integer>() {
@Override
protected ImgPlus<T> doInBackground() throws Exception {
// universe for rendering the image
m_universe = new Image3DUniverse();
m_timeline = m_universe.getTimeline();
// Menubar
final ImageJ3DMenubar<T> ij3dbar = new ImageJ3DMenubar<T>(
m_universe, context);
// add menubar and 3Duniverse to the panel
m_rootPanel.add(ij3dbar, BorderLayout.NORTH);
// New image arrives
m_universe.resetView();
m_universe.removeAllContents(); // cleanup universe
m_dataValue = valueToView;
final ImgPlus<T> in = ((ImgPlusValue<T>) valueToView)
.getImgPlus();
// abort if input image has to few dimensions.
if (in.numDimensions() < 3) {
showError(
m_rootPanel,
new String[] {
"Only images with a minimum of three dimensions",
" are supported by the ImageJ 3D Viewer." },
true);
return null;
}
// abort if input image has to many dimensions.
if (in.numDimensions() > 5) {
showError(m_rootPanel, new String[] {
"Only images with up to five dimensions",
"are supported by the 3D Viewer." }, true);
return null;
}
// abort if unsuported type
if (in.firstElement() instanceof DoubleType) {
showError(
m_rootPanel,
new String[] {
"DoubleType images are not supported!",
" You have to convert your image to e.g. ByteType using the converter." },
true);
return null;
}
// validate if mapping can be inferred automatically
if (!ImgToIJ.validateMapping(in)) {
showError(
m_rootPanel,
new String[] { "Warning: The input image contains unknown dimensions. Currently we only support 'X','Y','Channel,'Z' and 'Time'!" },
true);
return null;
}
// here we create an converted ImagePlus
m_ijImagePlus = createImagePlus(in);
try {
// select the rendertype
switch (m_renderType) {
case ContentConstants.ORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
break;
case ContentConstants.MULTIORTHO:
m_c = m_universe.addOrthoslice(m_ijImagePlus);
m_c.displayAs(ContentConstants.MULTIORTHO);
case ContentConstants.VOLUME:
m_c = m_universe.addVoltex(m_ijImagePlus);
break;
case ContentConstants.SURFACE:
m_c = m_universe.addMesh(m_ijImagePlus);
break;
case ContentConstants.SURFACE_PLOT2D:
m_c = m_universe.addSurfacePlot(m_ijImagePlus);
break;
default:
break;
}
} catch (final Exception e) {
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
showError(m_rootPanel, new String[] {
"error adding picture to universe:",
e.getClass().getSimpleName() }, true);
return null;
}
m_universe.updateTimeline();
return in;
}
/**
* @param firstElement
* @param imgPlus
* @param factor
*/
private ImagePlus createImagePlus(final ImgPlus<T> in) {
final double minValue = in.firstElement().getMinValue();
final double maxValue = in.firstElement().getMaxValue();
final ValuePair<T, T> oldMinMax = Operations.compute(
new MinMax<T>(), in);
final double factor = (((maxValue - minValue) / 255))
/ Normalize.normalizationFactor(
oldMinMax.a.getRealDouble(),
oldMinMax.b.getRealDouble(), minValue,
maxValue);
return ImgToIJ.wrap(in, new ImageProcessorFactory() {
@Override
public <V extends Type<V>> ImageProcessor createProcessor(
final int width, final int height, final V type) {
return new ByteProcessor(width, height);
}
}, new Converter<T, FloatType>() {
@Override
public void convert(final T input,
final FloatType output) {
output.setReal(((input.getRealDouble() - minValue) / factor));
}
});
}
@Override
protected void done() {
ImgPlus<T> imgPlus = null;
try {
imgPlus = get();
} catch (final Exception e) {
e.printStackTrace();
return;
}
// Error happend during rendering
if (imgPlus == null) {
return;
}
//
m_universe.init(new ImageWindow3D("abc", m_universe));
m_universePanel = m_universe.getCanvas(0);
try {
m_rootPanel.add(m_universePanel, BorderLayout.CENTER);
} catch (final IllegalArgumentException e) {
// TEMPORARY error handling: openen the 3D view
// on different monitors doesn't work so far, at
// least with linux
if (e.getLocalizedMessage()
.equals("adding a container to a container on a different GraphicsDevice")) {
m_rootPanel
.add(new JLabel(
"Opening the ImageJ 3D Viewer on different monitors doesn't work so far, sorry. We are working on it ...!"));
} else {
throw e;
}
}
WaitingIndicatorUtils.setWaiting(m_rootPanel, false);
// enables the timeline gui if picture has 4 or 5
// Dimensions
if (m_ijImagePlus.getNFrames() > 1) {
m_timelineGUI = new TimelineGUI(m_timeline);
m_panel4D = m_timelineGUI.getPanel();
m_universe.setTimelineGui(m_timelineGUI);
m_panel4D.setVisible(true);
m_rootPanel.add(m_panel4D, BorderLayout.SOUTH);
} else {
m_panel4D.setVisible(false);
}
}
};
worker.execute();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.